Fix handling of quoted identifiers and strings in Parser::PostgreSQL
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Parser / PostgreSQL.pm
1 package SQL::Translator::Parser::PostgreSQL;
2
3 =head1 NAME
4
5 SQL::Translator::Parser::PostgreSQL - parser for PostgreSQL
6
7 =head1 SYNOPSIS
8
9   use SQL::Translator;
10   use SQL::Translator::Parser::PostgreSQL;
11
12   my $translator = SQL::Translator->new;
13   $translator->parser("SQL::Translator::Parser::PostgreSQL");
14
15 =head1 DESCRIPTION
16
17 The grammar was started from the MySQL parsers.  Here is the description
18 from PostgreSQL:
19
20 Table:
21 (http://www.postgresql.org/docs/view.php?version=7.3&idoc=1&file=sql-createtable.html)
22
23   CREATE [ [ LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (
24       { column_name data_type [ DEFAULT default_expr ]
25          [ column_constraint [, ... ] ]
26       | table_constraint }  [, ... ]
27   )
28   [ INHERITS ( parent_table [, ... ] ) ]
29   [ WITH OIDS | WITHOUT OIDS ]
30
31   where column_constraint is:
32
33   [ CONSTRAINT constraint_name ]
34   { NOT NULL | NULL | UNIQUE | PRIMARY KEY |
35     CHECK (expression) |
36     REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL ]
37       [ ON DELETE action ] [ ON UPDATE action ] }
38   [ DEFERRABLE | NOT DEFERRABLE ]
39   [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
40
41   and table_constraint is:
42
43   [ CONSTRAINT constraint_name ]
44   { UNIQUE ( column_name [, ... ] ) |
45     PRIMARY KEY ( column_name [, ... ] ) |
46     CHECK ( expression ) |
47     FOREIGN KEY ( column_name [, ... ] )
48      REFERENCES reftable [ ( refcolumn [, ... ] ) ]
49       [ MATCH FULL | MATCH PARTIAL ]
50       [ ON DELETE action ] [ ON UPDATE action ] }
51   [ DEFERRABLE | NOT DEFERRABLE ]
52   [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
53
54 Index:
55 (http://www.postgresql.org/docs/view.php?version=7.3&idoc=1&file=sql-createindex.html)
56
57   CREATE [ UNIQUE ] INDEX index_name ON table
58       [ USING acc_method ] ( column [ ops_name ] [, ...] )
59       [ WHERE predicate ]
60   CREATE [ UNIQUE ] INDEX index_name ON table
61       [ USING acc_method ] ( func_name( column [, ... ]) [ ops_name ] )
62       [ WHERE predicate ]
63
64 Alter table:
65
66   ALTER TABLE [ ONLY ] table [ * ]
67       ADD [ COLUMN ] column type [ column_constraint [ ... ] ]
68   ALTER TABLE [ ONLY ] table [ * ]
69       ALTER [ COLUMN ] column { SET DEFAULT value | DROP DEFAULT }
70   ALTER TABLE [ ONLY ] table [ * ]
71       ALTER [ COLUMN ] column SET STATISTICS integer
72   ALTER TABLE [ ONLY ] table [ * ]
73       RENAME [ COLUMN ] column TO newcolumn
74   ALTER TABLE table
75       RENAME TO new_table
76   ALTER TABLE table
77       ADD table_constraint_definition
78   ALTER TABLE [ ONLY ] table
79           DROP CONSTRAINT constraint { RESTRICT | CASCADE }
80   ALTER TABLE table
81           OWNER TO new_owner
82
83 View table:
84
85     CREATE [ OR REPLACE ] VIEW view [ ( column name list ) ] AS SELECT query
86
87 =cut
88
89 use strict;
90 use warnings;
91
92 our $VERSION = '1.59';
93
94 our $DEBUG;
95 $DEBUG   = 0 unless defined $DEBUG;
96
97 use Data::Dumper;
98 use SQL::Translator::Utils qw/ddl_parser_instance/;
99
100 use base qw(Exporter);
101 our @EXPORT_OK = qw(parse);
102
103 our $GRAMMAR = <<'END_OF_GRAMMAR';
104
105 { my ( %tables, @views, @triggers, $table_order, $field_order, @table_comments) }
106
107 #
108 # The "eofile" rule makes the parser fail if any "statement" rule
109 # fails.  Otherwise, the first successful match by a "statement"
110 # won't cause the failure needed to know that the parse, as a whole,
111 # failed. -ky
112 #
113 startrule : statement(s) eofile {
114     {
115         tables => \%tables,
116         views => \@views,
117         triggers => \@triggers,
118     }
119 }
120
121 eofile : /^\Z/
122
123 statement : create
124   | comment_on_table
125   | comment_on_column
126   | comment_on_other
127   | comment
128   | alter
129   | grant
130   | revoke
131   | drop
132   | insert
133   | connect
134   | update
135   | set
136   | select
137   | copy
138   | readin_symbol
139   | commit
140   | <error>
141
142 commit : /commit/i ';'
143
144 connect : /^\s*\\connect.*\n/
145
146 set : /set/i /[^;]*/ ';'
147
148 revoke : /revoke/i WORD(s /,/) /on/i TABLE(?) table_id /from/i NAME(s /,/) ';'
149     {
150         my $table_info  = $item{'table_id'};
151         my $schema_name = $table_info->{'schema_name'};
152         my $table_name  = $table_info->{'table_name'};
153         push @{ $tables{ $table_name }{'permissions'} }, {
154             type       => 'revoke',
155             actions    => $item[2],
156             users      => $item[7],
157         }
158     }
159
160 revoke : /revoke/i WORD(s /,/) /on/i SCHEMA(?) schema_name /from/i NAME(s /,/) ';'
161     { 1 }
162
163 grant : /grant/i WORD(s /,/) /on/i TABLE(?) table_id /to/i NAME(s /,/) ';'
164     {
165         my $table_info  = $item{'table_id'};
166         my $schema_name = $table_info->{'schema_name'};
167         my $table_name  = $table_info->{'table_name'};
168         push @{ $tables{ $table_name }{'permissions'} }, {
169             type       => 'grant',
170             actions    => $item[2],
171             users      => $item[7],
172         }
173     }
174
175 grant : /grant/i WORD(s /,/) /on/i SCHEMA(?) schema_name /to/i NAME(s /,/) ';'
176     { 1 }
177
178 drop : /drop/i /[^;]*/ ';'
179
180 string :
181    /'(\.|''|[^\\'])*'/
182
183 nonstring : /[^;\'"]+/
184
185 statement_body : string | nonstring
186
187 insert : /insert/i statement_body(s?) ';'
188
189 update : /update/i statement_body(s?) ';'
190
191 #
192 # Create table.
193 #
194 create : CREATE temporary(?) TABLE table_id '(' create_definition(s? /,/) ')' table_option(s?) ';'
195     {
196         my $table_info  = $item{'table_id'};
197         my $schema_name = $table_info->{'schema_name'};
198         my $table_name  = $table_info->{'table_name'};
199         $tables{ $table_name }{'order'}       = ++$table_order;
200         $tables{ $table_name }{'schema_name'} = $schema_name;
201         $tables{ $table_name }{'table_name'}  = $table_name;
202
203         $tables{ $table_name }{'temporary'} = $item[2][0];
204
205         if ( @table_comments ) {
206             $tables{ $table_name }{'comments'} = [ @table_comments ];
207             @table_comments = ();
208         }
209
210         my @constraints;
211         for my $definition ( @{ $item[6] } ) {
212             if ( $definition->{'supertype'} eq 'field' ) {
213                 my $field_name = $definition->{'name'};
214                 $tables{ $table_name }{'fields'}{ $field_name } =
215                     { %$definition, order => $field_order++ };
216
217                 for my $constraint ( @{ $definition->{'constraints'} || [] } ) {
218                     $constraint->{'fields'} = [ $field_name ];
219                     push @{ $tables{ $table_name }{'constraints'} },
220                         $constraint;
221                 }
222             }
223             elsif ( $definition->{'supertype'} eq 'constraint' ) {
224                 push @{ $tables{ $table_name }{'constraints'} }, $definition;
225             }
226             elsif ( $definition->{'supertype'} eq 'index' ) {
227                 push @{ $tables{ $table_name }{'indices'} }, $definition;
228             }
229         }
230
231         for my $option ( @{ $item[8] } ) {
232             $tables{ $table_name }{'table_options(s?)'}{ $option->{'type'} } =
233                 $option;
234         }
235
236         1;
237     }
238
239 create : CREATE unique(?) /(index|key)/i index_name /on/i table_id using_method(?) '(' field_name(s /,/) ')' where_predicate(?) ';'
240     {
241         my $table_info  = $item{'table_id'};
242         my $schema_name = $table_info->{'schema_name'};
243         my $table_name  = $table_info->{'table_name'};
244         push @{ $tables{ $table_name }{'indices'} },
245             {
246                 name      => $item{'index_name'},
247                 supertype => $item{'unique'}[0] ? 'constraint' : 'index',
248                 type      => $item{'unique'}[0] ? 'unique'     : 'normal',
249                 fields    => $item[9],
250                 method    => $item{'using_method'}[0],
251             }
252         ;
253     }
254
255 create : CREATE or_replace(?) temporary(?) VIEW view_id view_fields(?) /AS/i view_target ';'
256     {
257         push @views, {
258             schema_name  => $item{view_id}{schema_name},
259             view_name    => $item{view_id}{view_name},
260             sql          => $item{view_target},
261             fields       => $item[6],
262             is_temporary => $item[3][0],
263         }
264     }
265
266 trigger_name : NAME
267
268 trigger_scope : /FOR/i /EACH/i /(ROW|STATEMENT)/i { $return = lc $1 }
269
270 before_or_after : /(before|after)/i { $return = lc $1 }
271
272 trigger_action : /.+/
273
274 database_event : /insert|update|delete/i
275 database_events : database_event(s /OR/)
276
277 create : CREATE /TRIGGER/i trigger_name before_or_after database_events /ON/i table_id trigger_scope(?) trigger_action
278     {
279         # Hack to pass roundtrip tests which have trigger statements terminated by double semicolon
280         # and expect the returned data to have the same
281         my $action = $item{trigger_action};
282         $action =~ s/;$//;
283
284         push @triggers, {
285             name => $item{trigger_name},
286             perform_action_when => $item{before_or_after},
287             database_events => $item{database_events},
288             on_table => $item{table_id}{table_name},
289             scope => $item{'trigger_scope(?)'}[0],
290             action => $action,
291         }
292     }
293
294 #
295 # Create anything else (e.g., domain, etc.)
296 #
297 create : CREATE WORD /[^;]+/ ';'
298     { @table_comments = (); }
299
300 using_method : /using/i WORD { $item[2] }
301
302 where_predicate : /where/i /[^;]+/
303
304 create_definition : field
305     | table_constraint
306     | <error>
307
308 comment : /^\s*(?:#|-{2})(.*)\n/
309     {
310         my $comment =  $item[1];
311         $comment    =~ s/^\s*(#|-*)\s*//;
312         $comment    =~ s/\s*$//;
313         $return     = $comment;
314         push @table_comments, $comment;
315     }
316
317 comment_on_table : /comment/i /on/i /table/i table_id /is/i comment_phrase ';'
318     {
319         my $table_info  = $item{'table_id'};
320         my $schema_name = $table_info->{'schema_name'};
321         my $table_name  = $table_info->{'table_name'};
322         push @{ $tables{ $table_name }{'comments'} }, $item{'comment_phrase'};
323     }
324
325 comment_on_column : /comment/i /on/i /column/i column_name /is/i comment_phrase ';'
326     {
327         my $table_name = $item[4]->{'table'};
328         my $field_name = $item[4]->{'field'};
329         if ($tables{ $table_name }{'fields'}{ $field_name } ) {
330           push @{ $tables{ $table_name }{'fields'}{ $field_name }{'comments'} },
331               $item{'comment_phrase'};
332         }
333         else {
334            die "No such column as $table_name.$field_name";
335         }
336     }
337
338 comment_on_other : /comment/i /on/i /\w+/ /\w+/ /is/i comment_phrase ';'
339     {
340         push(@table_comments, $item{'comment_phrase'});
341     }
342
343 # [added by cjm 20041019]
344 # [TODO: other comment-on types]
345 # for now we just have a general mechanism for handling other
346 # kinds of comments than table/column; I'm not sure of the best
347 # way to incorporate these into the datamodel
348 #
349 # this is the exhaustive list of types of comment:
350 #COMMENT ON DATABASE my_database IS 'Development Database';
351 #COMMENT ON INDEX my_index IS 'Enforces uniqueness on employee id';
352 #COMMENT ON RULE my_rule IS 'Logs UPDATES of employee records';
353 #COMMENT ON SEQUENCE my_sequence IS 'Used to generate primary keys';
354 #COMMENT ON TABLE my_table IS 'Employee Information';
355 #COMMENT ON TYPE my_type IS 'Complex Number support';
356 #COMMENT ON VIEW my_view IS 'View of departmental costs';
357 #COMMENT ON COLUMN my_table.my_field IS 'Employee ID number';
358 #COMMENT ON TRIGGER my_trigger ON my_table IS 'Used for R.I.';
359 #
360 # this is tested by test 08
361
362 column_name : NAME '.' NAME
363     { $return = { table => $item[1], field => $item[3] } }
364
365 comment_phrase : /null/i
366     { $return = 'NULL' }
367     | SQSTRING
368
369 field : field_comment(s?) field_name data_type field_meta(s?) field_comment(s?)
370     {
371         my ( $default, @constraints, $is_pk );
372         my $is_nullable = 1;
373         for my $meta ( @{ $item[4] } ) {
374             if ( $meta->{'type'} eq 'default' ) {
375                 $default = $meta;
376                 next;
377             }
378             elsif ( $meta->{'type'} eq 'not_null' ) {
379                 $is_nullable = 0;
380             }
381             elsif ( $meta->{'type'} eq 'primary_key' ) {
382                 $is_pk = 1;
383             }
384
385             push @constraints, $meta if $meta->{'supertype'} eq 'constraint';
386         }
387
388         my @comments = ( @{ $item[1] }, @{ $item[5] } );
389
390         $return = {
391             supertype         => 'field',
392             name              => $item{'field_name'},
393             data_type         => $item{'data_type'}{'type'},
394             size              => $item{'data_type'}{'size'},
395             is_nullable       => $is_nullable,
396             default           => $default->{'value'},
397             constraints       => [ @constraints ],
398             comments          => [ @comments ],
399             is_primary_key    => $is_pk || 0,
400             is_auto_increment => $item{'data_type'}{'is_auto_increment'},
401         }
402     }
403     | <error>
404
405 field_comment : /^\s*(?:#|-{2})(.*)\n/
406     {
407         my $comment =  $item[1];
408         $comment    =~ s/^\s*(#|-*)\s*//;
409         $comment    =~ s/\s*$//;
410         $return     = $comment;
411     }
412
413 field_meta : default_val
414     | column_constraint
415
416 view_fields : '(' field_name(s /,/) ')'
417     { $return = join (',', @{$item[2]} ) }
418
419 column_constraint : constraint_name(?) column_constraint_type deferrable(?) deferred(?)
420     {
421         my $desc       = $item{'column_constraint_type'};
422         my $type       = $desc->{'type'};
423         my $fields     = $desc->{'fields'}     || [];
424         my $expression = $desc->{'expression'} || '';
425
426         $return              =  {
427             supertype        => 'constraint',
428             name             => $item{'constraint_name'}[0] || '',
429             type             => $type,
430             expression       => $type eq 'check' ? $expression : '',
431             deferrable       => $item{'deferrable'},
432             deferred         => $item{'deferred'},
433             reference_table  => $desc->{'reference_table'},
434             reference_fields => $desc->{'reference_fields'},
435             match_type       => $desc->{'match_type'},
436             on_delete        => $desc->{'on_delete'} || $desc->{'on_delete_do'},
437             on_update        => $desc->{'on_update'} || $desc->{'on_update_do'},
438         }
439     }
440
441 constraint_name : /constraint/i NAME { $item[2] }
442
443 column_constraint_type : /not null/i { $return = { type => 'not_null' } }
444     |
445     /null/i
446         { $return = { type => 'null' } }
447     |
448     /unique/i
449         { $return = { type => 'unique' } }
450     |
451     /primary key/i
452         { $return = { type => 'primary_key' } }
453     |
454     /check/i '(' /[^)]+/ ')'
455         { $return = { type => 'check', expression => $item[3] } }
456     |
457     /references/i table_id parens_word_list(?) match_type(?) key_action(s?)
458     {
459         my $table_info  = $item{'table_id'};
460         my $schema_name = $table_info->{'schema_name'};
461         my $table_name  = $table_info->{'table_name'};
462         my ( $on_delete, $on_update );
463         for my $action ( @{ $item[5] || [] } ) {
464             $on_delete = $action->{'action'} if $action->{'type'} eq 'delete';
465             $on_update = $action->{'action'} if $action->{'type'} eq 'update';
466         }
467
468         $return              =  {
469             type             => 'foreign_key',
470             reference_table  => $table_name,
471             reference_fields => $item[3][0],
472             match_type       => $item[4][0],
473             on_delete        => $on_delete,
474             on_update        => $on_update,
475         }
476     }
477
478 table_id : schema_qualification(?) NAME {
479     $return = { schema_name => $item[1][0], table_name => $item[2] }
480 }
481
482 view_id : schema_qualification(?) NAME {
483     $return = { schema_name => $item[1][0], view_name => $item[2] }
484 }
485
486 view_target : /select|with/i /[^;]+/ {
487     $return = "$item[1] $item[2]";
488 }
489
490 # SELECT views _may_ support outer parens, and we used to produce
491 # such sql, although non-standard. Use ugly lookeahead to parse
492 view_target : '('   /select/i    / [^;]+ (?= \) ) /x    ')'    {
493     $return = "$item[2] $item[3]"
494 }
495
496 view_target_spec :
497
498 schema_qualification : NAME '.'
499
500 schema_name : NAME
501
502 field_name : NAME
503
504 double_quote: /"/
505
506 index_name : NAME
507
508
509 data_type : pg_data_type parens_value_list(?)
510     {
511         my $data_type = $item[1];
512
513         #
514         # We can deduce some sizes from the data type's name.
515         #
516         if ( my $size = $item[2][0] ) {
517             $data_type->{'size'} = $size;
518         }
519
520         $return  = $data_type;
521     }
522
523 pg_data_type :
524     /(bigint|int8)/i
525         {
526             $return = {
527                 type => 'integer',
528                 size => 20,
529             };
530         }
531     |
532     /(smallint|int2)/i
533         {
534             $return = {
535                 type => 'integer',
536                 size => 5,
537             };
538         }
539     |
540     /interval/i
541         {
542             $return = { type => 'interval' };
543         }
544     |
545     /(integer|int4?)/i # interval must come before this
546         {
547             $return = {
548                 type => 'integer',
549                 size => 10,
550             };
551         }
552     |
553     /(real|float4)/i
554         {
555             $return = {
556                 type => 'real',
557                 size => 10,
558             };
559         }
560     |
561     /(double precision|float8?)/i
562         {
563             $return = {
564                 type => 'float',
565                 size => 20,
566             };
567         }
568     |
569     /(bigserial|serial8)/i
570         {
571             $return = {
572                 type              => 'integer',
573                 size              => 20,
574                 is_auto_increment => 1,
575             };
576         }
577     |
578     /serial4?/i
579         {
580             $return = {
581                 type              => 'integer',
582                 size              => 11,
583                 is_auto_increment => 1,
584             };
585         }
586     |
587     /(bit varying|varbit)/i
588         {
589             $return = { type => 'varbit' };
590         }
591     |
592     /character varying/i
593         {
594             $return = { type => 'varchar' };
595         }
596     |
597     /char(acter)?/i
598         {
599             $return = { type => 'char' };
600         }
601     |
602     /bool(ean)?/i
603         {
604             $return = { type => 'boolean' };
605         }
606     |
607     /bytea/i
608         {
609             $return = { type => 'bytea' };
610         }
611     |
612     /(timestamptz|timestamp)(?:\(\d\))?( with(?:out)? time zone)?/i
613         {
614             $return = { type => 'timestamp' . ($2||'') };
615         }
616     |
617     /text/i
618         {
619             $return = {
620                 type => 'text',
621                 size => 64_000,
622             };
623         }
624     |
625     /(bit|box|cidr|circle|date|inet|line|lseg|macaddr|money|numeric|decimal|path|point|polygon|timetz|time|varchar|json|hstore)/i
626         {
627             $return = { type => $item[1] };
628         }
629
630 parens_value_list : '(' VALUE(s /,/) ')'
631     { $item[2] }
632
633
634 parens_word_list : '(' NAME(s /,/) ')'
635     { $item[2] }
636
637 field_size : '(' num_range ')' { $item{'num_range'} }
638
639 num_range : DIGITS ',' DIGITS
640     { $return = $item[1].','.$item[3] }
641     | DIGITS
642     { $return = $item[1] }
643
644 table_constraint : comment(s?) constraint_name(?) table_constraint_type deferrable(?) deferred(?) comment(s?)
645     {
646         my $desc       = $item{'table_constraint_type'};
647         my $type       = $desc->{'type'};
648         my $fields     = $desc->{'fields'};
649         my $expression = $desc->{'expression'};
650         my @comments   = ( @{ $item[1] }, @{ $item[-1] } );
651
652         $return              =  {
653             name             => $item[2][0] || '',
654             supertype        => 'constraint',
655             type             => $type,
656             fields           => $type ne 'check' ? $fields : [],
657             expression       => $type eq 'check' ? $expression : '',
658             deferrable       => $item{'deferrable'},
659             deferred         => $item{'deferred'},
660             reference_table  => $desc->{'reference_table'},
661             reference_fields => $desc->{'reference_fields'},
662             match_type       => $desc->{'match_type'},
663             on_delete        => $desc->{'on_delete'} || $desc->{'on_delete_do'},
664             on_update        => $desc->{'on_update'} || $desc->{'on_update_do'},
665             comments         => [ @comments ],
666         }
667     }
668
669 table_constraint_type : /primary key/i '(' NAME(s /,/) ')'
670     {
671         $return = {
672             type   => 'primary_key',
673             fields => $item[3],
674         }
675     }
676     |
677     /unique/i '(' NAME(s /,/) ')'
678     {
679         $return    =  {
680             type   => 'unique',
681             fields => $item[3],
682         }
683     }
684     |
685     /check/i '(' /[^)]+/ ')'
686     {
687         $return        =  {
688             type       => 'check',
689             expression => $item[3],
690         }
691     }
692     |
693     /foreign key/i '(' NAME(s /,/) ')' /references/i table_id parens_word_list(?) match_type(?) key_action(s?)
694     {
695         my ( $on_delete, $on_update );
696         for my $action ( @{ $item[9] || [] } ) {
697             $on_delete = $action->{'action'} if $action->{'type'} eq 'delete';
698             $on_update = $action->{'action'} if $action->{'type'} eq 'update';
699         }
700
701         $return              =  {
702             supertype        => 'constraint',
703             type             => 'foreign_key',
704             fields           => $item[3],
705             reference_table  => $item[6]->{'table_name'},
706             reference_fields => $item[7][0],
707             match_type       => $item[8][0],
708             on_delete     => $on_delete || '',
709             on_update     => $on_update || '',
710         }
711     }
712
713 deferrable : not(?) /deferrable/i
714     {
715         $return = ( $item[1] =~ /not/i ) ? 0 : 1;
716     }
717
718 deferred : /initially/i /(deferred|immediate)/i { $item[2] }
719
720 match_type : /match/i /partial|full|simple/i { $item[2] }
721
722 key_action : key_delete
723     |
724     key_update
725
726 key_delete : /on delete/i key_mutation
727     {
728         $return = {
729             type   => 'delete',
730             action => $item[2],
731         };
732     }
733
734 key_update : /on update/i key_mutation
735     {
736         $return = {
737             type   => 'update',
738             action => $item[2],
739         };
740     }
741
742 key_mutation : /no action/i { $return = 'no_action' }
743     |
744     /restrict/i { $return = 'restrict' }
745     |
746     /cascade/i { $return = 'cascade' }
747     |
748     /set null/i { $return = 'set null' }
749     |
750     /set default/i { $return = 'set default' }
751
752 alter : alter_table table_id add_column field ';'
753     {
754         my $field_def = $item[4];
755         $tables{ $item[2]->{'table_name'} }{'fields'}{ $field_def->{'name'} } = {
756             %$field_def, order => $field_order++
757         };
758         1;
759     }
760
761 alter : alter_table table_id ADD table_constraint ';'
762     {
763         my $table_name = $item[2]->{'table_name'};
764         my $constraint = $item[4];
765         push @{ $tables{ $table_name }{'constraints'} }, $constraint;
766         1;
767     }
768
769 alter : alter_table table_id drop_column NAME restrict_or_cascade(?) ';'
770     {
771         $tables{ $item[2]->{'table_name'} }{'fields'}{ $item[4] }{'drop'} = 1;
772         1;
773     }
774
775 alter : alter_table table_id alter_column NAME alter_default_val ';'
776     {
777         $tables{ $item[2]->{'table_name'} }{'fields'}{ $item[4] }{'default'} =
778             $item[5]->{'value'};
779         1;
780     }
781
782 #
783 # These will just parse for now but won't affect the structure. - ky
784 #
785 alter : alter_table table_id /rename/i /to/i NAME ';'
786     { 1 }
787
788 alter : alter_table table_id alter_column NAME SET /statistics/i INTEGER ';'
789     { 1 }
790
791 alter : alter_table table_id alter_column NAME SET /storage/i storage_type ';'
792     { 1 }
793
794 alter : alter_table table_id rename_column NAME /to/i NAME ';'
795     { 1 }
796
797 alter : alter_table table_id DROP /constraint/i NAME restrict_or_cascade ';'
798     { 1 }
799
800 alter : alter_table table_id /owner/i /to/i NAME ';'
801     { 1 }
802
803 alter : alter_sequence NAME /owned/i /by/i column_name ';'
804     { 1 }
805
806 storage_type : /(plain|external|extended|main)/i
807
808 temporary : /temp(orary)?\b/i
809   {
810     1;
811   }
812
813 or_replace : /or replace/i
814
815 alter_default_val : SET default_val
816     {
817         $return = { value => $item[2]->{'value'} }
818     }
819     | DROP DEFAULT
820     {
821         $return = { value => undef }
822     }
823
824 #
825 # This is a little tricky to get right, at least WRT to making the
826 # tests pass.  The problem is that the constraints are stored just as
827 # a list (no name access), and the tests expect the constraints in a
828 # particular order.  I'm going to leave the rule but disable the code
829 # for now. - ky
830 #
831 alter : alter_table table_id alter_column NAME alter_nullable ';'
832     {
833 #        my $table_name  = $item[2]->{'table_name'};
834 #        my $field_name  = $item[4];
835 #        my $is_nullable = $item[5]->{'is_nullable'};
836 #
837 #        $tables{ $table_name }{'fields'}{ $field_name }{'is_nullable'} =
838 #            $is_nullable;
839 #
840 #        if ( $is_nullable ) {
841 #            1;
842 #            push @{ $tables{ $table_name }{'constraints'} }, {
843 #                type   => 'not_null',
844 #                fields => [ $field_name ],
845 #            };
846 #        }
847 #        else {
848 #            for my $i (
849 #                0 .. $#{ $tables{ $table_name }{'constraints'} || [] }
850 #            ) {
851 #                my $c = $tables{ $table_name }{'constraints'}[ $i ] or next;
852 #                my $fields = join( '', @{ $c->{'fields'} || [] } ) or next;
853 #                if ( $c->{'type'} eq 'not_null' && $fields eq $field_name ) {
854 #                    delete $tables{ $table_name }{'constraints'}[ $i ];
855 #                    last;
856 #                }
857 #            }
858 #        }
859
860         1;
861     }
862
863 alter_nullable : SET not_null
864     {
865         $return = { is_nullable => 0 }
866     }
867     | DROP not_null
868     {
869         $return = { is_nullable => 1 }
870     }
871
872 not_null : /not/i /null/i
873
874 not : /not/i
875
876 add_column : ADD COLUMN(?)
877
878 alter_table : ALTER TABLE ONLY(?)
879
880 alter_sequence : ALTER SEQUENCE
881
882 drop_column : DROP COLUMN(?)
883
884 alter_column : ALTER COLUMN(?)
885
886 rename_column : /rename/i COLUMN(?)
887
888 restrict_or_cascade : /restrict/i |
889     /cascade/i
890
891 # Handle functions that can be called
892 select : SELECT select_function ';'
893     { 1 }
894
895 # Read the setval function but don't do anything with it because this parser
896 # isn't handling sequences
897 select_function : schema_qualification(?) /setval/i '(' VALUE /,/ VALUE /,/ /(true|false)/i ')'
898     { 1 }
899
900 # Skipping all COPY commands
901 copy : COPY WORD /[^;]+/ ';' { 1 }
902     { 1 }
903
904 # The "\." allows reading in from STDIN but this isn't needed for schema
905 # creation, so it is skipped.
906 readin_symbol : '\.'
907     {1}
908
909 #
910 # End basically useless stuff. - ky
911 #
912
913 create_table : CREATE TABLE
914
915 create_index : CREATE /index/i
916
917 default_val  : DEFAULT DEFAULT_VALUE ( '::' data_type )(?)
918     {
919         my $val =  $item[2];
920         $val =~ s/^\((\d+)\)\z/$1/; # for example (0)::smallint
921         $return =  {
922             supertype => 'constraint',
923             type      => 'default',
924             value     => $val,
925         }
926     }
927     | /null/i
928     {
929         $return =  {
930             supertype => 'constraint',
931             type      => 'default',
932             value     => 'NULL',
933         }
934     }
935
936 DEFAULT_VALUE : VALUE
937     | /\w+\(.*\)/
938     | /\w+/
939     | /\(\d+\)/
940
941 name_with_opt_paren : NAME parens_value_list(s?)
942     { $item[2][0] ? "$item[1]($item[2][0][0])" : $item[1] }
943
944 unique : /unique/i { 1 }
945
946 key : /key/i | /index/i
947
948 table_option : /inherits/i '(' NAME(s /,/) ')'
949     {
950         $return = { type => 'inherits', table_name => $item[3] }
951     }
952     |
953     /with(out)? oids/i
954     {
955         $return = { type => $item[1] =~ /out/i ? 'without_oids' : 'with_oids' }
956     }
957
958 ADD : /add/i
959
960 ALTER : /alter/i
961
962 CREATE : /create/i
963
964 ONLY : /only/i
965
966 DEFAULT : /default/i
967
968 DROP : /drop/i
969
970 COLUMN : /column/i
971
972 TABLE : /table/i
973
974 VIEW : /view/i
975
976 SCHEMA : /schema/i
977
978 SEMICOLON : /\s*;\n?/
979
980 SEQUENCE : /sequence/i
981
982 SELECT : /select/i
983
984 COPY : /copy/i
985
986 INTEGER : /\d+/
987
988 WORD : /\w+/
989
990 DIGITS : /\d+/
991
992 COMMA : ','
993
994 SET : /set/i
995
996 NAME : DQSTRING
997     | /\w+/
998
999 DQSTRING : '"' /((?:[^"]|"")+)/ '"'
1000     { ($return = $item[2]) =~ s/""/"/g; }
1001
1002 SQSTRING : "'" /((?:[^']|'')*)/ "'"
1003     { ($return = $item[2]) =~ s/''/'/g }
1004
1005 VALUE : /[-+]?\d*\.?\d+(?:[eE]\d+)?/
1006     | SQSTRING
1007     | /null/i
1008     { 'NULL' }
1009
1010 END_OF_GRAMMAR
1011
1012 sub parse {
1013     my ( $translator, $data ) = @_;
1014
1015     # Enable warnings within the Parse::RecDescent module.
1016     local $::RD_ERRORS = 1 unless defined $::RD_ERRORS; # Make sure the parser dies when it encounters an error
1017     local $::RD_WARN   = 1 unless defined $::RD_WARN; # Enable warnings. This will warn on unused rules &c.
1018     local $::RD_HINT   = 1 unless defined $::RD_HINT; # Give out hints to help fix problems.
1019
1020     local $::RD_TRACE  = $translator->trace ? 1 : undef;
1021     local $DEBUG       = $translator->debug;
1022
1023     my $parser = ddl_parser_instance('PostgreSQL');
1024
1025     my $result = $parser->startrule($data);
1026     die "Parse failed.\n" unless defined $result;
1027     warn Dumper($result) if $DEBUG;
1028
1029     my $schema = $translator->schema;
1030     my @tables = sort {
1031         ( $result->{tables}{ $a }{'order'} || 0 ) <=> ( $result->{tables}{ $b }{'order'} || 0 )
1032     } keys %{ $result->{tables} };
1033
1034     for my $table_name ( @tables ) {
1035         my $tdata =  $result->{tables}{ $table_name };
1036         my $table =  $schema->add_table(
1037             #schema => $tdata->{'schema_name'},
1038             name   => $tdata->{'table_name'},
1039         ) or die "Couldn't create table '$table_name': " . $schema->error;
1040
1041         $table->extra(temporary => 1) if $tdata->{'temporary'};
1042
1043         $table->comments( $tdata->{'comments'} );
1044
1045         my @fields = sort {
1046             $tdata->{'fields'}{ $a }{'order'}
1047             <=>
1048             $tdata->{'fields'}{ $b }{'order'}
1049         } keys %{ $tdata->{'fields'} };
1050
1051         for my $fname ( @fields ) {
1052             my $fdata = $tdata->{'fields'}{ $fname };
1053             next if $fdata->{'drop'};
1054             my $field = $table->add_field(
1055                 name              => $fdata->{'name'},
1056                 data_type         => $fdata->{'data_type'},
1057                 size              => $fdata->{'size'},
1058                 default_value     => $fdata->{'default'},
1059                 is_auto_increment => $fdata->{'is_auto_increment'},
1060                 is_nullable       => $fdata->{'is_nullable'},
1061                 comments          => $fdata->{'comments'},
1062             ) or die $table->error;
1063
1064             $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
1065
1066             for my $cdata ( @{ $fdata->{'constraints'} } ) {
1067                 next unless $cdata->{'type'} eq 'foreign_key';
1068                 $cdata->{'fields'} ||= [ $field->name ];
1069                 push @{ $tdata->{'constraints'} }, $cdata;
1070             }
1071         }
1072
1073         for my $idata ( @{ $tdata->{'indices'} || [] } ) {
1074             my $index  =  $table->add_index(
1075                 name   => $idata->{'name'},
1076                 type   => uc $idata->{'type'},
1077                 fields => $idata->{'fields'},
1078             ) or die $table->error . ' ' . $table->name;
1079         }
1080
1081         for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
1082             my $constraint       =  $table->add_constraint(
1083                 name             => $cdata->{'name'},
1084                 type             => $cdata->{'type'},
1085                 fields           => $cdata->{'fields'},
1086                 reference_table  => $cdata->{'reference_table'},
1087                 reference_fields => $cdata->{'reference_fields'},
1088                 match_type       => $cdata->{'match_type'} || '',
1089                 on_delete        => $cdata->{'on_delete'} || $cdata->{'on_delete_do'},
1090                 on_update        => $cdata->{'on_update'} || $cdata->{'on_update_do'},
1091                 expression       => $cdata->{'expression'},
1092             ) or die "Can't add constraint of type '" .
1093                 $cdata->{'type'} .  "' to table '" . $table->name .
1094                 "': " . $table->error;
1095         }
1096     }
1097
1098     for my $vinfo (@{$result->{views}}) {
1099       my $sql = $vinfo->{sql};
1100       $sql =~ s/\A\s+|\s+\z//g;
1101       my $view = $schema->add_view (
1102         name => $vinfo->{view_name},
1103         sql => $sql,
1104         fields => $vinfo->{fields},
1105       );
1106
1107       $view->extra ( temporary => 1 ) if $vinfo->{is_temporary};
1108     }
1109
1110     for my $trigger (@{ $result->{triggers} }) {
1111         $schema->add_trigger( %$trigger );
1112     }
1113
1114     return 1;
1115 }
1116
1117 1;
1118
1119 # -------------------------------------------------------------------
1120 # Rescue the drowning and tie your shoestrings.
1121 # Henry David Thoreau
1122 # -------------------------------------------------------------------
1123
1124 =pod
1125
1126 =head1 AUTHORS
1127
1128 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>,
1129 Allen Day E<lt>allenday@ucla.eduE<gt>.
1130
1131 =head1 SEE ALSO
1132
1133 perl(1), Parse::RecDescent.
1134
1135 =cut