4d53c3b44fe2123627458dac841dd4fe14b66f89
[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_with_opt_quotes(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_with_opt_quotes(s /,/) ';'
161     { 1 }
162
163 grant : /grant/i WORD(s /,/) /on/i TABLE(?) table_id /to/i name_with_opt_quotes(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_with_opt_quotes(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_with_opt_quotes
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
368 comment_phrase : /'/ comment_phrase_unquoted(s) /'/
369     { my $phrase = join(' ', @{ $item[2] });
370       $return = $phrase}
371
372 # [cjm TODO: double-single quotes in a comment_phrase]
373 comment_phrase_unquoted : /[^\']*/
374     { $return = $item[1] }
375
376
377 xxxcomment_phrase : /'.*?'|NULL/
378     {
379         my $val = $item[1] || '';
380         $val =~ s/^'|'$//g;
381         $return = $val;
382     }
383
384 field : field_comment(s?) field_name data_type field_meta(s?) field_comment(s?)
385     {
386         my ( $default, @constraints, $is_pk );
387         my $is_nullable = 1;
388         for my $meta ( @{ $item[4] } ) {
389             if ( $meta->{'type'} eq 'default' ) {
390                 $default = $meta;
391                 next;
392             }
393             elsif ( $meta->{'type'} eq 'not_null' ) {
394                 $is_nullable = 0;
395             }
396             elsif ( $meta->{'type'} eq 'primary_key' ) {
397                 $is_pk = 1;
398             }
399
400             push @constraints, $meta if $meta->{'supertype'} eq 'constraint';
401         }
402
403         my @comments = ( @{ $item[1] }, @{ $item[5] } );
404
405         $return = {
406             supertype         => 'field',
407             name              => $item{'field_name'},
408             data_type         => $item{'data_type'}{'type'},
409             size              => $item{'data_type'}{'size'},
410             is_nullable       => $is_nullable,
411             default           => $default->{'value'},
412             constraints       => [ @constraints ],
413             comments          => [ @comments ],
414             is_primary_key    => $is_pk || 0,
415             is_auto_increment => $item{'data_type'}{'is_auto_increment'},
416         }
417     }
418     | <error>
419
420 field_comment : /^\s*(?:#|-{2})(.*)\n/
421     {
422         my $comment =  $item[1];
423         $comment    =~ s/^\s*(#|-*)\s*//;
424         $comment    =~ s/\s*$//;
425         $return     = $comment;
426     }
427
428 field_meta : default_val
429     | column_constraint
430
431 view_fields : '(' field_name(s /,/) ')'
432     { $return = join (',', @{$item[2]} ) }
433
434 column_constraint : constraint_name(?) column_constraint_type deferrable(?) deferred(?)
435     {
436         my $desc       = $item{'column_constraint_type'};
437         my $type       = $desc->{'type'};
438         my $fields     = $desc->{'fields'}     || [];
439         my $expression = $desc->{'expression'} || '';
440
441         $return              =  {
442             supertype        => 'constraint',
443             name             => $item{'constraint_name'}[0] || '',
444             type             => $type,
445             expression       => $type eq 'check' ? $expression : '',
446             deferrable       => $item{'deferrable'},
447             deferred         => $item{'deferred'},
448             reference_table  => $desc->{'reference_table'},
449             reference_fields => $desc->{'reference_fields'},
450             match_type       => $desc->{'match_type'},
451             on_delete        => $desc->{'on_delete'} || $desc->{'on_delete_do'},
452             on_update        => $desc->{'on_update'} || $desc->{'on_update_do'},
453         }
454     }
455
456 constraint_name : /constraint/i name_with_opt_quotes { $item[2] }
457
458 column_constraint_type : /not null/i { $return = { type => 'not_null' } }
459     |
460     /null/i
461         { $return = { type => 'null' } }
462     |
463     /unique/i
464         { $return = { type => 'unique' } }
465     |
466     /primary key/i
467         { $return = { type => 'primary_key' } }
468     |
469     /check/i '(' /[^)]+/ ')'
470         { $return = { type => 'check', expression => $item[3] } }
471     |
472     /references/i table_id parens_word_list(?) match_type(?) key_action(s?)
473     {
474         my $table_info  = $item{'table_id'};
475         my $schema_name = $table_info->{'schema_name'};
476         my $table_name  = $table_info->{'table_name'};
477         my ( $on_delete, $on_update );
478         for my $action ( @{ $item[5] || [] } ) {
479             $on_delete = $action->{'action'} if $action->{'type'} eq 'delete';
480             $on_update = $action->{'action'} if $action->{'type'} eq 'update';
481         }
482
483         $return              =  {
484             type             => 'foreign_key',
485             reference_table  => $table_name,
486             reference_fields => $item[3][0],
487             match_type       => $item[4][0],
488             on_delete        => $on_delete,
489             on_update        => $on_update,
490         }
491     }
492
493 table_id : schema_qualification(?) name_with_opt_quotes {
494     $return = { schema_name => $item[1][0], table_name => $item[2] }
495 }
496
497 view_id : schema_qualification(?) name_with_opt_quotes {
498     $return = { schema_name => $item[1][0], view_name => $item[2] }
499 }
500
501 view_target : /select|with/i /[^;]+/ {
502     $return = "$item[1] $item[2]";
503 }
504
505 # SELECT views _may_ support outer parens, and we used to produce
506 # such sql, although non-standard. Use ugly lookeahead to parse
507 view_target : '('   /select/i    / [^;]+ (?= \) ) /x    ')'    {
508     $return = "$item[2] $item[3]"
509 }
510
511 view_target_spec :
512
513 schema_qualification : name_with_opt_quotes '.'
514
515 schema_name : name_with_opt_quotes
516
517 field_name : name_with_opt_quotes
518
519 name_with_opt_quotes : double_quote(?) NAME double_quote(?) { $item[2] }
520
521 double_quote: /"/
522
523 index_name : name_with_opt_quotes
524
525
526 data_type : pg_data_type parens_value_list(?)
527     {
528         my $data_type = $item[1];
529
530         #
531         # We can deduce some sizes from the data type's name.
532         #
533         if ( my $size = $item[2][0] ) {
534             $data_type->{'size'} = $size;
535         }
536
537         $return  = $data_type;
538     }
539
540 pg_data_type :
541     /(bigint|int8)/i
542         {
543             $return = {
544                 type => 'integer',
545                 size => 20,
546             };
547         }
548     |
549     /(smallint|int2)/i
550         {
551             $return = {
552                 type => 'integer',
553                 size => 5,
554             };
555         }
556     |
557     /interval/i
558         {
559             $return = { type => 'interval' };
560         }
561     |
562     /(integer|int4?)/i # interval must come before this
563         {
564             $return = {
565                 type => 'integer',
566                 size => 10,
567             };
568         }
569     |
570     /(real|float4)/i
571         {
572             $return = {
573                 type => 'real',
574                 size => 10,
575             };
576         }
577     |
578     /(double precision|float8?)/i
579         {
580             $return = {
581                 type => 'float',
582                 size => 20,
583             };
584         }
585     |
586     /(bigserial|serial8)/i
587         {
588             $return = {
589                 type              => 'integer',
590                 size              => 20,
591                 is_auto_increment => 1,
592             };
593         }
594     |
595     /serial4?/i
596         {
597             $return = {
598                 type              => 'integer',
599                 size              => 11,
600                 is_auto_increment => 1,
601             };
602         }
603     |
604     /(bit varying|varbit)/i
605         {
606             $return = { type => 'varbit' };
607         }
608     |
609     /character varying/i
610         {
611             $return = { type => 'varchar' };
612         }
613     |
614     /char(acter)?/i
615         {
616             $return = { type => 'char' };
617         }
618     |
619     /bool(ean)?/i
620         {
621             $return = { type => 'boolean' };
622         }
623     |
624     /bytea/i
625         {
626             $return = { type => 'bytea' };
627         }
628     |
629     /(timestamptz|timestamp)(?:\(\d\))?( with(?:out)? time zone)?/i
630         {
631             $return = { type => 'timestamp' . ($2||'') };
632         }
633     |
634     /text/i
635         {
636             $return = {
637                 type => 'text',
638                 size => 64_000,
639             };
640         }
641     |
642     /(bit|box|cidr|circle|date|inet|line|lseg|macaddr|money|numeric|decimal|path|point|polygon|timetz|time|varchar|json|hstore)/i
643         {
644             $return = { type => $item[1] };
645         }
646
647 parens_value_list : '(' VALUE(s /,/) ')'
648     { $item[2] }
649
650
651 parens_word_list : '(' name_with_opt_quotes(s /,/) ')'
652     { $item[2] }
653
654 field_size : '(' num_range ')' { $item{'num_range'} }
655
656 num_range : DIGITS ',' DIGITS
657     { $return = $item[1].','.$item[3] }
658     | DIGITS
659     { $return = $item[1] }
660
661 table_constraint : comment(s?) constraint_name(?) table_constraint_type deferrable(?) deferred(?) comment(s?)
662     {
663         my $desc       = $item{'table_constraint_type'};
664         my $type       = $desc->{'type'};
665         my $fields     = $desc->{'fields'};
666         my $expression = $desc->{'expression'};
667         my @comments   = ( @{ $item[1] }, @{ $item[-1] } );
668
669         $return              =  {
670             name             => $item[2][0] || '',
671             supertype        => 'constraint',
672             type             => $type,
673             fields           => $type ne 'check' ? $fields : [],
674             expression       => $type eq 'check' ? $expression : '',
675             deferrable       => $item{'deferrable'},
676             deferred         => $item{'deferred'},
677             reference_table  => $desc->{'reference_table'},
678             reference_fields => $desc->{'reference_fields'},
679             match_type       => $desc->{'match_type'},
680             on_delete        => $desc->{'on_delete'} || $desc->{'on_delete_do'},
681             on_update        => $desc->{'on_update'} || $desc->{'on_update_do'},
682             comments         => [ @comments ],
683         }
684     }
685
686 table_constraint_type : /primary key/i '(' name_with_opt_quotes(s /,/) ')'
687     {
688         $return = {
689             type   => 'primary_key',
690             fields => $item[3],
691         }
692     }
693     |
694     /unique/i '(' name_with_opt_quotes(s /,/) ')'
695     {
696         $return    =  {
697             type   => 'unique',
698             fields => $item[3],
699         }
700     }
701     |
702     /check/i '(' /[^)]+/ ')'
703     {
704         $return        =  {
705             type       => 'check',
706             expression => $item[3],
707         }
708     }
709     |
710     /foreign key/i '(' name_with_opt_quotes(s /,/) ')' /references/i table_id parens_word_list(?) match_type(?) key_action(s?)
711     {
712         my ( $on_delete, $on_update );
713         for my $action ( @{ $item[9] || [] } ) {
714             $on_delete = $action->{'action'} if $action->{'type'} eq 'delete';
715             $on_update = $action->{'action'} if $action->{'type'} eq 'update';
716         }
717
718         $return              =  {
719             supertype        => 'constraint',
720             type             => 'foreign_key',
721             fields           => $item[3],
722             reference_table  => $item[6]->{'table_name'},
723             reference_fields => $item[7][0],
724             match_type       => $item[8][0],
725             on_delete     => $on_delete || '',
726             on_update     => $on_update || '',
727         }
728     }
729
730 deferrable : not(?) /deferrable/i
731     {
732         $return = ( $item[1] =~ /not/i ) ? 0 : 1;
733     }
734
735 deferred : /initially/i /(deferred|immediate)/i { $item[2] }
736
737 match_type : /match/i /partial|full|simple/i { $item[2] }
738
739 key_action : key_delete
740     |
741     key_update
742
743 key_delete : /on delete/i key_mutation
744     {
745         $return = {
746             type   => 'delete',
747             action => $item[2],
748         };
749     }
750
751 key_update : /on update/i key_mutation
752     {
753         $return = {
754             type   => 'update',
755             action => $item[2],
756         };
757     }
758
759 key_mutation : /no action/i { $return = 'no_action' }
760     |
761     /restrict/i { $return = 'restrict' }
762     |
763     /cascade/i { $return = 'cascade' }
764     |
765     /set null/i { $return = 'set null' }
766     |
767     /set default/i { $return = 'set default' }
768
769 alter : alter_table table_id add_column field ';'
770     {
771         my $field_def = $item[4];
772         $tables{ $item[2]->{'table_name'} }{'fields'}{ $field_def->{'name'} } = {
773             %$field_def, order => $field_order++
774         };
775         1;
776     }
777
778 alter : alter_table table_id ADD table_constraint ';'
779     {
780         my $table_name = $item[2]->{'table_name'};
781         my $constraint = $item[4];
782         push @{ $tables{ $table_name }{'constraints'} }, $constraint;
783         1;
784     }
785
786 alter : alter_table table_id drop_column NAME restrict_or_cascade(?) ';'
787     {
788         $tables{ $item[2]->{'table_name'} }{'fields'}{ $item[4] }{'drop'} = 1;
789         1;
790     }
791
792 alter : alter_table table_id alter_column NAME alter_default_val ';'
793     {
794         $tables{ $item[2]->{'table_name'} }{'fields'}{ $item[4] }{'default'} =
795             $item[5]->{'value'};
796         1;
797     }
798
799 #
800 # These will just parse for now but won't affect the structure. - ky
801 #
802 alter : alter_table table_id /rename/i /to/i NAME ';'
803     { 1 }
804
805 alter : alter_table table_id alter_column NAME SET /statistics/i INTEGER ';'
806     { 1 }
807
808 alter : alter_table table_id alter_column NAME SET /storage/i storage_type ';'
809     { 1 }
810
811 alter : alter_table table_id rename_column NAME /to/i NAME ';'
812     { 1 }
813
814 alter : alter_table table_id DROP /constraint/i NAME restrict_or_cascade ';'
815     { 1 }
816
817 alter : alter_table table_id /owner/i /to/i NAME ';'
818     { 1 }
819
820 alter : alter_sequence NAME /owned/i /by/i column_name ';'
821     { 1 }
822
823 storage_type : /(plain|external|extended|main)/i
824
825 temporary : /temp(orary)?\b/i
826   {
827     1;
828   }
829
830 or_replace : /or replace/i
831
832 alter_default_val : SET default_val
833     {
834         $return = { value => $item[2]->{'value'} }
835     }
836     | DROP DEFAULT
837     {
838         $return = { value => undef }
839     }
840
841 #
842 # This is a little tricky to get right, at least WRT to making the
843 # tests pass.  The problem is that the constraints are stored just as
844 # a list (no name access), and the tests expect the constraints in a
845 # particular order.  I'm going to leave the rule but disable the code
846 # for now. - ky
847 #
848 alter : alter_table table_id alter_column NAME alter_nullable ';'
849     {
850 #        my $table_name  = $item[2]->{'table_name'};
851 #        my $field_name  = $item[4];
852 #        my $is_nullable = $item[5]->{'is_nullable'};
853 #
854 #        $tables{ $table_name }{'fields'}{ $field_name }{'is_nullable'} =
855 #            $is_nullable;
856 #
857 #        if ( $is_nullable ) {
858 #            1;
859 #            push @{ $tables{ $table_name }{'constraints'} }, {
860 #                type   => 'not_null',
861 #                fields => [ $field_name ],
862 #            };
863 #        }
864 #        else {
865 #            for my $i (
866 #                0 .. $#{ $tables{ $table_name }{'constraints'} || [] }
867 #            ) {
868 #                my $c = $tables{ $table_name }{'constraints'}[ $i ] or next;
869 #                my $fields = join( '', @{ $c->{'fields'} || [] } ) or next;
870 #                if ( $c->{'type'} eq 'not_null' && $fields eq $field_name ) {
871 #                    delete $tables{ $table_name }{'constraints'}[ $i ];
872 #                    last;
873 #                }
874 #            }
875 #        }
876
877         1;
878     }
879
880 alter_nullable : SET not_null
881     {
882         $return = { is_nullable => 0 }
883     }
884     | DROP not_null
885     {
886         $return = { is_nullable => 1 }
887     }
888
889 not_null : /not/i /null/i
890
891 not : /not/i
892
893 add_column : ADD COLUMN(?)
894
895 alter_table : ALTER TABLE ONLY(?)
896
897 alter_sequence : ALTER SEQUENCE
898
899 drop_column : DROP COLUMN(?)
900
901 alter_column : ALTER COLUMN(?)
902
903 rename_column : /rename/i COLUMN(?)
904
905 restrict_or_cascade : /restrict/i |
906     /cascade/i
907
908 # Handle functions that can be called
909 select : SELECT select_function ';'
910     { 1 }
911
912 # Read the setval function but don't do anything with it because this parser
913 # isn't handling sequences
914 select_function : schema_qualification(?) /setval/i '(' VALUE /,/ VALUE /,/ /(true|false)/i ')'
915     { 1 }
916
917 # Skipping all COPY commands
918 copy : COPY WORD /[^;]+/ ';' { 1 }
919     { 1 }
920
921 # The "\." allows reading in from STDIN but this isn't needed for schema
922 # creation, so it is skipped.
923 readin_symbol : '\.'
924     {1}
925
926 #
927 # End basically useless stuff. - ky
928 #
929
930 create_table : CREATE TABLE
931
932 create_index : CREATE /index/i
933
934 default_val  : DEFAULT /(\d+|'[^']*'|\w+\(.*\))|\w+|\(\d+\)/ ( '::' data_type )(?)
935     {
936         my $val =  defined $item[2] ? $item[2] : '';
937         $val    =~ s/^'|'$//g;
938         $val =~ s/^\((\d+)\)\z/$1/; # for example (0)::smallint
939         $return =  {
940             supertype => 'constraint',
941             type      => 'default',
942             value     => $val,
943         }
944     }
945     | /null/i
946     {
947         $return =  {
948             supertype => 'constraint',
949             type      => 'default',
950             value     => 'NULL',
951         }
952     }
953
954 name_with_opt_paren : NAME parens_value_list(s?)
955     { $item[2][0] ? "$item[1]($item[2][0][0])" : $item[1] }
956
957 unique : /unique/i { 1 }
958
959 key : /key/i | /index/i
960
961 table_option : /inherits/i '(' name_with_opt_quotes(s /,/) ')'
962     {
963         $return = { type => 'inherits', table_name => $item[3] }
964     }
965     |
966     /with(out)? oids/i
967     {
968         $return = { type => $item[1] =~ /out/i ? 'without_oids' : 'with_oids' }
969     }
970
971 ADD : /add/i
972
973 ALTER : /alter/i
974
975 CREATE : /create/i
976
977 ONLY : /only/i
978
979 DEFAULT : /default/i
980
981 DROP : /drop/i
982
983 COLUMN : /column/i
984
985 TABLE : /table/i
986
987 VIEW : /view/i
988
989 SCHEMA : /schema/i
990
991 SEMICOLON : /\s*;\n?/
992
993 SEQUENCE : /sequence/i
994
995 SELECT : /select/i
996
997 COPY : /copy/i
998
999 INTEGER : /\d+/
1000
1001 WORD : /\w+/
1002
1003 DIGITS : /\d+/
1004
1005 COMMA : ','
1006
1007 SET : /set/i
1008
1009 NAME    : "`" /\w+/ "`"
1010     { $item[2] }
1011     | /\w+/
1012     { $item[1] }
1013     | /[\$\w]+/
1014     { $item[1] }
1015
1016 VALUE   : /[-+]?\.?\d+(?:[eE]\d+)?/
1017     { $item[1] }
1018     | /'.*?'/   # XXX doesn't handle embedded quotes
1019     { $item[1] }
1020     | /null/i
1021     { 'NULL' }
1022
1023 END_OF_GRAMMAR
1024
1025 sub parse {
1026     my ( $translator, $data ) = @_;
1027
1028     # Enable warnings within the Parse::RecDescent module.
1029     local $::RD_ERRORS = 1 unless defined $::RD_ERRORS; # Make sure the parser dies when it encounters an error
1030     local $::RD_WARN   = 1 unless defined $::RD_WARN; # Enable warnings. This will warn on unused rules &c.
1031     local $::RD_HINT   = 1 unless defined $::RD_HINT; # Give out hints to help fix problems.
1032
1033     local $::RD_TRACE  = $translator->trace ? 1 : undef;
1034     local $DEBUG       = $translator->debug;
1035
1036     my $parser = ddl_parser_instance('PostgreSQL');
1037
1038     my $result = $parser->startrule($data);
1039     die "Parse failed.\n" unless defined $result;
1040     warn Dumper($result) if $DEBUG;
1041
1042     my $schema = $translator->schema;
1043     my @tables = sort {
1044         ( $result->{tables}{ $a }{'order'} || 0 ) <=> ( $result->{tables}{ $b }{'order'} || 0 )
1045     } keys %{ $result->{tables} };
1046
1047     for my $table_name ( @tables ) {
1048         my $tdata =  $result->{tables}{ $table_name };
1049         my $table =  $schema->add_table(
1050             #schema => $tdata->{'schema_name'},
1051             name   => $tdata->{'table_name'},
1052         ) or die "Couldn't create table '$table_name': " . $schema->error;
1053
1054         $table->extra(temporary => 1) if $tdata->{'temporary'};
1055
1056         $table->comments( $tdata->{'comments'} );
1057
1058         my @fields = sort {
1059             $tdata->{'fields'}{ $a }{'order'}
1060             <=>
1061             $tdata->{'fields'}{ $b }{'order'}
1062         } keys %{ $tdata->{'fields'} };
1063
1064         for my $fname ( @fields ) {
1065             my $fdata = $tdata->{'fields'}{ $fname };
1066             next if $fdata->{'drop'};
1067             my $field = $table->add_field(
1068                 name              => $fdata->{'name'},
1069                 data_type         => $fdata->{'data_type'},
1070                 size              => $fdata->{'size'},
1071                 default_value     => $fdata->{'default'},
1072                 is_auto_increment => $fdata->{'is_auto_increment'},
1073                 is_nullable       => $fdata->{'is_nullable'},
1074                 comments          => $fdata->{'comments'},
1075             ) or die $table->error;
1076
1077             $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
1078
1079             for my $cdata ( @{ $fdata->{'constraints'} } ) {
1080                 next unless $cdata->{'type'} eq 'foreign_key';
1081                 $cdata->{'fields'} ||= [ $field->name ];
1082                 push @{ $tdata->{'constraints'} }, $cdata;
1083             }
1084         }
1085
1086         for my $idata ( @{ $tdata->{'indices'} || [] } ) {
1087             my $index  =  $table->add_index(
1088                 name   => $idata->{'name'},
1089                 type   => uc $idata->{'type'},
1090                 fields => $idata->{'fields'},
1091             ) or die $table->error . ' ' . $table->name;
1092         }
1093
1094         for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
1095             my $constraint       =  $table->add_constraint(
1096                 name             => $cdata->{'name'},
1097                 type             => $cdata->{'type'},
1098                 fields           => $cdata->{'fields'},
1099                 reference_table  => $cdata->{'reference_table'},
1100                 reference_fields => $cdata->{'reference_fields'},
1101                 match_type       => $cdata->{'match_type'} || '',
1102                 on_delete        => $cdata->{'on_delete'} || $cdata->{'on_delete_do'},
1103                 on_update        => $cdata->{'on_update'} || $cdata->{'on_update_do'},
1104                 expression       => $cdata->{'expression'},
1105             ) or die "Can't add constraint of type '" .
1106                 $cdata->{'type'} .  "' to table '" . $table->name .
1107                 "': " . $table->error;
1108         }
1109     }
1110
1111     for my $vinfo (@{$result->{views}}) {
1112       my $sql = $vinfo->{sql};
1113       $sql =~ s/\A\s+|\s+\z//g;
1114       my $view = $schema->add_view (
1115         name => $vinfo->{view_name},
1116         sql => $sql,
1117         fields => $vinfo->{fields},
1118       );
1119
1120       $view->extra ( temporary => 1 ) if $vinfo->{is_temporary};
1121     }
1122
1123     for my $trigger (@{ $result->{triggers} }) {
1124         $schema->add_trigger( %$trigger );
1125     }
1126
1127     return 1;
1128 }
1129
1130 1;
1131
1132 # -------------------------------------------------------------------
1133 # Rescue the drowning and tie your shoestrings.
1134 # Henry David Thoreau
1135 # -------------------------------------------------------------------
1136
1137 =pod
1138
1139 =head1 AUTHORS
1140
1141 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>,
1142 Allen Day E<lt>allenday@ucla.eduE<gt>.
1143
1144 =head1 SEE ALSO
1145
1146 perl(1), Parse::RecDescent.
1147
1148 =cut