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