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