Not much to say ... just trying to get this working.
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Parser / PostgreSQL.pm
CommitLineData
84012a55 1package SQL::Translator::Parser::PostgreSQL;
4422e22a 2
3# -------------------------------------------------------------------
7d5bcab8 4# $Id: PostgreSQL.pm,v 1.12 2003-04-17 23:16:29 allenday Exp $
4422e22a 5# -------------------------------------------------------------------
6# Copyright (C) 2003 Ken Y. Clark <kclark@cpan.org>,
0efb6e1b 7# Allen Day <allenday@users.sourceforge.net>,
4422e22a 8# darren chamberlain <darren@cpan.org>,
9# Chris Mungall <cjm@fruitfly.org>
10#
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.
14#
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.
19#
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
0efb6e1b 22# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
4422e22a 23# 02111-1307 USA
24# -------------------------------------------------------------------
25
26=head1 NAME
27
84012a55 28SQL::Translator::Parser::PostgreSQL - parser for PostgreSQL
4422e22a 29
30=head1 SYNOPSIS
31
32 use SQL::Translator;
84012a55 33 use SQL::Translator::Parser::PostgreSQL;
4422e22a 34
35 my $translator = SQL::Translator->new;
84012a55 36 $translator->parser("SQL::Translator::Parser::PostgreSQL");
4422e22a 37
38=head1 DESCRIPTION
39
0efb6e1b 40The grammar was started from the MySQL parsers. Here is the description
41from PostgreSQL:
42
43Table:
629b76f9 44(http://www.postgresql.org/docs/view.php?version=7.3&idoc=1&file=sql-createtable.html)
45
46 CREATE [ [ LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (
47 { column_name data_type [ DEFAULT default_expr ]
48 [ column_constraint [, ... ] ]
49 | table_constraint } [, ... ]
50 )
51 [ INHERITS ( parent_table [, ... ] ) ]
52 [ WITH OIDS | WITHOUT OIDS ]
53
54 where column_constraint is:
55
56 [ CONSTRAINT constraint_name ]
57 { NOT NULL | NULL | UNIQUE | PRIMARY KEY |
58 CHECK (expression) |
59 REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL ]
60 [ ON DELETE action ] [ ON UPDATE action ] }
61 [ DEFERRABLE | NOT DEFERRABLE ]
62 [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
63
64 and table_constraint is:
65
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 ]
0efb6e1b 76
77Index:
629b76f9 78(http://www.postgresql.org/docs/view.php?version=7.3&idoc=1&file=sql-createindex.html)
0efb6e1b 79
629b76f9 80 CREATE [ UNIQUE ] INDEX index_name ON table
81 [ USING acc_method ] ( column [ ops_name ] [, ...] )
82 [ WHERE predicate ]
83 CREATE [ UNIQUE ] INDEX index_name ON table
84 [ USING acc_method ] ( func_name( column [, ... ]) [ ops_name ] )
85 [ WHERE predicate ]
4422e22a 86
0012a163 87Alter table:
88
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
97 ALTER TABLE table
98 RENAME TO new_table
99 ALTER TABLE table
100 ADD table_constraint_definition
101 ALTER TABLE [ ONLY ] table
102 DROP CONSTRAINT constraint { RESTRICT | CASCADE }
103 ALTER TABLE table
104 OWNER TO new_owner
105
4422e22a 106=cut
107
108use strict;
109use vars qw[ $DEBUG $VERSION $GRAMMAR @EXPORT_OK ];
7d5bcab8 110$VERSION = sprintf "%d.%02d", q$Revision: 1.12 $ =~ /(\d+)\.(\d+)/;
4422e22a 111$DEBUG = 0 unless defined $DEBUG;
112
113use Data::Dumper;
114use Parse::RecDescent;
115use Exporter;
116use base qw(Exporter);
117
118@EXPORT_OK = qw(parse);
119
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.
124
125my $parser; # should we do this? There's no programmic way to
126 # change the grammar, so I think this is safe.
127
128$GRAMMAR = q!
129
0efb6e1b 130{ our ( %tables, $table_order ) }
4422e22a 131
629b76f9 132#
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,
136# failed. -ky
137#
0efb6e1b 138startrule : statement(s) eofile { \%tables }
4422e22a 139
0efb6e1b 140eofile : /^\Z/
141
142statement : create
143 | comment
0012a163 144 | alter
0efb6e1b 145 | grant
146 | revoke
4422e22a 147 | drop
0efb6e1b 148 | connect
0012a163 149 | set
4422e22a 150 | <error>
151
0efb6e1b 152connect : /^\s*\\\connect.*\n/
153
0012a163 154set : /SET/ /[^;]*/ ';'
155
0efb6e1b 156revoke : /revoke/i WORD(s /,/) /on/i table_name /from/i name_with_opt_quotes(s /,/) ';'
157 {
158 my $table_name = $item{'table_name'};
159 push @{ $tables{ $table_name }{'permissions'} }, {
160 type => 'revoke',
161 actions => $item[2],
162 users => $item[6],
163 }
164 }
165
166grant : /grant/i WORD(s /,/) /on/i table_name /to/i name_with_opt_quotes(s /,/) ';'
167 {
168 my $table_name = $item{'table_name'};
169 push @{ $tables{ $table_name }{'permissions'} }, {
170 type => 'grant',
171 actions => $item[2],
172 users => $item[6],
173 }
174 }
175
176drop : /drop/i /[^;]*/ ';'
4422e22a 177
0012a163 178#
179# Create table.
180#
ba1a1626 181create : create_table table_name '(' create_definition(s /,/) ')' table_option(s?) ';'
0efb6e1b 182 {
183 my $table_name = $item{'table_name'};
184 $tables{ $table_name }{'order'} = ++$table_order;
185 $tables{ $table_name }{'table_name'} = $table_name;
186
187 my $i = 1;
188 my @constraints;
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 };
194 $i++;
4422e22a 195
0efb6e1b 196 if ( $definition->{'is_primary_key'} ) {
197 push @{ $tables{ $table_name }{'indices'} }, {
198 type => 'primary_key',
199 fields => [ $field_name ],
200 };
201 }
202
0138f7bb 203 for my $constraint ( @{ $definition->{'constraints'} || [] } ) {
204 $constraint->{'fields'} = [ $field_name ];
7d5bcab8 205 push @{ $tables{ $table_name }{'constraints'} },
0138f7bb 206 $constraint;
0efb6e1b 207 }
208 }
209 elsif ( $definition->{'type'} eq 'constraint' ) {
210 $definition->{'type'} = $definition->{'constraint_type'};
0138f7bb 211 # group FKs at the field level
212 if ( $definition->{'type'} eq 'foreign_key' ) {
213 for my $fld ( @{ $definition->{'fields'} || [] } ) {
214 push @{
215 $tables{$table_name}{'fields'}{$fld}{'constraints'}
216 }, $definition;
217 }
218 }
219 else {
220 push @{ $tables{ $table_name }{'constraints'} },
221 $definition;
222 }
0efb6e1b 223 }
224 else {
225 push @{ $tables{ $table_name }{'indices'} }, $definition;
226 }
227 }
228
229 for my $option ( @{ $item[6] } ) {
230 $tables{ $table_name }{'table_options'}{ $option->{'type'} } =
231 $option;
232 }
233
234 1;
235 }
236
0012a163 237#
238# Create index.
239#
0efb6e1b 240create : /create/i unique(?) /(index|key)/i index_name /on/i table_name using_method(?) '(' field_name(s /,/) ')' where_predicate(?) ';'
4422e22a 241 {
242 push @{ $tables{ $item{'table_name'} }{'indices'} },
243 {
0efb6e1b 244 name => $item{'index_name'},
245 type => $item{'unique'}[0] ? 'unique' : 'normal',
246 fields => $item[9],
247 method => $item{'using_method'}[0],
4422e22a 248 }
249 ;
250 }
251
0012a163 252#
253# Create anything else (e.g., domain, function, etc.)
254#
255create : /create/i WORD /[^;]+/ ';'
256
0efb6e1b 257using_method : /using/i WORD { $item[2] }
258
259where_predicate : /where/i /[^;]+/
260
261create_definition : field
0efb6e1b 262 | table_constraint
4422e22a 263 | <error>
264
265comment : /^\s*(?:#|-{2}).*\n/
266
f2f71b8e 267field : comment(s?) field_name data_type field_meta(s?) comment(s?)
4422e22a 268 {
0efb6e1b 269 my ( $default, @constraints );
41fc9cb3 270 for my $meta ( @{ $item[4] } ) {
0efb6e1b 271 $default = $meta if $meta->{'meta_type'} eq 'default';
272 push @constraints, $meta if $meta->{'meta_type'} eq 'constraint';
4422e22a 273 }
274
0efb6e1b 275 my $null = ( grep { $_->{'type'} eq 'not_null' } @constraints ) ? 0 : 1;
276
f2f71b8e 277 my @comments = ( @{ $item[1] }, @{ $item[5] } );
278
0a7fc605 279 $return = {
4422e22a 280 type => 'field',
281 name => $item{'field_name'},
282 data_type => $item{'data_type'}{'type'},
283 size => $item{'data_type'}{'size'},
284 list => $item{'data_type'}{'list'},
285 null => $null,
0efb6e1b 286 default => $default->{'value'},
287 constraints => [ @constraints ],
f2f71b8e 288 comments => [ @comments ],
4422e22a 289 }
290 }
291 | <error>
292
0efb6e1b 293field_meta : default_val
294 |
295 column_constraint
4422e22a 296
0efb6e1b 297column_constraint : constraint_name(?) column_constraint_type deferrable(?) deferred(?)
298 {
299 my $desc = $item{'column_constraint_type'};
300 my $type = $desc->{'type'};
301 my $fields = $desc->{'fields'} || [];
302 my $expression = $desc->{'expression'} || '';
303
304 $return = {
305 meta_type => 'constraint',
306 name => $item{'constraint_name'}[0] || '',
307 type => $type,
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'},
4422e22a 316 }
317 }
318
0efb6e1b 319constraint_name : /constraint/i name_with_opt_quotes { $item[2] }
320
321column_constraint_type : /not null/i { $return = { type => 'not_null' } }
322 |
323 /null/
324 { $return = { type => 'null' } }
325 |
326 /unique/
327 { $return = { type => 'unique' } }
328 |
329 /primary key/i
330 { $return = { type => 'primary_key' } }
331 |
332 /check/i '(' /[^)]+/ ')'
333 { $return = { type => 'check', expression => $item[2] } }
334 |
0138f7bb 335 /references/i table_name parens_word_list(?) match_type(?) on_delete_do(?) on_update_do(?)
0efb6e1b 336 {
337 $return = {
338 type => 'foreign_key',
339 reference_table => $item[2],
0138f7bb 340 reference_fields => $item[3][0],
0efb6e1b 341 match_type => $item[4][0],
342 on_delete_do => $item[5][0],
343 on_update_do => $item[6][0],
ba1a1626 344 }
4422e22a 345 }
346
0efb6e1b 347table_name : name_with_opt_quotes
4422e22a 348
0efb6e1b 349field_name : name_with_opt_quotes
4422e22a 350
0012a163 351name_with_opt_quotes : double_quote(?) NAME double_quote(?) { $item[2] }
4422e22a 352
0efb6e1b 353double_quote: /"/
4422e22a 354
0efb6e1b 355index_name : WORD
4422e22a 356
0efb6e1b 357data_type : pg_data_type parens_value_list(?)
4422e22a 358 {
359 my $type = $item[1];
ba1a1626 360
0efb6e1b 361 #
362 # We can deduce some sizes from the data type's name.
363 #
364 my $size;
365 if ( ref $type eq 'ARRAY' ) {
366 $size = [ $type->[1] ];
367 $type = $type->[0];
4422e22a 368 }
369 else {
0efb6e1b 370 $size = $item[2][0] || '';
4422e22a 371 }
372
0efb6e1b 373 $return = {
374 type => $type,
375 size => $size,
4422e22a 376 }
377 }
378
0efb6e1b 379pg_data_type :
0a7fc605 380 /(bigint|int8|bigserial|serial8)/ { $return = [ 'integer(8) auto_increment'] }
0efb6e1b 381 |
382 /(smallint|int2)/ { $return = [ 'integer', 2 ] }
383 |
384 /int(eger)?|int4/ { $return = [ 'integer', 4 ] }
385 |
386 /(double precision|float8?)/ { $return = [ 'float', 8 ] }
387 |
388 /(real|float4)/ { $return = [ 'real', 4 ] }
389 |
0a7fc605 390 /serial4?/ { $return = [ 'integer(4) auto_increment'] }
0efb6e1b 391 |
0a7fc605 392 /bigserial/ { $return = [ 'integer(8) auto_increment'] }
0efb6e1b 393 |
394 /(bit varying|varbit)/ { $return = 'varbit' }
395 |
396 /character varying/ { $return = 'varchar' }
397 |
398 /char(acter)?/ { $return = 'char' }
399 |
400 /bool(ean)?/ { $return = 'boolean' }
401 |
402 /(bytea|binary data)/ { $return = 'binary' }
403 |
404 /timestampz?/ { $return = 'timestamp' }
405 |
406 /(bit|box|cidr|circle|date|inet|interval|line|lseg|macaddr|money|numeric|decimal|path|point|polygon|text|time|varchar)/
407 { $item[1] }
408
4422e22a 409parens_value_list : '(' VALUE(s /,/) ')'
410 { $item[2] }
411
0efb6e1b 412parens_word_list : '(' WORD(s /,/) ')'
413 { $item[2] }
4422e22a 414
0efb6e1b 415field_size : '(' num_range ')' { $item{'num_range'} }
4422e22a 416
0efb6e1b 417num_range : DIGITS ',' DIGITS
4422e22a 418 { $return = $item[1].','.$item[3] }
419 | DIGITS
420 { $return = $item[1] }
421
f2f71b8e 422table_constraint : comment(s?) constraint_name(?) table_constraint_type deferrable(?) deferred(?) comment(s?)
0efb6e1b 423 {
424 my $desc = $item{'table_constraint_type'};
425 my $type = $desc->{'type'};
426 my $fields = $desc->{'fields'};
427 my $expression = $desc->{'expression'};
f2f71b8e 428 my @comments = ( @{ $item[1] }, @{ $item[-1] } );
0efb6e1b 429
430 $return = {
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],
0012a163 441 on_delete_do => $desc->{'on_delete_do'},
442 on_update_do => $desc->{'on_update_do'},
f2f71b8e 443 comments => [ @comments ],
0efb6e1b 444 }
445 }
4422e22a 446
0efb6e1b 447table_constraint_type : /primary key/i '(' name_with_opt_quotes(s /,/) ')'
448 {
449 $return = {
450 type => 'primary_key',
451 fields => $item[3],
452 }
453 }
454 |
455 /unique/i '(' name_with_opt_quotes(s /,/) ')'
456 {
457 $return = {
458 type => 'unique',
459 fields => $item[3],
460 }
461 }
462 |
463 /check/ '(' /(.+)/ ')'
464 {
465 $return = {
466 type => 'check',
467 expression => $item[3],
468 }
469 }
470 |
471 /foreign key/i '(' name_with_opt_quotes(s /,/) ')' /references/i table_name parens_word_list(?) match_type(?) on_delete_do(?) on_update_do(?)
472 {
473 $return = {
474 type => 'foreign_key',
475 fields => $item[3],
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],
481 }
482 }
483
484deferrable : /not/i /deferrable/i
485 {
486 $return = ( $item[1] =~ /not/i ) ? 0 : 1;
487 }
4422e22a 488
0efb6e1b 489deferred : /initially/i /(deferred|immediate)/i { $item[2] }
4422e22a 490
0efb6e1b 491match_type : /match full/i { 'match_full' }
492 |
493 /match partial/i { 'match_partial' }
494
0012a163 495on_delete_do : /on delete/i WORD(s)
0efb6e1b 496 { $item[2] }
497
0012a163 498on_update_do : /on update/i WORD(s)
0efb6e1b 499 { $item[2] }
500
0012a163 501alter : alter_table table_name /add/i table_constraint ';'
502 {
503 my $table_name = $item[2];
504 my $constraint = $item[4];
505 $constraint->{'type'} = $constraint->{'constraint_type'};
506 push @{ $tables{ $table_name }{'constraints'} }, $constraint;
507 }
508
509alter_table : /alter/i /table/i only(?)
510
511only : /only/i
512
0efb6e1b 513create_table : /create/i /table/i
514
515create_index : /create/i /index/i
4422e22a 516
517default_val : /default/i /(?:')?[\w\d.-]*(?:')?/
518 {
0efb6e1b 519 my $val = $item[2] || '';
520 $val =~ s/'//g;
521 $return = {
522 meta_type => 'default',
523 value => $val,
524 }
4422e22a 525 }
526
4422e22a 527name_with_opt_paren : NAME parens_value_list(s?)
0efb6e1b 528 { $item[2][0] ? "$item[1]($item[2][0][0])" : $item[1] }
4422e22a 529
530unique : /unique/i { 1 }
531
532key : /key/i | /index/i
533
0efb6e1b 534table_option : /inherits/i '(' name_with_opt_quotes(s /,/) ')'
4422e22a 535 {
0efb6e1b 536 $return = { type => 'inherits', table_name => $item[3] }
537 }
538 |
539 /with(out)? oids/i
540 {
541 $return = { type => $item[1] =~ /out/i ? 'without_oids' : 'with_oids' }
4422e22a 542 }
543
0efb6e1b 544SEMICOLON : /\s*;\n?/
545
4422e22a 546WORD : /\w+/
547
548DIGITS : /\d+/
549
550COMMA : ','
551
552NAME : "`" /\w+/ "`"
553 { $item[2] }
554 | /\w+/
555 { $item[1] }
0012a163 556 | /[\$\w]+/
557 { $item[1] }
4422e22a 558
559VALUE : /[-+]?\.?\d+(?:[eE]\d+)?/
560 { $item[1] }
561 | /'.*?'/ # XXX doesn't handle embedded quotes
562 { $item[1] }
563 | /NULL/
564 { 'NULL' }
565
566!;
567
568# -------------------------------------------------------------------
569sub parse {
570 my ( $translator, $data ) = @_;
571 $parser ||= Parse::RecDescent->new($GRAMMAR);
572
573 $::RD_TRACE = $translator->trace ? 1 : undef;
574 $DEBUG = $translator->debug;
575
576 unless (defined $parser) {
577 return $translator->error("Error instantiating Parse::RecDescent ".
578 "instance: Bad grammer");
579 }
580
581 my $result = $parser->startrule($data);
582 die "Parse failed.\n" unless defined $result;
583 warn Dumper($result) if $DEBUG;
584 return $result;
585}
586
5871;
588
589#-----------------------------------------------------
590# Where man is not nature is barren.
591# William Blake
592#-----------------------------------------------------
593
594=pod
595
0efb6e1b 596=head1 AUTHORS
4422e22a 597
598Ken Y. Clark E<lt>kclark@cpan.orgE<gt>,
0a7fc605 599Allen Day <allenday@ucla.edu>.
4422e22a 600
601=head1 SEE ALSO
602
603perl(1), Parse::RecDescent.
604
605=cut