1 package SQL::Translator::Parser::MySQL;
3 # -------------------------------------------------------------------
4 # $Id: MySQL.pm,v 1.53 2006-03-16 19:24:02 kycl4rk Exp $
5 # -------------------------------------------------------------------
6 # Copyright (C) 2002-4 SQLFairy Authors
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU General Public License as
10 # published by the Free Software Foundation; version 2.
12 # This program is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 # General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
21 # -------------------------------------------------------------------
25 SQL::Translator::Parser::MySQL - parser for MySQL
30 use SQL::Translator::Parser::MySQL;
32 my $translator = SQL::Translator->new;
33 $translator->parser("SQL::Translator::Parser::MySQL");
37 The grammar is influenced heavily by Tim Bunce's "mysql2ora" grammar.
39 Here's the word from the MySQL site
40 (http://www.mysql.com/doc/en/CREATE_TABLE.html):
42 CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]
43 [table_options] [select_statement]
47 CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name LIKE old_table_name;
50 col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]
51 [PRIMARY KEY] [reference_definition]
52 or PRIMARY KEY (index_col_name,...)
53 or KEY [index_name] (index_col_name,...)
54 or INDEX [index_name] (index_col_name,...)
55 or UNIQUE [INDEX] [index_name] (index_col_name,...)
56 or FULLTEXT [INDEX] [index_name] (index_col_name,...)
57 or [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)
58 [reference_definition]
62 TINYINT[(length)] [UNSIGNED] [ZEROFILL]
63 or SMALLINT[(length)] [UNSIGNED] [ZEROFILL]
64 or MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL]
65 or INT[(length)] [UNSIGNED] [ZEROFILL]
66 or INTEGER[(length)] [UNSIGNED] [ZEROFILL]
67 or BIGINT[(length)] [UNSIGNED] [ZEROFILL]
68 or REAL[(length,decimals)] [UNSIGNED] [ZEROFILL]
69 or DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL]
70 or FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL]
71 or DECIMAL(length,decimals) [UNSIGNED] [ZEROFILL]
72 or NUMERIC(length,decimals) [UNSIGNED] [ZEROFILL]
73 or CHAR(length) [BINARY]
74 or VARCHAR(length) [BINARY]
87 or ENUM(value1,value2,value3,...)
88 or SET(value1,value2,value3,...)
94 REFERENCES tbl_name [(index_col_name,...)]
95 [MATCH FULL | MATCH PARTIAL]
96 [ON DELETE reference_option]
97 [ON UPDATE reference_option]
100 RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT
103 TYPE = {BDB | HEAP | ISAM | InnoDB | MERGE | MRG_MYISAM | MYISAM }
104 or AUTO_INCREMENT = #
105 or AVG_ROW_LENGTH = #
106 or CHECKSUM = {0 | 1}
107 or COMMENT = "string"
110 or PACK_KEYS = {0 | 1 | DEFAULT}
111 or PASSWORD = "string"
112 or DELAY_KEY_WRITE = {0 | 1}
113 or ROW_FORMAT= { default | dynamic | fixed | compressed }
114 or RAID_TYPE= {1 | STRIPED | RAID0 } RAID_CHUNKS=# RAID_CHUNKSIZE=#
115 or UNION = (table_name,[table_name...])
116 or INSERT_METHOD= {NO | FIRST | LAST }
117 or DATA DIRECTORY="absolute path to directory"
118 or INDEX DIRECTORY="absolute path to directory"
120 A subset of the ALTER TABLE syntax that allows addition of foreign keys:
122 ALTER [IGNORE] TABLE tbl_name alter_specification [, alter_specification] ...
125 ADD [CONSTRAINT [symbol]]
126 FOREIGN KEY [index_name] (index_col_name,...)
127 [reference_definition]
129 A subset of INSERT that we ignore:
136 use vars qw[ $DEBUG $VERSION $GRAMMAR @EXPORT_OK ];
137 $VERSION = sprintf "%d.%02d", q$Revision: 1.53 $ =~ /(\d+)\.(\d+)/;
138 $DEBUG = 0 unless defined $DEBUG;
141 use Parse::RecDescent;
143 use base qw(Exporter);
145 @EXPORT_OK = qw(parse);
147 # Enable warnings within the Parse::RecDescent module.
148 $::RD_ERRORS = 1; # Make sure the parser dies when it encounters an error
149 $::RD_WARN = 1; # Enable warnings. This will warn on unused rules &c.
150 $::RD_HINT = 1; # Give out hints to help fix problems.
155 my ( $database_name, %tables, $table_order, @table_comments );
159 # The "eofile" rule makes the parser fail if any "statement" rule
160 # fails. Otherwise, the first successful match by a "statement"
161 # won't cause the failure needed to know that the parse, as a whole,
164 startrule : statement(s) eofile {
165 { tables => \%tables, database_name => $database_name }
179 use : /use/i WORD ';'
181 $database_name = $item[2];
182 @table_comments = ();
185 set : /set/i /[^;]+/ ';'
186 { @table_comments = () }
188 drop : /drop/i TABLE /[^;]+/ ';'
190 drop : /drop/i WORD(s) ';'
191 { @table_comments = () }
193 insert : /insert/i /[^;]+/ ';'
195 alter : ALTER TABLE table_name alter_specification(s /,/) ';'
197 my $table_name = $item{'table_name'};
198 die "Cannot ALTER table '$table_name'; it does not exist"
199 unless $tables{ $table_name };
200 for my $definition ( @{ $item[4] } ) {
201 $definition->{'extra'}->{'alter'} = 1;
202 push @{ $tables{ $table_name }{'constraints'} }, $definition;
206 alter_specification : ADD foreign_key_def
207 { $return = $item[2] }
209 create : CREATE /database/i WORD ';'
210 { @table_comments = () }
212 create : CREATE TEMPORARY(?) TABLE opt_if_not_exists(?) table_name '(' create_definition(s /,/) /(,\s*)?\)/ table_option(s?) ';'
214 my $table_name = $item{'table_name'};
215 $tables{ $table_name }{'order'} = ++$table_order;
216 $tables{ $table_name }{'table_name'} = $table_name;
218 if ( @table_comments ) {
219 $tables{ $table_name }{'comments'} = [ @table_comments ];
220 @table_comments = ();
224 for my $definition ( @{ $item[7] } ) {
225 if ( $definition->{'supertype'} eq 'field' ) {
226 my $field_name = $definition->{'name'};
227 $tables{ $table_name }{'fields'}{ $field_name } =
228 { %$definition, order => $i };
231 if ( $definition->{'is_primary_key'} ) {
232 push @{ $tables{ $table_name }{'constraints'} },
234 type => 'primary_key',
235 fields => [ $field_name ],
240 elsif ( $definition->{'supertype'} eq 'constraint' ) {
241 push @{ $tables{ $table_name }{'constraints'} }, $definition;
243 elsif ( $definition->{'supertype'} eq 'index' ) {
244 push @{ $tables{ $table_name }{'indices'} }, $definition;
248 if ( my @options = @{ $item{'table_option(s?)'} } ) {
249 for my $option ( @options ) {
250 my ( $key, $value ) = each %$option;
251 if ( $key eq 'comment' ) {
252 push @{ $tables{ $table_name }{'comments'} }, $value;
255 push @{ $tables{ $table_name }{'table_options'} }, $option;
263 opt_if_not_exists : /if not exists/i
265 create : CREATE UNIQUE(?) /(index|key)/i index_name /on/i table_name '(' field_name(s /,/) ')' ';'
267 @table_comments = ();
268 push @{ $tables{ $item{'table_name'} }{'indices'} },
271 type => $item[2] ? 'unique' : 'normal',
277 create_definition : constraint
283 comment : /^\s*(?:#|-{2}).*\n/
285 my $comment = $item[1];
286 $comment =~ s/^\s*(#|--)\s*//;
287 $comment =~ s/\s*$//;
291 comment : /\/\*/ /[^\*]+/ /\*\// ';'
293 my $comment = $item[2];
294 $comment =~ s/^\s*|\s*$//g;
298 field_comment : /^\s*(?:#|-{2}).*\n/
300 my $comment = $item[1];
301 $comment =~ s/^\s*(#|--)\s*//;
302 $comment =~ s/\s*$//;
307 field_comment2 : /comment/i /'.*?'/
309 my $comment = $item[2];
317 field : field_comment(s?) field_name data_type field_qualifier(s?) field_comment2(?) reference_definition(?) on_update(?) field_comment(s?)
319 my %qualifiers = map { %$_ } @{ $item{'field_qualifier(s?)'} || [] };
320 if ( my @type_quals = @{ $item{'data_type'}{'qualifiers'} || [] } ) {
321 $qualifiers{ $_ } = 1 for @type_quals;
324 my $null = defined $qualifiers{'not_null'}
325 ? $qualifiers{'not_null'} : 1;
326 delete $qualifiers{'not_null'};
328 my @comments = ( @{ $item[1] }, @{ $item[5] }, @{ $item[8] } );
331 supertype => 'field',
332 name => $item{'field_name'},
333 data_type => $item{'data_type'}{'type'},
334 size => $item{'data_type'}{'size'},
335 list => $item{'data_type'}{'list'},
337 constraints => $item{'reference_definition(?)'},
338 comments => [ @comments ],
344 field_qualifier : not_null
347 null => $item{'not_null'},
351 field_qualifier : default_val
354 default => $item{'default_val'},
358 field_qualifier : auto_inc
361 is_auto_inc => $item{'auto_inc'},
365 field_qualifier : primary_key
368 is_primary_key => $item{'primary_key'},
372 field_qualifier : unsigned
375 is_unsigned => $item{'unsigned'},
379 field_qualifier : /character set/i WORD
382 'CHARACTER SET' => $item[2],
386 field_qualifier : /collate/i WORD
393 field_qualifier : /on update/i CURRENT_TIMESTAMP
396 'ON UPDATE' => $item[2],
400 field_qualifier : /unique/i KEY(?)
407 field_qualifier : KEY
414 reference_definition : /references/i table_name parens_field_list(?) match_type(?) on_delete(?) on_update(?)
417 type => 'foreign_key',
418 reference_table => $item[2],
419 reference_fields => $item[3][0],
420 match_type => $item[4][0],
421 on_delete => $item[5][0],
422 on_update => $item[6][0],
426 match_type : /match full/i { 'full' }
428 /match partial/i { 'partial' }
430 on_delete : /on delete/i reference_option
434 /on update/i 'CURRENT_TIMESTAMP'
437 /on update/i reference_option
440 reference_option: /restrict/i |
457 data_type : WORD parens_value_list(s?) type_qualifier(s?)
460 my $size; # field size, applicable only to non-set fields
461 my $list; # set list, applicable only to sets (duh)
463 if ( uc($type) =~ /^(SET|ENUM)$/ ) {
472 unless ( @{ $size || [] } ) {
473 if ( lc $type eq 'tinyint' ) {
476 elsif ( lc $type eq 'smallint' ) {
479 elsif ( lc $type eq 'mediumint' ) {
482 elsif ( $type =~ /^int(eger)?$/i ) {
486 elsif ( lc $type eq 'bigint' ) {
490 lc $type =~ /(float|double|decimal|numeric|real|fixed|dec)/
496 if ( $type =~ /^tiny(text|blob)$/i ) {
499 elsif ( $type =~ /^(blob|text)$/i ) {
502 elsif ( $type =~ /^medium(blob|text)$/i ) {
505 elsif ( $type =~ /^long(blob|text)$/i ) {
506 $size = 4_294_967_295;
513 qualifiers => $item[3],
517 parens_field_list : '(' field_name(s /,/) ')'
520 parens_value_list : '(' VALUE(s /,/) ')'
523 type_qualifier : /(BINARY|UNSIGNED|ZEROFILL)/i
528 create_index : /create/i /index/i
530 not_null : /not/i /null/i
536 unsigned : /unsigned/i { $return = 0 }
538 #default_val : /default/i /(?:')?[\s\w\d:.-]*(?:')?/
540 # $item[2] =~ s/'//g;
541 # $return = $item[2];
545 /default/i 'CURRENT_TIMESTAMP'
550 /default/i /'(?:.*?\\')*.*?'|(?:')?[\w\d:.-]*(?:')?/
552 $item[2] =~ s/^\s*'|'\s*$//g;
556 auto_inc : /auto_increment/i { 1 }
558 primary_key : /primary/i /key/i { 1 }
560 constraint : primary_key_def
565 foreign_key_def : foreign_key_def_begin parens_field_list reference_definition
568 supertype => 'constraint',
569 type => 'foreign_key',
572 %{ $item{'reference_definition'} },
576 foreign_key_def_begin : /constraint/i /foreign key/i WORD
577 { $return = $item[3] }
579 /constraint/i NAME /foreign key/i
580 { $return = $item[2] }
582 /constraint/i /foreign key/i
586 { $return = $item[2] }
591 primary_key_def : primary_key index_name(?) '(' name_with_opt_paren(s /,/) ')'
594 supertype => 'constraint',
595 name => $item{'index_name(?)'}[0],
596 type => 'primary_key',
601 unique_key_def : UNIQUE KEY(?) index_name(?) '(' name_with_opt_paren(s /,/) ')'
604 supertype => 'constraint',
605 name => $item{'index_name(?)'}[0],
611 normal_index : KEY index_name(?) '(' name_with_opt_paren(s /,/) ')'
614 supertype => 'index',
616 name => $item{'index_name(?)'}[0],
621 fulltext_index : /fulltext/i KEY(?) index_name(?) '(' name_with_opt_paren(s /,/) ')'
624 supertype => 'index',
626 name => $item{'index_name(?)'}[0],
631 name_with_opt_paren : NAME parens_value_list(s?)
632 { $item[2][0] ? "$item[1]($item[2][0][0])" : $item[1] }
634 UNIQUE : /unique/i { 1 }
636 KEY : /key/i | /index/i
638 table_option : /comment/i /=/ /'.*?'/
640 my $comment = $item[3];
643 $return = { comment => $comment };
645 | /(default )?(charset|character set)/i /\s*=\s*/ WORD
647 $return = { 'CHARACTER SET' => $item[3] };
649 | WORD /\s*=\s*/ WORD
651 $return = { $item[1] => $item[3] };
662 TEMPORARY : /temporary/i
677 VALUE : /[-+]?\.?\d+(?:[eE]\d+)?/
681 # remove leading/trailing quotes
683 $val =~ s/^['"]|['"]$//g;
689 CURRENT_TIMESTAMP : /current_timestamp(\(\))?/i
691 { 'CURRENT_TIMESTAMP' }
695 # -------------------------------------------------------------------
697 my ( $translator, $data ) = @_;
698 my $parser = Parse::RecDescent->new($GRAMMAR);
700 local $::RD_TRACE = $translator->trace ? 1 : undef;
701 local $DEBUG = $translator->debug;
703 unless (defined $parser) {
704 return $translator->error("Error instantiating Parse::RecDescent ".
705 "instance: Bad grammer");
708 my $result = $parser->startrule($data);
709 return $translator->error( "Parse failed." ) unless defined $result;
710 warn "Parse result:".Dumper( $result ) if $DEBUG;
712 my $schema = $translator->schema;
713 $schema->name($result->{'database_name'}) if $result->{'database_name'};
716 $result->{'tables'}{ $a }{'order'}
718 $result->{'tables'}{ $b }{'order'}
719 } keys %{ $result->{'tables'} };
721 for my $table_name ( @tables ) {
722 my $tdata = $result->{tables}{ $table_name };
723 my $table = $schema->add_table(
724 name => $tdata->{'table_name'},
725 ) or die $schema->error;
727 $table->comments( $tdata->{'comments'} );
730 $tdata->{'fields'}->{$a}->{'order'}
732 $tdata->{'fields'}->{$b}->{'order'}
733 } keys %{ $tdata->{'fields'} };
735 for my $fname ( @fields ) {
736 my $fdata = $tdata->{'fields'}{ $fname };
737 my $field = $table->add_field(
738 name => $fdata->{'name'},
739 data_type => $fdata->{'data_type'},
740 size => $fdata->{'size'},
741 default_value => $fdata->{'default'},
742 is_auto_increment => $fdata->{'is_auto_inc'},
743 is_nullable => $fdata->{'null'},
744 comments => $fdata->{'comments'},
745 ) or die $table->error;
747 $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
749 for my $qual ( qw[ binary unsigned zerofill list collate ],
750 'character set', 'on update' ) {
751 if ( my $val = $fdata->{ $qual } || $fdata->{ uc $qual } ) {
752 next if ref $val eq 'ARRAY' && !@$val;
753 $field->extra( $qual, $val );
757 if ( $fdata->{'has_index'} ) {
761 fields => $fdata->{'name'},
762 ) or die $table->error;
765 if ( $fdata->{'is_unique'} ) {
766 $table->add_constraint(
769 fields => $fdata->{'name'},
770 ) or die $table->error;
773 if ( $field->data_type =~ /(set|enum)/i && !$field->size ) {
774 my %extra = $field->extra;
776 for my $len ( map { length } @{ $extra{'list'} || [] } ) {
777 $longest = $len if $len > $longest;
779 $field->size( $longest ) if $longest;
782 for my $cdata ( @{ $fdata->{'constraints'} } ) {
783 next unless $cdata->{'type'} eq 'foreign_key';
784 $cdata->{'fields'} ||= [ $field->name ];
785 push @{ $tdata->{'constraints'} }, $cdata;
789 for my $idata ( @{ $tdata->{'indices'} || [] } ) {
790 my $index = $table->add_index(
791 name => $idata->{'name'},
792 type => uc $idata->{'type'},
793 fields => $idata->{'fields'},
794 ) or die $table->error;
797 if ( my @options = @{ $tdata->{'table_options'} || [] } ) {
798 $table->options( \@options ) or die $table->error;
801 for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
802 my $constraint = $table->add_constraint(
803 name => $cdata->{'name'},
804 type => $cdata->{'type'},
805 fields => $cdata->{'fields'},
806 reference_table => $cdata->{'reference_table'},
807 reference_fields => $cdata->{'reference_fields'},
808 match_type => $cdata->{'match_type'} || '',
809 on_delete => $cdata->{'on_delete'} || $cdata->{'on_delete_do'},
810 on_update => $cdata->{'on_update'} || $cdata->{'on_update_do'},
811 ) or die $table->error;
820 # -------------------------------------------------------------------
821 # Where man is not nature is barren.
823 # -------------------------------------------------------------------
829 Ken Youens-Clark E<lt>kclark@cpan.orgE<gt>,
830 Chris Mungall E<lt>cjm@fruitfly.orgE<gt>.
834 Parse::RecDescent, SQL::Translator::Schema.