1 package SQL::Translator::Parser::SQLite;
3 # -------------------------------------------------------------------
4 # Copyright (C) 2002-2009 SQLFairy Authors
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License as
8 # published by the Free Software Foundation; version 2.
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 # -------------------------------------------------------------------
23 SQL::Translator::Parser::SQLite - parser for SQLite
28 use SQL::Translator::Parser::SQLite;
30 my $translator = SQL::Translator->new;
31 $translator->parser("SQL::Translator::Parser::SQLite");
35 This is a grammar for parsing CREATE statements for SQLite as
38 http://www.sqlite.org/lang.html
43 CREATE [TEMP | TEMPORARY] [UNIQUE] INDEX index-name
44 ON [database-name .] table-name ( column-name [, column-name]* )
45 [ ON CONFLICT conflict-algorithm ]
53 CREATE [TEMP | TEMPORARY] TABLE table-name (
54 column-def [, column-def]*
59 CREATE [TEMP | TEMPORARY] TABLE table-name AS select-statement
62 name [type] [[CONSTRAINT name] column-constraint]*
67 typename ( number , number )
70 NOT NULL [ conflict-clause ] |
71 PRIMARY KEY [sort-order] [ conflict-clause ] |
72 UNIQUE [ conflict-clause ] |
73 CHECK ( expr ) [ conflict-clause ] |
77 PRIMARY KEY ( name [, name]* ) [ conflict-clause ]|
78 UNIQUE ( name [, name]* ) [ conflict-clause ] |
79 CHECK ( expr ) [ conflict-clause ]
82 ON CONFLICT conflict-algorithm
87 CREATE [TEMP | TEMPORARY] TRIGGER trigger-name [ BEFORE | AFTER ]
88 database-event ON [database-name .] table-name
92 CREATE [TEMP | TEMPORARY] TRIGGER trigger-name INSTEAD OF
93 database-event ON [database-name .] view-name
100 UPDATE OF column-list
103 [ FOR EACH ROW | FOR EACH STATEMENT ] [ WHEN expression ]
105 trigger-step ; [ trigger-step ; ]*
109 update-statement | insert-statement |
110 delete-statement | select-statement
115 CREATE [TEMP | TEMPORARY] VIEW view-name AS select-statement
120 ON CONFLICT conflict-algorithm
122 conflict-algorithm ::=
123 ROLLBACK | ABORT | FAIL | IGNORE | REPLACE
128 expr binary-op expr |
133 table-name . column-name |
134 database-name . table-name . column-name |
136 function-name ( expr-list | * ) |
140 expr [NOT] BETWEEN expr AND expr |
141 expr [NOT] IN ( value-list ) |
142 expr [NOT] IN ( select-statement ) |
143 ( select-statement ) |
144 CASE [expr] ( WHEN expr THEN expr )+ [ELSE expr] END
147 LIKE | GLOB | NOT LIKE | NOT GLOB
152 use vars qw[ $DEBUG $VERSION $GRAMMAR @EXPORT_OK ];
154 $DEBUG = 0 unless defined $DEBUG;
157 use Parse::RecDescent;
159 use base qw(Exporter);
161 @EXPORT_OK = qw(parse);
163 # Enable warnings within the Parse::RecDescent module.
164 $::RD_ERRORS = 1; # Make sure the parser dies when it encounters an error
165 $::RD_WARN = 1; # Enable warnings. This will warn on unused rules &c.
166 $::RD_HINT = 1; # Give out hints to help fix problems.
171 my ( %tables, $table_order, @table_comments, @views, @triggers );
175 # The "eofile" rule makes the parser fail if any "statement" rule
176 # fails. Otherwise, the first successful match by a "statement"
177 # won't cause the failure needed to know that the parse, as a whole,
180 startrule : statement(s) eofile {
184 triggers => \@triggers,
190 statement : begin_transaction
197 begin_transaction : /begin/i TRANSACTION(?) SEMICOLON
199 commit : /commit/i SEMICOLON
201 drop : /drop/i (tbl_drop | view_drop | trg_drop) SEMICOLON
203 tbl_drop: TABLE <commit> table_name
205 view_drop: VIEW if_exists(?) view_name
207 trg_drop: TRIGGER if_exists(?) trigger_name
209 comment : /^\s*(?:#|-{2}).*\n/
211 my $comment = $item[1];
212 $comment =~ s/^\s*(#|-{2})\s*//;
213 $comment =~ s/\s*$//;
217 comment : /\/\*/ /[^\*]+/ /\*\//
219 my $comment = $item[2];
220 $comment =~ s/^\s*|\s*$//g;
227 create : CREATE TEMPORARY(?) UNIQUE(?) INDEX WORD ON table_name parens_field_list conflict_clause(?) SEMICOLON
229 my $db_name = $item[7]->{'db_name'} || '';
230 my $table_name = $item[7]->{'name'};
235 on_conflict => $item[9][0],
236 is_temporary => $item[2][0] ? 1 : 0,
239 my $is_unique = $item[3][0];
242 $index->{'type'} = 'unique';
243 push @{ $tables{ $table_name }{'constraints'} }, $index;
246 push @{ $tables{ $table_name }{'indices'} }, $index;
253 create : CREATE TEMPORARY(?) TABLE table_name '(' definition(s /,/) ')' SEMICOLON
255 my $db_name = $item[4]->{'db_name'} || '';
256 my $table_name = $item[4]->{'name'};
258 $tables{ $table_name }{'name'} = $table_name;
259 $tables{ $table_name }{'is_temporary'} = $item[2][0] ? 1 : 0;
260 $tables{ $table_name }{'order'} = ++$table_order;
262 for my $def ( @{ $item[6] } ) {
263 if ( $def->{'supertype'} eq 'column' ) {
264 push @{ $tables{ $table_name }{'fields'} }, $def;
266 elsif ( $def->{'supertype'} eq 'constraint' ) {
267 push @{ $tables{ $table_name }{'constraints'} }, $def;
272 definition : constraint_def | column_def
274 column_def: comment(s?) NAME type(?) column_constraint(s?)
277 supertype => 'column',
279 data_type => $item[3][0]->{'type'},
280 size => $item[3][0]->{'size'},
286 constraints => $item[4],
287 comments => $item[1],
291 for my $c ( @{ $item[4] } ) {
292 if ( $c->{'type'} eq 'not_null' ) {
293 $column->{'is_nullable'} = 0;
295 elsif ( $c->{'type'} eq 'primary_key' ) {
296 $column->{'is_primary_key'} = 1;
298 elsif ( $c->{'type'} eq 'unique' ) {
299 $column->{'is_unique'} = 1;
301 elsif ( $c->{'type'} eq 'check' ) {
302 $column->{'check'} = $c->{'expression'};
304 elsif ( $c->{'type'} eq 'default' ) {
305 $column->{'default'} = $c->{'value'};
312 type : WORD parens_value_list(?)
320 column_constraint : NOT_NULL conflict_clause(?)
327 PRIMARY_KEY sort_order(?) conflict_clause(?)
330 type => 'primary_key',
331 sort_order => $item[2][0],
332 on_conflict => $item[2][0],
336 UNIQUE conflict_clause(?)
340 on_conflict => $item[2][0],
344 CHECK_C '(' expr ')' conflict_clause(?)
348 expression => $item[3],
349 on_conflict => $item[5][0],
361 constraint_def : PRIMARY_KEY parens_field_list conflict_clause(?)
364 supertype => 'constraint',
365 type => 'primary_key',
367 on_conflict => $item[3][0],
371 UNIQUE parens_field_list conflict_clause(?)
374 supertype => 'constraint',
377 on_conflict => $item[3][0],
381 CHECK_C '(' expr ')' conflict_clause(?)
384 supertype => 'constraint',
386 expression => $item[3],
387 on_conflict => $item[5][0],
391 table_name : qualified_name
393 qualified_name : NAME
394 { $return = { name => $item[1] } }
396 qualified_name : /(\w+)\.(\w+)/
397 { $return = { db_name => $1, name => $2 } }
401 conflict_clause : /on conflict/i conflict_algorigthm
403 conflict_algorigthm : /(rollback|abort|fail|ignore|replace)/i
405 parens_field_list : '(' column_list ')'
408 column_list : field_name(s /,/)
410 parens_value_list : '(' VALUE(s /,/) ')'
415 sort_order : /(ASC|DESC)/i
420 create : CREATE TEMPORARY(?) TRIGGER NAME before_or_after(?) database_event ON table_name trigger_action SEMICOLON
422 my $table_name = $item[8]->{'name'};
425 is_temporary => $item[2][0] ? 1 : 0,
428 db_events => [ $item[6] ],
430 on_table => $table_name,
434 create : CREATE TEMPORARY(?) TRIGGER NAME instead_of database_event ON view_name trigger_action
436 my $table_name = $item[8]->{'name'};
439 is_temporary => $item[2][0] ? 1 : 0,
442 db_events => [ $item[6] ],
444 on_table => $table_name,
448 database_event : /(delete|insert|update)/i
450 database_event : /update of/i column_list
452 trigger_action : for_each(?) when(?) BEGIN_C trigger_step(s) END_C
455 for_each => $item[1][0],
461 for_each : /FOR EACH ROW/i
463 when : WHEN expr { $item[2] }
466 /'(\\.|''|[^\\\'])*'/
468 nonstring : /[^;\'"]+/
470 statement_body : string | nonstring
472 trigger_step : /(select|delete|insert|update)/i statement_body(s?) SEMICOLON
474 $return = join( ' ', $item[1], join ' ', @{ $item[2] || [] } )
477 before_or_after : /(before|after)/i { $return = lc $1 }
479 instead_of : /instead of/i
481 if_exists : /if exists/i
483 view_name : qualified_name
485 trigger_name : qualified_name
490 create : CREATE TEMPORARY(?) VIEW view_name AS select_statement
493 name => $item[4]->{'name'},
495 is_temporary => $item[2][0] ? 1 : 0,
499 select_statement : SELECT /[^;]+/ SEMICOLON
501 $return = join( ' ', $item[1], $item[2] );
511 TRANSACTION: /transaction/i
515 TEMPORARY : /temp(orary)?/i { 1 }
521 NOT_NULL : /not null/i
523 PRIMARY_KEY : /primary key/i
543 UNIQUE : /unique/i { 1 }
547 NAME : /'?(\w+)'?/ { $return = $1 }
549 VALUE : /[-+]?\.?\d+(?:[eE]\d+)?/
553 # remove leading/trailing quotes
555 $val =~ s/^['"]|['"]$//g;
560 | /CURRENT_TIMESTAMP/i
561 { 'CURRENT_TIMESTAMP' }
565 # -------------------------------------------------------------------
567 my ( $translator, $data ) = @_;
568 my $parser = Parse::RecDescent->new($GRAMMAR);
570 local $::RD_TRACE = $translator->trace ? 1 : undef;
571 local $DEBUG = $translator->debug;
573 unless (defined $parser) {
574 return $translator->error("Error instantiating Parse::RecDescent ".
575 "instance: Bad grammer");
578 my $result = $parser->startrule($data);
579 return $translator->error( "Parse failed." ) unless defined $result;
580 warn Dumper( $result ) if $DEBUG;
582 my $schema = $translator->schema;
585 sort { $a->[0] <=> $b->[0] }
586 map { [ $result->{'tables'}{ $_ }->{'order'}, $_ ] }
587 keys %{ $result->{'tables'} };
589 for my $table_name ( @tables ) {
590 my $tdata = $result->{'tables'}{ $table_name };
591 my $table = $schema->add_table(
592 name => $tdata->{'name'},
593 ) or die $schema->error;
595 $table->comments( $tdata->{'comments'} );
597 for my $fdata ( @{ $tdata->{'fields'} } ) {
598 my $field = $table->add_field(
599 name => $fdata->{'name'},
600 data_type => $fdata->{'data_type'},
601 size => $fdata->{'size'},
602 default_value => $fdata->{'default'},
603 is_auto_increment => $fdata->{'is_auto_inc'},
604 is_nullable => $fdata->{'is_nullable'},
605 comments => $fdata->{'comments'},
606 ) or die $table->error;
608 $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
610 for my $cdata ( @{ $fdata->{'constraints'} } ) {
611 next unless $cdata->{'type'} eq 'foreign_key';
612 $cdata->{'fields'} ||= [ $field->name ];
613 push @{ $tdata->{'constraints'} }, $cdata;
617 for my $idata ( @{ $tdata->{'indices'} || [] } ) {
618 my $index = $table->add_index(
619 name => $idata->{'name'},
620 type => uc $idata->{'type'},
621 fields => $idata->{'fields'},
622 ) or die $table->error;
625 for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
626 my $constraint = $table->add_constraint(
627 name => $cdata->{'name'},
628 type => $cdata->{'type'},
629 fields => $cdata->{'fields'},
630 reference_table => $cdata->{'reference_table'},
631 reference_fields => $cdata->{'reference_fields'},
632 match_type => $cdata->{'match_type'} || '',
633 on_delete => $cdata->{'on_delete'} || $cdata->{'on_delete_do'},
634 on_update => $cdata->{'on_update'} || $cdata->{'on_update_do'},
635 ) or die $table->error;
639 for my $def ( @{ $result->{'views'} || [] } ) {
640 my $view = $schema->add_view(
641 name => $def->{'name'},
642 sql => $def->{'sql'},
646 for my $def ( @{ $result->{'triggers'} || [] } ) {
647 my $view = $schema->add_trigger(
648 name => $def->{'name'},
649 perform_action_when => $def->{'when'},
650 database_events => $def->{'db_events'},
651 action => $def->{'action'},
652 on_table => $def->{'on_table'},
661 # -------------------------------------------------------------------
662 # All wholsome food is caught without a net or a trap.
664 # -------------------------------------------------------------------
670 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.
674 perl(1), Parse::RecDescent, SQL::Translator::Schema.