1 package SQL::Translator::Parser::PostgreSQL;
3 # -------------------------------------------------------------------
4 # $Id: PostgreSQL.pm,v 1.10 2003-04-02 01:46:16 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 }
109 use vars qw[ $DEBUG $VERSION $GRAMMAR @EXPORT_OK ];
110 $VERSION = sprintf "%d.%02d", q$Revision: 1.10 $ =~ /(\d+)\.(\d+)/;
111 $DEBUG = 0 unless defined $DEBUG;
114 use Parse::RecDescent;
116 use base qw(Exporter);
118 @EXPORT_OK = qw(parse);
120 # Enable warnings within the Parse::RecDescent module.
121 $::RD_ERRORS = 1; # Make sure the parser dies when it encounters an error
122 $::RD_WARN = 1; # Enable warnings. This will warn on unused rules &c.
123 $::RD_HINT = 1; # Give out hints to help fix problems.
125 my $parser; # should we do this? There's no programmic way to
126 # change the grammar, so I think this is safe.
130 { our ( %tables, $table_order ) }
133 # The "eofile" rule makes the parser fail if any "statement" rule
134 # fails. Otherwise, the first successful match by a "statement"
135 # won't cause the failure needed to know that the parse, as a whole,
138 startrule : statement(s) eofile { \%tables }
152 connect : /^\s*\\\connect.*\n/
154 set : /SET/ /[^;]*/ ';'
156 revoke : /revoke/i WORD(s /,/) /on/i table_name /from/i name_with_opt_quotes(s /,/) ';'
158 my $table_name = $item{'table_name'};
159 push @{ $tables{ $table_name }{'permissions'} }, {
166 grant : /grant/i WORD(s /,/) /on/i table_name /to/i name_with_opt_quotes(s /,/) ';'
168 my $table_name = $item{'table_name'};
169 push @{ $tables{ $table_name }{'permissions'} }, {
176 drop : /drop/i /[^;]*/ ';'
181 create : create_table table_name '(' create_definition(s /,/) ')' table_option(s?) ';'
183 my $table_name = $item{'table_name'};
184 $tables{ $table_name }{'order'} = ++$table_order;
185 $tables{ $table_name }{'table_name'} = $table_name;
189 for my $definition ( @{ $item[4] } ) {
190 if ( $definition->{'type'} eq 'field' ) {
191 my $field_name = $definition->{'name'};
192 $tables{ $table_name }{'fields'}{ $field_name } =
193 { %$definition, order => $i };
196 if ( $definition->{'is_primary_key'} ) {
197 push @{ $tables{ $table_name }{'indices'} }, {
198 type => 'primary_key',
199 fields => [ $field_name ],
203 for my $constraint ( @{ $definition->{'constraints'} || [] } ) {
204 $constraint->{'fields'} = [ $field_name ];
205 push @{ $tables{ $table_name }{'constraints'} },
209 elsif ( $definition->{'type'} eq 'constraint' ) {
210 $definition->{'type'} = $definition->{'constraint_type'};
211 # group FKs at the field level
212 if ( $definition->{'type'} eq 'foreign_key' ) {
213 for my $fld ( @{ $definition->{'fields'} || [] } ) {
215 $tables{$table_name}{'fields'}{$fld}{'constraints'}
220 push @{ $tables{ $table_name }{'constraints'} },
225 push @{ $tables{ $table_name }{'indices'} }, $definition;
229 for my $option ( @{ $item[6] } ) {
230 $tables{ $table_name }{'table_options'}{ $option->{'type'} } =
240 create : /create/i unique(?) /(index|key)/i index_name /on/i table_name using_method(?) '(' field_name(s /,/) ')' where_predicate(?) ';'
242 push @{ $tables{ $item{'table_name'} }{'indices'} },
244 name => $item{'index_name'},
245 type => $item{'unique'}[0] ? 'unique' : 'normal',
247 method => $item{'using_method'}[0],
253 # Create anything else (e.g., domain, function, etc.)
255 create : /create/i WORD /[^;]+/ ';'
257 using_method : /using/i WORD { $item[2] }
259 where_predicate : /where/i /[^;]+/
261 create_definition : field
265 comment : /^\s*(?:#|-{2}).*\n/
267 field : comment(s?) field_name data_type field_meta(s?) comment(s?)
269 my ( $default, @constraints );
270 for my $meta ( @{ $item[4] } ) {
271 $default = $meta if $meta->{'meta_type'} eq 'default';
272 push @constraints, $meta if $meta->{'meta_type'} eq 'constraint';
275 my $null = ( grep { $_->{'type'} eq 'not_null' } @constraints ) ? 0 : 1;
277 my @comments = ( @{ $item[1] }, @{ $item[5] } );
281 name => $item{'field_name'},
282 data_type => $item{'data_type'}{'type'},
283 size => $item{'data_type'}{'size'},
284 list => $item{'data_type'}{'list'},
286 default => $default->{'value'},
287 constraints => [ @constraints ],
288 comments => [ @comments ],
293 field_meta : default_val
297 column_constraint : constraint_name(?) column_constraint_type deferrable(?) deferred(?)
299 my $desc = $item{'column_constraint_type'};
300 my $type = $desc->{'type'};
301 my $fields = $desc->{'fields'} || [];
302 my $expression = $desc->{'expression'} || '';
305 meta_type => 'constraint',
306 name => $item{'constraint_name'}[0] || '',
308 expression => $type eq 'check' ? $expression : '',
309 deferreable => $item{'deferrable'},
310 deferred => $item{'deferred'},
311 reference_table => $desc->{'reference_table'},
312 reference_fields => $desc->{'reference_fields'},
313 match_type => $desc->{'match_type'},
314 on_delete_do => $desc->{'on_delete_do'},
315 on_update_do => $desc->{'on_update_do'},
319 constraint_name : /constraint/i name_with_opt_quotes { $item[2] }
321 column_constraint_type : /not null/i { $return = { type => 'not_null' } }
324 { $return = { type => 'null' } }
327 { $return = { type => 'unique' } }
330 { $return = { type => 'primary_key' } }
332 /check/i '(' /[^)]+/ ')'
333 { $return = { type => 'check', expression => $item[2] } }
335 /references/i table_name parens_word_list(?) match_type(?) on_delete_do(?) on_update_do(?)
338 type => 'foreign_key',
339 reference_table => $item[2],
340 reference_fields => $item[3][0],
341 match_type => $item[4][0],
342 on_delete_do => $item[5][0],
343 on_update_do => $item[6][0],
347 table_name : name_with_opt_quotes
349 field_name : name_with_opt_quotes
351 name_with_opt_quotes : double_quote(?) NAME double_quote(?) { $item[2] }
357 data_type : pg_data_type parens_value_list(?)
362 # We can deduce some sizes from the data type's name.
365 if ( ref $type eq 'ARRAY' ) {
366 $size = [ $type->[1] ];
370 $size = $item[2][0] || '';
380 /(bigint|int8|bigserial|serial8)/ { $return = [ 'integer', 8 ] }
382 /(smallint|int2)/ { $return = [ 'integer', 2 ] }
384 /int(eger)?|int4/ { $return = [ 'integer', 4 ] }
386 /(double precision|float8?)/ { $return = [ 'float', 8 ] }
388 /(real|float4)/ { $return = [ 'real', 4 ] }
390 /serial4?/ { $return = [ 'serial', 4 ] }
392 /bigserial/ { $return = [ 'serial', 8 ] }
394 /(bit varying|varbit)/ { $return = 'varbit' }
396 /character varying/ { $return = 'varchar' }
398 /char(acter)?/ { $return = 'char' }
400 /bool(ean)?/ { $return = 'boolean' }
402 /(bytea|binary data)/ { $return = 'binary' }
404 /timestampz?/ { $return = 'timestamp' }
406 /(bit|box|cidr|circle|date|inet|interval|line|lseg|macaddr|money|numeric|decimal|path|point|polygon|text|time|varchar)/
409 parens_value_list : '(' VALUE(s /,/) ')'
412 parens_word_list : '(' WORD(s /,/) ')'
415 field_size : '(' num_range ')' { $item{'num_range'} }
417 num_range : DIGITS ',' DIGITS
418 { $return = $item[1].','.$item[3] }
420 { $return = $item[1] }
422 table_constraint : comment(s?) constraint_name(?) table_constraint_type deferrable(?) deferred(?) comment(s?)
424 my $desc = $item{'table_constraint_type'};
425 my $type = $desc->{'type'};
426 my $fields = $desc->{'fields'};
427 my $expression = $desc->{'expression'};
428 my @comments = ( @{ $item[1] }, @{ $item[-1] } );
431 name => $item{'constraint_name'}[0] || '',
432 type => 'constraint',
433 constraint_type => $type,
434 fields => $type ne 'check' ? $fields : [],
435 expression => $type eq 'check' ? $expression : '',
436 deferreable => $item{'deferrable'},
437 deferred => $item{'deferred'},
438 reference_table => $desc->{'reference_table'},
439 reference_fields => $desc->{'reference_fields'},
440 match_type => $desc->{'match_type'}[0],
441 on_delete_do => $desc->{'on_delete_do'},
442 on_update_do => $desc->{'on_update_do'},
443 comments => [ @comments ],
447 table_constraint_type : /primary key/i '(' name_with_opt_quotes(s /,/) ')'
450 type => 'primary_key',
455 /unique/i '(' name_with_opt_quotes(s /,/) ')'
463 /check/ '(' /(.+)/ ')'
467 expression => $item[3],
471 /foreign key/i '(' name_with_opt_quotes(s /,/) ')' /references/i table_name parens_word_list(?) match_type(?) on_delete_do(?) on_update_do(?)
474 type => 'foreign_key',
476 reference_table => $item[6],
477 reference_fields => $item[7][0],
478 match_type => $item[8][0],
479 on_delete_do => $item[9][0],
480 on_update_do => $item[10][0],
484 deferrable : /not/i /deferrable/i
486 $return = ( $item[1] =~ /not/i ) ? 0 : 1;
489 deferred : /initially/i /(deferred|immediate)/i { $item[2] }
491 match_type : /match full/i { 'match_full' }
493 /match partial/i { 'match_partial' }
495 on_delete_do : /on delete/i WORD(s)
498 on_update_do : /on update/i WORD(s)
501 alter : alter_table table_name /add/i table_constraint ';'
503 my $table_name = $item[2];
504 my $constraint = $item[4];
505 $constraint->{'type'} = $constraint->{'constraint_type'};
506 push @{ $tables{ $table_name }{'constraints'} }, $constraint;
509 alter_table : /alter/i /table/i only(?)
513 create_table : /create/i /table/i
515 create_index : /create/i /index/i
517 default_val : /default/i /(?:')?[\w\d.-]*(?:')?/
519 my $val = $item[2] || '';
522 meta_type => 'default',
527 name_with_opt_paren : NAME parens_value_list(s?)
528 { $item[2][0] ? "$item[1]($item[2][0][0])" : $item[1] }
530 unique : /unique/i { 1 }
532 key : /key/i | /index/i
534 table_option : /inherits/i '(' name_with_opt_quotes(s /,/) ')'
536 $return = { type => 'inherits', table_name => $item[3] }
541 $return = { type => $item[1] =~ /out/i ? 'without_oids' : 'with_oids' }
544 SEMICOLON : /\s*;\n?/
559 VALUE : /[-+]?\.?\d+(?:[eE]\d+)?/
561 | /'.*?'/ # XXX doesn't handle embedded quotes
568 # -------------------------------------------------------------------
570 my ( $translator, $data ) = @_;
571 $parser ||= Parse::RecDescent->new($GRAMMAR);
573 $::RD_TRACE = $translator->trace ? 1 : undef;
574 $DEBUG = $translator->debug;
576 unless (defined $parser) {
577 return $translator->error("Error instantiating Parse::RecDescent ".
578 "instance: Bad grammer");
581 my $result = $parser->startrule($data);
582 die "Parse failed.\n" unless defined $result;
583 warn Dumper($result) if $DEBUG;
589 #-----------------------------------------------------
590 # Where man is not nature is barren.
592 #-----------------------------------------------------
598 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>,
599 Allen Day <allenday@users.sourceforge.net>.
603 perl(1), Parse::RecDescent.