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