1 package SQL::Translator::Parser::PostgreSQL;
3 # -------------------------------------------------------------------
4 # $Id: PostgreSQL.pm,v 1.21 2003-07-11 15:22:45 kycl4rk Exp $
5 # -------------------------------------------------------------------
6 # Copyright (C) 2003 Ken Y. Clark <kclark@cpan.org>,
7 # Allen Day <allenday@users.sourceforge.net>,
8 # darren chamberlain <darren@cpan.org>,
9 # Chris Mungall <cjm@fruitfly.org>
11 # This program is free software; you can redistribute it and/or
12 # modify it under the terms of the GNU General Public License as
13 # published by the Free Software Foundation; version 2.
15 # This program is distributed in the hope that it will be useful, but
16 # WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 # General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with this program; if not, write to the Free Software
22 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
24 # -------------------------------------------------------------------
28 SQL::Translator::Parser::PostgreSQL - parser for PostgreSQL
33 use SQL::Translator::Parser::PostgreSQL;
35 my $translator = SQL::Translator->new;
36 $translator->parser("SQL::Translator::Parser::PostgreSQL");
40 The grammar was started from the MySQL parsers. Here is the description
44 (http://www.postgresql.org/docs/view.php?version=7.3&idoc=1&file=sql-createtable.html)
46 CREATE [ [ LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (
47 { column_name data_type [ DEFAULT default_expr ]
48 [ column_constraint [, ... ] ]
49 | table_constraint } [, ... ]
51 [ INHERITS ( parent_table [, ... ] ) ]
52 [ WITH OIDS | WITHOUT OIDS ]
54 where column_constraint is:
56 [ CONSTRAINT constraint_name ]
57 { NOT NULL | NULL | UNIQUE | PRIMARY KEY |
59 REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL ]
60 [ ON DELETE action ] [ ON UPDATE action ] }
61 [ DEFERRABLE | NOT DEFERRABLE ]
62 [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
64 and table_constraint is:
66 [ CONSTRAINT constraint_name ]
67 { UNIQUE ( column_name [, ... ] ) |
68 PRIMARY KEY ( column_name [, ... ] ) |
69 CHECK ( expression ) |
70 FOREIGN KEY ( column_name [, ... ] )
71 REFERENCES reftable [ ( refcolumn [, ... ] ) ]
72 [ MATCH FULL | MATCH PARTIAL ]
73 [ ON DELETE action ] [ ON UPDATE action ] }
74 [ DEFERRABLE | NOT DEFERRABLE ]
75 [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
78 (http://www.postgresql.org/docs/view.php?version=7.3&idoc=1&file=sql-createindex.html)
80 CREATE [ UNIQUE ] INDEX index_name ON table
81 [ USING acc_method ] ( column [ ops_name ] [, ...] )
83 CREATE [ UNIQUE ] INDEX index_name ON table
84 [ USING acc_method ] ( func_name( column [, ... ]) [ ops_name ] )
89 ALTER TABLE [ ONLY ] table [ * ]
90 ADD [ COLUMN ] column type [ column_constraint [ ... ] ]
91 ALTER TABLE [ ONLY ] table [ * ]
92 ALTER [ COLUMN ] column { SET DEFAULT value | DROP DEFAULT }
93 ALTER TABLE [ ONLY ] table [ * ]
94 ALTER [ COLUMN ] column SET STATISTICS integer
95 ALTER TABLE [ ONLY ] table [ * ]
96 RENAME [ COLUMN ] column TO newcolumn
100 ADD table_constraint_definition
101 ALTER TABLE [ ONLY ] table
102 DROP CONSTRAINT constraint { RESTRICT | CASCADE }
108 CREATE [ OR REPLACE ] VIEW view [ ( column name list ) ] AS SELECT query
113 use vars qw[ $DEBUG $VERSION $GRAMMAR @EXPORT_OK ];
114 $VERSION = sprintf "%d.%02d", q$Revision: 1.21 $ =~ /(\d+)\.(\d+)/;
115 $DEBUG = 0 unless defined $DEBUG;
118 use Parse::RecDescent;
120 use base qw(Exporter);
122 @EXPORT_OK = qw(parse);
124 # Enable warnings within the Parse::RecDescent module.
125 $::RD_ERRORS = 1; # Make sure the parser dies when it encounters an error
126 $::RD_WARN = 1; # Enable warnings. This will warn on unused rules &c.
127 $::RD_HINT = 1; # Give out hints to help fix problems.
129 my $parser; # should we do this? There's no programmic way to
130 # change the grammar, so I think this is safe.
134 { our ( %tables, $table_order ) }
137 # The "eofile" rule makes the parser fail if any "statement" rule
138 # fails. Otherwise, the first successful match by a "statement"
139 # won't cause the failure needed to know that the parse, as a whole,
142 startrule : statement(s) eofile { \%tables }
158 connect : /^\s*\\\connect.*\n/
160 set : /SET/ /[^;]*/ ';'
162 revoke : /revoke/i WORD(s /,/) /on/i /table/i table_name /from/i name_with_opt_quotes(s /,/) ';'
164 my $table_name = $item{'table_name'};
165 push @{ $tables{ $table_name }{'permissions'} }, {
172 grant : /grant/i WORD(s /,/) /on/i /table/i table_name /to/i name_with_opt_quotes(s /,/) ';'
174 my $table_name = $item{'table_name'};
175 push @{ $tables{ $table_name }{'permissions'} }, {
182 drop : /drop/i /[^;]*/ ';'
184 insert : /insert/i /[^;]*/ ';'
186 update : /update/i /[^;]*/ ';'
191 create : create_table table_name '(' create_definition(s /,/) ')' table_option(s?) ';'
193 my $table_name = $item{'table_name'};
194 $tables{ $table_name }{'order'} = ++$table_order;
195 $tables{ $table_name }{'table_name'} = $table_name;
199 for my $definition ( @{ $item[4] } ) {
200 if ( $definition->{'type'} eq 'field' ) {
201 my $field_name = $definition->{'name'};
202 $tables{ $table_name }{'fields'}{ $field_name } =
203 { %$definition, order => $i };
206 for my $constraint ( @{ $definition->{'constraints'} || [] } ) {
207 $constraint->{'fields'} = [ $field_name ];
208 push @{ $tables{ $table_name }{'constraints'} },
212 elsif ( $definition->{'type'} eq 'constraint' ) {
213 $definition->{'type'} = $definition->{'constraint_type'};
214 # group FKs at the field level
215 # if ( $definition->{'type'} eq 'foreign_key' ) {
216 # for my $fld ( @{ $definition->{'fields'} || [] } ) {
218 # $tables{$table_name}{'fields'}{$fld}{'constraints'}
223 push @{ $tables{ $table_name }{'constraints'} },
228 push @{ $tables{ $table_name }{'indices'} }, $definition;
232 for my $option ( @{ $item[6] } ) {
233 $tables{ $table_name }{'table_options(s?)'}{ $option->{'type'} } =
243 create : /create/i unique(?) /(index|key)/i index_name /on/i table_name using_method(?) '(' field_name(s /,/) ')' where_predicate(?) ';'
245 push @{ $tables{ $item{'table_name'} }{'indices'} },
247 name => $item{'index_name'},
248 type => $item{'unique'}[0] ? 'unique' : 'normal',
250 method => $item{'using_method'}[0],
256 # Create anything else (e.g., domain, function, etc.)
258 create : /create/i WORD /[^;]+/ ';'
260 using_method : /using/i WORD { $item[2] }
262 where_predicate : /where/i /[^;]+/
264 create_definition : field
268 comment : /^\s*(?:#|-{2}).*\n/
270 field : comment(s?) field_name data_type field_meta(s?) comment(s?)
272 my ( $default, @constraints, $is_pk );
274 for my $meta ( @{ $item[4] } ) {
275 if ( $meta->{'type'} eq 'default' ) {
279 elsif ( $meta->{'type'} eq 'not_null' ) {
283 elsif ( $meta->{'type'} eq 'primary_key' ) {
287 push @constraints, $meta if $meta->{'supertype'} eq 'constraint';
290 my @comments = ( @{ $item[1] }, @{ $item[5] } );
294 name => $item{'field_name'},
295 data_type => $item{'data_type'}{'type'},
296 size => $item{'data_type'}{'size'},
298 default => $default->{'value'},
299 constraints => [ @constraints ],
300 comments => [ @comments ],
301 is_primary_key => $is_pk || 0,
306 field_meta : default_val
309 column_constraint : constraint_name(?) column_constraint_type deferrable(?) deferred(?)
311 my $desc = $item{'column_constraint_type'};
312 my $type = $desc->{'type'};
313 my $fields = $desc->{'fields'} || [];
314 my $expression = $desc->{'expression'} || '';
317 supertype => 'constraint',
318 name => $item{'constraint_name'}[0] || '',
320 expression => $type eq 'check' ? $expression : '',
321 deferreable => $item{'deferrable'},
322 deferred => $item{'deferred'},
323 reference_table => $desc->{'reference_table'},
324 reference_fields => $desc->{'reference_fields'},
325 match_type => $desc->{'match_type'},
326 on_delete_do => $desc->{'on_delete_do'},
327 on_update_do => $desc->{'on_update_do'},
331 constraint_name : /constraint/i name_with_opt_quotes { $item[2] }
333 column_constraint_type : /not null/i { $return = { type => 'not_null' } }
336 { $return = { type => 'null' } }
339 { $return = { type => 'unique' } }
342 { $return = { type => 'primary_key' } }
344 /check/i '(' /[^)]+/ ')'
345 { $return = { type => 'check', expression => $item[2] } }
347 /references/i table_name parens_word_list(?) match_type(?) key_action(s?)
349 my ( $on_delete, $on_update );
350 for my $action ( @{ $item[5] || [] } ) {
351 $on_delete = $action->{'action'} if $action->{'type'} eq 'delete';
352 $on_update = $action->{'action'} if $action->{'type'} eq 'update';
356 type => 'foreign_key',
357 reference_table => $item[2],
358 reference_fields => $item[3][0],
359 match_type => $item[4][0],
360 on_delete_do => $on_delete,
361 on_update_do => $on_update,
365 table_name : name_with_opt_quotes
367 field_name : name_with_opt_quotes
369 name_with_opt_quotes : double_quote(?) NAME double_quote(?) { $item[2] }
375 data_type : pg_data_type parens_value_list(?)
377 my $data_type = $item[1];
380 # We can deduce some sizes from the data type's name.
382 $data_type->{'size'} ||= $item[2][0];
384 $return = $data_type;
388 /(bigint|int8|bigserial|serial8)/i
413 /(double precision|float8?)/i
447 /(bit varying|varbit)/i
449 $return = { type => 'varbit' };
454 $return = { type => 'varchar' };
459 $return = { type => 'char' };
464 $return = { type => 'boolean' };
469 $return = { type => 'bytea' };
474 $return = { type => 'timestamp' };
477 /(bit|box|cidr|circle|date|inet|interval|line|lseg|macaddr|money|numeric|decimal|path|point|polygon|text|time|varchar)/i
479 $return = { type => $item[1] };
482 parens_value_list : '(' VALUE(s /,/) ')'
485 parens_word_list : '(' WORD(s /,/) ')'
488 field_size : '(' num_range ')' { $item{'num_range'} }
490 num_range : DIGITS ',' DIGITS
491 { $return = $item[1].','.$item[3] }
493 { $return = $item[1] }
495 table_constraint : comment(s?) constraint_name(?) table_constraint_type deferrable(?) deferred(?) comment(s?)
497 my $desc = $item{'table_constraint_type'};
498 my $type = $desc->{'type'};
499 my $fields = $desc->{'fields'};
500 my $expression = $desc->{'expression'};
501 my @comments = ( @{ $item[1] }, @{ $item[-1] } );
504 name => $item{'constraint_name'}[0] || '',
505 type => 'constraint',
506 constraint_type => $type,
507 fields => $type ne 'check' ? $fields : [],
508 expression => $type eq 'check' ? $expression : '',
509 deferreable => $item{'deferrable'},
510 deferred => $item{'deferred'},
511 reference_table => $desc->{'reference_table'},
512 reference_fields => $desc->{'reference_fields'},
513 match_type => $desc->{'match_type'}[0],
514 on_delete_do => $desc->{'on_delete_do'},
515 on_update_do => $desc->{'on_update_do'},
516 comments => [ @comments ],
520 table_constraint_type : /primary key/i '(' name_with_opt_quotes(s /,/) ')'
523 type => 'primary_key',
528 /unique/i '(' name_with_opt_quotes(s /,/) ')'
536 /check/ '(' /(.+)/ ')'
540 expression => $item[3],
544 /foreign key/i '(' name_with_opt_quotes(s /,/) ')' /references/i table_name parens_word_list(?) match_type(?) key_action(s?)
546 my ( $on_delete, $on_update );
547 for my $action ( @{ $item[9] || [] } ) {
548 $on_delete = $action->{'action'} if $action->{'type'} eq 'delete';
549 $on_update = $action->{'action'} if $action->{'type'} eq 'update';
553 type => 'foreign_key',
555 reference_table => $item[6],
556 reference_fields => $item[7][0],
557 match_type => $item[8][0],
558 on_delete_do => $on_delete || '',
559 on_update_do => $on_update || '',
563 deferrable : /not/i /deferrable/i
565 $return = ( $item[1] =~ /not/i ) ? 0 : 1;
568 deferred : /initially/i /(deferred|immediate)/i { $item[2] }
570 match_type : /match full/i { 'match_full' }
572 /match partial/i { 'match_partial' }
574 key_action : key_delete
578 key_delete : /on delete/i key_mutation
586 key_update : /on update/i key_mutation
594 key_mutation : /no action/i { $return = 'no_action' }
596 /restrict/i { $return = 'restrict' }
598 /cascade/i { $return = 'cascade' }
600 /set null/i { $return = 'set_null' }
602 /set default/i { $return = 'set_default' }
604 alter : alter_table table_name /add/i table_constraint ';'
606 my $table_name = $item[2];
607 my $constraint = $item[4];
608 $constraint->{'type'} = $constraint->{'constraint_type'};
609 push @{ $tables{ $table_name }{'constraints'} }, $constraint;
612 alter_table : /alter/i /table/i only(?)
616 create_table : /create/i /table/i
618 create_index : /create/i /index/i
620 default_val : /default/i /(?:')?[\w\d().-]*(?:')?/
622 my $val = $item[2] || '';
625 supertype => 'constraint',
633 supertype => 'constraint',
639 name_with_opt_paren : NAME parens_value_list(s?)
640 { $item[2][0] ? "$item[1]($item[2][0][0])" : $item[1] }
642 unique : /unique/i { 1 }
644 key : /key/i | /index/i
646 table_option : /inherits/i '(' name_with_opt_quotes(s /,/) ')'
648 $return = { type => 'inherits', table_name => $item[3] }
653 $return = { type => $item[1] =~ /out/i ? 'without_oids' : 'with_oids' }
656 SEMICOLON : /\s*;\n?/
671 VALUE : /[-+]?\.?\d+(?:[eE]\d+)?/
673 | /'.*?'/ # XXX doesn't handle embedded quotes
680 # -------------------------------------------------------------------
682 my ( $translator, $data ) = @_;
683 $parser ||= Parse::RecDescent->new($GRAMMAR);
685 $::RD_TRACE = $translator->trace ? 1 : undef;
686 $DEBUG = $translator->debug;
688 unless (defined $parser) {
689 return $translator->error("Error instantiating Parse::RecDescent ".
690 "instance: Bad grammer");
693 my $result = $parser->startrule($data);
694 die "Parse failed.\n" unless defined $result;
695 warn Dumper($result) if $DEBUG;
697 my $schema = $translator->schema;
699 $result->{ $a }->{'order'} <=> $result->{ $b }->{'order'}
702 for my $table_name ( @tables ) {
703 my $tdata = $result->{ $table_name };
704 my $table = $schema->add_table(
705 name => $tdata->{'table_name'},
706 ) or die $schema->error;
709 $tdata->{'fields'}->{$a}->{'order'}
711 $tdata->{'fields'}->{$b}->{'order'}
712 } keys %{ $tdata->{'fields'} };
714 for my $fname ( @fields ) {
715 my $fdata = $tdata->{'fields'}{ $fname };
716 my $field = $table->add_field(
717 name => $fdata->{'name'},
718 data_type => $fdata->{'data_type'},
719 size => $fdata->{'size'},
720 default_value => $fdata->{'default'},
721 is_auto_increment => $fdata->{'is_auto_inc'},
722 is_nullable => $fdata->{'null'},
723 ) or die $table->error;
725 $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
727 for my $cdata ( @{ $fdata->{'constraints'} } ) {
728 next unless $cdata->{'type'} eq 'foreign_key';
729 $cdata->{'fields'} ||= [ $field->name ];
730 push @{ $tdata->{'constraints'} }, $cdata;
734 for my $idata ( @{ $tdata->{'indices'} || [] } ) {
735 my $index = $table->add_index(
736 name => $idata->{'name'},
737 type => uc $idata->{'type'},
738 fields => $idata->{'fields'},
739 ) or die $table->error;
742 for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
743 my $constraint = $table->add_constraint(
744 name => $cdata->{'name'},
745 type => $cdata->{'type'},
746 fields => $cdata->{'fields'},
747 reference_table => $cdata->{'reference_table'},
748 reference_fields => $cdata->{'reference_fields'},
749 match_type => $cdata->{'match_type'} || '',
750 on_delete => $cdata->{'on_delete_do'},
751 on_update => $cdata->{'on_update_do'},
752 ) or die $table->error;
761 # -------------------------------------------------------------------
762 # Rescue the drowning and tie your shoestrings.
763 # Henry David Thoreau
764 # -------------------------------------------------------------------
770 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>,
771 Allen Day <allenday@ucla.edu>.
775 perl(1), Parse::RecDescent.