1 package SQL::Translator::Parser::PostgreSQL;
3 # -------------------------------------------------------------------
4 # $Id: PostgreSQL.pm,v 1.15 2003-06-06 22:27:46 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.15 $ =~ /(\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 }
156 connect : /^\s*\\\connect.*\n/
158 set : /SET/ /[^;]*/ ';'
160 revoke : /revoke/i WORD(s /,/) /on/i table_name /from/i name_with_opt_quotes(s /,/) ';'
162 my $table_name = $item{'table_name'};
163 push @{ $tables{ $table_name }{'permissions'} }, {
170 grant : /grant/i WORD(s /,/) /on/i table_name /to/i name_with_opt_quotes(s /,/) ';'
172 my $table_name = $item{'table_name'};
173 push @{ $tables{ $table_name }{'permissions'} }, {
180 drop : /drop/i /[^;]*/ ';'
185 create : create_table table_name '(' create_definition(s /,/) ')' table_option(s?) ';'
187 my $table_name = $item{'table_name'};
188 $tables{ $table_name }{'order'} = ++$table_order;
189 $tables{ $table_name }{'table_name'} = $table_name;
193 for my $definition ( @{ $item[4] } ) {
194 if ( $definition->{'type'} eq 'field' ) {
195 my $field_name = $definition->{'name'};
196 $tables{ $table_name }{'fields'}{ $field_name } =
197 { %$definition, order => $i };
200 for my $constraint ( @{ $definition->{'constraints'} || [] } ) {
201 $constraint->{'fields'} = [ $field_name ];
202 push @{ $tables{ $table_name }{'constraints'} },
206 elsif ( $definition->{'type'} eq 'constraint' ) {
207 $definition->{'type'} = $definition->{'constraint_type'};
208 # group FKs at the field level
209 # if ( $definition->{'type'} eq 'foreign_key' ) {
210 # for my $fld ( @{ $definition->{'fields'} || [] } ) {
212 # $tables{$table_name}{'fields'}{$fld}{'constraints'}
217 push @{ $tables{ $table_name }{'constraints'} },
222 push @{ $tables{ $table_name }{'indices'} }, $definition;
226 for my $option ( @{ $item[6] } ) {
227 $tables{ $table_name }{'table_options(s?)'}{ $option->{'type'} } =
237 create : /create/i unique(?) /(index|key)/i index_name /on/i table_name using_method(?) '(' field_name(s /,/) ')' where_predicate(?) ';'
239 push @{ $tables{ $item{'table_name'} }{'indices'} },
241 name => $item{'index_name'},
242 type => $item{'unique'}[0] ? 'unique' : 'normal',
244 method => $item{'using_method'}[0],
250 # Create anything else (e.g., domain, function, etc.)
252 create : /create/i WORD /[^;]+/ ';'
254 using_method : /using/i WORD { $item[2] }
256 where_predicate : /where/i /[^;]+/
258 create_definition : field
262 comment : /^\s*(?:#|-{2}).*\n/
264 field : comment(s?) field_name data_type field_meta(s?) comment(s?)
266 my ( $default, @constraints, $is_pk );
268 for my $meta ( @{ $item[4] } ) {
269 if ( $meta->{'type'} eq 'default' ) {
273 elsif ( $meta->{'type'} eq 'not_null' ) {
277 elsif ( $meta->{'type'} eq 'primary_key' ) {
281 push @constraints, $meta if $meta->{'supertype'} eq 'constraint';
284 my @comments = ( @{ $item[1] }, @{ $item[5] } );
288 name => $item{'field_name'},
289 data_type => $item{'data_type'}{'type'},
290 size => $item{'data_type'}{'size'},
292 default => $default->{'value'},
293 constraints => [ @constraints ],
294 comments => [ @comments ],
295 is_primary_key => $is_pk || 0,
300 field_meta : default_val
303 column_constraint : constraint_name(?) column_constraint_type deferrable(?) deferred(?)
305 my $desc = $item{'column_constraint_type'};
306 my $type = $desc->{'type'};
307 my $fields = $desc->{'fields'} || [];
308 my $expression = $desc->{'expression'} || '';
311 supertype => 'constraint',
312 name => $item{'constraint_name'}[0] || '',
314 expression => $type eq 'check' ? $expression : '',
315 deferreable => $item{'deferrable'},
316 deferred => $item{'deferred'},
317 reference_table => $desc->{'reference_table'},
318 reference_fields => $desc->{'reference_fields'},
319 match_type => $desc->{'match_type'},
320 on_delete_do => $desc->{'on_delete_do'},
321 on_update_do => $desc->{'on_update_do'},
325 constraint_name : /constraint/i name_with_opt_quotes { $item[2] }
327 column_constraint_type : /not null/i { $return = { type => 'not_null' } }
330 { $return = { type => 'null' } }
333 { $return = { type => 'unique' } }
336 { $return = { type => 'primary_key' } }
338 /check/i '(' /[^)]+/ ')'
339 { $return = { type => 'check', expression => $item[2] } }
341 /references/i table_name parens_word_list(?) match_type(?) key_action(s?)
343 my ( $on_delete, $on_update );
344 for my $action ( @{ $item[5] || [] } ) {
345 $on_delete = $action->{'action'} if $action->{'type'} eq 'delete';
346 $on_update = $action->{'action'} if $action->{'type'} eq 'update';
350 type => 'foreign_key',
351 reference_table => $item[2],
352 reference_fields => $item[3][0],
353 match_type => $item[4][0],
354 on_delete_do => $on_delete,
355 on_update_do => $on_update,
359 table_name : name_with_opt_quotes
361 field_name : name_with_opt_quotes
363 name_with_opt_quotes : double_quote(?) NAME double_quote(?) { $item[2] }
369 data_type : pg_data_type parens_value_list(?)
371 my $data_type = $item[1];
374 # We can deduce some sizes from the data type's name.
376 $data_type->{'size'} ||= $item[2][0];
378 $return = $data_type;
382 /(bigint|int8|bigserial|serial8)/
407 /(double precision|float8?)/
441 /(bit varying|varbit)/
443 $return = { type => 'varbit' };
448 $return = { type => 'varchar' };
453 $return = { type => 'char' };
458 $return = { type => 'boolean' };
463 $return = { type => 'bytea' };
468 $return = { type => 'timestamp' };
471 /(bit|box|cidr|circle|date|inet|interval|line|lseg|macaddr|money|numeric|decimal|path|point|polygon|text|time|varchar)/
473 $return = { type => $item[1] };
476 parens_value_list : '(' VALUE(s /,/) ')'
479 parens_word_list : '(' WORD(s /,/) ')'
482 field_size : '(' num_range ')' { $item{'num_range'} }
484 num_range : DIGITS ',' DIGITS
485 { $return = $item[1].','.$item[3] }
487 { $return = $item[1] }
489 table_constraint : comment(s?) constraint_name(?) table_constraint_type deferrable(?) deferred(?) comment(s?)
491 my $desc = $item{'table_constraint_type'};
492 my $type = $desc->{'type'};
493 my $fields = $desc->{'fields'};
494 my $expression = $desc->{'expression'};
495 my @comments = ( @{ $item[1] }, @{ $item[-1] } );
498 name => $item{'constraint_name'}[0] || '',
499 type => 'constraint',
500 constraint_type => $type,
501 fields => $type ne 'check' ? $fields : [],
502 expression => $type eq 'check' ? $expression : '',
503 deferreable => $item{'deferrable'},
504 deferred => $item{'deferred'},
505 reference_table => $desc->{'reference_table'},
506 reference_fields => $desc->{'reference_fields'},
507 match_type => $desc->{'match_type'}[0],
508 on_delete_do => $desc->{'on_delete_do'},
509 on_update_do => $desc->{'on_update_do'},
510 comments => [ @comments ],
514 table_constraint_type : /primary key/i '(' name_with_opt_quotes(s /,/) ')'
517 type => 'primary_key',
522 /unique/i '(' name_with_opt_quotes(s /,/) ')'
530 /check/ '(' /(.+)/ ')'
534 expression => $item[3],
538 /foreign key/i '(' name_with_opt_quotes(s /,/) ')' /references/i table_name parens_word_list(?) match_type(?) key_action(s?)
540 my ( $on_delete, $on_update );
541 for my $action ( @{ $item[9] || [] } ) {
542 $on_delete = $action->{'action'} if $action->{'type'} eq 'delete';
543 $on_update = $action->{'action'} if $action->{'type'} eq 'update';
547 type => 'foreign_key',
549 reference_table => $item[6],
550 reference_fields => $item[7][0],
551 match_type => $item[8][0],
552 on_delete_do => $on_delete || '',
553 on_update_do => $on_update || '',
557 deferrable : /not/i /deferrable/i
559 $return = ( $item[1] =~ /not/i ) ? 0 : 1;
562 deferred : /initially/i /(deferred|immediate)/i { $item[2] }
564 match_type : /match full/i { 'match_full' }
566 /match partial/i { 'match_partial' }
568 key_action : key_delete
572 key_delete : /on delete/i key_mutation
580 key_update : /on update/i key_mutation
588 key_mutation : /no action/i { $return = 'no_action' }
590 /restrict/i { $return = 'restrict' }
592 /cascade/i { $return = 'cascade' }
594 /set null/i { $return = 'set_null' }
596 /set default/i { $return = 'set_default' }
598 alter : alter_table table_name /add/i table_constraint ';'
600 my $table_name = $item[2];
601 my $constraint = $item[4];
602 $constraint->{'type'} = $constraint->{'constraint_type'};
603 push @{ $tables{ $table_name }{'constraints'} }, $constraint;
606 alter_table : /alter/i /table/i only(?)
610 create_table : /create/i /table/i
612 create_index : /create/i /index/i
614 default_val : /default/i /(?:')?[\w\d.-]*(?:')?/
616 my $val = $item[2] || '';
619 supertype => 'constraint',
625 name_with_opt_paren : NAME parens_value_list(s?)
626 { $item[2][0] ? "$item[1]($item[2][0][0])" : $item[1] }
628 unique : /unique/i { 1 }
630 key : /key/i | /index/i
632 table_option : /inherits/i '(' name_with_opt_quotes(s /,/) ')'
634 $return = { type => 'inherits', table_name => $item[3] }
639 $return = { type => $item[1] =~ /out/i ? 'without_oids' : 'with_oids' }
642 SEMICOLON : /\s*;\n?/
657 VALUE : /[-+]?\.?\d+(?:[eE]\d+)?/
659 | /'.*?'/ # XXX doesn't handle embedded quotes
666 # -------------------------------------------------------------------
668 my ( $translator, $data ) = @_;
669 $parser ||= Parse::RecDescent->new($GRAMMAR);
671 $::RD_TRACE = $translator->trace ? 1 : undef;
672 $DEBUG = $translator->debug;
674 unless (defined $parser) {
675 return $translator->error("Error instantiating Parse::RecDescent ".
676 "instance: Bad grammer");
679 my $result = $parser->startrule($data);
680 die "Parse failed.\n" unless defined $result;
681 warn Dumper($result) if $DEBUG;
683 my $schema = $translator->schema;
685 $result->{ $a }->{'order'} <=> $result->{ $b }->{'order'}
688 for my $table_name ( @tables ) {
689 my $tdata = $result->{ $table_name };
690 my $table = $schema->add_table(
691 name => $tdata->{'table_name'},
692 ) or die $schema->error;
695 $tdata->{'fields'}->{$a}->{'order'}
697 $tdata->{'fields'}->{$b}->{'order'}
698 } keys %{ $tdata->{'fields'} };
700 for my $fname ( @fields ) {
701 my $fdata = $tdata->{'fields'}{ $fname };
702 my $field = $table->add_field(
703 name => $fdata->{'name'},
704 data_type => $fdata->{'data_type'},
705 size => $fdata->{'size'},
706 default_value => $fdata->{'default'},
707 is_auto_increment => $fdata->{'is_auto_inc'},
708 is_nullable => $fdata->{'null'},
709 ) or die $table->error;
711 $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
713 for my $cdata ( @{ $fdata->{'constraints'} } ) {
714 next unless $cdata->{'type'} eq 'foreign_key';
715 $cdata->{'fields'} ||= [ $field->name ];
716 push @{ $tdata->{'constraints'} }, $cdata;
720 for my $idata ( @{ $tdata->{'indices'} || [] } ) {
721 my $index = $table->add_index(
722 name => $idata->{'name'},
723 type => uc $idata->{'type'},
724 fields => $idata->{'fields'},
725 ) or die $table->error;
728 for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
729 my $constraint = $table->add_constraint(
730 name => $cdata->{'name'},
731 type => $cdata->{'type'},
732 fields => $cdata->{'fields'},
733 reference_table => $cdata->{'reference_table'},
734 reference_fields => $cdata->{'reference_fields'},
735 match_type => $cdata->{'match_type'} || '',
736 on_delete => $cdata->{'on_delete_do'},
737 on_update => $cdata->{'on_update_do'},
738 ) or die $table->error;
747 # -------------------------------------------------------------------
748 # Rescue the drowning and tie your shoestrings.
749 # Henry David Thoreau
750 # -------------------------------------------------------------------
756 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>,
757 Allen Day <allenday@ucla.edu>.
761 perl(1), Parse::RecDescent.