349fd25b0e661163cc31394202d23ea735a26129
[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                     table             => $table,
67                 });
68                 $field->comments($fdata->{comments});
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                 }
93     
94                 for my $cdata ( @{ $fdata->{constraints} } ) {
95                     next unless lc $cdata->{type} eq 'foreign_key';
96                     $cdata->{fields} ||= [ $field->name ];
97                     push @{ $tdata->{constraints} }, $cdata;
98                 }
99             }
100     
101             for my $idata ( @{ $tdata->{indices} || [] } ) {
102                 my $index = Index->new({ name => $idata->{name} || '', type => uc($idata->{type}), table => $table });
103                 map { $index->add_column($table->get_column($_)) } @{$idata->{fields}};
104                 $table->add_index($index);
105             }
106             
107     
108 #            if ( my @options = @{ $tdata->{'table_options'} || [] } ) {
109 #                my @cleaned_options;
110 #                my @ignore_opts = $self->parser_args->{'ignore_opts'}
111 #                    ? split( /,/, $self->parser_args->{'ignore_opts'} )
112 #                    : ();
113 #                if (@ignore_opts) {
114 #                    my $ignores = { map { $_ => 1 } @ignore_opts };
115 #                    foreach my $option (@options) {
116 #                        # make sure the option isn't in ignore list
117 #                        my ($option_key) = keys %$option;
118 #                        if ( !exists $ignores->{$option_key} ) {
119 #                            push @cleaned_options, $option;
120 #                        }
121 #                    }
122 #                } else {
123 #                    @cleaned_options = @options;
124 #                }
125 #                $table->options( \@cleaned_options ) or die $table->error;
126 #            }
127     
128             for my $cdata ( @{ $tdata->{constraints} || [] } ) {
129                 my $constraint;
130                 if (uc $cdata->{type} eq 'PRIMARY_KEY') {
131                     $constraint = PrimaryKey->new({ name => $cdata->{name} || '', table => $table });
132                     $table->get_column($_)->is_primary_key(1) for @{$cdata->{fields}};
133                 } elsif (uc $cdata->{type} eq 'FOREIGN_KEY') {
134                     $constraint = ForeignKey->new({ name => $cdata->{name} || '',
135                                                     table => $table,
136                                                     reference_table => $cdata->{reference_table},
137                                                     reference_columns => $cdata->{reference_fields},
138                                                     on_delete => $cdata->{on_delete} || $cdata->{on_delete_do},
139                                                     on_update => $cdata->{on_update} || $cdata->{on_update_do} });
140                     $table->get_column($_)->is_foreign_key(1) for @{$cdata->{fields}};
141                     $table->get_column($_)->foreign_key_reference($constraint) for @{$cdata->{fields}};
142                 } else {
143                     $constraint = Constraint->new({ name => $cdata->{name} || '', type => uc $cdata->{type}, table => $table });
144                 }
145                 $constraint->add_column($table->get_column($_)) for @{$cdata->{fields}};
146                 $table->add_constraint($constraint);
147             }
148         }
149         
150         for my $proc_name ( keys %{ $result->{procedures} } ) {
151             my $procedure = Procedure->new({ name  => $proc_name,
152                                              owner => $result->{procedures}->{$proc_name}->{owner},
153                                              sql   => $result->{procedures}->{$proc_name}->{sql}
154             });
155             $schema->add_procedure($procedure);
156         }
157     
158         for my $view_name ( keys %{ $result->{'views'} } ) {
159             my $view = View->new({ 
160                 name => $view_name,
161                 sql  => $result->{'views'}->{$view_name}->{sql},
162             });
163             $schema->add_view($view);
164         }
165         return 1;
166     }
167 }