1 package SQL::Translator::Parser::PostgreSQL;
3 # -------------------------------------------------------------------
4 # $Id: PostgreSQL.pm,v 1.6 2003-02-25 14:55:36 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 ] )
90 use vars qw[ $DEBUG $VERSION $GRAMMAR @EXPORT_OK ];
91 $VERSION = sprintf "%d.%02d", q$Revision: 1.6 $ =~ /(\d+)\.(\d+)/;
92 $DEBUG = 0 unless defined $DEBUG;
95 use Parse::RecDescent;
97 use base qw(Exporter);
99 @EXPORT_OK = qw(parse);
101 # Enable warnings within the Parse::RecDescent module.
102 $::RD_ERRORS = 1; # Make sure the parser dies when it encounters an error
103 $::RD_WARN = 1; # Enable warnings. This will warn on unused rules &c.
104 $::RD_HINT = 1; # Give out hints to help fix problems.
106 my $parser; # should we do this? There's no programmic way to
107 # change the grammar, so I think this is safe.
111 { our ( %tables, $table_order ) }
114 # The "eofile" rule makes the parser fail if any "statement" rule
115 # fails. Otherwise, the first successful match by a "statement"
116 # won't cause the failure needed to know that the parse, as a whole,
119 startrule : statement(s) eofile { \%tables }
131 connect : /^\s*\\\connect.*\n/
133 revoke : /revoke/i WORD(s /,/) /on/i table_name /from/i name_with_opt_quotes(s /,/) ';'
135 my $table_name = $item{'table_name'};
136 push @{ $tables{ $table_name }{'permissions'} }, {
143 grant : /grant/i WORD(s /,/) /on/i table_name /to/i name_with_opt_quotes(s /,/) ';'
145 my $table_name = $item{'table_name'};
146 push @{ $tables{ $table_name }{'permissions'} }, {
153 drop : /drop/i /[^;]*/ ';'
155 create : create_table table_name '(' create_definition(s /,/) ')' table_option(s?) ';'
157 my $table_name = $item{'table_name'};
158 $tables{ $table_name }{'order'} = ++$table_order;
159 $tables{ $table_name }{'table_name'} = $table_name;
163 for my $definition ( @{ $item[4] } ) {
164 if ( $definition->{'type'} eq 'field' ) {
165 my $field_name = $definition->{'name'};
166 $tables{ $table_name }{'fields'}{ $field_name } =
167 { %$definition, order => $i };
170 if ( $definition->{'is_primary_key'} ) {
171 push @{ $tables{ $table_name }{'indices'} }, {
172 type => 'primary_key',
173 fields => [ $field_name ],
177 for my $constraint ( @{ $definition->{'constaints'} || [] } ) {
178 $constraint->{'fields' } = [ $field_name ];
179 push @{$tables{ $table_name }{'constraints'}}, $constraint;
182 elsif ( $definition->{'type'} eq 'constraint' ) {
183 $definition->{'type'} = $definition->{'constraint_type'};
184 push @{ $tables{ $table_name }{'constraints'} }, $definition;
187 push @{ $tables{ $table_name }{'indices'} }, $definition;
191 for my $option ( @{ $item[6] } ) {
192 $tables{ $table_name }{'table_options'}{ $option->{'type'} } =
199 create : /create/i unique(?) /(index|key)/i index_name /on/i table_name using_method(?) '(' field_name(s /,/) ')' where_predicate(?) ';'
201 push @{ $tables{ $item{'table_name'} }{'indices'} },
203 name => $item{'index_name'},
204 type => $item{'unique'}[0] ? 'unique' : 'normal',
206 method => $item{'using_method'}[0],
211 using_method : /using/i WORD { $item[2] }
213 where_predicate : /where/i /[^;]+/
215 create_definition : field
220 comment : /^\s*(?:#|-{2}).*\n/
222 field : field_name data_type field_meta(s?)
224 my ( $default, @constraints );
225 for my $meta ( @{ $item[3] } ) {
226 $default = $meta if $meta->{'meta_type'} eq 'default';
227 push @constraints, $meta if $meta->{'meta_type'} eq 'constraint';
230 my $null = ( grep { $_->{'type'} eq 'not_null' } @constraints ) ? 0 : 1;
234 name => $item{'field_name'},
235 data_type => $item{'data_type'}{'type'},
236 size => $item{'data_type'}{'size'},
237 list => $item{'data_type'}{'list'},
239 default => $default->{'value'},
240 constraints => [ @constraints ],
245 field_meta : default_val
249 column_constraint : constraint_name(?) column_constraint_type deferrable(?) deferred(?)
251 my $desc = $item{'column_constraint_type'};
252 my $type = $desc->{'type'};
253 my $fields = $desc->{'fields'} || [];
254 my $expression = $desc->{'expression'} || '';
257 meta_type => 'constraint',
258 name => $item{'constraint_name'}[0] || '',
260 expression => $type eq 'check' ? $expression : '',
261 deferreable => $item{'deferrable'},
262 deferred => $item{'deferred'},
263 reference_table => $desc->{'reference_table'},
264 reference_fields => $desc->{'reference_fields'},
265 match_type => $desc->{'match_type'},
266 on_delete_do => $desc->{'on_delete_do'},
267 on_update_do => $desc->{'on_update_do'},
271 constraint_name : /constraint/i name_with_opt_quotes { $item[2] }
273 column_constraint_type : /not null/i { $return = { type => 'not_null' } }
276 { $return = { type => 'null' } }
279 { $return = { type => 'unique' } }
282 { $return = { type => 'primary_key' } }
284 /check/i '(' /[^)]+/ ')'
285 { $return = { type => 'check', expression => $item[2] } }
287 /references/i table_name parens_value_list(?) match_type(?) on_delete_do(?) on_update_do(?)
290 type => 'foreign_key',
291 reference_table => $item[2],
292 reference_fields => $item[3],
293 match_type => $item[4][0],
294 on_delete_do => $item[5][0],
295 on_update_do => $item[6][0],
299 index : primary_key_index
303 table_name : name_with_opt_quotes
305 field_name : name_with_opt_quotes
307 name_with_opt_quotes : double_quote(?) WORD double_quote(?) { $item[2] }
313 data_type : pg_data_type parens_value_list(?)
318 # We can deduce some sizes from the data type's name.
321 if ( ref $type eq 'ARRAY' ) {
322 $size = [ $type->[1] ];
326 $size = $item[2][0] || '';
336 /(bigint|int8|bigserial|serial8)/ { $return = [ 'integer', 8 ] }
338 /(smallint|int2)/ { $return = [ 'integer', 2 ] }
340 /int(eger)?|int4/ { $return = [ 'integer', 4 ] }
342 /(double precision|float8?)/ { $return = [ 'float', 8 ] }
344 /(real|float4)/ { $return = [ 'real', 4 ] }
346 /serial4?/ { $return = [ 'serial', 4 ] }
348 /bigserial/ { $return = [ 'serial', 8 ] }
350 /(bit varying|varbit)/ { $return = 'varbit' }
352 /character varying/ { $return = 'varchar' }
354 /char(acter)?/ { $return = 'char' }
356 /bool(ean)?/ { $return = 'boolean' }
358 /(bytea|binary data)/ { $return = 'binary' }
360 /timestampz?/ { $return = 'timestamp' }
362 /(bit|box|cidr|circle|date|inet|interval|line|lseg|macaddr|money|numeric|decimal|path|point|polygon|text|time|varchar)/
365 parens_value_list : '(' VALUE(s /,/) ')'
368 parens_word_list : '(' WORD(s /,/) ')'
371 field_size : '(' num_range ')' { $item{'num_range'} }
373 num_range : DIGITS ',' DIGITS
374 { $return = $item[1].','.$item[3] }
376 { $return = $item[1] }
378 table_constraint : constraint_name(?) table_constraint_type deferrable(?) deferred(?)
380 my $desc = $item{'table_constraint_type'};
381 my $type = $desc->{'type'};
382 my $fields = $desc->{'fields'};
383 my $expression = $desc->{'expression'};
386 name => $item{'constraint_name'}[0] || '',
387 type => 'constraint',
388 constraint_type => $type,
389 fields => $type ne 'check' ? $fields : [],
390 expression => $type eq 'check' ? $expression : '',
391 deferreable => $item{'deferrable'},
392 deferred => $item{'deferred'},
393 reference_table => $desc->{'reference_table'},
394 reference_fields => $desc->{'reference_fields'},
395 match_type => $desc->{'match_type'}[0],
396 on_delete_do => $desc->{'on_delete_do'}[0],
397 on_update_do => $desc->{'on_update_do'}[0],
401 table_constraint_type : /primary key/i '(' name_with_opt_quotes(s /,/) ')'
404 type => 'primary_key',
409 /unique/i '(' name_with_opt_quotes(s /,/) ')'
417 /check/ '(' /(.+)/ ')'
421 expression => $item[3],
425 /foreign key/i '(' name_with_opt_quotes(s /,/) ')' /references/i table_name parens_word_list(?) match_type(?) on_delete_do(?) on_update_do(?)
428 type => 'foreign_key',
430 reference_table => $item[6],
431 reference_fields => $item[7][0],
432 match_type => $item[8][0],
433 on_delete_do => $item[9][0],
434 on_update_do => $item[10][0],
438 deferrable : /not/i /deferrable/i
440 $return = ( $item[1] =~ /not/i ) ? 0 : 1;
443 deferred : /initially/i /(deferred|immediate)/i { $item[2] }
445 match_type : /match full/i { 'match_full' }
447 /match partial/i { 'match_partial' }
449 on_delete_do : /on delete/i WORD
452 on_update_do : /on update/i WORD
455 create_table : /create/i /table/i
457 create_index : /create/i /index/i
459 default_val : /default/i /(?:')?[\w\d.-]*(?:')?/
461 my $val = $item[2] || '';
464 meta_type => 'default',
469 auto_inc : /auto_increment/i { 1 }
471 primary_key : /primary/i /key/i { 1 }
473 primary_key_index : primary_key index_name(?) '(' field_name(s /,/) ')'
476 name => $item{'index_name'}[0],
477 type => 'primary_key',
482 normal_index : key index_name(?) '(' name_with_opt_paren(s /,/) ')'
485 name => $item{'index_name'}[0],
491 unique_index : unique key(?) index_name(?) '(' name_with_opt_paren(s /,/) ')'
494 name => $item{'index_name'}[0],
500 name_with_opt_paren : NAME parens_value_list(s?)
501 { $item[2][0] ? "$item[1]($item[2][0][0])" : $item[1] }
503 unique : /unique/i { 1 }
505 key : /key/i | /index/i
507 table_option : /inherits/i '(' name_with_opt_quotes(s /,/) ')'
509 $return = { type => 'inherits', table_name => $item[3] }
514 $return = { type => $item[1] =~ /out/i ? 'without_oids' : 'with_oids' }
517 SEMICOLON : /\s*;\n?/
530 VALUE : /[-+]?\.?\d+(?:[eE]\d+)?/
532 | /'.*?'/ # XXX doesn't handle embedded quotes
539 # -------------------------------------------------------------------
541 my ( $translator, $data ) = @_;
542 $parser ||= Parse::RecDescent->new($GRAMMAR);
544 $::RD_TRACE = $translator->trace ? 1 : undef;
545 $DEBUG = $translator->debug;
547 unless (defined $parser) {
548 return $translator->error("Error instantiating Parse::RecDescent ".
549 "instance: Bad grammer");
552 my $result = $parser->startrule($data);
553 die "Parse failed.\n" unless defined $result;
554 warn Dumper($result) if $DEBUG;
560 #-----------------------------------------------------
561 # Where man is not nature is barren.
563 #-----------------------------------------------------
569 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>,
570 Allen Day <allenday@users.sourceforge.net>.
574 perl(1), Parse::RecDescent.