fix constraint production
[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          => $fdata->{comments},
67                     table             => $table,
68                 });
69                 $table->add_column($field);
70     
71                 $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
72
73                 my %extra;
74                 for my $qual ( qw[ binary unsigned zerofill list collate ],
75                         'character set', 'on update' ) {
76                     if ( my $val = $fdata->{ $qual } || $fdata->{ uc $qual } ) {
77                         next if ref $val eq 'ARRAY' && !@$val;
78                         $extra{$qual} = $val;
79                         #$field->extra( $qual, $val );
80                     }
81                 }
82                 $field->extra(\%extra);
83
84                 if ( $fdata->{has_index} ) {
85                     my $index = Index->new({ name => '', type => 'NORMAL', table => $table });
86                     $index->add_column($table->get_column($fdata->{name}));
87                     $table->add_index($index);
88                 }
89     
90                 if ( $fdata->{is_unique} ) {
91                     push @{ $tdata->{constraints} }, { name => '', type => 'UNIQUE', fields => [ $fdata->{name} ] };
92 #                     my $constraint = Constraint->new({ name => '', type => 'UNIQUE' });
93 #                     $constraint->add_column($table->get_column($fdata->{name}));
94 #                     $table->add_constraint($constraint);
95                 }
96     
97                 for my $cdata ( @{ $fdata->{constraints} } ) {
98                     next unless lc $cdata->{type} eq 'foreign_key';
99                     $cdata->{fields} ||= [ $field->name ];
100                     push @{ $tdata->{constraints} }, $cdata;
101                 }
102             }
103     
104             for my $idata ( @{ $tdata->{indices} || [] } ) {
105                 my $index = Index->new({ name => $idata->{name} || '', type => uc($idata->{type}), table => $table });
106                 map { $index->add_column($table->get_column($_)) } @{$idata->{fields}};
107                 $table->add_index($index);
108             }
109             
110     
111 #            if ( my @options = @{ $tdata->{'table_options'} || [] } ) {
112 #                my @cleaned_options;
113 #                my @ignore_opts = $self->parser_args->{'ignore_opts'}
114 #                    ? split( /,/, $self->parser_args->{'ignore_opts'} )
115 #                    : ();
116 #                if (@ignore_opts) {
117 #                    my $ignores = { map { $_ => 1 } @ignore_opts };
118 #                    foreach my $option (@options) {
119 #                        # make sure the option isn't in ignore list
120 #                        my ($option_key) = keys %$option;
121 #                        if ( !exists $ignores->{$option_key} ) {
122 #                            push @cleaned_options, $option;
123 #                        }
124 #                    }
125 #                } else {
126 #                    @cleaned_options = @options;
127 #                }
128 #                $table->options( \@cleaned_options ) or die $table->error;
129 #            }
130     
131             for my $cdata ( @{ $tdata->{constraints} || [] } ) {
132                 my $constraint;
133                 if (uc $cdata->{type} eq 'PRIMARY_KEY') {
134                     $constraint = PrimaryKey->new({ name => $cdata->{name} || 'primary_key', table => $table });
135                     $constraint->add_column($table->get_column($_)) for @{$cdata->{fields}};
136                 $table->get_column($_)->is_primary_key(1) for @{$cdata->{fields}};
137                 } elsif (uc $cdata->{type} eq 'FOREIGN_KEY') {
138                     $constraint = ForeignKey->new({ name => $cdata->{name} || 'foreign_key',
139                                                     table => $table,
140                                                     reference_table => $cdata->{reference_table},
141                                                     reference_columns => $cdata->{reference_fields},
142                                                     on_delete => $cdata->{on_delete} || $cdata->{on_delete_do},
143                                                     on_update => $cdata->{on_update} || $cdata->{on_update_do} });
144                     $table->get_column($_)->is_foreign_key(1) for @{$cdata->{fields}};
145                     $table->get_column($_)->foreign_key_reference($constraint) for @{$cdata->{fields}};
146                 } else {
147                     $constraint = Constraint->new({ name => $cdata->{name} || 'constraint', type => uc $cdata->{type}, table => $table });
148                     $constraint->add_column($table->get_column($_)) for @{$cdata->{fields}};
149                 }
150                 $table->add_constraint($constraint);
151
152 #                my $constraint       =  $table->add_constraint(
153 #                    name             => $cdata->{'name'},
154 #                    type             => $cdata->{'type'},
155 #                    fields           => $cdata->{'fields'},
156 #                    reference_table  => $cdata->{'reference_table'},
157 #                    reference_fields => $cdata->{'reference_fields'},
158 #                    match_type       => $cdata->{'match_type'} || '',
159 #                    on_delete        => $cdata->{'on_delete'} 
160 #                                     || $cdata->{'on_delete_do'},
161 #                    on_update        => $cdata->{'on_update'} 
162 #                                     || $cdata->{'on_update_do'},
163 #                ) or die $table->error;
164             }
165     
166             # After the constrains and PK/idxs have been created, 
167             # we normalize fields
168             normalize_field($_) for $table->get_fields;
169         }
170         
171 #        my @procedures = sort { $result->{procedures}->{ $a }->{'order'} <=> $result->{procedures}->{ $b }->{'order'} } keys %{ $result->{procedures} };
172     
173 #        for my $proc_name ( @procedures ) {
174 #            $schema->add_procedure(
175 #                name  => $proc_name,
176 #                owner => $result->{procedures}->{$proc_name}->{owner},
177 #                sql   => $result->{procedures}->{$proc_name}->{sql},
178 #            );
179 #        }
180     
181 #        my @views = sort { $result->{views}->{ $a }->{'order'} <=> $result->{views}->{ $b }->{'order'} } keys %{ $result->{views} };
182     
183 #        for my $view_name ( keys %{ $result->{'views'} } ) {
184 #            $schema->add_view(
185 #                name => $view_name,
186 #                sql  => $result->{'views'}->{$view_name}->{sql},
187 #            );
188 #        }
189         return $schema;
190     }
191     
192     # Takes a field, and returns 
193     method normalize_field {
194         my ($size, $type, $list, $changed); # = @_;
195       
196         $size = $self->size || 0;
197         $type = $self->data_type;
198         $list = $self->extra->{list} || [];
199
200         if ( !ref $size && $size == 0 ) {
201             if ( lc $type eq 'tinyint' ) {
202                 $changed = $size != 4;
203                 $size = 4;
204             }
205             elsif ( lc $type eq 'smallint' ) {
206                 $changed = $size != 6;
207                 $size = 6;
208             }
209             elsif ( lc $type eq 'mediumint' ) {
210                 $changed = $size != 9;
211                 $size = 9;
212             }
213             elsif ( $type =~ /^int(eger)?$/i ) {
214                 $changed = $size != 11 || $type ne 'int';
215                 $type = 'int';
216                 $size = 11;
217             }
218             elsif ( lc $type eq 'bigint' ) {
219                 $changed = $size != 20;
220                 $size = 20;
221             }
222             elsif ( lc $type =~ /(float|double|decimal|numeric|real|fixed|dec)/ ) {
223                 my $old_size = (ref $size || '') eq 'ARRAY' ? $size : [];
224                 $changed     = @$old_size != 2 
225                             || $old_size->[0] != 8 
226                             || $old_size->[1] != 2;
227                 $size        = [8,2];
228             }
229         }
230     
231         if ( $type =~ /^tiny(text|blob)$/i ) {
232             $changed = $size != 255;
233             $size = 255;
234         }
235         elsif ( $type =~ /^(blob|text)$/i ) {
236             $changed = $size != 65_535;
237             $size = 65_535;
238         }
239         elsif ( $type =~ /^medium(blob|text)$/i ) {
240             $changed = $size != 16_777_215;
241             $size = 16_777_215;
242         }
243         elsif ( $type =~ /^long(blob|text)$/i ) {
244             $changed = $size != 4_294_967_295;
245             $size = 4_294_967_295;
246         }
247     
248         if ( $type =~ /(set|enum)/i && !$size ) {
249             my %extra = $self->extra;
250             my $longest = 0;
251             for my $len ( map { length } @{ $extra{'list'} || [] } ) {
252                 $longest = $len if $len > $longest;
253             }
254             $changed = 1;
255             $size = $longest if $longest;
256         }
257     
258 #        if ( $changed ) {
259             # We only want to clone the field, not *everything*
260 #            {
261 #                local $field->{table} = undef;
262 #                $field->parsed_field( dclone( $field ) );
263 #                $field->parsed_field->{table} = $field->table;
264 #            }
265             $self->size( $size );
266             $self->data_type( $type );
267 #            $column->sql_data_type( $self->data_type_mapping->{$type} || -99999 );
268             $self->extra->{list} = $list if @$list;
269 #        }
270         return 1;
271     }
272 }