1 package SQL::Translator::Parser::MySQL;
3 # -------------------------------------------------------------------
4 # $Id: MySQL.pm,v 1.26 2003-07-18 22:56:12 kycl4rk Exp $
5 # -------------------------------------------------------------------
6 # Copyright (C) 2003 Ken Y. Clark <kclark@cpan.org>,
7 # darren chamberlain <darren@cpan.org>,
8 # Chris Mungall <cjm@fruitfly.org>
10 # This program is free software; you can redistribute it and/or
11 # modify it under the terms of the GNU General Public License as
12 # published by the Free Software Foundation; version 2.
14 # This program is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 # General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with this program; if not, write to the Free Software
21 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
23 # -------------------------------------------------------------------
27 SQL::Translator::Parser::MySQL - parser for MySQL
32 use SQL::Translator::Parser::MySQL;
34 my $translator = SQL::Translator->new;
35 $translator->parser("SQL::Translator::Parser::MySQL");
39 The grammar is influenced heavily by Tim Bunce's "mysql2ora" grammar.
41 Here's the word from the MySQL site
42 (http://www.mysql.com/doc/en/CREATE_TABLE.html):
44 CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]
45 [table_options] [select_statement]
49 CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name LIKE old_table_name;
52 col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]
53 [PRIMARY KEY] [reference_definition]
54 or PRIMARY KEY (index_col_name,...)
55 or KEY [index_name] (index_col_name,...)
56 or INDEX [index_name] (index_col_name,...)
57 or UNIQUE [INDEX] [index_name] (index_col_name,...)
58 or FULLTEXT [INDEX] [index_name] (index_col_name,...)
59 or [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)
60 [reference_definition]
64 TINYINT[(length)] [UNSIGNED] [ZEROFILL]
65 or SMALLINT[(length)] [UNSIGNED] [ZEROFILL]
66 or MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL]
67 or INT[(length)] [UNSIGNED] [ZEROFILL]
68 or INTEGER[(length)] [UNSIGNED] [ZEROFILL]
69 or BIGINT[(length)] [UNSIGNED] [ZEROFILL]
70 or REAL[(length,decimals)] [UNSIGNED] [ZEROFILL]
71 or DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL]
72 or FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL]
73 or DECIMAL(length,decimals) [UNSIGNED] [ZEROFILL]
74 or NUMERIC(length,decimals) [UNSIGNED] [ZEROFILL]
75 or CHAR(length) [BINARY]
76 or VARCHAR(length) [BINARY]
89 or ENUM(value1,value2,value3,...)
90 or SET(value1,value2,value3,...)
96 REFERENCES tbl_name [(index_col_name,...)]
97 [MATCH FULL | MATCH PARTIAL]
98 [ON DELETE reference_option]
99 [ON UPDATE reference_option]
102 RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT
105 TYPE = {BDB | HEAP | ISAM | InnoDB | MERGE | MRG_MYISAM | MYISAM }
106 or AUTO_INCREMENT = #
107 or AVG_ROW_LENGTH = #
108 or CHECKSUM = {0 | 1}
109 or COMMENT = "string"
112 or PACK_KEYS = {0 | 1 | DEFAULT}
113 or PASSWORD = "string"
114 or DELAY_KEY_WRITE = {0 | 1}
115 or ROW_FORMAT= { default | dynamic | fixed | compressed }
116 or RAID_TYPE= {1 | STRIPED | RAID0 } RAID_CHUNKS=# RAID_CHUNKSIZE=#
117 or UNION = (table_name,[table_name...])
118 or INSERT_METHOD= {NO | FIRST | LAST }
119 or DATA DIRECTORY="absolute path to directory"
120 or INDEX DIRECTORY="absolute path to directory"
125 use vars qw[ $DEBUG $VERSION $GRAMMAR @EXPORT_OK ];
126 $VERSION = sprintf "%d.%02d", q$Revision: 1.26 $ =~ /(\d+)\.(\d+)/;
127 $DEBUG = 0 unless defined $DEBUG;
130 use Parse::RecDescent;
132 use base qw(Exporter);
134 @EXPORT_OK = qw(parse);
136 # Enable warnings within the Parse::RecDescent module.
137 $::RD_ERRORS = 1; # Make sure the parser dies when it encounters an error
138 $::RD_WARN = 1; # Enable warnings. This will warn on unused rules &c.
139 $::RD_HINT = 1; # Give out hints to help fix problems.
144 our ( %tables, $table_order );
148 # The "eofile" rule makes the parser fail if any "statement" rule
149 # fails. Otherwise, the first successful match by a "statement"
150 # won't cause the failure needed to know that the parse, as a whole,
153 startrule : statement(s) eofile { \%tables }
163 use : /use/i WORD ';'
165 drop : /drop/i WORD(s) ';'
167 create : CREATE /database/i WORD ';'
169 create : CREATE TEMPORARY(?) TABLE opt_if_not_exists(?) table_name '(' create_definition(s /,/) ')' table_option(s?) ';'
171 my $table_name = $item{'table_name'};
172 $tables{ $table_name }{'order'} = ++$table_order;
173 $tables{ $table_name }{'table_name'} = $table_name;
176 for my $definition ( @{ $item[7] } ) {
177 if ( $definition->{'supertype'} eq 'field' ) {
179 my $field_name = $definition->{'name'};
180 $tables{ $table_name }{'fields'}{ $field_name } =
181 { %$definition, order => $i };
184 if ( $definition->{'is_primary_key'} ) {
185 push @{ $tables{ $table_name }{'constraints'} },
187 type => 'primary_key',
188 fields => [ $field_name ],
193 elsif ( $definition->{'supertype'} eq 'constraint' ) {
194 # prob get rid of this?
195 # for my $field ( @{ $definition->{'fields'} } ) {
197 # $tables{$table_name}{'fields'}{$field}{'constraints'}
202 # this should be the only one needed
203 push @{ $tables{ $table_name }{'constraints'} }, $definition;
205 elsif ( $definition->{'supertype'} eq 'index' ) {
206 push @{ $tables{ $table_name }{'indices'} },
211 for my $opt ( @{ $item{'table_option(s?)'} } ) {
212 if ( my ( $key, $val ) = each %$opt ) {
213 $tables{ $table_name }{'table_options'}{ $key } = $val;
220 opt_if_not_exists : /if not exists/i
222 create : CREATE UNIQUE(?) /(index|key)/i index_name /on/i table_name '(' field_name(s /,/) ')' ';'
224 push @{ $tables{ $item{'table_name'} }{'indices'} },
227 type => $item[2] ? 'unique' : 'normal',
233 create_definition : constraint
238 comment : /^\s*(?:#|-{2}).*\n/ {
239 my $comment = $item[1];
240 $comment =~ s/^\s*(#|-{2})//;
241 $comment =~ s/\s*$//;
247 field : comment(s?) field_name data_type field_qualifier(s?) reference_definition(?) comment(s?)
249 my %qualifiers = map { %$_ } @{ $item{'field_qualifier(s?)'} || [] };
250 my $null = defined $item{'not_null'} ? $item{'not_null'} : 1;
251 delete $qualifiers{'not_null'};
252 if ( my @type_quals = @{ $item{'data_type'}{'qualifiers'} || [] } ) {
253 $qualifiers{ $_ } = 1 for @type_quals;
256 my @comments = ( @{ $item[1] }, @{ $item[6] } );
259 supertype => 'field',
260 name => $item{'field_name'},
261 data_type => $item{'data_type'}{'type'},
262 size => $item{'data_type'}{'size'},
263 list => $item{'data_type'}{'list'},
265 constraints => $item{'reference_definition(?)'},
266 comments => [ @comments ],
272 field_qualifier : not_null
275 null => $item{'not_null'},
279 field_qualifier : default_val
282 default => $item{'default_val'},
286 field_qualifier : auto_inc
289 is_auto_inc => $item{'auto_inc'},
293 field_qualifier : primary_key
296 is_primary_key => $item{'primary_key'},
300 field_qualifier : unsigned
303 is_unsigned => $item{'unsigned'},
307 reference_definition : /references/i table_name parens_field_list(?) match_type(?) on_delete_do(?) on_update_do(?)
310 type => 'foreign_key',
311 reference_table => $item[2],
312 reference_fields => $item[3][0],
313 match_type => $item[4][0],
314 on_delete_do => $item[5][0],
315 on_update_do => $item[6][0],
319 match_type : /match full/i { 'match_full' }
321 /match partial/i { 'match_partial' }
323 on_delete_do : /on delete/i reference_option
326 on_update_do : /on update/i reference_option
329 reference_option: /restrict/i |
346 data_type : WORD parens_value_list(s?) type_qualifier(s?)
349 my $size; # field size, applicable only to non-set fields
350 my $list; # set list, applicable only to sets (duh)
352 if ( uc($type) =~ /^(SET|ENUM)$/ ) {
361 unless ( @{ $size || [] } ) {
362 if ( lc $type eq 'tinyint' ) {
365 elsif ( lc $type eq 'smallint' ) {
368 elsif ( lc $type eq 'mediumint' ) {
371 elsif ( $type =~ /^int(eger)?$/ ) {
375 elsif ( lc $type eq 'bigint' ) {
378 elsif ( lc $type =~ /(float|double|decimal|numeric|real)/ ) {
387 qualifiers => $item[3],
391 parens_field_list : '(' field_name(s /,/) ')'
394 parens_value_list : '(' VALUE(s /,/) ')'
397 type_qualifier : /(BINARY|UNSIGNED|ZEROFILL)/i
402 create_index : /create/i /index/i
404 not_null : /not/i /null/i { $return = 0 }
406 unsigned : /unsigned/i { $return = 0 }
408 default_val : /default/i /(?:')?[\w\d:.-]*(?:')?/
414 auto_inc : /auto_increment/i { 1 }
416 primary_key : /primary/i /key/i { 1 }
418 constraint : primary_key_def
423 foreign_key_def : opt_constraint(?) /foreign key/i WORD(?) parens_field_list reference_definition
426 supertype => 'constraint',
427 type => 'foreign_key',
430 %{ $item{'reference_definition'} },
434 opt_constraint : /constraint/i WORD
436 primary_key_def : primary_key index_name(?) '(' field_name(s /,/) ')'
439 supertype => 'constraint',
440 name => $item{'index_name(?)'}[0],
441 type => 'primary_key',
446 unique_key_def : UNIQUE KEY(?) index_name(?) '(' name_with_opt_paren(s /,/) ')'
449 supertype => 'constraint',
450 name => $item{'index_name(?)'}[0],
456 normal_index : KEY index_name(?) '(' name_with_opt_paren(s /,/) ')'
459 supertype => 'index',
461 name => $item{'index_name(?)'}[0],
466 fulltext_index : /fulltext/i KEY(?) index_name(?) '(' name_with_opt_paren(s /,/) ')'
469 supertype => 'index',
471 name => $item{'index_name(?)'}[0],
476 name_with_opt_paren : NAME parens_value_list(s?)
477 { $item[2][0] ? "$item[1]($item[2][0][0])" : $item[1] }
479 UNIQUE : /unique/i { 1 }
481 KEY : /key/i | /index/i
483 table_option : /[^\s;]*/
485 $return = { split /=/, $item[1] }
490 TEMPORARY : /temporary/i
505 VALUE : /[-+]?\.?\d+(?:[eE]\d+)?/
509 # remove leading/trailing quotes
511 $val =~ s/^['"]|['"]$//g;
519 # -------------------------------------------------------------------
521 my ( $translator, $data ) = @_;
522 my $parser = Parse::RecDescent->new($GRAMMAR);
524 local $::RD_TRACE = $translator->trace ? 1 : undef;
525 local $DEBUG = $translator->debug;
527 unless (defined $parser) {
528 return $translator->error("Error instantiating Parse::RecDescent ".
529 "instance: Bad grammer");
532 my $result = $parser->startrule($data);
533 return $translator->error( "Parse failed." ) unless defined $result;
534 warn Dumper( $result ) if $DEBUG;
536 my $schema = $translator->schema;
538 $result->{ $a }->{'order'} <=> $result->{ $b }->{'order'}
541 for my $table_name ( @tables ) {
542 my $tdata = $result->{ $table_name };
543 my $table = $schema->add_table(
544 name => $tdata->{'table_name'},
545 ) or die $schema->error;
547 # for my $opt ( @{ $tdata->{'table_options'} } ) {
548 # if ( my ( $key, $val ) = each %$opt ) {
554 $tdata->{'fields'}->{$a}->{'order'}
556 $tdata->{'fields'}->{$b}->{'order'}
557 } keys %{ $tdata->{'fields'} };
559 for my $fname ( @fields ) {
560 my $fdata = $tdata->{'fields'}{ $fname };
561 my $field = $table->add_field(
562 name => $fdata->{'name'},
563 data_type => $fdata->{'data_type'},
564 size => $fdata->{'size'},
565 default_value => $fdata->{'default'},
566 is_auto_increment => $fdata->{'is_auto_inc'},
567 is_nullable => $fdata->{'null'},
568 comments => $fdata->{'comments'},
569 ) or die $table->error;
571 $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
573 for my $qual ( qw[ binary unsigned zerofill list ] ) {
574 if ( my $val = $fdata->{ $qual } || $fdata->{ uc $qual } ) {
575 next if ref $val eq 'ARRAY' && !@$val;
576 $field->extra( $qual, $val );
580 if ( $field->data_type =~ /(set|enum)/i && !$field->size ) {
581 my %extra = $field->extra;
583 for my $len ( map { length } @{ $extra{'list'} || [] } ) {
584 $longest = $len if $len > $longest;
586 $field->size( $longest ) if $longest;
589 for my $cdata ( @{ $fdata->{'constraints'} } ) {
590 next unless $cdata->{'type'} eq 'foreign_key';
591 $cdata->{'fields'} ||= [ $field->name ];
592 push @{ $tdata->{'constraints'} }, $cdata;
596 for my $idata ( @{ $tdata->{'indices'} || [] } ) {
597 my $index = $table->add_index(
598 name => $idata->{'name'},
599 type => uc $idata->{'type'},
600 fields => $idata->{'fields'},
601 ) or die $table->error;
604 for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
605 my $constraint = $table->add_constraint(
606 name => $cdata->{'name'},
607 type => $cdata->{'type'},
608 fields => $cdata->{'fields'},
609 reference_table => $cdata->{'reference_table'},
610 reference_fields => $cdata->{'reference_fields'},
611 match_type => $cdata->{'match_type'} || '',
612 on_delete => $cdata->{'on_delete_do'},
613 on_update => $cdata->{'on_update_do'},
614 ) or die $table->error;
623 # -------------------------------------------------------------------
624 # Where man is not nature is barren.
626 # -------------------------------------------------------------------
632 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>,
633 Chris Mungall E<lt>cjm@fruitfly.orgE<gt>.
637 perl(1), Parse::RecDescent, SQL::Translator::Schema.