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