1 package SQL::Translator::Parser::MySQL;
3 # -------------------------------------------------------------------
4 # $Id: MySQL.pm,v 1.35 2003-08-19 15:46:09 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.35 $ =~ /(\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, @table_comments );
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 }
164 use : /use/i WORD ';'
165 # { @table_comments = () }
167 set : /set/i /[^;]+/ ';'
168 # { @table_comments = () }
170 drop : /drop/i TABLE ';'
172 drop : /drop/i WORD(s) ';'
173 # { @table_comments = () }
175 create : CREATE /database/i WORD ';'
176 # { @table_comments = () }
178 create : CREATE TEMPORARY(?) TABLE opt_if_not_exists(?) table_name '(' create_definition(s /,/) ')' table_option(s?) ';'
180 my $table_name = $item{'table_name'};
181 $tables{ $table_name }{'order'} = ++$table_order;
182 $tables{ $table_name }{'table_name'} = $table_name;
184 if ( @table_comments ) {
185 $tables{ $table_name }{'comments'} = [ @table_comments ];
186 @table_comments = ();
190 for my $definition ( @{ $item[7] } ) {
191 if ( $definition->{'supertype'} eq 'field' ) {
192 my $field_name = $definition->{'name'};
193 $tables{ $table_name }{'fields'}{ $field_name } =
194 { %$definition, order => $i };
197 if ( $definition->{'is_primary_key'} ) {
198 push @{ $tables{ $table_name }{'constraints'} },
200 type => 'primary_key',
201 fields => [ $field_name ],
206 elsif ( $definition->{'supertype'} eq 'constraint' ) {
207 push @{ $tables{ $table_name }{'constraints'} }, $definition;
209 elsif ( $definition->{'supertype'} eq 'index' ) {
210 push @{ $tables{ $table_name }{'indices'} }, $definition;
214 for my $opt ( @{ $item{'table_option(s?)'} } ) {
215 if ( my ( $key, $val ) = each %$opt ) {
216 $tables{ $table_name }{'table_options'}{ $key } = $val;
223 opt_if_not_exists : /if not exists/i
225 create : CREATE UNIQUE(?) /(index|key)/i index_name /on/i table_name '(' field_name(s /,/) ')' ';'
227 @table_comments = ();
228 push @{ $tables{ $item{'table_name'} }{'indices'} },
231 type => $item[2] ? 'unique' : 'normal',
237 create_definition : constraint
242 comment : /^\s*(?:#|-{2}).*\n/
244 my $comment = $item[1];
245 $comment =~ s/^\s*(#|-{2})\s*//;
246 $comment =~ s/\s*$//;
248 push @table_comments, $comment;
251 field_comment : /^\s*(?:#|-{2}).*\n/
253 my $comment = $item[1];
254 $comment =~ s/^\s*(#|-{2})\s*//;
255 $comment =~ s/\s*$//;
261 field : field_comment(s?) field_name data_type field_qualifier(s?) reference_definition(?) field_comment(s?)
263 my %qualifiers = map { %$_ } @{ $item{'field_qualifier(s?)'} || [] };
264 my $null = defined $item{'not_null'} ? $item{'not_null'} : 1;
265 delete $qualifiers{'not_null'};
266 if ( my @type_quals = @{ $item{'data_type'}{'qualifiers'} || [] } ) {
267 $qualifiers{ $_ } = 1 for @type_quals;
270 my @comments = ( @{ $item[1] }, @{ $item[6] } );
273 supertype => 'field',
274 name => $item{'field_name'},
275 data_type => $item{'data_type'}{'type'},
276 size => $item{'data_type'}{'size'},
277 list => $item{'data_type'}{'list'},
279 constraints => $item{'reference_definition(?)'},
280 comments => [ @comments ],
286 field_qualifier : not_null
289 null => $item{'not_null'},
293 field_qualifier : default_val
296 default => $item{'default_val'},
300 field_qualifier : auto_inc
303 is_auto_inc => $item{'auto_inc'},
307 field_qualifier : primary_key
310 is_primary_key => $item{'primary_key'},
314 field_qualifier : unsigned
317 is_unsigned => $item{'unsigned'},
321 field_qualifier : /character set/i WORD
324 character_set => $item[2],
328 reference_definition : /references/i table_name parens_field_list(?) match_type(?) on_delete_do(?) on_update_do(?)
331 type => 'foreign_key',
332 reference_table => $item[2],
333 reference_fields => $item[3][0],
334 match_type => $item[4][0],
335 on_delete_do => $item[5][0],
336 on_update_do => $item[6][0],
340 match_type : /match full/i { 'match_full' }
342 /match partial/i { 'match_partial' }
344 on_delete_do : /on delete/i reference_option
347 on_update_do : /on update/i reference_option
350 reference_option: /restrict/i |
367 data_type : WORD parens_value_list(s?) type_qualifier(s?)
370 my $size; # field size, applicable only to non-set fields
371 my $list; # set list, applicable only to sets (duh)
373 if ( uc($type) =~ /^(SET|ENUM)$/ ) {
382 unless ( @{ $size || [] } ) {
383 if ( lc $type eq 'tinyint' ) {
386 elsif ( lc $type eq 'smallint' ) {
389 elsif ( lc $type eq 'mediumint' ) {
392 elsif ( $type =~ /^int(eger)?$/ ) {
396 elsif ( lc $type eq 'bigint' ) {
400 lc $type =~ /(float|double|decimal|numeric|real|fixed|dec)/
406 if ( lc $type eq 'tinytext' ) {
409 elsif ( lc $type eq 'text' ) {
412 elsif ( lc $type eq 'mediumtext' ) {
413 $size = [16_000_000];
415 elsif ( lc $type eq 'longtext' ) {
416 $size = [4_000_000_000];
423 qualifiers => $item[3],
427 parens_field_list : '(' field_name(s /,/) ')'
430 parens_value_list : '(' VALUE(s /,/) ')'
433 type_qualifier : /(BINARY|UNSIGNED|ZEROFILL)/i
438 create_index : /create/i /index/i
440 not_null : /not/i /null/i { $return = 0 }
442 unsigned : /unsigned/i { $return = 0 }
444 default_val : /default/i /(?:')?[\w\d:.-]*(?:')?/
450 auto_inc : /auto_increment/i { 1 }
452 primary_key : /primary/i /key/i { 1 }
454 constraint : primary_key_def
459 foreign_key_def : opt_constraint(?) /foreign key/i WORD(?) parens_field_list reference_definition
462 supertype => 'constraint',
463 type => 'foreign_key',
466 %{ $item{'reference_definition'} },
470 opt_constraint : /constraint/i WORD
472 primary_key_def : primary_key index_name(?) '(' name_with_opt_paren(s /,/) ')'
475 supertype => 'constraint',
476 name => $item{'index_name(?)'}[0],
477 type => 'primary_key',
482 unique_key_def : UNIQUE KEY(?) index_name(?) '(' name_with_opt_paren(s /,/) ')'
485 supertype => 'constraint',
486 name => $item{'index_name(?)'}[0],
492 normal_index : KEY index_name(?) '(' name_with_opt_paren(s /,/) ')'
495 supertype => 'index',
497 name => $item{'index_name(?)'}[0],
502 fulltext_index : /fulltext/i KEY(?) index_name(?) '(' name_with_opt_paren(s /,/) ')'
505 supertype => 'index',
507 name => $item{'index_name(?)'}[0],
512 name_with_opt_paren : NAME parens_value_list(s?)
513 { $item[2][0] ? "$item[1]($item[2][0][0])" : $item[1] }
515 UNIQUE : /unique/i { 1 }
517 KEY : /key/i | /index/i
519 table_option : /[^\s;]*/
521 $return = { split /=/, $item[1] }
526 TEMPORARY : /temporary/i
541 VALUE : /[-+]?\.?\d+(?:[eE]\d+)?/
545 # remove leading/trailing quotes
547 $val =~ s/^['"]|['"]$//g;
555 # -------------------------------------------------------------------
557 my ( $translator, $data ) = @_;
558 my $parser = Parse::RecDescent->new($GRAMMAR);
560 local $::RD_TRACE = $translator->trace ? 1 : undef;
561 local $DEBUG = $translator->debug;
563 unless (defined $parser) {
564 return $translator->error("Error instantiating Parse::RecDescent ".
565 "instance: Bad grammer");
568 my $result = $parser->startrule($data);
569 return $translator->error( "Parse failed." ) unless defined $result;
570 warn Dumper( $result ) if $DEBUG;
572 my $schema = $translator->schema;
574 $result->{ $a }->{'order'} <=> $result->{ $b }->{'order'}
577 for my $table_name ( @tables ) {
578 my $tdata = $result->{ $table_name };
579 my $table = $schema->add_table(
580 name => $tdata->{'table_name'},
581 ) or die $schema->error;
583 $table->comments( $tdata->{'comments'} );
586 $tdata->{'fields'}->{$a}->{'order'}
588 $tdata->{'fields'}->{$b}->{'order'}
589 } keys %{ $tdata->{'fields'} };
591 for my $fname ( @fields ) {
592 my $fdata = $tdata->{'fields'}{ $fname };
593 my $field = $table->add_field(
594 name => $fdata->{'name'},
595 data_type => $fdata->{'data_type'},
596 size => $fdata->{'size'},
597 default_value => $fdata->{'default'},
598 is_auto_increment => $fdata->{'is_auto_inc'},
599 is_nullable => $fdata->{'null'},
600 comments => $fdata->{'comments'},
601 ) or die $table->error;
603 $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
605 for my $qual ( qw[ binary unsigned zerofill list ] ) {
606 if ( my $val = $fdata->{ $qual } || $fdata->{ uc $qual } ) {
607 next if ref $val eq 'ARRAY' && !@$val;
608 $field->extra( $qual, $val );
612 if ( $field->data_type =~ /(set|enum)/i && !$field->size ) {
613 my %extra = $field->extra;
615 for my $len ( map { length } @{ $extra{'list'} || [] } ) {
616 $longest = $len if $len > $longest;
618 $field->size( $longest ) if $longest;
621 for my $cdata ( @{ $fdata->{'constraints'} } ) {
622 next unless $cdata->{'type'} eq 'foreign_key';
623 $cdata->{'fields'} ||= [ $field->name ];
624 push @{ $tdata->{'constraints'} }, $cdata;
628 for my $idata ( @{ $tdata->{'indices'} || [] } ) {
629 my $index = $table->add_index(
630 name => $idata->{'name'},
631 type => uc $idata->{'type'},
632 fields => $idata->{'fields'},
633 ) or die $table->error;
636 for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
637 my $constraint = $table->add_constraint(
638 name => $cdata->{'name'},
639 type => $cdata->{'type'},
640 fields => $cdata->{'fields'},
641 reference_table => $cdata->{'reference_table'},
642 reference_fields => $cdata->{'reference_fields'},
643 match_type => $cdata->{'match_type'} || '',
644 on_delete => $cdata->{'on_delete_do'},
645 on_update => $cdata->{'on_update_do'},
646 ) or die $table->error;
655 # -------------------------------------------------------------------
656 # Where man is not nature is barren.
658 # -------------------------------------------------------------------
664 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>,
665 Chris Mungall E<lt>cjm@fruitfly.orgE<gt>.
669 perl(1), Parse::RecDescent, SQL::Translator::Schema.