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