b7e05a02f12e729ed18e2b52308eef0ea892982f
[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::Procedure';
12     use aliased 'SQL::Translator::Object::Schema';
13     use aliased 'SQL::Translator::Object::Table';
14     use aliased 'SQL::Translator::Object::View';
15
16     around _build_data_type_mapping {
17         my $data_type_mapping = $self->$orig;
18         $data_type_mapping->{date} = SQL_DATE();
19
20         return $data_type_mapping;
21     }; 
22
23     multi method parse(Schema $data) { $data }
24
25     multi method parse(Str $data) {
26         my $parser = Parse::RecDescent->new($self->grammar);
27
28         unless (defined $parser) {
29             return $self->error("Error instantiating Parse::RecDescent ".
30                 "instance: Bad grammar");
31         }
32
33         my $translator = $self->translator;
34
35         my $parser_version = $translator->has_parser_args
36                              ? $translator->engine_version($translator->parser_args->{mysql_parser_version}, 'mysql') || DEFAULT_PARSER_VERSION
37                              : DEFAULT_PARSER_VERSION;
38     
39         while ($data =~ s#/\*!(\d{5})?(.*?)\*/#($1 && $1 > $parser_version ? '' : $2)#es) { }
40
41         my $result = $parser->startrule($data);
42         die "Parse failed" unless defined $result;
43     
44         my $schema = $translator->schema;
45         $schema->name($result->{'database_name'}) if $result->{'database_name'};
46     
47         my @tables = sort { $result->{'tables'}{ $a }{'order'} <=> $result->{'tables'}{ $b }{'order'} } keys %{ $result->{'tables'} };
48     
49         for my $table_name ( @tables ) {
50             my $tdata = $result->{tables}{ $table_name };
51             my $table = Table->new({ name => $tdata->{table_name}, schema => $schema });
52             $schema->add_table($table);
53             $table->comments( join "\n", @{$tdata->{comments}} ) if $tdata->{comments};
54     
55             my @fields = sort { $tdata->{'fields'}->{$a}->{'order'} <=> $tdata->{'fields'}->{$b}->{'order'} } keys %{ $tdata->{'fields'} };
56     
57             for my $fname ( @fields ) {
58                 my $fdata = $tdata->{fields}{ $fname };
59                 my $field = Column->new({
60                     name              => $fdata->{name},
61                     data_type         => $fdata->{data_type},
62                     sql_data_type     => $self->data_type_mapping->{$fdata->{data_type}} || -999999,
63                     size              => $fdata->{size},
64                     default_value     => $fdata->{default},
65                     is_auto_increment => $fdata->{is_auto_inc},
66                     is_nullable       => $fdata->{null},
67                     is_primary_key    => $fdata->{is_primary_key} ? 1 : 0,
68                     table             => $table,
69                 });
70                 $field->comments($fdata->{comments});
71                 $table->add_column($field);
72     
73                 $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
74
75                 my %extra;
76                 for my $qual ( qw[ binary unsigned zerofill list collate ],
77                         'character set', 'on update' ) {
78                     if ( my $val = $fdata->{ $qual } || $fdata->{ uc $qual } ) {
79                         next if ref $val eq 'ARRAY' && !@$val;
80                         $extra{$qual} = $val;
81                         #$field->extra( $qual, $val );
82                     }
83                 }
84                 $field->extra(\%extra);
85
86                 if ( $fdata->{has_index} ) {
87                     my $index = Index->new({ name => '', type => 'NORMAL', table => $table });
88                     $index->add_column($table->get_column($fdata->{name}));
89                     $table->add_index($index);
90                 }
91     
92                 if ( $fdata->{is_unique} ) {
93                     push @{ $tdata->{constraints} }, { name => '', type => 'UNIQUE', fields => [ $fdata->{name} ] };
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}), table => $table });
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 = $translator->has_parser_args && $translator->parser_args->{'ignore_opts'}
113                     ? split( /,/, $translator->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} || '', table => $table });
134                     $table->get_column($_)->is_primary_key(1) for @{$cdata->{fields}};
135                 } elsif (uc $cdata->{type} eq 'FOREIGN_KEY') {
136                     $constraint = ForeignKey->new({ name => $cdata->{name} || '',
137                                                     table => $table,
138                                                     reference_table => $cdata->{reference_table},
139                                                     defined $cdata->{reference_fields} ? (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} || '', type => uc $cdata->{type}, table => $table });
146                 }
147                 $constraint->add_column($table->get_column($_)) for @{$cdata->{fields}};
148                 $table->add_constraint($constraint);
149             }
150         }
151         
152         for my $proc_name ( keys %{ $result->{procedures} } ) {
153             my $procedure = Procedure->new({ name  => $proc_name,
154                                              owner => $result->{procedures}->{$proc_name}->{owner},
155                                              sql   => $result->{procedures}->{$proc_name}->{sql}
156             });
157             $schema->add_procedure($procedure);
158         }
159     
160         for my $view_name ( keys %{ $result->{'views'} } ) {
161             my $view = View->new({ 
162                 name => $view_name,
163                 sql  => $result->{'views'}->{$view_name}->{sql},
164             });
165             $schema->add_view($view);
166         }
167         return 1;
168     }
169 }