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