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