Added an 'alter sequence' line to the parser grammer which will simply skip over...
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Parser / PostgreSQL.pm
CommitLineData
84012a55 1package SQL::Translator::Parser::PostgreSQL;
4422e22a 2
3# -------------------------------------------------------------------
a20abbda 4# $Id: PostgreSQL.pm,v 1.50 2007-11-13 19:25:04 mwz444 Exp $
4422e22a 5# -------------------------------------------------------------------
90075866 6# Copyright (C) 2002-4 SQLFairy Authors
4422e22a 7#
8# This program is free software; you can redistribute it and/or
9# modify it under the terms of the GNU General Public License as
10# published by the Free Software Foundation; version 2.
11#
12# This program is distributed in the hope that it will be useful, but
13# WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15# General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
0efb6e1b 19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
4422e22a 20# 02111-1307 USA
21# -------------------------------------------------------------------
22
23=head1 NAME
24
84012a55 25SQL::Translator::Parser::PostgreSQL - parser for PostgreSQL
4422e22a 26
27=head1 SYNOPSIS
28
29 use SQL::Translator;
84012a55 30 use SQL::Translator::Parser::PostgreSQL;
4422e22a 31
32 my $translator = SQL::Translator->new;
84012a55 33 $translator->parser("SQL::Translator::Parser::PostgreSQL");
4422e22a 34
35=head1 DESCRIPTION
36
0efb6e1b 37The grammar was started from the MySQL parsers. Here is the description
38from PostgreSQL:
39
40Table:
629b76f9 41(http://www.postgresql.org/docs/view.php?version=7.3&idoc=1&file=sql-createtable.html)
42
43 CREATE [ [ LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (
44 { column_name data_type [ DEFAULT default_expr ]
45 [ column_constraint [, ... ] ]
46 | table_constraint } [, ... ]
47 )
48 [ INHERITS ( parent_table [, ... ] ) ]
49 [ WITH OIDS | WITHOUT OIDS ]
50
51 where column_constraint is:
52
53 [ CONSTRAINT constraint_name ]
54 { NOT NULL | NULL | UNIQUE | PRIMARY KEY |
55 CHECK (expression) |
56 REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL ]
57 [ ON DELETE action ] [ ON UPDATE action ] }
58 [ DEFERRABLE | NOT DEFERRABLE ]
59 [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
60
61 and table_constraint is:
62
63 [ CONSTRAINT constraint_name ]
64 { UNIQUE ( column_name [, ... ] ) |
65 PRIMARY KEY ( column_name [, ... ] ) |
66 CHECK ( expression ) |
67 FOREIGN KEY ( column_name [, ... ] )
68 REFERENCES reftable [ ( refcolumn [, ... ] ) ]
69 [ MATCH FULL | MATCH PARTIAL ]
70 [ ON DELETE action ] [ ON UPDATE action ] }
71 [ DEFERRABLE | NOT DEFERRABLE ]
72 [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
0efb6e1b 73
74Index:
629b76f9 75(http://www.postgresql.org/docs/view.php?version=7.3&idoc=1&file=sql-createindex.html)
0efb6e1b 76
629b76f9 77 CREATE [ UNIQUE ] INDEX index_name ON table
78 [ USING acc_method ] ( column [ ops_name ] [, ...] )
79 [ WHERE predicate ]
80 CREATE [ UNIQUE ] INDEX index_name ON table
81 [ USING acc_method ] ( func_name( column [, ... ]) [ ops_name ] )
82 [ WHERE predicate ]
4422e22a 83
0012a163 84Alter table:
85
86 ALTER TABLE [ ONLY ] table [ * ]
87 ADD [ COLUMN ] column type [ column_constraint [ ... ] ]
88 ALTER TABLE [ ONLY ] table [ * ]
89 ALTER [ COLUMN ] column { SET DEFAULT value | DROP DEFAULT }
90 ALTER TABLE [ ONLY ] table [ * ]
91 ALTER [ COLUMN ] column SET STATISTICS integer
92 ALTER TABLE [ ONLY ] table [ * ]
93 RENAME [ COLUMN ] column TO newcolumn
94 ALTER TABLE table
95 RENAME TO new_table
96 ALTER TABLE table
97 ADD table_constraint_definition
98 ALTER TABLE [ ONLY ] table
99 DROP CONSTRAINT constraint { RESTRICT | CASCADE }
100 ALTER TABLE table
101 OWNER TO new_owner
102
3022f45b 103View table:
104
105 CREATE [ OR REPLACE ] VIEW view [ ( column name list ) ] AS SELECT query
106
4422e22a 107=cut
108
109use strict;
110use vars qw[ $DEBUG $VERSION $GRAMMAR @EXPORT_OK ];
a20abbda 111$VERSION = sprintf "%d.%02d", q$Revision: 1.50 $ =~ /(\d+)\.(\d+)/;
4422e22a 112$DEBUG = 0 unless defined $DEBUG;
113
114use Data::Dumper;
115use Parse::RecDescent;
116use Exporter;
117use base qw(Exporter);
118
119@EXPORT_OK = qw(parse);
120
121# Enable warnings within the Parse::RecDescent module.
122$::RD_ERRORS = 1; # Make sure the parser dies when it encounters an error
123$::RD_WARN = 1; # Enable warnings. This will warn on unused rules &c.
124$::RD_HINT = 1; # Give out hints to help fix problems.
125
126my $parser; # should we do this? There's no programmic way to
127 # change the grammar, so I think this is safe.
128
129$GRAMMAR = q!
130
00ef67ea 131{ my ( %tables, $table_order, $field_order, @table_comments) }
4422e22a 132
629b76f9 133#
134# The "eofile" rule makes the parser fail if any "statement" rule
135# fails. Otherwise, the first successful match by a "statement"
136# won't cause the failure needed to know that the parse, as a whole,
137# failed. -ky
138#
0efb6e1b 139startrule : statement(s) eofile { \%tables }
4422e22a 140
0efb6e1b 141eofile : /^\Z/
e4a9818d 142
0efb6e1b 143
144statement : create
ac397a49 145 | comment_on_table
146 | comment_on_column
e4a9818d 147 | comment_on_other
0efb6e1b 148 | comment
0012a163 149 | alter
0efb6e1b 150 | grant
151 | revoke
4422e22a 152 | drop
4d2da1f7 153 | insert
0efb6e1b 154 | connect
4d2da1f7 155 | update
0012a163 156 | set
4422e22a 157 | <error>
158
0efb6e1b 159connect : /^\s*\\\connect.*\n/
160
f04713db 161set : /set/i /[^;]*/ ';'
0012a163 162
0d51cd9e 163revoke : /revoke/i WORD(s /,/) /on/i TABLE(?) table_name /from/i name_with_opt_quotes(s /,/) ';'
0efb6e1b 164 {
a20abbda 165 my $table_info = $item{'table_name'};
166 my $schema_name = $table_info->{'schema_name'};
167 my $table_name = $table_info->{'table_name'};
0efb6e1b 168 push @{ $tables{ $table_name }{'permissions'} }, {
169 type => 'revoke',
170 actions => $item[2],
91c75eab 171 users => $item[7],
0efb6e1b 172 }
173 }
174
0d51cd9e 175grant : /grant/i WORD(s /,/) /on/i TABLE(?) table_name /to/i name_with_opt_quotes(s /,/) ';'
0efb6e1b 176 {
a20abbda 177 my $table_info = $item{'table_name'};
178 my $schema_name = $table_info->{'schema_name'};
179 my $table_name = $table_info->{'table_name'};
0efb6e1b 180 push @{ $tables{ $table_name }{'permissions'} }, {
181 type => 'grant',
182 actions => $item[2],
91c75eab 183 users => $item[7],
0efb6e1b 184 }
185 }
186
187drop : /drop/i /[^;]*/ ';'
4422e22a 188
9bf756df 189string :
190 /'(\\.|''|[^\\\'])*'/
4d2da1f7 191
9bf756df 192nonstring : /[^;\'"]+/
193
194statement_body : (string | nonstring)(s?)
195
196insert : /insert/i statement_body ';'
197
198update : /update/i statement_body ';'
4d2da1f7 199
0012a163 200#
201# Create table.
202#
c7ea1132 203create : create_table table_name '(' create_definition(s? /,/) ')' table_option(s?) ';'
0efb6e1b 204 {
a20abbda 205 my $table_info = $item{'table_name'};
206 my $schema_name = $table_info->{'schema_name'};
207 my $table_name = $table_info->{'table_name'};
208 $tables{ $table_name }{'order'} = ++$table_order;
209 $tables{ $table_name }{'schema_name'} = $schema_name;
210 $tables{ $table_name }{'table_name'} = $table_name;
0efb6e1b 211
ac397a49 212 if ( @table_comments ) {
213 $tables{ $table_name }{'comments'} = [ @table_comments ];
214 @table_comments = ();
215 }
216
0efb6e1b 217 my @constraints;
218 for my $definition ( @{ $item[4] } ) {
b3384294 219 if ( $definition->{'supertype'} eq 'field' ) {
0efb6e1b 220 my $field_name = $definition->{'name'};
221 $tables{ $table_name }{'fields'}{ $field_name } =
00ef67ea 222 { %$definition, order => $field_order++ };
4422e22a 223
0138f7bb 224 for my $constraint ( @{ $definition->{'constraints'} || [] } ) {
225 $constraint->{'fields'} = [ $field_name ];
7d5bcab8 226 push @{ $tables{ $table_name }{'constraints'} },
0138f7bb 227 $constraint;
0efb6e1b 228 }
229 }
b3384294 230 elsif ( $definition->{'supertype'} eq 'constraint' ) {
231 push @{ $tables{ $table_name }{'constraints'} }, $definition;
0efb6e1b 232 }
b3384294 233 elsif ( $definition->{'supertype'} eq 'index' ) {
0efb6e1b 234 push @{ $tables{ $table_name }{'indices'} }, $definition;
235 }
236 }
237
238 for my $option ( @{ $item[6] } ) {
3022f45b 239 $tables{ $table_name }{'table_options(s?)'}{ $option->{'type'} } =
0efb6e1b 240 $option;
241 }
242
243 1;
244 }
245
211e2e90 246create : CREATE unique(?) /(index|key)/i index_name /on/i table_name using_method(?) '(' field_name(s /,/) ')' where_predicate(?) ';'
4422e22a 247 {
a20abbda 248 my $table_info = $item{'table_name'};
249 my $schema_name = $table_info->{'schema_name'};
250 my $table_name = $table_info->{'table_name'};
251 push @{ $tables{ $table_name }{'indices'} },
4422e22a 252 {
b3384294 253 name => $item{'index_name'},
254 supertype => $item{'unique'}[0] ? 'constraint' : 'index',
255 type => $item{'unique'}[0] ? 'unique' : 'normal',
256 fields => $item[9],
257 method => $item{'using_method'}[0],
4422e22a 258 }
259 ;
ac397a49 260
4422e22a 261 }
262
0012a163 263#
211e2e90 264# Create anything else (e.g., domain, etc.)
0012a163 265#
211e2e90 266create : CREATE WORD /[^;]+/ ';'
ac397a49 267 { @table_comments = (); }
0012a163 268
0efb6e1b 269using_method : /using/i WORD { $item[2] }
270
271where_predicate : /where/i /[^;]+/
272
273create_definition : field
0efb6e1b 274 | table_constraint
4422e22a 275 | <error>
276
a82fa2cb 277comment : /^\s*(?:#|-{2})(.*)\n/
278 {
279 my $comment = $item[1];
280 $comment =~ s/^\s*(#|-*)\s*//;
281 $comment =~ s/\s*$//;
ac397a49 282 $return = $comment;
283 push @table_comments, $comment;
284 }
285
ac397a49 286comment_on_table : /comment/i /on/i /table/i table_name /is/i comment_phrase ';'
287 {
a20abbda 288 my $table_info = $item{'table_name'};
289 my $schema_name = $table_info->{'schema_name'};
290 my $table_name = $table_info->{'table_name'};
291 push @{ $tables{ $table_name }{'comments'} }, $item{'comment_phrase'};
ac397a49 292 }
293
294comment_on_column : /comment/i /on/i /column/i column_name /is/i comment_phrase ';'
295 {
296 my $table_name = $item[4]->{'table'};
297 my $field_name = $item[4]->{'field'};
e1fa2c52 298 if ($tables{ $table_name }{'fields'}{ $field_name } ) {
299 push @{ $tables{ $table_name }{'fields'}{ $field_name }{'comments'} },
300 $item{'comment_phrase'};
301 }
302 else {
303 die "No such column as $table_name.$field_name";
304 }
ac397a49 305 }
306
e4a9818d 307comment_on_other : /comment/i /on/i /\w+/ /\w+/ /is/i comment_phrase ';'
308 {
309 push(@table_comments, $item{'comment_phrase'});
310 }
311
312# [added by cjm 20041019]
313# [TODO: other comment-on types]
314# for now we just have a general mechanism for handling other
315# kinds of comments than table/column; I'm not sure of the best
316# way to incorporate these into the datamodel
317#
318# this is the exhaustive list of types of comment:
319#COMMENT ON DATABASE my_database IS 'Development Database';
320#COMMENT ON INDEX my_index IS 'Enforces uniqueness on employee id';
321#COMMENT ON RULE my_rule IS 'Logs UPDATES of employee records';
322#COMMENT ON SEQUENCE my_sequence IS 'Used to generate primary keys';
323#COMMENT ON TABLE my_table IS 'Employee Information';
324#COMMENT ON TYPE my_type IS 'Complex Number support';
325#COMMENT ON VIEW my_view IS 'View of departmental costs';
326#COMMENT ON COLUMN my_table.my_field IS 'Employee ID number';
327#COMMENT ON TRIGGER my_trigger ON my_table IS 'Used for R.I.';
328#
329# this is tested by test 08
330
ac397a49 331column_name : NAME '.' NAME
332 { $return = { table => $item[1], field => $item[3] } }
333
e4a9818d 334comment_phrase : /null/i
335 { $return = 'NULL' }
336
337comment_phrase : /'/ comment_phrase_unquoted(s) /'/
338 { my $phrase = join(' ', @{ $item[2] });
339 $return = $phrase}
340
341# [cjm TODO: double-single quotes in a comment_phrase]
342comment_phrase_unquoted : /[^\']*/
343 { $return = $item[1] }
344
345
346xxxcomment_phrase : /'.*?'|NULL/
ac397a49 347 {
8e9e79dc 348 my $val = $item[1] || '';
ac397a49 349 $val =~ s/^'|'$//g;
350 $return = $val;
351 }
352
a82fa2cb 353field : field_comment(s?) field_name data_type field_meta(s?) field_comment(s?)
4422e22a 354 {
3022f45b 355 my ( $default, @constraints, $is_pk );
00ef67ea 356 my $is_nullable = 1;
41fc9cb3 357 for my $meta ( @{ $item[4] } ) {
82968eb9 358 if ( $meta->{'type'} eq 'default' ) {
359 $default = $meta;
360 next;
361 }
362 elsif ( $meta->{'type'} eq 'not_null' ) {
00ef67ea 363 $is_nullable = 0;
82968eb9 364 }
365 elsif ( $meta->{'type'} eq 'primary_key' ) {
366 $is_pk = 1;
367 }
4422e22a 368
82968eb9 369 push @constraints, $meta if $meta->{'supertype'} eq 'constraint';
370 }
0efb6e1b 371
f2f71b8e 372 my @comments = ( @{ $item[1] }, @{ $item[5] } );
373
0a7fc605 374 $return = {
b3384294 375 supertype => 'field',
7eac5e12 376 name => $item{'field_name'},
377 data_type => $item{'data_type'}{'type'},
378 size => $item{'data_type'}{'size'},
00ef67ea 379 is_nullable => $is_nullable,
7eac5e12 380 default => $default->{'value'},
381 constraints => [ @constraints ],
382 comments => [ @comments ],
383 is_primary_key => $is_pk || 0,
384 is_auto_increment => $item{'data_type'}{'is_auto_increment'},
4422e22a 385 }
386 }
387 | <error>
388
a82fa2cb 389field_comment : /^\s*(?:#|-{2})(.*)\n/
390 {
391 my $comment = $item[1];
392 $comment =~ s/^\s*(#|-*)\s*//;
393 $comment =~ s/\s*$//;
394 $return = $comment;
395 }
396
0efb6e1b 397field_meta : default_val
82968eb9 398 | column_constraint
4422e22a 399
0efb6e1b 400column_constraint : constraint_name(?) column_constraint_type deferrable(?) deferred(?)
401 {
402 my $desc = $item{'column_constraint_type'};
403 my $type = $desc->{'type'};
404 my $fields = $desc->{'fields'} || [];
405 my $expression = $desc->{'expression'} || '';
406
407 $return = {
82968eb9 408 supertype => 'constraint',
0efb6e1b 409 name => $item{'constraint_name'}[0] || '',
410 type => $type,
411 expression => $type eq 'check' ? $expression : '',
f04713db 412 deferrable => $item{'deferrable'},
0efb6e1b 413 deferred => $item{'deferred'},
414 reference_table => $desc->{'reference_table'},
415 reference_fields => $desc->{'reference_fields'},
416 match_type => $desc->{'match_type'},
100684f3 417 on_delete => $desc->{'on_delete'} || $desc->{'on_delete_do'},
418 on_update => $desc->{'on_update'} || $desc->{'on_update_do'},
4422e22a 419 }
420 }
421
0efb6e1b 422constraint_name : /constraint/i name_with_opt_quotes { $item[2] }
423
424column_constraint_type : /not null/i { $return = { type => 'not_null' } }
425 |
f04713db 426 /null/i
0efb6e1b 427 { $return = { type => 'null' } }
428 |
f04713db 429 /unique/i
0efb6e1b 430 { $return = { type => 'unique' } }
431 |
432 /primary key/i
433 { $return = { type => 'primary_key' } }
434 |
435 /check/i '(' /[^)]+/ ')'
b3384294 436 { $return = { type => 'check', expression => $item[3] } }
0efb6e1b 437 |
3022f45b 438 /references/i table_name parens_word_list(?) match_type(?) key_action(s?)
0efb6e1b 439 {
a20abbda 440 my $table_info = $item{'table_name'};
441 my $schema_name = $table_info->{'schema_name'};
442 my $table_name = $table_info->{'table_name'};
3022f45b 443 my ( $on_delete, $on_update );
444 for my $action ( @{ $item[5] || [] } ) {
445 $on_delete = $action->{'action'} if $action->{'type'} eq 'delete';
446 $on_update = $action->{'action'} if $action->{'type'} eq 'update';
447 }
448
0efb6e1b 449 $return = {
450 type => 'foreign_key',
a20abbda 451 reference_table => $table_name,
0138f7bb 452 reference_fields => $item[3][0],
0efb6e1b 453 match_type => $item[4][0],
100684f3 454 on_delete => $on_delete,
455 on_update => $on_update,
ba1a1626 456 }
4422e22a 457 }
458
a20abbda 459table_name : schema_qualification(?) name_with_opt_quotes {
460 $return = { schema_name => $item[1], table_name => $item[2] }
461}
462
463 schema_qualification : name_with_opt_quotes '.'
4422e22a 464
0efb6e1b 465field_name : name_with_opt_quotes
4422e22a 466
0012a163 467name_with_opt_quotes : double_quote(?) NAME double_quote(?) { $item[2] }
4422e22a 468
0efb6e1b 469double_quote: /"/
4422e22a 470
0efb6e1b 471index_name : WORD
4422e22a 472
0efb6e1b 473data_type : pg_data_type parens_value_list(?)
4422e22a 474 {
3022f45b 475 my $data_type = $item[1];
ba1a1626 476
0efb6e1b 477 #
478 # We can deduce some sizes from the data type's name.
479 #
44ffdb73 480 if ( my $size = $item[2][0] ) {
481 $data_type->{'size'} = $size;
482 }
4422e22a 483
3022f45b 484 $return = $data_type;
4422e22a 485 }
486
0efb6e1b 487pg_data_type :
50840472 488 /(bigint|int8)/i
3022f45b 489 {
490 $return = {
50840472 491 type => 'integer',
b8ea6076 492 size => 20,
3022f45b 493 };
494 }
0efb6e1b 495 |
1bbd4a2b 496 /(smallint|int2)/i
3022f45b 497 {
498 $return = {
499 type => 'integer',
b8ea6076 500 size => 5,
3022f45b 501 };
502 }
0efb6e1b 503 |
c4c363bb 504 /interval/i
505 {
506 $return = { type => 'interval' };
507 }
508 |
50840472 509 /(integer|int4?)/i # interval must come before this
3022f45b 510 {
511 $return = {
512 type => 'integer',
b8ea6076 513 size => 10,
3022f45b 514 };
515 }
50840472 516 |
517 /(real|float4)/i
518 {
519 $return = {
520 type => 'real',
b8ea6076 521 size => 10,
50840472 522 };
523 }
0efb6e1b 524 |
1bbd4a2b 525 /(double precision|float8?)/i
3022f45b 526 {
527 $return = {
528 type => 'float',
b8ea6076 529 size => 20,
3022f45b 530 };
531 }
0efb6e1b 532 |
50840472 533 /(bigserial|serial8)/i
3022f45b 534 {
50840472 535 $return = {
7eac5e12 536 type => 'integer',
b8ea6076 537 size => 20,
7eac5e12 538 is_auto_increment => 1,
3022f45b 539 };
540 }
0efb6e1b 541 |
1bbd4a2b 542 /serial4?/i
3022f45b 543 {
544 $return = {
7eac5e12 545 type => 'integer',
b8ea6076 546 size => 11,
7eac5e12 547 is_auto_increment => 1,
3022f45b 548 };
549 }
0efb6e1b 550 |
1bbd4a2b 551 /(bit varying|varbit)/i
3022f45b 552 {
553 $return = { type => 'varbit' };
554 }
0efb6e1b 555 |
1bbd4a2b 556 /character varying/i
3022f45b 557 {
558 $return = { type => 'varchar' };
559 }
0efb6e1b 560 |
1bbd4a2b 561 /char(acter)?/i
3022f45b 562 {
563 $return = { type => 'char' };
564 }
0efb6e1b 565 |
1bbd4a2b 566 /bool(ean)?/i
3022f45b 567 {
568 $return = { type => 'boolean' };
569 }
0efb6e1b 570 |
1bbd4a2b 571 /bytea/i
3022f45b 572 {
82968eb9 573 $return = { type => 'bytea' };
3022f45b 574 }
0efb6e1b 575 |
b0f2faf8 576 /(timestamptz|timestamp)(?:\(\d\))?( with(out)? time zone)?/i
3022f45b 577 {
578 $return = { type => 'timestamp' };
579 }
0efb6e1b 580 |
38a6a4f9 581 /text/i
582 {
583 $return = {
584 type => 'text',
585 size => 64_000,
586 };
587 }
588 |
c4c363bb 589 /(bit|box|cidr|circle|date|inet|line|lseg|macaddr|money|numeric|decimal|path|point|polygon|timetz|time|varchar)/i
3022f45b 590 {
591 $return = { type => $item[1] };
592 }
0efb6e1b 593
4422e22a 594parens_value_list : '(' VALUE(s /,/) ')'
595 { $item[2] }
596
0efb6e1b 597parens_word_list : '(' WORD(s /,/) ')'
598 { $item[2] }
4422e22a 599
0efb6e1b 600field_size : '(' num_range ')' { $item{'num_range'} }
4422e22a 601
0efb6e1b 602num_range : DIGITS ',' DIGITS
4422e22a 603 { $return = $item[1].','.$item[3] }
604 | DIGITS
605 { $return = $item[1] }
606
f2f71b8e 607table_constraint : comment(s?) constraint_name(?) table_constraint_type deferrable(?) deferred(?) comment(s?)
0efb6e1b 608 {
609 my $desc = $item{'table_constraint_type'};
610 my $type = $desc->{'type'};
611 my $fields = $desc->{'fields'};
612 my $expression = $desc->{'expression'};
f2f71b8e 613 my @comments = ( @{ $item[1] }, @{ $item[-1] } );
0efb6e1b 614
615 $return = {
616 name => $item{'constraint_name'}[0] || '',
b3384294 617 supertype => 'constraint',
618 type => $type,
0efb6e1b 619 fields => $type ne 'check' ? $fields : [],
620 expression => $type eq 'check' ? $expression : '',
f04713db 621 deferrable => $item{'deferrable'},
0efb6e1b 622 deferred => $item{'deferred'},
623 reference_table => $desc->{'reference_table'},
624 reference_fields => $desc->{'reference_fields'},
625 match_type => $desc->{'match_type'}[0],
100684f3 626 on_delete => $desc->{'on_delete'} || $desc->{'on_delete_do'},
627 on_update => $desc->{'on_update'} || $desc->{'on_update_do'},
f2f71b8e 628 comments => [ @comments ],
0efb6e1b 629 }
630 }
4422e22a 631
0efb6e1b 632table_constraint_type : /primary key/i '(' name_with_opt_quotes(s /,/) ')'
633 {
634 $return = {
635 type => 'primary_key',
636 fields => $item[3],
637 }
638 }
639 |
640 /unique/i '(' name_with_opt_quotes(s /,/) ')'
641 {
642 $return = {
643 type => 'unique',
644 fields => $item[3],
645 }
646 }
647 |
b3384294 648 /check/i '(' /[^)]+/ ')'
0efb6e1b 649 {
650 $return = {
651 type => 'check',
652 expression => $item[3],
653 }
654 }
655 |
3022f45b 656 /foreign key/i '(' name_with_opt_quotes(s /,/) ')' /references/i table_name parens_word_list(?) match_type(?) key_action(s?)
0efb6e1b 657 {
3022f45b 658 my ( $on_delete, $on_update );
659 for my $action ( @{ $item[9] || [] } ) {
660 $on_delete = $action->{'action'} if $action->{'type'} eq 'delete';
661 $on_update = $action->{'action'} if $action->{'type'} eq 'update';
662 }
663
0efb6e1b 664 $return = {
b3384294 665 supertype => 'constraint',
0efb6e1b 666 type => 'foreign_key',
667 fields => $item[3],
a20abbda 668 reference_table => $item[6]->{'table_name'},
0efb6e1b 669 reference_fields => $item[7][0],
670 match_type => $item[8][0],
100684f3 671 on_delete => $on_delete || '',
672 on_update => $on_update || '',
0efb6e1b 673 }
674 }
675
99f3fab6 676deferrable : not(?) /deferrable/i
0efb6e1b 677 {
678 $return = ( $item[1] =~ /not/i ) ? 0 : 1;
679 }
4422e22a 680
0efb6e1b 681deferred : /initially/i /(deferred|immediate)/i { $item[2] }
4422e22a 682
0efb6e1b 683match_type : /match full/i { 'match_full' }
684 |
685 /match partial/i { 'match_partial' }
686
3022f45b 687key_action : key_delete
688 |
689 key_update
0efb6e1b 690
3022f45b 691key_delete : /on delete/i key_mutation
692 {
8c12c406 693 $return = {
3022f45b 694 type => 'delete',
695 action => $item[2],
696 };
697 }
698
699key_update : /on update/i key_mutation
700 {
8c12c406 701 $return = {
3022f45b 702 type => 'update',
703 action => $item[2],
704 };
705 }
706
707key_mutation : /no action/i { $return = 'no_action' }
708 |
709 /restrict/i { $return = 'restrict' }
710 |
711 /cascade/i { $return = 'cascade' }
712 |
38a6a4f9 713 /set null/i { $return = 'set null' }
3022f45b 714 |
38a6a4f9 715 /set default/i { $return = 'set default' }
0efb6e1b 716
00ef67ea 717alter : alter_table table_name add_column field ';'
718 {
719 my $field_def = $item[4];
a20abbda 720 $tables{ $item[2]->{'table_name'} }{'fields'}{ $field_def->{'name'} } = {
00ef67ea 721 %$field_def, order => $field_order++
722 };
723 1;
724 }
725
726alter : alter_table table_name ADD table_constraint ';'
0012a163 727 {
a20abbda 728 my $table_name = $item[2]->{'table_name'};
0012a163 729 my $constraint = $item[4];
0012a163 730 push @{ $tables{ $table_name }{'constraints'} }, $constraint;
00ef67ea 731 1;
0012a163 732 }
733
00ef67ea 734alter : alter_table table_name drop_column NAME restrict_or_cascade(?) ';'
735 {
a20abbda 736 $tables{ $item[2]->{'table_name'} }{'fields'}{ $item[4] }{'drop'} = 1;
00ef67ea 737 1;
738 }
0012a163 739
00ef67ea 740alter : alter_table table_name alter_column NAME alter_default_val ';'
741 {
a20abbda 742 $tables{ $item[2]->{'table_name'} }{'fields'}{ $item[4] }{'default'} =
00ef67ea 743 $item[5]->{'value'};
744 1;
745 }
746
747#
748# These will just parse for now but won't affect the structure. - ky
749#
750alter : alter_table table_name /rename/i /to/i NAME ';'
751 { 1 }
752
753alter : alter_table table_name alter_column NAME SET /statistics/i INTEGER ';'
754 { 1 }
755
756alter : alter_table table_name alter_column NAME SET /storage/i storage_type ';'
757 { 1 }
758
759alter : alter_table table_name rename_column NAME /to/i NAME ';'
760 { 1 }
761
762alter : alter_table table_name DROP /constraint/i NAME restrict_or_cascade ';'
763 { 1 }
764
765alter : alter_table table_name /owner/i /to/i NAME ';'
766 { 1 }
767
6f28e7ac 768alter : alter_sequence NAME /owned/i /by/i column_name ';'
769 { 1 }
770
00ef67ea 771storage_type : /(plain|external|extended|main)/i
772
773alter_default_val : SET default_val
774 {
775 $return = { value => $item[2]->{'value'} }
776 }
777 | DROP DEFAULT
778 {
779 $return = { value => undef }
780 }
781
782#
783# This is a little tricky to get right, at least WRT to making the
784# tests pass. The problem is that the constraints are stored just as
785# a list (no name access), and the tests expect the constraints in a
786# particular order. I'm going to leave the rule but disable the code
787# for now. - ky
788#
789alter : alter_table table_name alter_column NAME alter_nullable ';'
790 {
a20abbda 791# my $table_name = $item[2]->{'table_name'};
00ef67ea 792# my $field_name = $item[4];
793# my $is_nullable = $item[5]->{'is_nullable'};
794#
795# $tables{ $table_name }{'fields'}{ $field_name }{'is_nullable'} =
796# $is_nullable;
797#
798# if ( $is_nullable ) {
799# 1;
800# push @{ $tables{ $table_name }{'constraints'} }, {
801# type => 'not_null',
802# fields => [ $field_name ],
803# };
804# }
805# else {
806# for my $i (
807# 0 .. $#{ $tables{ $table_name }{'constraints'} || [] }
808# ) {
809# my $c = $tables{ $table_name }{'constraints'}[ $i ] or next;
810# my $fields = join( '', @{ $c->{'fields'} || [] } ) or next;
811# if ( $c->{'type'} eq 'not_null' && $fields eq $field_name ) {
812# delete $tables{ $table_name }{'constraints'}[ $i ];
813# last;
814# }
815# }
816# }
817
818 1;
819 }
820
821alter_nullable : SET not_null
822 {
823 $return = { is_nullable => 0 }
824 }
825 | DROP not_null
826 {
827 $return = { is_nullable => 1 }
828 }
829
830not_null : /not/i /null/i
831
99f3fab6 832not : /not/i
833
00ef67ea 834add_column : ADD COLUMN(?)
835
836alter_table : ALTER TABLE ONLY(?)
837
6f28e7ac 838alter_sequence : ALTER SEQUENCE
839
00ef67ea 840drop_column : DROP COLUMN(?)
841
842alter_column : ALTER COLUMN(?)
843
844rename_column : /rename/i COLUMN(?)
845
846restrict_or_cascade : /restrict/i |
847 /cascade/i
848
849#
850# End basically useless stuff. - ky
851#
0012a163 852
211e2e90 853create_table : CREATE TABLE
0efb6e1b 854
211e2e90 855create_index : CREATE /index/i
4422e22a 856
00ef67ea 857default_val : DEFAULT /(\d+|'[^']*'|\w+\(.*?\))|\w+/
4422e22a 858 {
f04713db 859 my $val = defined $item[2] ? $item[2] : '';
860 $val =~ s/^'|'$//g;
0efb6e1b 861 $return = {
82968eb9 862 supertype => 'constraint',
863 type => 'default',
0efb6e1b 864 value => $val,
865 }
4422e22a 866 }
f27085c9 867 | /null/i
868 {
869 $return = {
870 supertype => 'constraint',
871 type => 'default',
872 value => 'NULL',
873 }
874 }
4422e22a 875
4422e22a 876name_with_opt_paren : NAME parens_value_list(s?)
0efb6e1b 877 { $item[2][0] ? "$item[1]($item[2][0][0])" : $item[1] }
4422e22a 878
879unique : /unique/i { 1 }
880
881key : /key/i | /index/i
882
0efb6e1b 883table_option : /inherits/i '(' name_with_opt_quotes(s /,/) ')'
4422e22a 884 {
0efb6e1b 885 $return = { type => 'inherits', table_name => $item[3] }
886 }
887 |
888 /with(out)? oids/i
889 {
890 $return = { type => $item[1] =~ /out/i ? 'without_oids' : 'with_oids' }
4422e22a 891 }
892
00ef67ea 893ADD : /add/i
894
895ALTER : /alter/i
896
211e2e90 897CREATE : /create/i
898
00ef67ea 899ONLY : /only/i
900
901DEFAULT : /default/i
902
903DROP : /drop/i
904
905COLUMN : /column/i
906
0d51cd9e 907TABLE : /table/i
908
0efb6e1b 909SEMICOLON : /\s*;\n?/
910
6f28e7ac 911SEQUENCE : /sequence/i
912
00ef67ea 913INTEGER : /\d+/
914
4422e22a 915WORD : /\w+/
916
917DIGITS : /\d+/
918
919COMMA : ','
920
00ef67ea 921SET : /set/i
922
4422e22a 923NAME : "`" /\w+/ "`"
924 { $item[2] }
925 | /\w+/
926 { $item[1] }
0012a163 927 | /[\$\w]+/
928 { $item[1] }
4422e22a 929
930VALUE : /[-+]?\.?\d+(?:[eE]\d+)?/
931 { $item[1] }
932 | /'.*?'/ # XXX doesn't handle embedded quotes
933 { $item[1] }
f04713db 934 | /null/i
4422e22a 935 { 'NULL' }
936
937!;
938
939# -------------------------------------------------------------------
940sub parse {
941 my ( $translator, $data ) = @_;
942 $parser ||= Parse::RecDescent->new($GRAMMAR);
943
944 $::RD_TRACE = $translator->trace ? 1 : undef;
945 $DEBUG = $translator->debug;
946
947 unless (defined $parser) {
948 return $translator->error("Error instantiating Parse::RecDescent ".
949 "instance: Bad grammer");
950 }
951
952 my $result = $parser->startrule($data);
953 die "Parse failed.\n" unless defined $result;
954 warn Dumper($result) if $DEBUG;
82968eb9 955
956 my $schema = $translator->schema;
957 my @tables = sort {
429f639c 958 ( $result->{ $a }{'order'} || 0 ) <=> ( $result->{ $b }{'order'} || 0 )
82968eb9 959 } keys %{ $result };
960
961 for my $table_name ( @tables ) {
962 my $tdata = $result->{ $table_name };
963 my $table = $schema->add_table(
a20abbda 964 #schema => $tdata->{'schema_name'},
965 name => $tdata->{'table_name'},
d7fcc1d6 966 ) or die "Couldn't create table '$table_name': " . $schema->error;
82968eb9 967
a82fa2cb 968 $table->comments( $tdata->{'comments'} );
969
82968eb9 970 my @fields = sort {
429f639c 971 $tdata->{'fields'}{ $a }{'order'}
82968eb9 972 <=>
429f639c 973 $tdata->{'fields'}{ $b }{'order'}
82968eb9 974 } keys %{ $tdata->{'fields'} };
975
976 for my $fname ( @fields ) {
977 my $fdata = $tdata->{'fields'}{ $fname };
00ef67ea 978 next if $fdata->{'drop'};
82968eb9 979 my $field = $table->add_field(
980 name => $fdata->{'name'},
981 data_type => $fdata->{'data_type'},
982 size => $fdata->{'size'},
983 default_value => $fdata->{'default'},
7eac5e12 984 is_auto_increment => $fdata->{'is_auto_increment'},
00ef67ea 985 is_nullable => $fdata->{'is_nullable'},
a82fa2cb 986 comments => $fdata->{'comments'},
82968eb9 987 ) or die $table->error;
988
989 $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
990
991 for my $cdata ( @{ $fdata->{'constraints'} } ) {
992 next unless $cdata->{'type'} eq 'foreign_key';
993 $cdata->{'fields'} ||= [ $field->name ];
994 push @{ $tdata->{'constraints'} }, $cdata;
995 }
996 }
997
998 for my $idata ( @{ $tdata->{'indices'} || [] } ) {
999 my $index = $table->add_index(
1000 name => $idata->{'name'},
1001 type => uc $idata->{'type'},
1002 fields => $idata->{'fields'},
1003 ) or die $table->error;
1004 }
1005
1006 for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
1007 my $constraint = $table->add_constraint(
1008 name => $cdata->{'name'},
1009 type => $cdata->{'type'},
1010 fields => $cdata->{'fields'},
1011 reference_table => $cdata->{'reference_table'},
1012 reference_fields => $cdata->{'reference_fields'},
1013 match_type => $cdata->{'match_type'} || '',
100684f3 1014 on_delete => $cdata->{'on_delete'} || $cdata->{'on_delete_do'},
1015 on_update => $cdata->{'on_update'} || $cdata->{'on_update_do'},
b3384294 1016 expression => $cdata->{'expression'},
1017 ) or die "Can't add constraint of type '" .
1018 $cdata->{'type'} . "' to table '" . $table->name .
1019 "': " . $table->error;
82968eb9 1020 }
1021 }
1022
f62bd16c 1023 return 1;
4422e22a 1024}
1025
10261;
1027
82968eb9 1028# -------------------------------------------------------------------
1029# Rescue the drowning and tie your shoestrings.
1030# Henry David Thoreau
1031# -------------------------------------------------------------------
4422e22a 1032
1033=pod
1034
0efb6e1b 1035=head1 AUTHORS
4422e22a 1036
1037Ken Y. Clark E<lt>kclark@cpan.orgE<gt>,
b8ea6076 1038Allen Day E<lt>allenday@ucla.eduE<gt>.
4422e22a 1039
1040=head1 SEE ALSO
1041
1042perl(1), Parse::RecDescent.
1043
1044=cut