1 package SQL::Translator::Parser::SQLite;
5 SQL::Translator::Parser::SQLite - parser for SQLite
10 use SQL::Translator::Parser::SQLite;
12 my $translator = SQL::Translator->new;
13 $translator->parser("SQL::Translator::Parser::SQLite");
17 This is a grammar for parsing CREATE statements for SQLite as
20 http://www.sqlite.org/lang.html
25 CREATE [TEMP | TEMPORARY] [UNIQUE] INDEX index-name
26 ON [database-name .] table-name ( column-name [, column-name]* )
27 [ ON CONFLICT conflict-algorithm ]
35 CREATE [TEMP | TEMPORARY] TABLE table-name (
36 column-def [, column-def]*
41 CREATE [TEMP | TEMPORARY] TABLE table-name AS select-statement
44 name [type] [[CONSTRAINT name] column-constraint]*
49 typename ( number , number )
52 NOT NULL [ conflict-clause ] |
53 PRIMARY KEY [sort-order] [ conflict-clause ] |
54 UNIQUE [ conflict-clause ] |
55 CHECK ( expr ) [ conflict-clause ] |
59 PRIMARY KEY ( name [, name]* ) [ conflict-clause ]|
60 UNIQUE ( name [, name]* ) [ conflict-clause ] |
61 CHECK ( expr ) [ conflict-clause ]
64 ON CONFLICT conflict-algorithm
69 CREATE [TEMP | TEMPORARY] TRIGGER trigger-name [ BEFORE | AFTER ]
70 database-event ON [database-name .] table-name
74 CREATE [TEMP | TEMPORARY] TRIGGER trigger-name INSTEAD OF
75 database-event ON [database-name .] view-name
85 [ FOR EACH ROW | FOR EACH STATEMENT ] [ WHEN expression ]
87 trigger-step ; [ trigger-step ; ]*
91 update-statement | insert-statement |
92 delete-statement | select-statement
97 CREATE [TEMP | TEMPORARY] VIEW view-name AS select-statement
102 ON CONFLICT conflict-algorithm
104 conflict-algorithm ::=
105 ROLLBACK | ABORT | FAIL | IGNORE | REPLACE
110 expr binary-op expr |
115 table-name . column-name |
116 database-name . table-name . column-name |
118 function-name ( expr-list | * ) |
122 expr [NOT] BETWEEN expr AND expr |
123 expr [NOT] IN ( value-list ) |
124 expr [NOT] IN ( select-statement ) |
125 ( select-statement ) |
126 CASE [expr] ( WHEN expr THEN expr )+ [ELSE expr] END
129 LIKE | GLOB | NOT LIKE | NOT GLOB
135 our ( $DEBUG, $GRAMMAR, @EXPORT_OK );
136 our $VERSION = '1.59';
137 $DEBUG = 0 unless defined $DEBUG;
140 use Parse::RecDescent;
142 use base qw(Exporter);
144 @EXPORT_OK = qw(parse);
146 # Enable warnings within the Parse::RecDescent module.
147 $::RD_ERRORS = 1; # Make sure the parser dies when it encounters an error
148 $::RD_WARN = 1; # Enable warnings. This will warn on unused rules &c.
149 $::RD_HINT = 1; # Give out hints to help fix problems.
154 my ( %tables, $table_order, @table_comments, @views, @triggers );
158 my @up_to_N_lines = split (/\n/, $_[1], $max_lines + 1);
159 die sprintf ("Unable to parse line %d:\n%s\n",
161 join "\n", (map { "'$_'" } @up_to_N_lines[0..$max_lines - 1 ]), @up_to_N_lines > $max_lines ? '...' : ()
168 # The "eofile" rule makes the parser fail if any "statement" rule
169 # fails. Otherwise, the first successful match by a "statement"
170 # won't cause the failure needed to know that the parse, as a whole,
173 startrule : statement(s) eofile {
177 triggers => \@triggers,
183 statement : begin_transaction
188 | /^\Z/ | { _err ($thisline, $text) }
190 begin_transaction : /begin/i TRANSACTION(?) SEMICOLON
192 commit : /commit/i SEMICOLON
194 drop : /drop/i (tbl_drop | view_drop | trg_drop) SEMICOLON
196 tbl_drop: TABLE <commit> table_name
198 view_drop: VIEW if_exists(?) view_name
200 trg_drop: TRIGGER if_exists(?) trigger_name
202 comment : /^\s*(?:#|-{2}).*\n/
204 my $comment = $item[1];
205 $comment =~ s/^\s*(#|-{2})\s*//;
206 $comment =~ s/\s*$//;
210 comment : /\/\*/ /[^\*]+/ /\*\//
212 my $comment = $item[2];
213 $comment =~ s/^\s*|\s*$//g;
220 create : CREATE TEMPORARY(?) UNIQUE(?) INDEX NAME ON table_name parens_field_list conflict_clause(?) SEMICOLON
222 my $db_name = $item[7]->{'db_name'} || '';
223 my $table_name = $item[7]->{'name'};
228 on_conflict => $item[9][0],
229 is_temporary => $item[2][0] ? 1 : 0,
232 my $is_unique = $item[3][0];
235 $index->{'type'} = 'unique';
236 push @{ $tables{ $table_name }{'constraints'} }, $index;
239 push @{ $tables{ $table_name }{'indices'} }, $index;
246 create : CREATE TEMPORARY(?) TABLE table_name '(' definition(s /,/) ')' SEMICOLON
248 my $db_name = $item[4]->{'db_name'} || '';
249 my $table_name = $item[4]->{'name'};
251 $tables{ $table_name }{'name'} = $table_name;
252 $tables{ $table_name }{'is_temporary'} = $item[2][0] ? 1 : 0;
253 $tables{ $table_name }{'order'} = ++$table_order;
255 for my $def ( @{ $item[6] } ) {
256 if ( $def->{'supertype'} eq 'column' ) {
257 push @{ $tables{ $table_name }{'fields'} }, $def;
259 elsif ( $def->{'supertype'} eq 'constraint' ) {
260 push @{ $tables{ $table_name }{'constraints'} }, $def;
265 definition : constraint_def | column_def
267 column_def: comment(s?) NAME type(?) column_constraint_def(s?)
270 supertype => 'column',
272 data_type => $item[3][0]->{'type'},
273 size => $item[3][0]->{'size'},
279 constraints => $item[4],
280 comments => $item[1],
284 for my $c ( @{ $item[4] } ) {
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'};
300 elsif ( $c->{'type'} eq 'autoincrement' ) {
301 $column->{'is_auto_inc'} = 1;
308 type : WORD parens_value_list(?)
316 column_constraint_def : CONSTRAINT constraint_name column_constraint
326 column_constraint : NOT_NULL conflict_clause(?)
333 PRIMARY_KEY sort_order(?) conflict_clause(?)
336 type => 'primary_key',
337 sort_order => $item[2][0],
338 on_conflict => $item[2][0],
342 UNIQUE conflict_clause(?)
346 on_conflict => $item[2][0],
350 CHECK_C '(' expr ')' conflict_clause(?)
354 expression => $item[3],
355 on_conflict => $item[5][0],
370 type => 'foreign_key',
371 reference_table => $item[2]{'reference_table'},
372 reference_fields => $item[2]{'reference_fields'},
379 type => 'autoincrement',
383 constraint_def : comment(s?) CONSTRAINT constraint_name table_constraint
386 comments => $item[1],
392 comment(s?) table_constraint
395 comments => $item[1],
400 table_constraint : PRIMARY_KEY parens_field_list conflict_clause(?)
403 supertype => 'constraint',
404 type => 'primary_key',
406 on_conflict => $item[3][0],
410 UNIQUE parens_field_list conflict_clause(?)
413 supertype => 'constraint',
416 on_conflict => $item[3][0],
420 CHECK_C '(' expr ')' conflict_clause(?)
423 supertype => 'constraint',
425 expression => $item[3],
426 on_conflict => $item[5][0],
430 FOREIGN_KEY parens_field_list REFERENCES ref_def
433 supertype => 'constraint',
434 type => 'foreign_key',
436 reference_table => $item[4]{'reference_table'},
437 reference_fields => $item[4]{'reference_fields'},
441 ref_def : table_name parens_field_list
442 { $return = { reference_table => $item[1]{name}, reference_fields => $item[2] } }
444 table_name : qualified_name
446 qualified_name : NAME
447 { $return = { name => $item[1] } }
449 qualified_name : /(\w+)\.(\w+)/
450 { $return = { db_name => $1, name => $2 } }
454 constraint_name : NAME
456 conflict_clause : /on conflict/i conflict_algorigthm
458 conflict_algorigthm : /(rollback|abort|fail|ignore|replace)/i
460 parens_field_list : '(' column_list ')'
463 column_list : field_name(s /,/)
465 parens_value_list : '(' VALUE(s /,/) ')'
470 sort_order : /(ASC|DESC)/i
475 create : CREATE TEMPORARY(?) TRIGGER NAME before_or_after(?) database_event ON table_name trigger_action SEMICOLON
477 my $table_name = $item[8]->{'name'};
480 is_temporary => $item[2][0] ? 1 : 0,
483 db_events => [ $item[6] ],
485 on_table => $table_name,
489 create : CREATE TEMPORARY(?) TRIGGER NAME instead_of database_event ON view_name trigger_action
491 my $table_name = $item[8]->{'name'};
494 is_temporary => $item[2][0] ? 1 : 0,
497 db_events => [ $item[6] ],
499 on_table => $table_name,
503 database_event : /(delete|insert|update)/i
505 database_event : /update of/i column_list
507 trigger_action : for_each(?) when(?) BEGIN_C trigger_step(s) END_C
510 for_each => $item[1][0],
516 for_each : /FOR EACH ROW/i
518 when : WHEN expr { $item[2] }
521 /'(\\.|''|[^\\\'])*'/
523 nonstring : /[^;\'"]+/
525 statement_body : string | nonstring
527 trigger_step : /(select|delete|insert|update)/i statement_body(s?) SEMICOLON
529 $return = join( ' ', $item[1], join ' ', @{ $item[2] || [] } )
532 before_or_after : /(before|after)/i { $return = lc $1 }
534 instead_of : /instead of/i
536 if_exists : /if exists/i
538 view_name : qualified_name
540 trigger_name : qualified_name
545 create : CREATE TEMPORARY(?) VIEW view_name AS select_statement
548 name => $item[4]->{'name'},
550 is_temporary => $item[2][0] ? 1 : 0,
554 select_statement : SELECT /[^;]+/ SEMICOLON
556 $return = join( ' ', $item[1], $item[2] );
566 TRANSACTION: /transaction/i
570 TEMPORARY : /temp(orary)?/i { 1 }
576 NOT_NULL : /not null/i
578 PRIMARY_KEY : /primary key/i
580 FOREIGN_KEY : /foreign key/i
600 REFERENCES : /references/i
602 CONSTRAINT : /constraint/i
604 AUTOINCREMENT : /autoincrement/i
606 UNIQUE : /unique/i { 1 }
610 NAME : /["']?(\w+)["']?/ { $return = $1 }
612 VALUE : /[-+]?\.?\d+(?:[eE]\d+)?/
616 # remove leading/trailing quotes
618 $val =~ s/^['"]|['"]$//g;
623 | /CURRENT_TIMESTAMP/i
624 { 'CURRENT_TIMESTAMP' }
629 my ( $translator, $data ) = @_;
630 my $parser = Parse::RecDescent->new($GRAMMAR);
632 local $::RD_TRACE = $translator->trace ? 1 : undef;
633 local $DEBUG = $translator->debug;
635 unless (defined $parser) {
636 return $translator->error("Error instantiating Parse::RecDescent ".
637 "instance: Bad grammer");
640 my $result = $parser->startrule($data);
641 return $translator->error( "Parse failed." ) unless defined $result;
642 warn Dumper( $result ) if $DEBUG;
644 my $schema = $translator->schema;
647 sort { $a->[0] <=> $b->[0] }
648 map { [ $result->{'tables'}{ $_ }->{'order'}, $_ ] }
649 keys %{ $result->{'tables'} };
651 for my $table_name ( @tables ) {
652 my $tdata = $result->{'tables'}{ $table_name };
653 my $table = $schema->add_table(
654 name => $tdata->{'name'},
655 ) or die $schema->error;
657 $table->comments( $tdata->{'comments'} );
659 for my $fdata ( @{ $tdata->{'fields'} } ) {
660 my $field = $table->add_field(
661 name => $fdata->{'name'},
662 data_type => $fdata->{'data_type'},
663 size => $fdata->{'size'},
664 default_value => $fdata->{'default'},
665 is_auto_increment => $fdata->{'is_auto_inc'},
666 is_nullable => $fdata->{'is_nullable'},
667 comments => $fdata->{'comments'},
668 ) or die $table->error;
670 $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
672 for my $cdata ( @{ $fdata->{'constraints'} } ) {
673 next unless $cdata->{'type'} eq 'foreign_key';
674 $cdata->{'fields'} ||= [ $field->name ];
675 push @{ $tdata->{'constraints'} }, $cdata;
679 for my $idata ( @{ $tdata->{'indices'} || [] } ) {
680 my $index = $table->add_index(
681 name => $idata->{'name'},
682 type => uc ($idata->{'type'}||''),
683 fields => $idata->{'fields'},
684 ) or die $table->error;
687 for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
688 my $constraint = $table->add_constraint(
689 name => $cdata->{'name'},
690 type => $cdata->{'type'},
691 fields => $cdata->{'fields'},
692 reference_table => $cdata->{'reference_table'},
693 reference_fields => $cdata->{'reference_fields'},
694 match_type => $cdata->{'match_type'} || '',
695 on_delete => $cdata->{'on_delete'}
696 || $cdata->{'on_delete_do'},
697 on_update => $cdata->{'on_update'}
698 || $cdata->{'on_update_do'},
699 ) or die $table->error;
703 for my $def ( @{ $result->{'views'} || [] } ) {
704 my $view = $schema->add_view(
705 name => $def->{'name'},
706 sql => $def->{'sql'},
710 for my $def ( @{ $result->{'triggers'} || [] } ) {
711 my $view = $schema->add_trigger(
712 name => $def->{'name'},
713 perform_action_when => $def->{'when'},
714 database_events => $def->{'db_events'},
715 action => $def->{'action'},
716 on_table => $def->{'on_table'},
725 # -------------------------------------------------------------------
726 # All wholsome food is caught without a net or a trap.
728 # -------------------------------------------------------------------
734 Ken Youens-Clark E<lt>kclark@cpan.orgE<gt>.
738 perl(1), Parse::RecDescent, SQL::Translator::Schema.