fixed typo reported in rt68912
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Parser / SQLite.pm
CommitLineData
72aa2647 1package SQL::Translator::Parser::SQLite;
2
72aa2647 3=head1 NAME
4
5SQL::Translator::Parser::SQLite - parser for SQLite
6
7=head1 SYNOPSIS
8
9 use SQL::Translator;
10 use SQL::Translator::Parser::SQLite;
11
12 my $translator = SQL::Translator->new;
13 $translator->parser("SQL::Translator::Parser::SQLite");
14
15=head1 DESCRIPTION
16
ea93df61 17This is a grammar for parsing CREATE statements for SQLite as
72aa2647 18described here:
19
20 http://www.sqlite.org/lang.html
21
22CREATE INDEX
23
24sql-statement ::=
ea93df61 25 CREATE [TEMP | TEMPORARY] [UNIQUE] INDEX index-name
72aa2647 26 ON [database-name .] table-name ( column-name [, column-name]* )
27 [ ON CONFLICT conflict-algorithm ]
28
29column-name ::=
30 name [ ASC | DESC ]
31
32CREATE TABLE
33
34sql-command ::=
35 CREATE [TEMP | TEMPORARY] TABLE table-name (
36 column-def [, column-def]*
37 [, constraint]*
38 )
39
40sql-command ::=
41 CREATE [TEMP | TEMPORARY] TABLE table-name AS select-statement
42
43column-def ::=
44 name [type] [[CONSTRAINT name] column-constraint]*
45
46type ::=
47 typename |
48 typename ( number ) |
49 typename ( number , number )
50
51column-constraint ::=
52 NOT NULL [ conflict-clause ] |
53 PRIMARY KEY [sort-order] [ conflict-clause ] |
54 UNIQUE [ conflict-clause ] |
55 CHECK ( expr ) [ conflict-clause ] |
56 DEFAULT value
57
58constraint ::=
59 PRIMARY KEY ( name [, name]* ) [ conflict-clause ]|
60 UNIQUE ( name [, name]* ) [ conflict-clause ] |
61 CHECK ( expr ) [ conflict-clause ]
62
63conflict-clause ::=
64 ON CONFLICT conflict-algorithm
65
66CREATE TRIGGER
67
68sql-statement ::=
69 CREATE [TEMP | TEMPORARY] TRIGGER trigger-name [ BEFORE | AFTER ]
70 database-event ON [database-name .] table-name
71 trigger-action
72
73sql-statement ::=
74 CREATE [TEMP | TEMPORARY] TRIGGER trigger-name INSTEAD OF
75 database-event ON [database-name .] view-name
76 trigger-action
77
78database-event ::=
ea93df61 79 DELETE |
80 INSERT |
81 UPDATE |
72aa2647 82 UPDATE OF column-list
83
84trigger-action ::=
ea93df61 85 [ FOR EACH ROW | FOR EACH STATEMENT ] [ WHEN expression ]
86 BEGIN
72aa2647 87 trigger-step ; [ trigger-step ; ]*
88 END
89
90trigger-step ::=
ea93df61 91 update-statement | insert-statement |
51af147e 92 delete-statement | select-statement
72aa2647 93
94CREATE VIEW
95
96sql-command ::=
97 CREATE [TEMP | TEMPORARY] VIEW view-name AS select-statement
98
99ON CONFLICT clause
100
101 conflict-clause ::=
102 ON CONFLICT conflict-algorithm
103
104 conflict-algorithm ::=
105 ROLLBACK | ABORT | FAIL | IGNORE | REPLACE
106
107expression
108
109expr ::=
110 expr binary-op expr |
111 expr like-op expr |
112 unary-op expr |
113 ( expr ) |
114 column-name |
115 table-name . column-name |
116 database-name . table-name . column-name |
117 literal-value |
118 function-name ( expr-list | * ) |
119 expr (+) |
120 expr ISNULL |
121 expr NOTNULL |
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
127
128like-op::=
129 LIKE | GLOB | NOT LIKE | NOT GLOB
130
131=cut
132
133use strict;
f27f9229 134use warnings;
bdf60588 135
0c04c5a2 136our $VERSION = '1.59';
bdf60588 137
138our $DEBUG;
72aa2647 139$DEBUG = 0 unless defined $DEBUG;
140
141use Data::Dumper;
bdf60588 142use SQL::Translator::Utils qw/ddl_parser_instance/;
72aa2647 143
bdf60588 144use base qw(Exporter);
145our @EXPORT_OK = qw(parse);
72aa2647 146
bdf60588 147our $GRAMMAR = <<'END_OF_GRAMMAR';
72aa2647 148
ea93df61 149{
70698e1c 150 my ( %tables, $table_order, @table_comments, @views, @triggers );
95044c79 151
152 sub _err {
153 my $max_lines = 5;
154 my @up_to_N_lines = split (/\n/, $_[1], $max_lines + 1);
155 die sprintf ("Unable to parse line %d:\n%s\n",
156 $_[0],
157 join "\n", (map { "'$_'" } @up_to_N_lines[0..$max_lines - 1 ]), @up_to_N_lines > $max_lines ? '...' : ()
158 );
159 }
160
72aa2647 161}
162
163#
164# The "eofile" rule makes the parser fail if any "statement" rule
ea93df61 165# fails. Otherwise, the first successful match by a "statement"
72aa2647 166# won't cause the failure needed to know that the parse, as a whole,
167# failed. -ky
168#
ea93df61 169startrule : statement(s) eofile {
8c12c406 170 $return = {
ea93df61 171 tables => \%tables,
70698e1c 172 views => \@views,
173 triggers => \@triggers,
174 }
175}
72aa2647 176
177eofile : /^\Z/
178
179statement : begin_transaction
180 | commit
ac9c4e2e 181 | drop
72aa2647 182 | comment
183 | create
95044c79 184 | /^\Z/ | { _err ($thisline, $text) }
72aa2647 185
f9c96971 186begin_transaction : /begin/i TRANSACTION(?) SEMICOLON
72aa2647 187
188commit : /commit/i SEMICOLON
189
ae602737 190drop : /drop/i (tbl_drop | view_drop | trg_drop) SEMICOLON
191
192tbl_drop: TABLE <commit> table_name
193
194view_drop: VIEW if_exists(?) view_name
195
196trg_drop: TRIGGER if_exists(?) trigger_name
ac9c4e2e 197
72aa2647 198comment : /^\s*(?:#|-{2}).*\n/
199 {
200 my $comment = $item[1];
201 $comment =~ s/^\s*(#|-{2})\s*//;
202 $comment =~ s/\s*$//;
203 $return = $comment;
204 }
205
ea93df61 206comment : /\/\*/ /[^\*]+/ /\*\//
72aa2647 207 {
208 my $comment = $item[2];
209 $comment =~ s/^\s*|\s*$//g;
210 $return = $comment;
211 }
212
213#
214# Create Index
215#
6ceb5f1c 216create : CREATE TEMPORARY(?) UNIQUE(?) INDEX NAME ON table_name parens_field_list conflict_clause(?) SEMICOLON
72aa2647 217 {
218 my $db_name = $item[7]->{'db_name'} || '';
219 my $table_name = $item[7]->{'name'};
220
ea93df61 221 my $index = {
72aa2647 222 name => $item[5],
223 fields => $item[8],
224 on_conflict => $item[9][0],
225 is_temporary => $item[2][0] ? 1 : 0,
226 };
227
228 my $is_unique = $item[3][0];
229
230 if ( $is_unique ) {
231 $index->{'type'} = 'unique';
232 push @{ $tables{ $table_name }{'constraints'} }, $index;
233 }
234 else {
235 push @{ $tables{ $table_name }{'indices'} }, $index;
236 }
237 }
238
239#
240# Create Table
241#
242create : CREATE TEMPORARY(?) TABLE table_name '(' definition(s /,/) ')' SEMICOLON
243 {
244 my $db_name = $item[4]->{'db_name'} || '';
245 my $table_name = $item[4]->{'name'};
246
247 $tables{ $table_name }{'name'} = $table_name;
248 $tables{ $table_name }{'is_temporary'} = $item[2][0] ? 1 : 0;
249 $tables{ $table_name }{'order'} = ++$table_order;
250
251 for my $def ( @{ $item[6] } ) {
252 if ( $def->{'supertype'} eq 'column' ) {
253 push @{ $tables{ $table_name }{'fields'} }, $def;
254 }
255 elsif ( $def->{'supertype'} eq 'constraint' ) {
256 push @{ $tables{ $table_name }{'constraints'} }, $def;
257 }
258 }
259 }
260
ea93df61 261definition : constraint_def | column_def
72aa2647 262
7179cb09 263column_def: comment(s?) NAME type(?) column_constraint_def(s?)
72aa2647 264 {
265 my $column = {
266 supertype => 'column',
ae602737 267 name => $item[2],
268 data_type => $item[3][0]->{'type'},
269 size => $item[3][0]->{'size'},
72aa2647 270 is_nullable => 1,
271 is_primary_key => 0,
272 is_unique => 0,
273 check => '',
274 default => undef,
ae602737 275 constraints => $item[4],
276 comments => $item[1],
72aa2647 277 };
278
ae602737 279
280 for my $c ( @{ $item[4] } ) {
72aa2647 281 if ( $c->{'type'} eq 'not_null' ) {
282 $column->{'is_nullable'} = 0;
283 }
284 elsif ( $c->{'type'} eq 'primary_key' ) {
285 $column->{'is_primary_key'} = 1;
286 }
287 elsif ( $c->{'type'} eq 'unique' ) {
288 $column->{'is_unique'} = 1;
289 }
290 elsif ( $c->{'type'} eq 'check' ) {
291 $column->{'check'} = $c->{'expression'};
292 }
293 elsif ( $c->{'type'} eq 'default' ) {
294 $column->{'default'} = $c->{'value'};
295 }
6ceb5f1c 296 elsif ( $c->{'type'} eq 'autoincrement' ) {
297 $column->{'is_auto_inc'} = 1;
298 }
72aa2647 299 }
300
301 $column;
302 }
303
304type : WORD parens_value_list(?)
305 {
306 $return = {
307 type => $item[1],
308 size => $item[2][0],
309 }
310 }
311
7179cb09 312column_constraint_def : CONSTRAINT constraint_name column_constraint
313 {
314 $return = {
315 name => $item[2],
316 %{ $item[3] },
317 }
318 }
319 |
320 column_constraint
321
72aa2647 322column_constraint : NOT_NULL conflict_clause(?)
323 {
324 $return = {
325 type => 'not_null',
326 }
327 }
328 |
329 PRIMARY_KEY sort_order(?) conflict_clause(?)
330 {
331 $return = {
332 type => 'primary_key',
333 sort_order => $item[2][0],
ea93df61 334 on_conflict => $item[2][0],
72aa2647 335 }
336 }
337 |
338 UNIQUE conflict_clause(?)
339 {
340 $return = {
341 type => 'unique',
ea93df61 342 on_conflict => $item[2][0],
72aa2647 343 }
344 }
345 |
346 CHECK_C '(' expr ')' conflict_clause(?)
347 {
348 $return = {
349 type => 'check',
350 expression => $item[3],
ea93df61 351 on_conflict => $item[5][0],
72aa2647 352 }
353 }
354 |
355 DEFAULT VALUE
356 {
357 $return = {
358 type => 'default',
359 value => $item[2],
360 }
361 }
08e01b5c 362 |
363 REFERENCES ref_def
364 {
365 $return = {
366 type => 'foreign_key',
367 reference_table => $item[2]{'reference_table'},
368 reference_fields => $item[2]{'reference_fields'},
369 }
370 }
6ceb5f1c 371 |
372 AUTOINCREMENT
373 {
374 $return = {
375 type => 'autoincrement',
376 }
377 }
72aa2647 378
7179cb09 379constraint_def : comment(s?) CONSTRAINT constraint_name table_constraint
380 {
381 $return = {
382 comments => $item[1],
383 name => $item[3],
384 %{ $item[4] },
385 }
386 }
387 |
388 comment(s?) table_constraint
389 {
390 $return = {
391 comments => $item[1],
392 %{ $item[2] },
393 }
394 }
395
396table_constraint : PRIMARY_KEY parens_field_list conflict_clause(?)
72aa2647 397 {
398 $return = {
399 supertype => 'constraint',
400 type => 'primary_key',
401 fields => $item[2],
402 on_conflict => $item[3][0],
403 }
404 }
405 |
406 UNIQUE parens_field_list conflict_clause(?)
407 {
408 $return = {
409 supertype => 'constraint',
410 type => 'unique',
411 fields => $item[2],
412 on_conflict => $item[3][0],
413 }
414 }
415 |
416 CHECK_C '(' expr ')' conflict_clause(?)
417 {
418 $return = {
419 supertype => 'constraint',
420 type => 'check',
421 expression => $item[3],
422 on_conflict => $item[5][0],
423 }
424 }
0dbd2362 425 |
426 FOREIGN_KEY parens_field_list REFERENCES ref_def
427 {
428 $return = {
429 supertype => 'constraint',
430 type => 'foreign_key',
431 fields => $item[2],
432 reference_table => $item[4]{'reference_table'},
433 reference_fields => $item[4]{'reference_fields'},
434 }
435 }
72aa2647 436
d8cf2279 437ref_def : table_name parens_field_list
438 { $return = { reference_table => $item[1]{name}, reference_fields => $item[2] } }
08e01b5c 439
72aa2647 440table_name : qualified_name
ea93df61 441
442qualified_name : NAME
72aa2647 443 { $return = { name => $item[1] } }
444
ea93df61 445qualified_name : /(\w+)\.(\w+)/
72aa2647 446 { $return = { db_name => $1, name => $2 } }
447
448field_name : NAME
449
7179cb09 450constraint_name : NAME
451
72aa2647 452conflict_clause : /on conflict/i conflict_algorigthm
453
454conflict_algorigthm : /(rollback|abort|fail|ignore|replace)/i
455
456parens_field_list : '(' column_list ')'
457 { $item[2] }
458
459column_list : field_name(s /,/)
460
461parens_value_list : '(' VALUE(s /,/) ')'
462 { $item[2] }
463
464expr : /[^)]+/
465
466sort_order : /(ASC|DESC)/i
467
468#
469# Create Trigger
470
2661d702 471create : CREATE TEMPORARY(?) TRIGGER NAME before_or_after(?) database_event ON table_name trigger_action SEMICOLON
72aa2647 472 {
473 my $table_name = $item[8]->{'name'};
70698e1c 474 push @triggers, {
72aa2647 475 name => $item[4],
476 is_temporary => $item[2][0] ? 1 : 0,
477 when => $item[5][0],
478 instead_of => 0,
d0fcb05d 479 db_events => [ $item[6] ],
72aa2647 480 action => $item[9],
da2f5992 481 on_table => $table_name,
72aa2647 482 }
483 }
484
485create : CREATE TEMPORARY(?) TRIGGER NAME instead_of database_event ON view_name trigger_action
486 {
487 my $table_name = $item[8]->{'name'};
70698e1c 488 push @triggers, {
72aa2647 489 name => $item[4],
490 is_temporary => $item[2][0] ? 1 : 0,
491 when => undef,
492 instead_of => 1,
d0fcb05d 493 db_events => [ $item[6] ],
72aa2647 494 action => $item[9],
da2f5992 495 on_table => $table_name,
72aa2647 496 }
497 }
498
499database_event : /(delete|insert|update)/i
500
501database_event : /update of/i column_list
502
503trigger_action : for_each(?) when(?) BEGIN_C trigger_step(s) END_C
504 {
505 $return = {
506 for_each => $item[1][0],
507 when => $item[2][0],
508 steps => $item[4],
509 }
510 }
511
d0fcb05d 512for_each : /FOR EACH ROW/i
72aa2647 513
514when : WHEN expr { $item[2] }
515
9bf756df 516string :
bdf60588 517 /'(\.|''|[^\\'])*'/
9bf756df 518
519nonstring : /[^;\'"]+/
520
9644fab3 521statement_body : string | nonstring
9bf756df 522
9644fab3 523trigger_step : /(select|delete|insert|update)/i statement_body(s?) SEMICOLON
72aa2647 524 {
67a1819d 525 $return = join( ' ', $item[1], join ' ', @{ $item[2] || [] } )
ea93df61 526 }
72aa2647 527
528before_or_after : /(before|after)/i { $return = lc $1 }
529
530instead_of : /instead of/i
531
ae602737 532if_exists : /if exists/i
533
72aa2647 534view_name : qualified_name
535
ae602737 536trigger_name : qualified_name
537
72aa2647 538#
70698e1c 539# Create View
540#
ea93df61 541create : CREATE TEMPORARY(?) VIEW view_name AS select_statement
70698e1c 542 {
543 push @views, {
544 name => $item[4]->{'name'},
ea93df61 545 sql => $item[6],
70698e1c 546 is_temporary => $item[2][0] ? 1 : 0,
547 }
548 }
549
550select_statement : SELECT /[^;]+/ SEMICOLON
551 {
552 $return = join( ' ', $item[1], $item[2] );
553 }
554
555#
72aa2647 556# Tokens
557#
558BEGIN_C : /begin/i
559
560END_C : /end/i
561
f9c96971 562TRANSACTION: /transaction/i
563
72aa2647 564CREATE : /create/i
565
566TEMPORARY : /temp(orary)?/i { 1 }
567
568TABLE : /table/i
569
570INDEX : /index/i
571
572NOT_NULL : /not null/i
573
574PRIMARY_KEY : /primary key/i
575
0dbd2362 576FOREIGN_KEY : /foreign key/i
577
72aa2647 578CHECK_C : /check/i
579
580DEFAULT : /default/i
581
582TRIGGER : /trigger/i
583
70698e1c 584VIEW : /view/i
585
586SELECT : /select/i
587
72aa2647 588ON : /on/i
589
70698e1c 590AS : /as/i
591
72aa2647 592WORD : /\w+/
593
594WHEN : /when/i
595
08e01b5c 596REFERENCES : /references/i
597
7179cb09 598CONSTRAINT : /constraint/i
599
6ceb5f1c 600AUTOINCREMENT : /autoincrement/i
601
72aa2647 602UNIQUE : /unique/i { 1 }
603
604SEMICOLON : ';'
605
6ceb5f1c 606NAME : /["']?(\w+)["']?/ { $return = $1 }
72aa2647 607
70698e1c 608VALUE : /[-+]?\.?\d+(?:[eE]\d+)?/
72aa2647 609 { $item[1] }
ea93df61 610 | /'.*?'/
611 {
612 # remove leading/trailing quotes
72aa2647 613 my $val = $item[1];
614 $val =~ s/^['"]|['"]$//g;
615 $return = $val;
616 }
617 | /NULL/
618 { 'NULL' }
ac9c4e2e 619 | /CURRENT_TIMESTAMP/i
620 { 'CURRENT_TIMESTAMP' }
72aa2647 621
bdf60588 622END_OF_GRAMMAR
623
72aa2647 624
72aa2647 625sub parse {
626 my ( $translator, $data ) = @_;
bdf60588 627
628 # Enable warnings within the Parse::RecDescent module.
629 local $::RD_ERRORS = 1 unless defined $::RD_ERRORS; # Make sure the parser dies when it encounters an error
630 local $::RD_WARN = 1 unless defined $::RD_WARN; # Enable warnings. This will warn on unused rules &c.
631 local $::RD_HINT = 1 unless defined $::RD_HINT; # Give out hints to help fix problems.
72aa2647 632
633 local $::RD_TRACE = $translator->trace ? 1 : undef;
634 local $DEBUG = $translator->debug;
635
bdf60588 636 my $parser = ddl_parser_instance('SQLite');
72aa2647 637
638 my $result = $parser->startrule($data);
639 return $translator->error( "Parse failed." ) unless defined $result;
640 warn Dumper( $result ) if $DEBUG;
641
642 my $schema = $translator->schema;
ea93df61 643 my @tables =
b727fc08 644 map { $_->[1] }
ea93df61 645 sort { $a->[0] <=> $b->[0] }
b727fc08 646 map { [ $result->{'tables'}{ $_ }->{'order'}, $_ ] }
647 keys %{ $result->{'tables'} };
72aa2647 648
649 for my $table_name ( @tables ) {
70698e1c 650 my $tdata = $result->{'tables'}{ $table_name };
ea93df61 651 my $table = $schema->add_table(
72aa2647 652 name => $tdata->{'name'},
653 ) or die $schema->error;
654
655 $table->comments( $tdata->{'comments'} );
656
657 for my $fdata ( @{ $tdata->{'fields'} } ) {
658 my $field = $table->add_field(
659 name => $fdata->{'name'},
660 data_type => $fdata->{'data_type'},
661 size => $fdata->{'size'},
662 default_value => $fdata->{'default'},
663 is_auto_increment => $fdata->{'is_auto_inc'},
664 is_nullable => $fdata->{'is_nullable'},
665 comments => $fdata->{'comments'},
666 ) or die $table->error;
667
668 $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
669
670 for my $cdata ( @{ $fdata->{'constraints'} } ) {
671 next unless $cdata->{'type'} eq 'foreign_key';
672 $cdata->{'fields'} ||= [ $field->name ];
673 push @{ $tdata->{'constraints'} }, $cdata;
674 }
675 }
676
677 for my $idata ( @{ $tdata->{'indices'} || [] } ) {
678 my $index = $table->add_index(
679 name => $idata->{'name'},
56b9e6a5 680 type => uc ($idata->{'type'}||''),
72aa2647 681 fields => $idata->{'fields'},
682 ) or die $table->error;
683 }
684
685 for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
686 my $constraint = $table->add_constraint(
687 name => $cdata->{'name'},
688 type => $cdata->{'type'},
689 fields => $cdata->{'fields'},
690 reference_table => $cdata->{'reference_table'},
691 reference_fields => $cdata->{'reference_fields'},
692 match_type => $cdata->{'match_type'} || '',
ea93df61 693 on_delete => $cdata->{'on_delete'}
08e01b5c 694 || $cdata->{'on_delete_do'},
ea93df61 695 on_update => $cdata->{'on_update'}
08e01b5c 696 || $cdata->{'on_update_do'},
72aa2647 697 ) or die $table->error;
698 }
699 }
700
70698e1c 701 for my $def ( @{ $result->{'views'} || [] } ) {
702 my $view = $schema->add_view(
703 name => $def->{'name'},
704 sql => $def->{'sql'},
705 );
706 }
707
708 for my $def ( @{ $result->{'triggers'} || [] } ) {
709 my $view = $schema->add_trigger(
710 name => $def->{'name'},
711 perform_action_when => $def->{'when'},
d0fcb05d 712 database_events => $def->{'db_events'},
70698e1c 713 action => $def->{'action'},
da2f5992 714 on_table => $def->{'on_table'},
70698e1c 715 );
716 }
717
72aa2647 718 return 1;
719}
720
7211;
722
723# -------------------------------------------------------------------
724# All wholsome food is caught without a net or a trap.
725# William Blake
726# -------------------------------------------------------------------
727
728=pod
729
730=head1 AUTHOR
731
08e01b5c 732Ken Youens-Clark E<lt>kclark@cpan.orgE<gt>.
72aa2647 733
734=head1 SEE ALSO
735
736perl(1), Parse::RecDescent, SQL::Translator::Schema.
737
738=cut