cleanup and standardization
[dbsrgits/SQL-Translator-2.0-ish.git] / lib / SQL / Translator / Parser / DDL / MySQL.pm
1 use MooseX::Declare;
2 role SQL::Translator::Parser::DDL::MySQL {
3     use MooseX::Types::Moose qw(Str);
4     use MooseX::MultiMethods;
5     use SQL::Translator::Constants qw(:sqlt_types :sqlt_constants);
6     use aliased 'SQL::Translator::Object::Column';
7     use aliased 'SQL::Translator::Object::Constraint';
8     use aliased 'SQL::Translator::Object::ForeignKey';
9     use aliased 'SQL::Translator::Object::Index';
10     use aliased 'SQL::Translator::Object::PrimaryKey';
11     use aliased 'SQL::Translator::Object::Schema';
12     use aliased 'SQL::Translator::Object::Table';
13
14     around _build_data_type_mapping {
15         my $data_type_mapping = $self->$orig;
16         $data_type_mapping->{date} = SQL_DATE();
17
18         return $data_type_mapping;
19     }; 
20
21     multi method parse(Schema $data) { $data }
22
23     multi method parse(Str $data) {
24         my $parser = Parse::RecDescent->new($self->grammar);
25
26         unless (defined $parser) {
27             return $self->error("Error instantiating Parse::RecDescent ".
28                 "instance: Bad grammar");
29         }
30
31 #    my $parser_version = parse_mysql_version(
32 #        $translator->parser_args->{mysql_parser_version}, 'mysql'
33 #    ) || DEFAULT_PARSER_VERSION;
34         my $parser_version = 30000;
35     
36         while ($data =~ s#/\*!(\d{5})?(.*?)\*/#($1 && $1 > $parser_version ? '' : $2)#es) { }
37
38         my $result = $parser->startrule($data);
39         die "Parse failed" unless defined $result;
40     
41         my $translator = $self->translator;
42         my $schema = $translator->schema;
43         $schema->name($result->{'database_name'}) if $result->{'database_name'};
44     
45         my @tables = sort { $result->{'tables'}{ $a }{'order'} <=> $result->{'tables'}{ $b }{'order'} } keys %{ $result->{'tables'} };
46     
47         for my $table_name ( @tables ) {
48             my $tdata = $result->{tables}{ $table_name };
49             my $table = Table->new({ name => $tdata->{table_name}, schema => $schema });
50             $schema->add_table($table);
51             $table->comments( join "\n", @{$tdata->{comments}} ) if $tdata->{comments};
52     
53             my @fields = sort { $tdata->{'fields'}->{$a}->{'order'} <=> $tdata->{'fields'}->{$b}->{'order'} } keys %{ $tdata->{'fields'} };
54     
55             for my $fname ( @fields ) {
56                 my $fdata = $tdata->{fields}{ $fname };
57                 my $field = Column->new({
58                     name              => $fdata->{name},
59                     data_type         => $fdata->{data_type},
60                     sql_data_type     => $self->data_type_mapping->{$fdata->{data_type}} || -999999,
61                     size              => $fdata->{size},
62                     default_value     => $fdata->{default},
63                     is_auto_increment => $fdata->{is_auto_inc},
64                     is_nullable       => $fdata->{null},
65                     is_primary_key    => $fdata->{is_primary_key} ? 1 : 0,
66                     comments          => (join "\n", @{$fdata->{comments}}) || '',
67                 });
68                 $table->add_column($field);
69     
70                 $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
71
72                 my %extra;
73                 for my $qual ( qw[ binary unsigned zerofill list collate ],
74                         'character set', 'on update' ) {
75                     if ( my $val = $fdata->{ $qual } || $fdata->{ uc $qual } ) {
76                         next if ref $val eq 'ARRAY' && !@$val;
77                         $extra{$qual} = $val;
78                         #$field->extra( $qual, $val );
79                     }
80                 }
81                 $field->extra(\%extra);
82
83                 if ( $fdata->{has_index} ) {
84                     my $index = Index->new({ name => '', type => 'NORMAL' });
85                     $index->add_column($table->get_column($fdata->{name}));
86                     $table->add_index($index);
87                 }
88     
89                 if ( $fdata->{is_unique} ) {
90                     push @{ $tdata->{constraints} }, { name => '', type => 'UNIQUE', fields => [ $fdata->{name} ] };
91 #                     my $constraint = Constraint->new({ name => '', type => 'UNIQUE' });
92 #                     $constraint->add_column($table->get_column($fdata->{name}));
93 #                     $table->add_constraint($constraint);
94                 }
95     
96                 for my $cdata ( @{ $fdata->{constraints} } ) {
97                     next unless lc $cdata->{type} eq 'foreign_key';
98                     $cdata->{fields} ||= [ $field->name ];
99                     push @{ $tdata->{constraints} }, $cdata;
100                 }
101             }
102     
103             for my $idata ( @{ $tdata->{indices} || [] } ) {
104                 my $index = Index->new({ name => $idata->{name} || '', type => uc($idata->{type}) });
105                 map { $index->add_column($table->get_column($_)) } @{$idata->{fields}};
106                 $table->add_index($index);
107             }
108             
109     
110 #            if ( my @options = @{ $tdata->{'table_options'} || [] } ) {
111 #                my @cleaned_options;
112 #                my @ignore_opts = $self->parser_args->{'ignore_opts'}
113 #                    ? split( /,/, $self->parser_args->{'ignore_opts'} )
114 #                    : ();
115 #                if (@ignore_opts) {
116 #                    my $ignores = { map { $_ => 1 } @ignore_opts };
117 #                    foreach my $option (@options) {
118 #                        # make sure the option isn't in ignore list
119 #                        my ($option_key) = keys %$option;
120 #                        if ( !exists $ignores->{$option_key} ) {
121 #                            push @cleaned_options, $option;
122 #                        }
123 #                    }
124 #                } else {
125 #                    @cleaned_options = @options;
126 #                }
127 #                $table->options( \@cleaned_options ) or die $table->error;
128 #            }
129     
130             for my $cdata ( @{ $tdata->{constraints} || [] } ) {
131                 my $constraint;
132                 if (uc $cdata->{type} eq 'PRIMARY_KEY') {
133                     $constraint = PrimaryKey->new({ name => $cdata->{name} || 'primary_key' });
134                 map { $constraint->add_column($table->get_column($_)) } @{$cdata->{fields}};
135                 $table->get_column($_)->is_primary_key(1) for @{$cdata->{fields}};
136                 } elsif (uc $cdata->{type} eq 'FOREIGN_KEY') {
137                     $constraint = ForeignKey->new({ name => $cdata->{name} || 'foreign_key',
138                                                     reference_table => $cdata->{reference_table},
139                                                     reference_columns => $cdata->{reference_fields},
140                                                     on_delete => $cdata->{on_delete} || $cdata->{on_delete_do},
141                                                     on_update => $cdata->{on_update} || $cdata->{on_update_do} });
142                     $table->get_column($_)->is_foreign_key(1) for @{$cdata->{fields}};
143                     $table->get_column($_)->foreign_key_reference($constraint) for @{$cdata->{fields}};
144                 } else {
145                     $constraint = Constraint->new({ name => $cdata->{name} || 'constraint', type => uc $cdata->{type} });
146                 map { $constraint->add_column($table->get_column($_)) } @{$cdata->{fields}};
147                 }
148                 $table->add_constraint($constraint);
149
150 #                my $constraint       =  $table->add_constraint(
151 #                    name             => $cdata->{'name'},
152 #                    type             => $cdata->{'type'},
153 #                    fields           => $cdata->{'fields'},
154 #                    reference_table  => $cdata->{'reference_table'},
155 #                    reference_fields => $cdata->{'reference_fields'},
156 #                    match_type       => $cdata->{'match_type'} || '',
157 #                    on_delete        => $cdata->{'on_delete'} 
158 #                                     || $cdata->{'on_delete_do'},
159 #                    on_update        => $cdata->{'on_update'} 
160 #                                     || $cdata->{'on_update_do'},
161 #                ) or die $table->error;
162             }
163     
164             # After the constrains and PK/idxs have been created, 
165             # we normalize fields
166             normalize_field($_) for $table->get_fields;
167         }
168         
169 #        my @procedures = sort { $result->{procedures}->{ $a }->{'order'} <=> $result->{procedures}->{ $b }->{'order'} } keys %{ $result->{procedures} };
170     
171 #        for my $proc_name ( @procedures ) {
172 #            $schema->add_procedure(
173 #                name  => $proc_name,
174 #                owner => $result->{procedures}->{$proc_name}->{owner},
175 #                sql   => $result->{procedures}->{$proc_name}->{sql},
176 #            );
177 #        }
178     
179 #        my @views = sort { $result->{views}->{ $a }->{'order'} <=> $result->{views}->{ $b }->{'order'} } keys %{ $result->{views} };
180     
181 #        for my $view_name ( keys %{ $result->{'views'} } ) {
182 #            $schema->add_view(
183 #                name => $view_name,
184 #                sql  => $result->{'views'}->{$view_name}->{sql},
185 #            );
186 #        }
187         return $schema;
188     }
189     
190     # Takes a field, and returns 
191     method normalize_field {
192         my ($size, $type, $list, $changed); # = @_;
193       
194         $size = $self->size || 0;
195         $type = $self->data_type;
196         $list = $self->extra->{list} || [];
197
198         if ( !ref $size && $size == 0 ) {
199             if ( lc $type eq 'tinyint' ) {
200                 $changed = $size != 4;
201                 $size = 4;
202             }
203             elsif ( lc $type eq 'smallint' ) {
204                 $changed = $size != 6;
205                 $size = 6;
206             }
207             elsif ( lc $type eq 'mediumint' ) {
208                 $changed = $size != 9;
209                 $size = 9;
210             }
211             elsif ( $type =~ /^int(eger)?$/i ) {
212                 $changed = $size != 11 || $type ne 'int';
213                 $type = 'int';
214                 $size = 11;
215             }
216             elsif ( lc $type eq 'bigint' ) {
217                 $changed = $size != 20;
218                 $size = 20;
219             }
220             elsif ( lc $type =~ /(float|double|decimal|numeric|real|fixed|dec)/ ) {
221                 my $old_size = (ref $size || '') eq 'ARRAY' ? $size : [];
222                 $changed     = @$old_size != 2 
223                             || $old_size->[0] != 8 
224                             || $old_size->[1] != 2;
225                 $size        = [8,2];
226             }
227         }
228     
229         if ( $type =~ /^tiny(text|blob)$/i ) {
230             $changed = $size != 255;
231             $size = 255;
232         }
233         elsif ( $type =~ /^(blob|text)$/i ) {
234             $changed = $size != 65_535;
235             $size = 65_535;
236         }
237         elsif ( $type =~ /^medium(blob|text)$/i ) {
238             $changed = $size != 16_777_215;
239             $size = 16_777_215;
240         }
241         elsif ( $type =~ /^long(blob|text)$/i ) {
242             $changed = $size != 4_294_967_295;
243             $size = 4_294_967_295;
244         }
245     
246         if ( $type =~ /(set|enum)/i && !$size ) {
247             my %extra = $self->extra;
248             my $longest = 0;
249             for my $len ( map { length } @{ $extra{'list'} || [] } ) {
250                 $longest = $len if $len > $longest;
251             }
252             $changed = 1;
253             $size = $longest if $longest;
254         }
255     
256 #        if ( $changed ) {
257             # We only want to clone the field, not *everything*
258 #            {
259 #                local $field->{table} = undef;
260 #                $field->parsed_field( dclone( $field ) );
261 #                $field->parsed_field->{table} = $field->table;
262 #            }
263             $self->size( $size );
264             $self->data_type( $type );
265 #            $column->sql_data_type( $self->data_type_mapping->{$type} || -99999 );
266             $self->extra->{list} = $list if @$list;
267 #        }
268         return 1;
269     }
270 }