1 package SQL::Translator::Parser::MySQL;
3 # -------------------------------------------------------------------
4 # $Id: MySQL.pm,v 1.44 2004-03-01 17:39:22 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"
123 use vars qw[ $DEBUG $VERSION $GRAMMAR @EXPORT_OK ];
124 $VERSION = sprintf "%d.%02d", q$Revision: 1.44 $ =~ /(\d+)\.(\d+)/;
125 $DEBUG = 0 unless defined $DEBUG;
128 use Parse::RecDescent;
130 use base qw(Exporter);
132 @EXPORT_OK = qw(parse);
134 # Enable warnings within the Parse::RecDescent module.
135 $::RD_ERRORS = 1; # Make sure the parser dies when it encounters an error
136 $::RD_WARN = 1; # Enable warnings. This will warn on unused rules &c.
137 $::RD_HINT = 1; # Give out hints to help fix problems.
142 my ( %tables, $table_order, @table_comments );
146 # The "eofile" rule makes the parser fail if any "statement" rule
147 # fails. Otherwise, the first successful match by a "statement"
148 # won't cause the failure needed to know that the parse, as a whole,
151 startrule : statement(s) eofile { \%tables }
162 use : /use/i WORD ';'
163 { @table_comments = () }
165 set : /set/i /[^;]+/ ';'
166 { @table_comments = () }
168 drop : /drop/i TABLE /[^;]+/ ';'
170 drop : /drop/i WORD(s) ';'
171 { @table_comments = () }
173 create : CREATE /database/i WORD ';'
174 { @table_comments = () }
176 create : CREATE TEMPORARY(?) TABLE opt_if_not_exists(?) table_name '(' create_definition(s /,/) ')' table_option(s?) ';'
178 my $table_name = $item{'table_name'};
179 $tables{ $table_name }{'order'} = ++$table_order;
180 $tables{ $table_name }{'table_name'} = $table_name;
182 if ( @table_comments ) {
183 $tables{ $table_name }{'comments'} = [ @table_comments ];
184 @table_comments = ();
188 for my $definition ( @{ $item[7] } ) {
189 if ( $definition->{'supertype'} eq 'field' ) {
190 my $field_name = $definition->{'name'};
191 $tables{ $table_name }{'fields'}{ $field_name } =
192 { %$definition, order => $i };
195 if ( $definition->{'is_primary_key'} ) {
196 push @{ $tables{ $table_name }{'constraints'} },
198 type => 'primary_key',
199 fields => [ $field_name ],
204 elsif ( $definition->{'supertype'} eq 'constraint' ) {
205 push @{ $tables{ $table_name }{'constraints'} }, $definition;
207 elsif ( $definition->{'supertype'} eq 'index' ) {
208 push @{ $tables{ $table_name }{'indices'} }, $definition;
212 if ( my @options = @{ $item{'table_option(s?)'} } ) {
213 $tables{ $table_name }{'table_options'} = \@options;
219 opt_if_not_exists : /if not exists/i
221 create : CREATE UNIQUE(?) /(index|key)/i index_name /on/i table_name '(' field_name(s /,/) ')' ';'
223 @table_comments = ();
224 push @{ $tables{ $item{'table_name'} }{'indices'} },
227 type => $item[2] ? 'unique' : 'normal',
233 create_definition : constraint
239 comment : /^\s*(?:#|-{2}).*\n/
241 my $comment = $item[1];
242 $comment =~ s/^\s*(#|--)\s*//;
243 $comment =~ s/\s*$//;
245 push @table_comments, $comment;
248 field_comment : /^\s*(?:#|-{2}).*\n/
250 my $comment = $item[1];
251 $comment =~ s/^\s*(#|--)\s*//;
252 $comment =~ s/\s*$//;
258 field : field_comment(s?) field_name data_type field_qualifier(s?) reference_definition(?) field_comment(s?)
260 my %qualifiers = map { %$_ } @{ $item{'field_qualifier(s?)'} || [] };
261 if ( my @type_quals = @{ $item{'data_type'}{'qualifiers'} || [] } ) {
262 $qualifiers{ $_ } = 1 for @type_quals;
265 my $null = defined $qualifiers{'not_null'}
266 ? $qualifiers{'not_null'} : 1;
267 delete $qualifiers{'not_null'};
269 my @comments = ( @{ $item[1] }, @{ $item[6] } );
272 supertype => 'field',
273 name => $item{'field_name'},
274 data_type => $item{'data_type'}{'type'},
275 size => $item{'data_type'}{'size'},
276 list => $item{'data_type'}{'list'},
278 constraints => $item{'reference_definition(?)'},
279 comments => [ @comments ],
285 field_qualifier : not_null
288 null => $item{'not_null'},
292 field_qualifier : default_val
295 default => $item{'default_val'},
299 field_qualifier : auto_inc
302 is_auto_inc => $item{'auto_inc'},
306 field_qualifier : primary_key
309 is_primary_key => $item{'primary_key'},
313 field_qualifier : unsigned
316 is_unsigned => $item{'unsigned'},
320 field_qualifier : /character set/i WORD
323 character_set => $item[2],
327 reference_definition : /references/i table_name parens_field_list(?) match_type(?) on_delete_do(?) on_update_do(?)
330 type => 'foreign_key',
331 reference_table => $item[2],
332 reference_fields => $item[3][0],
333 match_type => $item[4][0],
334 on_delete_do => $item[5][0],
335 on_update_do => $item[6][0],
339 match_type : /match full/i { 'full' }
341 /match partial/i { 'partial' }
343 on_delete_do : /on delete/i reference_option
346 on_update_do : /on update/i reference_option
349 reference_option: /restrict/i |
366 data_type : WORD parens_value_list(s?) type_qualifier(s?)
369 my $size; # field size, applicable only to non-set fields
370 my $list; # set list, applicable only to sets (duh)
372 if ( uc($type) =~ /^(SET|ENUM)$/ ) {
381 unless ( @{ $size || [] } ) {
382 if ( lc $type eq 'tinyint' ) {
385 elsif ( lc $type eq 'smallint' ) {
388 elsif ( lc $type eq 'mediumint' ) {
391 elsif ( $type =~ /^int(eger)?$/ ) {
395 elsif ( lc $type eq 'bigint' ) {
399 lc $type =~ /(float|double|decimal|numeric|real|fixed|dec)/
405 if ( $type =~ /^tiny(text|blob)$/i ) {
408 elsif ( $type =~ /^(blob|text)$/i ) {
411 elsif ( $type =~ /^medium(blob|text)$/i ) {
414 elsif ( $type =~ /^long(blob|text)$/i ) {
415 $size = 4_294_967_295;
422 qualifiers => $item[3],
426 parens_field_list : '(' field_name(s /,/) ')'
429 parens_value_list : '(' VALUE(s /,/) ')'
432 type_qualifier : /(BINARY|UNSIGNED|ZEROFILL)/i
437 create_index : /create/i /index/i
439 not_null : /not/i /null/i { $return = 0 }
441 unsigned : /unsigned/i { $return = 0 }
443 #default_val : /default/i /(?:')?[\s\w\d:.-]*(?:')?/
445 # $item[2] =~ s/'//g;
446 # $return = $item[2];
449 default_val : /default/i /'(?:.*?\\')*.*?'|(?:')?[\w\d:.-]*(?:')?/
451 $item[2] =~ s/^\s*'|'\s*$//g;
455 auto_inc : /auto_increment/i { 1 }
457 primary_key : /primary/i /key/i { 1 }
459 constraint : primary_key_def
464 foreign_key_def : foreign_key_def_begin parens_field_list reference_definition
467 supertype => 'constraint',
468 type => 'foreign_key',
471 %{ $item{'reference_definition'} },
475 foreign_key_def_begin : /constraint/i /foreign key/i
478 /constraint/i WORD /foreign key/i
479 { $return = $item[2] }
484 primary_key_def : primary_key index_name(?) '(' name_with_opt_paren(s /,/) ')'
487 supertype => 'constraint',
488 name => $item{'index_name(?)'}[0],
489 type => 'primary_key',
494 unique_key_def : UNIQUE KEY(?) index_name(?) '(' name_with_opt_paren(s /,/) ')'
497 supertype => 'constraint',
498 name => $item{'index_name(?)'}[0],
504 normal_index : KEY index_name(?) '(' name_with_opt_paren(s /,/) ')'
507 supertype => 'index',
509 name => $item{'index_name(?)'}[0],
514 fulltext_index : /fulltext/i KEY(?) index_name(?) '(' name_with_opt_paren(s /,/) ')'
517 supertype => 'index',
519 name => $item{'index_name(?)'}[0],
524 name_with_opt_paren : NAME parens_value_list(s?)
525 { $item[2][0] ? "$item[1]($item[2][0][0])" : $item[1] }
527 UNIQUE : /unique/i { 1 }
529 KEY : /key/i | /index/i
531 table_option : WORD /\s*=\s*/ WORD
533 $return = { $item[1] => $item[3] };
538 TEMPORARY : /temporary/i
553 VALUE : /[-+]?\.?\d+(?:[eE]\d+)?/
557 # remove leading/trailing quotes
559 $val =~ s/^['"]|['"]$//g;
567 # -------------------------------------------------------------------
569 my ( $translator, $data ) = @_;
570 my $parser = Parse::RecDescent->new($GRAMMAR);
572 local $::RD_TRACE = $translator->trace ? 1 : undef;
573 local $DEBUG = $translator->debug;
575 unless (defined $parser) {
576 return $translator->error("Error instantiating Parse::RecDescent ".
577 "instance: Bad grammer");
580 my $result = $parser->startrule($data);
581 return $translator->error( "Parse failed." ) unless defined $result;
582 warn Dumper( $result ) if $DEBUG;
584 my $schema = $translator->schema;
586 $result->{ $a }->{'order'} <=> $result->{ $b }->{'order'}
589 for my $table_name ( @tables ) {
590 my $tdata = $result->{ $table_name };
591 my $table = $schema->add_table(
592 name => $tdata->{'table_name'},
593 ) or die $schema->error;
595 $table->comments( $tdata->{'comments'} );
598 $tdata->{'fields'}->{$a}->{'order'}
600 $tdata->{'fields'}->{$b}->{'order'}
601 } keys %{ $tdata->{'fields'} };
603 for my $fname ( @fields ) {
604 my $fdata = $tdata->{'fields'}{ $fname };
605 my $field = $table->add_field(
606 name => $fdata->{'name'},
607 data_type => $fdata->{'data_type'},
608 size => $fdata->{'size'},
609 default_value => $fdata->{'default'},
610 is_auto_increment => $fdata->{'is_auto_inc'},
611 is_nullable => $fdata->{'null'},
612 comments => $fdata->{'comments'},
613 ) or die $table->error;
615 $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
617 for my $qual ( qw[ binary unsigned zerofill list ] ) {
618 if ( my $val = $fdata->{ $qual } || $fdata->{ uc $qual } ) {
619 next if ref $val eq 'ARRAY' && !@$val;
620 $field->extra( $qual, $val );
624 if ( $field->data_type =~ /(set|enum)/i && !$field->size ) {
625 my %extra = $field->extra;
627 for my $len ( map { length } @{ $extra{'list'} || [] } ) {
628 $longest = $len if $len > $longest;
630 $field->size( $longest ) if $longest;
633 for my $cdata ( @{ $fdata->{'constraints'} } ) {
634 next unless $cdata->{'type'} eq 'foreign_key';
635 $cdata->{'fields'} ||= [ $field->name ];
636 push @{ $tdata->{'constraints'} }, $cdata;
640 for my $idata ( @{ $tdata->{'indices'} || [] } ) {
641 my $index = $table->add_index(
642 name => $idata->{'name'},
643 type => uc $idata->{'type'},
644 fields => $idata->{'fields'},
645 ) or die $table->error;
648 if ( my @options = @{ $tdata->{'table_options'} || [] } ) {
649 $table->options( \@options ) or die $table->error;
652 for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
653 my $constraint = $table->add_constraint(
654 name => $cdata->{'name'},
655 type => $cdata->{'type'},
656 fields => $cdata->{'fields'},
657 reference_table => $cdata->{'reference_table'},
658 reference_fields => $cdata->{'reference_fields'},
659 match_type => $cdata->{'match_type'} || '',
660 on_delete => $cdata->{'on_delete_do'},
661 on_update => $cdata->{'on_update_do'},
662 ) or die $table->error;
671 # -------------------------------------------------------------------
672 # Where man is not nature is barren.
674 # -------------------------------------------------------------------
680 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>,
681 Chris Mungall E<lt>cjm@fruitfly.orgE<gt>.
685 perl(1), Parse::RecDescent, SQL::Translator::Schema.