1 package SQL::Translator::Parser::MySQL;
3 # -------------------------------------------------------------------
4 # $Id: MySQL.pm,v 1.57 2007-02-19 23:35:27 duality72 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.57 $ =~ /(\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.
152 $GRAMMAR = << 'END_OF_GRAMMAR';
155 my ( $database_name, %tables, $table_order, @table_comments );
160 # The "eofile" rule makes the parser fail if any "statement" rule
161 # fails. Otherwise, the first successful match by a "statement"
162 # won't cause the failure needed to know that the parse, as a whole,
165 startrule : statement(s) eofile {
166 { tables => \%tables, database_name => $database_name }
182 use : /use/i WORD "$delimiter"
184 $database_name = $item[2];
185 @table_comments = ();
188 set : /set/i /[^;]+/ "$delimiter"
189 { @table_comments = () }
191 drop : /drop/i TABLE /[^;]+/ "$delimiter"
193 drop : /drop/i WORD(s) "$delimiter"
194 { @table_comments = () }
197 # MySQL strings, unlike common SQL strings, can be double-quoted or
198 # single-quoted, and you can escape the delmiters by doubling (but only the
199 # delimiter) or by backslashing.
201 /'(\\.|''|[^\\\'])*'/ |
202 /"(\\.|""|[^\\\"])*"/
203 # For reference, std sql str: /(?:(?:\')(?:[^\']*(?:(?:\'\')[^\']*)*)(?:\'))//
205 nonstring : /[^;\'"]+/
207 statement_body : (string | nonstring)(s?)
209 insert : /insert/i statement_body "$delimiter"
211 delimiter : /delimiter/i /[\S]+/
212 { $delimiter = $item[2] }
214 empty_statement : "$delimiter"
216 alter : ALTER TABLE table_name alter_specification(s /,/) "$delimiter"
218 my $table_name = $item{'table_name'};
219 die "Cannot ALTER table '$table_name'; it does not exist"
220 unless $tables{ $table_name };
221 for my $definition ( @{ $item[4] } ) {
222 $definition->{'extra'}->{'alter'} = 1;
223 push @{ $tables{ $table_name }{'constraints'} }, $definition;
227 alter_specification : ADD foreign_key_def
228 { $return = $item[2] }
230 create : CREATE /database/i WORD "$delimiter"
231 { @table_comments = () }
233 create : CREATE TEMPORARY(?) TABLE opt_if_not_exists(?) table_name '(' create_definition(s /,/) /(,\s*)?\)/ table_option(s?) "$delimiter"
235 my $table_name = $item{'table_name'};
236 $tables{ $table_name }{'order'} = ++$table_order;
237 $tables{ $table_name }{'table_name'} = $table_name;
239 if ( @table_comments ) {
240 $tables{ $table_name }{'comments'} = [ @table_comments ];
241 @table_comments = ();
245 for my $definition ( @{ $item[7] } ) {
246 if ( $definition->{'supertype'} eq 'field' ) {
247 my $field_name = $definition->{'name'};
248 $tables{ $table_name }{'fields'}{ $field_name } =
249 { %$definition, order => $i };
252 if ( $definition->{'is_primary_key'} ) {
253 push @{ $tables{ $table_name }{'constraints'} },
255 type => 'primary_key',
256 fields => [ $field_name ],
261 elsif ( $definition->{'supertype'} eq 'constraint' ) {
262 push @{ $tables{ $table_name }{'constraints'} }, $definition;
264 elsif ( $definition->{'supertype'} eq 'index' ) {
265 push @{ $tables{ $table_name }{'indices'} }, $definition;
269 if ( my @options = @{ $item{'table_option(s?)'} } ) {
270 for my $option ( @options ) {
271 my ( $key, $value ) = each %$option;
272 if ( $key eq 'comment' ) {
273 push @{ $tables{ $table_name }{'comments'} }, $value;
276 push @{ $tables{ $table_name }{'table_options'} }, $option;
284 opt_if_not_exists : /if not exists/i
286 create : CREATE UNIQUE(?) /(index|key)/i index_name /on/i table_name '(' field_name(s /,/) ')' "$delimiter"
288 @table_comments = ();
289 push @{ $tables{ $item{'table_name'} }{'indices'} },
292 type => $item[2] ? 'unique' : 'normal',
298 create_definition : constraint
304 comment : /^\s*(?:#|-{2}).*\n/
306 my $comment = $item[1];
307 $comment =~ s/^\s*(#|--)\s*//;
308 $comment =~ s/\s*$//;
312 comment : /\/\*/ /.*?\*\//s
314 my $comment = $item[2];
315 $comment = substr($comment, 0, -2);
316 $comment =~ s/^\s*|\s*$//g;
320 field_comment : /^\s*(?:#|-{2}).*\n/
322 my $comment = $item[1];
323 $comment =~ s/^\s*(#|--)\s*//;
324 $comment =~ s/\s*$//;
329 field_comment2 : /comment/i /'.*?'/
331 my $comment = $item[2];
339 field : field_comment(s?) field_name data_type field_qualifier(s?) field_comment2(?) reference_definition(?) on_update(?) field_comment(s?)
341 my %qualifiers = map { %$_ } @{ $item{'field_qualifier(s?)'} || [] };
342 if ( my @type_quals = @{ $item{'data_type'}{'qualifiers'} || [] } ) {
343 $qualifiers{ $_ } = 1 for @type_quals;
346 my $null = defined $qualifiers{'not_null'}
347 ? $qualifiers{'not_null'} : 1;
348 delete $qualifiers{'not_null'};
350 my @comments = ( @{ $item[1] }, @{ $item[5] }, @{ $item[8] } );
353 supertype => 'field',
354 name => $item{'field_name'},
355 data_type => $item{'data_type'}{'type'},
356 size => $item{'data_type'}{'size'},
357 list => $item{'data_type'}{'list'},
359 constraints => $item{'reference_definition(?)'},
360 comments => [ @comments ],
366 field_qualifier : not_null
369 null => $item{'not_null'},
373 field_qualifier : default_val
376 default => $item{'default_val'},
380 field_qualifier : auto_inc
383 is_auto_inc => $item{'auto_inc'},
387 field_qualifier : primary_key
390 is_primary_key => $item{'primary_key'},
394 field_qualifier : unsigned
397 is_unsigned => $item{'unsigned'},
401 field_qualifier : /character set/i WORD
404 'CHARACTER SET' => $item[2],
408 field_qualifier : /collate/i WORD
415 field_qualifier : /on update/i CURRENT_TIMESTAMP
418 'ON UPDATE' => $item[2],
422 field_qualifier : /unique/i KEY(?)
429 field_qualifier : KEY
436 reference_definition : /references/i table_name parens_field_list(?) match_type(?) on_delete(?) on_update(?)
439 type => 'foreign_key',
440 reference_table => $item[2],
441 reference_fields => $item[3][0],
442 match_type => $item[4][0],
443 on_delete => $item[5][0],
444 on_update => $item[6][0],
448 match_type : /match full/i { 'full' }
450 /match partial/i { 'partial' }
452 on_delete : /on delete/i reference_option
456 /on update/i 'CURRENT_TIMESTAMP'
459 /on update/i reference_option
462 reference_option: /restrict/i |
479 data_type : WORD parens_value_list(s?) type_qualifier(s?)
482 my $size; # field size, applicable only to non-set fields
483 my $list; # set list, applicable only to sets (duh)
485 if ( uc($type) =~ /^(SET|ENUM)$/ ) {
494 unless ( @{ $size || [] } ) {
495 if ( lc $type eq 'tinyint' ) {
498 elsif ( lc $type eq 'smallint' ) {
501 elsif ( lc $type eq 'mediumint' ) {
504 elsif ( $type =~ /^int(eger)?$/i ) {
508 elsif ( lc $type eq 'bigint' ) {
512 lc $type =~ /(float|double|decimal|numeric|real|fixed|dec)/
518 if ( $type =~ /^tiny(text|blob)$/i ) {
521 elsif ( $type =~ /^(blob|text)$/i ) {
524 elsif ( $type =~ /^medium(blob|text)$/i ) {
527 elsif ( $type =~ /^long(blob|text)$/i ) {
528 $size = 4_294_967_295;
535 qualifiers => $item[3],
539 parens_field_list : '(' field_name(s /,/) ')'
542 parens_value_list : '(' VALUE(s /,/) ')'
545 type_qualifier : /(BINARY|UNSIGNED|ZEROFILL)/i
550 create_index : /create/i /index/i
552 not_null : /not/i /null/i
558 unsigned : /unsigned/i { $return = 0 }
560 #default_val : /default/i /(?:')?[\s\w\d:.-]*(?:')?/
562 # $item[2] =~ s/'//g;
563 # $return = $item[2];
567 /default/i 'CURRENT_TIMESTAMP'
572 /default/i /'(?:.*?\\')*.*?'|(?:')?[\w\d:.-]*(?:')?/
574 $item[2] =~ s/^\s*'|'\s*$//g;
578 auto_inc : /auto_increment/i { 1 }
580 primary_key : /primary/i /key/i { 1 }
582 constraint : primary_key_def
587 foreign_key_def : foreign_key_def_begin parens_field_list reference_definition
590 supertype => 'constraint',
591 type => 'foreign_key',
594 %{ $item{'reference_definition'} },
598 foreign_key_def_begin : /constraint/i /foreign key/i WORD
599 { $return = $item[3] }
601 /constraint/i NAME /foreign key/i
602 { $return = $item[2] }
604 /constraint/i /foreign key/i
608 { $return = $item[2] }
613 primary_key_def : primary_key index_name(?) '(' name_with_opt_paren(s /,/) ')'
616 supertype => 'constraint',
617 name => $item{'index_name(?)'}[0],
618 type => 'primary_key',
623 unique_key_def : UNIQUE KEY(?) index_name(?) '(' name_with_opt_paren(s /,/) ')'
626 supertype => 'constraint',
627 name => $item{'index_name(?)'}[0],
633 normal_index : KEY index_name(?) '(' name_with_opt_paren(s /,/) ')'
636 supertype => 'index',
638 name => $item{'index_name(?)'}[0],
643 fulltext_index : /fulltext/i KEY(?) index_name(?) '(' name_with_opt_paren(s /,/) ')'
646 supertype => 'index',
648 name => $item{'index_name(?)'}[0],
653 name_with_opt_paren : NAME parens_value_list(s?)
654 { $item[2][0] ? "$item[1]($item[2][0][0])" : $item[1] }
656 UNIQUE : /unique/i { 1 }
658 KEY : /key/i | /index/i
660 table_option : /comment/i /=/ /'.*?'/
662 my $comment = $item[3];
665 $return = { comment => $comment };
667 | /(default )?(charset|character set)/i /\s*=\s*/ WORD
669 $return = { 'CHARACTER SET' => $item[3] };
671 | WORD /\s*=\s*/ WORD
673 $return = { $item[1] => $item[3] };
684 TEMPORARY : /temporary/i
699 VALUE : /[-+]?\.?\d+(?:[eE]\d+)?/
703 # remove leading/trailing quotes
705 $val =~ s/^['"]|['"]$//g;
711 CURRENT_TIMESTAMP : /current_timestamp(\(\))?/i
713 { 'CURRENT_TIMESTAMP' }
717 # -------------------------------------------------------------------
719 my ( $translator, $data ) = @_;
720 my $parser = Parse::RecDescent->new($GRAMMAR);
722 local $::RD_TRACE = $translator->trace ? 1 : undef;
723 local $DEBUG = $translator->debug;
725 unless (defined $parser) {
726 return $translator->error("Error instantiating Parse::RecDescent ".
727 "instance: Bad grammer");
730 my $result = $parser->startrule($data);
731 return $translator->error( "Parse failed." ) unless defined $result;
732 warn "Parse result:".Dumper( $result ) if $DEBUG;
734 my $schema = $translator->schema;
735 $schema->name($result->{'database_name'}) if $result->{'database_name'};
738 $result->{'tables'}{ $a }{'order'}
740 $result->{'tables'}{ $b }{'order'}
741 } keys %{ $result->{'tables'} };
743 for my $table_name ( @tables ) {
744 my $tdata = $result->{tables}{ $table_name };
745 my $table = $schema->add_table(
746 name => $tdata->{'table_name'},
747 ) or die $schema->error;
749 $table->comments( $tdata->{'comments'} );
752 $tdata->{'fields'}->{$a}->{'order'}
754 $tdata->{'fields'}->{$b}->{'order'}
755 } keys %{ $tdata->{'fields'} };
757 for my $fname ( @fields ) {
758 my $fdata = $tdata->{'fields'}{ $fname };
759 my $field = $table->add_field(
760 name => $fdata->{'name'},
761 data_type => $fdata->{'data_type'},
762 size => $fdata->{'size'},
763 default_value => $fdata->{'default'},
764 is_auto_increment => $fdata->{'is_auto_inc'},
765 is_nullable => $fdata->{'null'},
766 comments => $fdata->{'comments'},
767 ) or die $table->error;
769 $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
771 for my $qual ( qw[ binary unsigned zerofill list collate ],
772 'character set', 'on update' ) {
773 if ( my $val = $fdata->{ $qual } || $fdata->{ uc $qual } ) {
774 next if ref $val eq 'ARRAY' && !@$val;
775 $field->extra( $qual, $val );
779 if ( $fdata->{'has_index'} ) {
783 fields => $fdata->{'name'},
784 ) or die $table->error;
787 if ( $fdata->{'is_unique'} ) {
788 $table->add_constraint(
791 fields => $fdata->{'name'},
792 ) or die $table->error;
795 if ( $field->data_type =~ /(set|enum)/i && !$field->size ) {
796 my %extra = $field->extra;
798 for my $len ( map { length } @{ $extra{'list'} || [] } ) {
799 $longest = $len if $len > $longest;
801 $field->size( $longest ) if $longest;
804 for my $cdata ( @{ $fdata->{'constraints'} } ) {
805 next unless $cdata->{'type'} eq 'foreign_key';
806 $cdata->{'fields'} ||= [ $field->name ];
807 push @{ $tdata->{'constraints'} }, $cdata;
811 for my $idata ( @{ $tdata->{'indices'} || [] } ) {
812 my $index = $table->add_index(
813 name => $idata->{'name'},
814 type => uc $idata->{'type'},
815 fields => $idata->{'fields'},
816 ) or die $table->error;
819 if ( my @options = @{ $tdata->{'table_options'} || [] } ) {
820 $table->options( \@options ) or die $table->error;
823 for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
824 my $constraint = $table->add_constraint(
825 name => $cdata->{'name'},
826 type => $cdata->{'type'},
827 fields => $cdata->{'fields'},
828 reference_table => $cdata->{'reference_table'},
829 reference_fields => $cdata->{'reference_fields'},
830 match_type => $cdata->{'match_type'} || '',
831 on_delete => $cdata->{'on_delete'} || $cdata->{'on_delete_do'},
832 on_update => $cdata->{'on_update'} || $cdata->{'on_update_do'},
833 ) or die $table->error;
842 # -------------------------------------------------------------------
843 # Where man is not nature is barren.
845 # -------------------------------------------------------------------
851 Ken Youens-Clark E<lt>kclark@cpan.orgE<gt>,
852 Chris Mungall E<lt>cjm@fruitfly.orgE<gt>.
856 Parse::RecDescent, SQL::Translator::Schema.