1 package SQL::Translator::Parser::SQLite;
3 # -------------------------------------------------------------------
5 # -------------------------------------------------------------------
6 # Copyright (C) 2002-2009 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::SQLite - parser for SQLite
30 use SQL::Translator::Parser::SQLite;
32 my $translator = SQL::Translator->new;
33 $translator->parser("SQL::Translator::Parser::SQLite");
37 This is a grammar for parsing CREATE statements for SQLite as
40 http://www.sqlite.org/lang.html
45 CREATE [TEMP | TEMPORARY] [UNIQUE] INDEX index-name
46 ON [database-name .] table-name ( column-name [, column-name]* )
47 [ ON CONFLICT conflict-algorithm ]
55 CREATE [TEMP | TEMPORARY] TABLE table-name (
56 column-def [, column-def]*
61 CREATE [TEMP | TEMPORARY] TABLE table-name AS select-statement
64 name [type] [[CONSTRAINT name] column-constraint]*
69 typename ( number , number )
72 NOT NULL [ conflict-clause ] |
73 PRIMARY KEY [sort-order] [ conflict-clause ] |
74 UNIQUE [ conflict-clause ] |
75 CHECK ( expr ) [ conflict-clause ] |
79 PRIMARY KEY ( name [, name]* ) [ conflict-clause ]|
80 UNIQUE ( name [, name]* ) [ conflict-clause ] |
81 CHECK ( expr ) [ conflict-clause ]
84 ON CONFLICT conflict-algorithm
89 CREATE [TEMP | TEMPORARY] TRIGGER trigger-name [ BEFORE | AFTER ]
90 database-event ON [database-name .] table-name
94 CREATE [TEMP | TEMPORARY] TRIGGER trigger-name INSTEAD OF
95 database-event ON [database-name .] view-name
102 UPDATE OF column-list
105 [ FOR EACH ROW | FOR EACH STATEMENT ] [ WHEN expression ]
107 trigger-step ; [ trigger-step ; ]*
111 update-statement | insert-statement |
112 delete-statement | select-statement
117 CREATE [TEMP | TEMPORARY] VIEW view-name AS select-statement
122 ON CONFLICT conflict-algorithm
124 conflict-algorithm ::=
125 ROLLBACK | ABORT | FAIL | IGNORE | REPLACE
130 expr binary-op expr |
135 table-name . column-name |
136 database-name . table-name . column-name |
138 function-name ( expr-list | * ) |
142 expr [NOT] BETWEEN expr AND expr |
143 expr [NOT] IN ( value-list ) |
144 expr [NOT] IN ( select-statement ) |
145 ( select-statement ) |
146 CASE [expr] ( WHEN expr THEN expr )+ [ELSE expr] END
149 LIKE | GLOB | NOT LIKE | NOT GLOB
154 use vars qw[ $DEBUG $GRAMMAR @EXPORT_OK ];
155 $DEBUG = 0 unless defined $DEBUG;
158 use Parse::RecDescent;
160 use base qw(Exporter);
162 @EXPORT_OK = qw(parse);
164 # Enable warnings within the Parse::RecDescent module.
165 $::RD_ERRORS = 1; # Make sure the parser dies when it encounters an error
166 $::RD_WARN = 1; # Enable warnings. This will warn on unused rules &c.
167 $::RD_HINT = 1; # Give out hints to help fix problems.
172 my ( %tables, $table_order, @table_comments, @views, @triggers );
176 # The "eofile" rule makes the parser fail if any "statement" rule
177 # fails. Otherwise, the first successful match by a "statement"
178 # won't cause the failure needed to know that the parse, as a whole,
181 startrule : statement(s) eofile {
185 triggers => \@triggers,
191 statement : begin_transaction
198 begin_transaction : /begin transaction/i SEMICOLON
200 commit : /commit/i SEMICOLON
202 drop : /drop/i TABLE <commit> table_name SEMICOLON
204 comment : /^\s*(?:#|-{2}).*\n/
206 my $comment = $item[1];
207 $comment =~ s/^\s*(#|-{2})\s*//;
208 $comment =~ s/\s*$//;
212 comment : /\/\*/ /[^\*]+/ /\*\//
214 my $comment = $item[2];
215 $comment =~ s/^\s*|\s*$//g;
222 create : CREATE TEMPORARY(?) UNIQUE(?) INDEX WORD ON table_name parens_field_list conflict_clause(?) SEMICOLON
224 my $db_name = $item[7]->{'db_name'} || '';
225 my $table_name = $item[7]->{'name'};
230 on_conflict => $item[9][0],
231 is_temporary => $item[2][0] ? 1 : 0,
234 my $is_unique = $item[3][0];
237 $index->{'type'} = 'unique';
238 push @{ $tables{ $table_name }{'constraints'} }, $index;
241 push @{ $tables{ $table_name }{'indices'} }, $index;
248 create : CREATE TEMPORARY(?) TABLE table_name '(' definition(s /,/) ')' SEMICOLON
250 my $db_name = $item[4]->{'db_name'} || '';
251 my $table_name = $item[4]->{'name'};
253 $tables{ $table_name }{'name'} = $table_name;
254 $tables{ $table_name }{'is_temporary'} = $item[2][0] ? 1 : 0;
255 $tables{ $table_name }{'order'} = ++$table_order;
257 for my $def ( @{ $item[6] } ) {
258 if ( $def->{'supertype'} eq 'column' ) {
259 push @{ $tables{ $table_name }{'fields'} }, $def;
261 elsif ( $def->{'supertype'} eq 'constraint' ) {
262 push @{ $tables{ $table_name }{'constraints'} }, $def;
267 definition : constraint_def | column_def
269 column_def: NAME type(?) column_constraint(s?)
272 supertype => 'column',
274 data_type => $item[2][0]->{'type'},
275 size => $item[2][0]->{'size'},
281 constraints => $item[3],
284 for my $c ( @{ $item[3] } ) {
285 if ( $c->{'type'} eq 'not_null' ) {
286 $column->{'is_nullable'} = 0;
288 elsif ( $c->{'type'} eq 'primary_key' ) {
289 $column->{'is_primary_key'} = 1;
291 elsif ( $c->{'type'} eq 'unique' ) {
292 $column->{'is_unique'} = 1;
294 elsif ( $c->{'type'} eq 'check' ) {
295 $column->{'check'} = $c->{'expression'};
297 elsif ( $c->{'type'} eq 'default' ) {
298 $column->{'default'} = $c->{'value'};
305 type : WORD parens_value_list(?)
313 column_constraint : NOT_NULL conflict_clause(?)
320 PRIMARY_KEY sort_order(?) conflict_clause(?)
323 type => 'primary_key',
324 sort_order => $item[2][0],
325 on_conflict => $item[2][0],
329 UNIQUE conflict_clause(?)
333 on_conflict => $item[2][0],
337 CHECK_C '(' expr ')' conflict_clause(?)
341 expression => $item[3],
342 on_conflict => $item[5][0],
354 constraint_def : PRIMARY_KEY parens_field_list conflict_clause(?)
357 supertype => 'constraint',
358 type => 'primary_key',
360 on_conflict => $item[3][0],
364 UNIQUE parens_field_list conflict_clause(?)
367 supertype => 'constraint',
370 on_conflict => $item[3][0],
374 CHECK_C '(' expr ')' conflict_clause(?)
377 supertype => 'constraint',
379 expression => $item[3],
380 on_conflict => $item[5][0],
384 table_name : qualified_name
386 qualified_name : NAME
387 { $return = { name => $item[1] } }
389 qualified_name : /(\w+)\.(\w+)/
390 { $return = { db_name => $1, name => $2 } }
394 conflict_clause : /on conflict/i conflict_algorigthm
396 conflict_algorigthm : /(rollback|abort|fail|ignore|replace)/i
398 parens_field_list : '(' column_list ')'
401 column_list : field_name(s /,/)
403 parens_value_list : '(' VALUE(s /,/) ')'
408 sort_order : /(ASC|DESC)/i
413 create : CREATE TEMPORARY(?) TRIGGER NAME before_or_after(?) database_event ON table_name trigger_action SEMICOLON
415 my $table_name = $item[8]->{'name'};
418 is_temporary => $item[2][0] ? 1 : 0,
421 db_events => [ $item[6] ],
423 on_table => $table_name,
427 create : CREATE TEMPORARY(?) TRIGGER NAME instead_of database_event ON view_name trigger_action
429 my $table_name = $item[8]->{'name'};
432 is_temporary => $item[2][0] ? 1 : 0,
435 db_events => [ $item[6] ],
437 on_table => $table_name,
441 database_event : /(delete|insert|update)/i
443 database_event : /update of/i column_list
445 trigger_action : for_each(?) when(?) BEGIN_C trigger_step(s) END_C
448 for_each => $item[1][0],
454 for_each : /FOR EACH ROW/i
456 when : WHEN expr { $item[2] }
459 /'(\\.|''|[^\\\'])*'/
461 nonstring : /[^;\'"]+/
463 statement_body : (string | nonstring)(s?)
465 trigger_step : /(select|delete|insert|update)/i statement_body SEMICOLON
467 $return = join( ' ', $item[1], join ' ', @{ $item[2] || [] } )
470 before_or_after : /(before|after)/i { $return = lc $1 }
472 instead_of : /instead of/i
474 view_name : qualified_name
479 create : CREATE TEMPORARY(?) VIEW view_name AS select_statement
482 name => $item[4]->{'name'},
484 is_temporary => $item[2][0] ? 1 : 0,
488 select_statement : SELECT /[^;]+/ SEMICOLON
490 $return = join( ' ', $item[1], $item[2] );
502 TEMPORARY : /temp(orary)?/i { 1 }
508 NOT_NULL : /not null/i
510 PRIMARY_KEY : /primary key/i
530 UNIQUE : /unique/i { 1 }
534 NAME : /'?(\w+)'?/ { $return = $1 }
536 VALUE : /[-+]?\.?\d+(?:[eE]\d+)?/
540 # remove leading/trailing quotes
542 $val =~ s/^['"]|['"]$//g;
547 | /CURRENT_TIMESTAMP/i
548 { 'CURRENT_TIMESTAMP' }
552 # -------------------------------------------------------------------
554 my ( $translator, $data ) = @_;
555 my $parser = Parse::RecDescent->new($GRAMMAR);
557 local $::RD_TRACE = $translator->trace ? 1 : undef;
558 local $DEBUG = $translator->debug;
560 unless (defined $parser) {
561 return $translator->error("Error instantiating Parse::RecDescent ".
562 "instance: Bad grammer");
565 my $result = $parser->startrule($data);
566 return $translator->error( "Parse failed." ) unless defined $result;
567 warn Dumper( $result ) if $DEBUG;
569 my $schema = $translator->schema;
572 sort { $a->[0] <=> $b->[0] }
573 map { [ $result->{'tables'}{ $_ }->{'order'}, $_ ] }
574 keys %{ $result->{'tables'} };
576 for my $table_name ( @tables ) {
577 my $tdata = $result->{'tables'}{ $table_name };
578 my $table = $schema->add_table(
579 name => $tdata->{'name'},
580 ) or die $schema->error;
582 $table->comments( $tdata->{'comments'} );
584 for my $fdata ( @{ $tdata->{'fields'} } ) {
585 my $field = $table->add_field(
586 name => $fdata->{'name'},
587 data_type => $fdata->{'data_type'},
588 size => $fdata->{'size'},
589 default_value => $fdata->{'default'},
590 is_auto_increment => $fdata->{'is_auto_inc'},
591 is_nullable => $fdata->{'is_nullable'},
592 comments => $fdata->{'comments'},
593 ) or die $table->error;
595 $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
597 for my $cdata ( @{ $fdata->{'constraints'} } ) {
598 next unless $cdata->{'type'} eq 'foreign_key';
599 $cdata->{'fields'} ||= [ $field->name ];
600 push @{ $tdata->{'constraints'} }, $cdata;
604 for my $idata ( @{ $tdata->{'indices'} || [] } ) {
605 my $index = $table->add_index(
606 name => $idata->{'name'},
607 type => uc $idata->{'type'},
608 fields => $idata->{'fields'},
609 ) or die $table->error;
612 for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
613 my $constraint = $table->add_constraint(
614 name => $cdata->{'name'},
615 type => $cdata->{'type'},
616 fields => $cdata->{'fields'},
617 reference_table => $cdata->{'reference_table'},
618 reference_fields => $cdata->{'reference_fields'},
619 match_type => $cdata->{'match_type'} || '',
620 on_delete => $cdata->{'on_delete'} || $cdata->{'on_delete_do'},
621 on_update => $cdata->{'on_update'} || $cdata->{'on_update_do'},
622 ) or die $table->error;
626 for my $def ( @{ $result->{'views'} || [] } ) {
627 my $view = $schema->add_view(
628 name => $def->{'name'},
629 sql => $def->{'sql'},
633 for my $def ( @{ $result->{'triggers'} || [] } ) {
634 my $view = $schema->add_trigger(
635 name => $def->{'name'},
636 perform_action_when => $def->{'when'},
637 database_events => $def->{'db_events'},
638 action => $def->{'action'},
639 on_table => $def->{'on_table'},
648 # -------------------------------------------------------------------
649 # All wholsome food is caught without a net or a trap.
651 # -------------------------------------------------------------------
657 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.
661 perl(1), Parse::RecDescent, SQL::Translator::Schema.