fixed parsing of Pg COMMENT ON ... syntax
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Parser / PostgreSQL.pm
CommitLineData
84012a55 1package SQL::Translator::Parser::PostgreSQL;
4422e22a 2
3# -------------------------------------------------------------------
e4a9818d 4# $Id: PostgreSQL.pm,v 1.42 2004-10-23 19:58:19 cmungall 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 ];
e4a9818d 111$VERSION = sprintf "%d.%02d", q$Revision: 1.42 $ =~ /(\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 {
165 my $table_name = $item{'table_name'};
166 push @{ $tables{ $table_name }{'permissions'} }, {
167 type => 'revoke',
168 actions => $item[2],
91c75eab 169 users => $item[7],
0efb6e1b 170 }
171 }
172
0d51cd9e 173grant : /grant/i WORD(s /,/) /on/i TABLE(?) table_name /to/i name_with_opt_quotes(s /,/) ';'
0efb6e1b 174 {
175 my $table_name = $item{'table_name'};
176 push @{ $tables{ $table_name }{'permissions'} }, {
177 type => 'grant',
178 actions => $item[2],
91c75eab 179 users => $item[7],
0efb6e1b 180 }
181 }
182
183drop : /drop/i /[^;]*/ ';'
4422e22a 184
4d2da1f7 185insert : /insert/i /[^;]*/ ';'
186
187update : /update/i /[^;]*/ ';'
188
0012a163 189#
190# Create table.
191#
ba1a1626 192create : create_table table_name '(' create_definition(s /,/) ')' table_option(s?) ';'
0efb6e1b 193 {
194 my $table_name = $item{'table_name'};
195 $tables{ $table_name }{'order'} = ++$table_order;
196 $tables{ $table_name }{'table_name'} = $table_name;
197
ac397a49 198 if ( @table_comments ) {
199 $tables{ $table_name }{'comments'} = [ @table_comments ];
200 @table_comments = ();
201 }
202
0efb6e1b 203 my @constraints;
204 for my $definition ( @{ $item[4] } ) {
b3384294 205 if ( $definition->{'supertype'} eq 'field' ) {
0efb6e1b 206 my $field_name = $definition->{'name'};
207 $tables{ $table_name }{'fields'}{ $field_name } =
00ef67ea 208 { %$definition, order => $field_order++ };
4422e22a 209
0138f7bb 210 for my $constraint ( @{ $definition->{'constraints'} || [] } ) {
211 $constraint->{'fields'} = [ $field_name ];
7d5bcab8 212 push @{ $tables{ $table_name }{'constraints'} },
0138f7bb 213 $constraint;
0efb6e1b 214 }
215 }
b3384294 216 elsif ( $definition->{'supertype'} eq 'constraint' ) {
217 push @{ $tables{ $table_name }{'constraints'} }, $definition;
0efb6e1b 218 }
b3384294 219 elsif ( $definition->{'supertype'} eq 'index' ) {
0efb6e1b 220 push @{ $tables{ $table_name }{'indices'} }, $definition;
221 }
222 }
223
224 for my $option ( @{ $item[6] } ) {
3022f45b 225 $tables{ $table_name }{'table_options(s?)'}{ $option->{'type'} } =
0efb6e1b 226 $option;
227 }
228
229 1;
230 }
231
211e2e90 232create : CREATE unique(?) /(index|key)/i index_name /on/i table_name using_method(?) '(' field_name(s /,/) ')' where_predicate(?) ';'
4422e22a 233 {
234 push @{ $tables{ $item{'table_name'} }{'indices'} },
235 {
b3384294 236 name => $item{'index_name'},
237 supertype => $item{'unique'}[0] ? 'constraint' : 'index',
238 type => $item{'unique'}[0] ? 'unique' : 'normal',
239 fields => $item[9],
240 method => $item{'using_method'}[0],
4422e22a 241 }
242 ;
ac397a49 243
4422e22a 244 }
245
0012a163 246#
211e2e90 247# Create anything else (e.g., domain, etc.)
0012a163 248#
211e2e90 249create : CREATE WORD /[^;]+/ ';'
ac397a49 250 { @table_comments = (); }
0012a163 251
0efb6e1b 252using_method : /using/i WORD { $item[2] }
253
254where_predicate : /where/i /[^;]+/
255
256create_definition : field
0efb6e1b 257 | table_constraint
4422e22a 258 | <error>
259
a82fa2cb 260comment : /^\s*(?:#|-{2})(.*)\n/
261 {
262 my $comment = $item[1];
263 $comment =~ s/^\s*(#|-*)\s*//;
264 $comment =~ s/\s*$//;
ac397a49 265 $return = $comment;
266 push @table_comments, $comment;
267 }
268
ac397a49 269comment_on_table : /comment/i /on/i /table/i table_name /is/i comment_phrase ';'
270 {
271 push @{ $tables{ $item{'table_name'} }{'comments'} }, $item{'comment_phrase'};
272 }
273
274comment_on_column : /comment/i /on/i /column/i column_name /is/i comment_phrase ';'
275 {
276 my $table_name = $item[4]->{'table'};
277 my $field_name = $item[4]->{'field'};
278 push @{ $tables{ $table_name }{'fields'}{ $field_name }{'comments'} },
279 $item{'comment_phrase'};
280 }
281
e4a9818d 282comment_on_other : /comment/i /on/i /\w+/ /\w+/ /is/i comment_phrase ';'
283 {
284 push(@table_comments, $item{'comment_phrase'});
285 }
286
287# [added by cjm 20041019]
288# [TODO: other comment-on types]
289# for now we just have a general mechanism for handling other
290# kinds of comments than table/column; I'm not sure of the best
291# way to incorporate these into the datamodel
292#
293# this is the exhaustive list of types of comment:
294#COMMENT ON DATABASE my_database IS 'Development Database';
295#COMMENT ON INDEX my_index IS 'Enforces uniqueness on employee id';
296#COMMENT ON RULE my_rule IS 'Logs UPDATES of employee records';
297#COMMENT ON SEQUENCE my_sequence IS 'Used to generate primary keys';
298#COMMENT ON TABLE my_table IS 'Employee Information';
299#COMMENT ON TYPE my_type IS 'Complex Number support';
300#COMMENT ON VIEW my_view IS 'View of departmental costs';
301#COMMENT ON COLUMN my_table.my_field IS 'Employee ID number';
302#COMMENT ON TRIGGER my_trigger ON my_table IS 'Used for R.I.';
303#
304# this is tested by test 08
305
ac397a49 306column_name : NAME '.' NAME
307 { $return = { table => $item[1], field => $item[3] } }
308
e4a9818d 309comment_phrase : /null/i
310 { $return = 'NULL' }
311
312comment_phrase : /'/ comment_phrase_unquoted(s) /'/
313 { my $phrase = join(' ', @{ $item[2] });
314 $return = $phrase}
315
316# [cjm TODO: double-single quotes in a comment_phrase]
317comment_phrase_unquoted : /[^\']*/
318 { $return = $item[1] }
319
320
321xxxcomment_phrase : /'.*?'|NULL/
ac397a49 322 {
8e9e79dc 323 my $val = $item[1] || '';
ac397a49 324 $val =~ s/^'|'$//g;
325 $return = $val;
326 }
327
a82fa2cb 328field : field_comment(s?) field_name data_type field_meta(s?) field_comment(s?)
4422e22a 329 {
3022f45b 330 my ( $default, @constraints, $is_pk );
00ef67ea 331 my $is_nullable = 1;
41fc9cb3 332 for my $meta ( @{ $item[4] } ) {
82968eb9 333 if ( $meta->{'type'} eq 'default' ) {
334 $default = $meta;
335 next;
336 }
337 elsif ( $meta->{'type'} eq 'not_null' ) {
00ef67ea 338 $is_nullable = 0;
82968eb9 339 }
340 elsif ( $meta->{'type'} eq 'primary_key' ) {
341 $is_pk = 1;
342 }
4422e22a 343
82968eb9 344 push @constraints, $meta if $meta->{'supertype'} eq 'constraint';
345 }
0efb6e1b 346
f2f71b8e 347 my @comments = ( @{ $item[1] }, @{ $item[5] } );
348
0a7fc605 349 $return = {
b3384294 350 supertype => 'field',
7eac5e12 351 name => $item{'field_name'},
352 data_type => $item{'data_type'}{'type'},
353 size => $item{'data_type'}{'size'},
00ef67ea 354 is_nullable => $is_nullable,
7eac5e12 355 default => $default->{'value'},
356 constraints => [ @constraints ],
357 comments => [ @comments ],
358 is_primary_key => $is_pk || 0,
359 is_auto_increment => $item{'data_type'}{'is_auto_increment'},
4422e22a 360 }
361 }
362 | <error>
363
a82fa2cb 364field_comment : /^\s*(?:#|-{2})(.*)\n/
365 {
366 my $comment = $item[1];
367 $comment =~ s/^\s*(#|-*)\s*//;
368 $comment =~ s/\s*$//;
369 $return = $comment;
370 }
371
0efb6e1b 372field_meta : default_val
82968eb9 373 | column_constraint
4422e22a 374
0efb6e1b 375column_constraint : constraint_name(?) column_constraint_type deferrable(?) deferred(?)
376 {
377 my $desc = $item{'column_constraint_type'};
378 my $type = $desc->{'type'};
379 my $fields = $desc->{'fields'} || [];
380 my $expression = $desc->{'expression'} || '';
381
382 $return = {
82968eb9 383 supertype => 'constraint',
0efb6e1b 384 name => $item{'constraint_name'}[0] || '',
385 type => $type,
386 expression => $type eq 'check' ? $expression : '',
f04713db 387 deferrable => $item{'deferrable'},
0efb6e1b 388 deferred => $item{'deferred'},
389 reference_table => $desc->{'reference_table'},
390 reference_fields => $desc->{'reference_fields'},
391 match_type => $desc->{'match_type'},
392 on_delete_do => $desc->{'on_delete_do'},
393 on_update_do => $desc->{'on_update_do'},
4422e22a 394 }
395 }
396
0efb6e1b 397constraint_name : /constraint/i name_with_opt_quotes { $item[2] }
398
399column_constraint_type : /not null/i { $return = { type => 'not_null' } }
400 |
f04713db 401 /null/i
0efb6e1b 402 { $return = { type => 'null' } }
403 |
f04713db 404 /unique/i
0efb6e1b 405 { $return = { type => 'unique' } }
406 |
407 /primary key/i
408 { $return = { type => 'primary_key' } }
409 |
410 /check/i '(' /[^)]+/ ')'
b3384294 411 { $return = { type => 'check', expression => $item[3] } }
0efb6e1b 412 |
3022f45b 413 /references/i table_name parens_word_list(?) match_type(?) key_action(s?)
0efb6e1b 414 {
3022f45b 415 my ( $on_delete, $on_update );
416 for my $action ( @{ $item[5] || [] } ) {
417 $on_delete = $action->{'action'} if $action->{'type'} eq 'delete';
418 $on_update = $action->{'action'} if $action->{'type'} eq 'update';
419 }
420
0efb6e1b 421 $return = {
422 type => 'foreign_key',
423 reference_table => $item[2],
0138f7bb 424 reference_fields => $item[3][0],
0efb6e1b 425 match_type => $item[4][0],
3022f45b 426 on_delete_do => $on_delete,
427 on_update_do => $on_update,
ba1a1626 428 }
4422e22a 429 }
430
0efb6e1b 431table_name : name_with_opt_quotes
4422e22a 432
0efb6e1b 433field_name : name_with_opt_quotes
4422e22a 434
0012a163 435name_with_opt_quotes : double_quote(?) NAME double_quote(?) { $item[2] }
4422e22a 436
0efb6e1b 437double_quote: /"/
4422e22a 438
0efb6e1b 439index_name : WORD
4422e22a 440
0efb6e1b 441data_type : pg_data_type parens_value_list(?)
4422e22a 442 {
3022f45b 443 my $data_type = $item[1];
ba1a1626 444
0efb6e1b 445 #
446 # We can deduce some sizes from the data type's name.
447 #
44ffdb73 448 if ( my $size = $item[2][0] ) {
449 $data_type->{'size'} = $size;
450 }
4422e22a 451
3022f45b 452 $return = $data_type;
4422e22a 453 }
454
0efb6e1b 455pg_data_type :
50840472 456 /(bigint|int8)/i
3022f45b 457 {
458 $return = {
50840472 459 type => 'integer',
b8ea6076 460 size => 20,
3022f45b 461 };
462 }
0efb6e1b 463 |
1bbd4a2b 464 /(smallint|int2)/i
3022f45b 465 {
466 $return = {
467 type => 'integer',
b8ea6076 468 size => 5,
3022f45b 469 };
470 }
0efb6e1b 471 |
c4c363bb 472 /interval/i
473 {
474 $return = { type => 'interval' };
475 }
476 |
50840472 477 /(integer|int4?)/i # interval must come before this
3022f45b 478 {
479 $return = {
480 type => 'integer',
b8ea6076 481 size => 10,
3022f45b 482 };
483 }
50840472 484 |
485 /(real|float4)/i
486 {
487 $return = {
488 type => 'real',
b8ea6076 489 size => 10,
50840472 490 };
491 }
0efb6e1b 492 |
1bbd4a2b 493 /(double precision|float8?)/i
3022f45b 494 {
495 $return = {
496 type => 'float',
b8ea6076 497 size => 20,
3022f45b 498 };
499 }
0efb6e1b 500 |
50840472 501 /(bigserial|serial8)/i
3022f45b 502 {
50840472 503 $return = {
7eac5e12 504 type => 'integer',
b8ea6076 505 size => 20,
7eac5e12 506 is_auto_increment => 1,
3022f45b 507 };
508 }
0efb6e1b 509 |
1bbd4a2b 510 /serial4?/i
3022f45b 511 {
512 $return = {
7eac5e12 513 type => 'integer',
b8ea6076 514 size => 11,
7eac5e12 515 is_auto_increment => 1,
3022f45b 516 };
517 }
0efb6e1b 518 |
1bbd4a2b 519 /(bit varying|varbit)/i
3022f45b 520 {
521 $return = { type => 'varbit' };
522 }
0efb6e1b 523 |
1bbd4a2b 524 /character varying/i
3022f45b 525 {
526 $return = { type => 'varchar' };
527 }
0efb6e1b 528 |
1bbd4a2b 529 /char(acter)?/i
3022f45b 530 {
531 $return = { type => 'char' };
532 }
0efb6e1b 533 |
1bbd4a2b 534 /bool(ean)?/i
3022f45b 535 {
536 $return = { type => 'boolean' };
537 }
0efb6e1b 538 |
1bbd4a2b 539 /bytea/i
3022f45b 540 {
82968eb9 541 $return = { type => 'bytea' };
3022f45b 542 }
0efb6e1b 543 |
c4c363bb 544 /(timestamptz|timestamp)( with time zone)?/i
545 {
546 $return = { type => 'timestamp' };
547 }
548 |
429f639c 549 /(timestamptz|timestamp)( without time zone)?/i
3022f45b 550 {
551 $return = { type => 'timestamp' };
552 }
0efb6e1b 553 |
38a6a4f9 554 /text/i
555 {
556 $return = {
557 type => 'text',
558 size => 64_000,
559 };
560 }
561 |
c4c363bb 562 /(bit|box|cidr|circle|date|inet|line|lseg|macaddr|money|numeric|decimal|path|point|polygon|timetz|time|varchar)/i
3022f45b 563 {
564 $return = { type => $item[1] };
565 }
0efb6e1b 566
4422e22a 567parens_value_list : '(' VALUE(s /,/) ')'
568 { $item[2] }
569
0efb6e1b 570parens_word_list : '(' WORD(s /,/) ')'
571 { $item[2] }
4422e22a 572
0efb6e1b 573field_size : '(' num_range ')' { $item{'num_range'} }
4422e22a 574
0efb6e1b 575num_range : DIGITS ',' DIGITS
4422e22a 576 { $return = $item[1].','.$item[3] }
577 | DIGITS
578 { $return = $item[1] }
579
f2f71b8e 580table_constraint : comment(s?) constraint_name(?) table_constraint_type deferrable(?) deferred(?) comment(s?)
0efb6e1b 581 {
582 my $desc = $item{'table_constraint_type'};
583 my $type = $desc->{'type'};
584 my $fields = $desc->{'fields'};
585 my $expression = $desc->{'expression'};
f2f71b8e 586 my @comments = ( @{ $item[1] }, @{ $item[-1] } );
0efb6e1b 587
588 $return = {
589 name => $item{'constraint_name'}[0] || '',
b3384294 590 supertype => 'constraint',
591 type => $type,
0efb6e1b 592 fields => $type ne 'check' ? $fields : [],
593 expression => $type eq 'check' ? $expression : '',
f04713db 594 deferrable => $item{'deferrable'},
0efb6e1b 595 deferred => $item{'deferred'},
596 reference_table => $desc->{'reference_table'},
597 reference_fields => $desc->{'reference_fields'},
598 match_type => $desc->{'match_type'}[0],
0012a163 599 on_delete_do => $desc->{'on_delete_do'},
600 on_update_do => $desc->{'on_update_do'},
f2f71b8e 601 comments => [ @comments ],
0efb6e1b 602 }
603 }
4422e22a 604
0efb6e1b 605table_constraint_type : /primary key/i '(' name_with_opt_quotes(s /,/) ')'
606 {
607 $return = {
608 type => 'primary_key',
609 fields => $item[3],
610 }
611 }
612 |
613 /unique/i '(' name_with_opt_quotes(s /,/) ')'
614 {
615 $return = {
616 type => 'unique',
617 fields => $item[3],
618 }
619 }
620 |
b3384294 621 /check/i '(' /[^)]+/ ')'
0efb6e1b 622 {
623 $return = {
624 type => 'check',
625 expression => $item[3],
626 }
627 }
628 |
3022f45b 629 /foreign key/i '(' name_with_opt_quotes(s /,/) ')' /references/i table_name parens_word_list(?) match_type(?) key_action(s?)
0efb6e1b 630 {
3022f45b 631 my ( $on_delete, $on_update );
632 for my $action ( @{ $item[9] || [] } ) {
633 $on_delete = $action->{'action'} if $action->{'type'} eq 'delete';
634 $on_update = $action->{'action'} if $action->{'type'} eq 'update';
635 }
636
0efb6e1b 637 $return = {
b3384294 638 supertype => 'constraint',
0efb6e1b 639 type => 'foreign_key',
640 fields => $item[3],
641 reference_table => $item[6],
642 reference_fields => $item[7][0],
643 match_type => $item[8][0],
3022f45b 644 on_delete_do => $on_delete || '',
645 on_update_do => $on_update || '',
0efb6e1b 646 }
647 }
648
649deferrable : /not/i /deferrable/i
650 {
651 $return = ( $item[1] =~ /not/i ) ? 0 : 1;
652 }
4422e22a 653
0efb6e1b 654deferred : /initially/i /(deferred|immediate)/i { $item[2] }
4422e22a 655
0efb6e1b 656match_type : /match full/i { 'match_full' }
657 |
658 /match partial/i { 'match_partial' }
659
3022f45b 660key_action : key_delete
661 |
662 key_update
0efb6e1b 663
3022f45b 664key_delete : /on delete/i key_mutation
665 {
8c12c406 666 $return = {
3022f45b 667 type => 'delete',
668 action => $item[2],
669 };
670 }
671
672key_update : /on update/i key_mutation
673 {
8c12c406 674 $return = {
3022f45b 675 type => 'update',
676 action => $item[2],
677 };
678 }
679
680key_mutation : /no action/i { $return = 'no_action' }
681 |
682 /restrict/i { $return = 'restrict' }
683 |
684 /cascade/i { $return = 'cascade' }
685 |
38a6a4f9 686 /set null/i { $return = 'set null' }
3022f45b 687 |
38a6a4f9 688 /set default/i { $return = 'set default' }
0efb6e1b 689
00ef67ea 690alter : alter_table table_name add_column field ';'
691 {
692 my $field_def = $item[4];
693 $tables{ $item[2] }{'fields'}{ $field_def->{'name'} } = {
694 %$field_def, order => $field_order++
695 };
696 1;
697 }
698
699alter : alter_table table_name ADD table_constraint ';'
0012a163 700 {
701 my $table_name = $item[2];
702 my $constraint = $item[4];
0012a163 703 push @{ $tables{ $table_name }{'constraints'} }, $constraint;
00ef67ea 704 1;
0012a163 705 }
706
00ef67ea 707alter : alter_table table_name drop_column NAME restrict_or_cascade(?) ';'
708 {
709 $tables{ $item[2] }{'fields'}{ $item[4] }{'drop'} = 1;
710 1;
711 }
0012a163 712
00ef67ea 713alter : alter_table table_name alter_column NAME alter_default_val ';'
714 {
715 $tables{ $item[2] }{'fields'}{ $item[4] }{'default'} =
716 $item[5]->{'value'};
717 1;
718 }
719
720#
721# These will just parse for now but won't affect the structure. - ky
722#
723alter : alter_table table_name /rename/i /to/i NAME ';'
724 { 1 }
725
726alter : alter_table table_name alter_column NAME SET /statistics/i INTEGER ';'
727 { 1 }
728
729alter : alter_table table_name alter_column NAME SET /storage/i storage_type ';'
730 { 1 }
731
732alter : alter_table table_name rename_column NAME /to/i NAME ';'
733 { 1 }
734
735alter : alter_table table_name DROP /constraint/i NAME restrict_or_cascade ';'
736 { 1 }
737
738alter : alter_table table_name /owner/i /to/i NAME ';'
739 { 1 }
740
741storage_type : /(plain|external|extended|main)/i
742
743alter_default_val : SET default_val
744 {
745 $return = { value => $item[2]->{'value'} }
746 }
747 | DROP DEFAULT
748 {
749 $return = { value => undef }
750 }
751
752#
753# This is a little tricky to get right, at least WRT to making the
754# tests pass. The problem is that the constraints are stored just as
755# a list (no name access), and the tests expect the constraints in a
756# particular order. I'm going to leave the rule but disable the code
757# for now. - ky
758#
759alter : alter_table table_name alter_column NAME alter_nullable ';'
760 {
761# my $table_name = $item[2];
762# my $field_name = $item[4];
763# my $is_nullable = $item[5]->{'is_nullable'};
764#
765# $tables{ $table_name }{'fields'}{ $field_name }{'is_nullable'} =
766# $is_nullable;
767#
768# if ( $is_nullable ) {
769# 1;
770# push @{ $tables{ $table_name }{'constraints'} }, {
771# type => 'not_null',
772# fields => [ $field_name ],
773# };
774# }
775# else {
776# for my $i (
777# 0 .. $#{ $tables{ $table_name }{'constraints'} || [] }
778# ) {
779# my $c = $tables{ $table_name }{'constraints'}[ $i ] or next;
780# my $fields = join( '', @{ $c->{'fields'} || [] } ) or next;
781# if ( $c->{'type'} eq 'not_null' && $fields eq $field_name ) {
782# delete $tables{ $table_name }{'constraints'}[ $i ];
783# last;
784# }
785# }
786# }
787
788 1;
789 }
790
791alter_nullable : SET not_null
792 {
793 $return = { is_nullable => 0 }
794 }
795 | DROP not_null
796 {
797 $return = { is_nullable => 1 }
798 }
799
800not_null : /not/i /null/i
801
802add_column : ADD COLUMN(?)
803
804alter_table : ALTER TABLE ONLY(?)
805
806drop_column : DROP COLUMN(?)
807
808alter_column : ALTER COLUMN(?)
809
810rename_column : /rename/i COLUMN(?)
811
812restrict_or_cascade : /restrict/i |
813 /cascade/i
814
815#
816# End basically useless stuff. - ky
817#
0012a163 818
211e2e90 819create_table : CREATE TABLE
0efb6e1b 820
211e2e90 821create_index : CREATE /index/i
4422e22a 822
00ef67ea 823default_val : DEFAULT /(\d+|'[^']*'|\w+\(.*?\))|\w+/
4422e22a 824 {
f04713db 825 my $val = defined $item[2] ? $item[2] : '';
826 $val =~ s/^'|'$//g;
0efb6e1b 827 $return = {
82968eb9 828 supertype => 'constraint',
829 type => 'default',
0efb6e1b 830 value => $val,
831 }
4422e22a 832 }
f27085c9 833 | /null/i
834 {
835 $return = {
836 supertype => 'constraint',
837 type => 'default',
838 value => 'NULL',
839 }
840 }
4422e22a 841
4422e22a 842name_with_opt_paren : NAME parens_value_list(s?)
0efb6e1b 843 { $item[2][0] ? "$item[1]($item[2][0][0])" : $item[1] }
4422e22a 844
845unique : /unique/i { 1 }
846
847key : /key/i | /index/i
848
0efb6e1b 849table_option : /inherits/i '(' name_with_opt_quotes(s /,/) ')'
4422e22a 850 {
0efb6e1b 851 $return = { type => 'inherits', table_name => $item[3] }
852 }
853 |
854 /with(out)? oids/i
855 {
856 $return = { type => $item[1] =~ /out/i ? 'without_oids' : 'with_oids' }
4422e22a 857 }
858
00ef67ea 859ADD : /add/i
860
861ALTER : /alter/i
862
211e2e90 863CREATE : /create/i
864
00ef67ea 865ONLY : /only/i
866
867DEFAULT : /default/i
868
869DROP : /drop/i
870
871COLUMN : /column/i
872
0d51cd9e 873TABLE : /table/i
874
0efb6e1b 875SEMICOLON : /\s*;\n?/
876
00ef67ea 877INTEGER : /\d+/
878
4422e22a 879WORD : /\w+/
880
881DIGITS : /\d+/
882
883COMMA : ','
884
00ef67ea 885SET : /set/i
886
4422e22a 887NAME : "`" /\w+/ "`"
888 { $item[2] }
889 | /\w+/
890 { $item[1] }
0012a163 891 | /[\$\w]+/
892 { $item[1] }
4422e22a 893
894VALUE : /[-+]?\.?\d+(?:[eE]\d+)?/
895 { $item[1] }
896 | /'.*?'/ # XXX doesn't handle embedded quotes
897 { $item[1] }
f04713db 898 | /null/i
4422e22a 899 { 'NULL' }
900
901!;
902
903# -------------------------------------------------------------------
904sub parse {
905 my ( $translator, $data ) = @_;
906 $parser ||= Parse::RecDescent->new($GRAMMAR);
907
908 $::RD_TRACE = $translator->trace ? 1 : undef;
909 $DEBUG = $translator->debug;
910
911 unless (defined $parser) {
912 return $translator->error("Error instantiating Parse::RecDescent ".
913 "instance: Bad grammer");
914 }
915
916 my $result = $parser->startrule($data);
917 die "Parse failed.\n" unless defined $result;
918 warn Dumper($result) if $DEBUG;
82968eb9 919
920 my $schema = $translator->schema;
921 my @tables = sort {
429f639c 922 ( $result->{ $a }{'order'} || 0 ) <=> ( $result->{ $b }{'order'} || 0 )
82968eb9 923 } keys %{ $result };
924
925 for my $table_name ( @tables ) {
926 my $tdata = $result->{ $table_name };
927 my $table = $schema->add_table(
928 name => $tdata->{'table_name'},
d7fcc1d6 929 ) or die "Couldn't create table '$table_name': " . $schema->error;
82968eb9 930
a82fa2cb 931 $table->comments( $tdata->{'comments'} );
932
82968eb9 933 my @fields = sort {
429f639c 934 $tdata->{'fields'}{ $a }{'order'}
82968eb9 935 <=>
429f639c 936 $tdata->{'fields'}{ $b }{'order'}
82968eb9 937 } keys %{ $tdata->{'fields'} };
938
939 for my $fname ( @fields ) {
940 my $fdata = $tdata->{'fields'}{ $fname };
00ef67ea 941 next if $fdata->{'drop'};
82968eb9 942 my $field = $table->add_field(
943 name => $fdata->{'name'},
944 data_type => $fdata->{'data_type'},
945 size => $fdata->{'size'},
946 default_value => $fdata->{'default'},
7eac5e12 947 is_auto_increment => $fdata->{'is_auto_increment'},
00ef67ea 948 is_nullable => $fdata->{'is_nullable'},
a82fa2cb 949 comments => $fdata->{'comments'},
82968eb9 950 ) or die $table->error;
951
952 $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
953
954 for my $cdata ( @{ $fdata->{'constraints'} } ) {
955 next unless $cdata->{'type'} eq 'foreign_key';
956 $cdata->{'fields'} ||= [ $field->name ];
957 push @{ $tdata->{'constraints'} }, $cdata;
958 }
959 }
960
961 for my $idata ( @{ $tdata->{'indices'} || [] } ) {
962 my $index = $table->add_index(
963 name => $idata->{'name'},
964 type => uc $idata->{'type'},
965 fields => $idata->{'fields'},
966 ) or die $table->error;
967 }
968
969 for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
970 my $constraint = $table->add_constraint(
971 name => $cdata->{'name'},
972 type => $cdata->{'type'},
973 fields => $cdata->{'fields'},
974 reference_table => $cdata->{'reference_table'},
975 reference_fields => $cdata->{'reference_fields'},
976 match_type => $cdata->{'match_type'} || '',
977 on_delete => $cdata->{'on_delete_do'},
978 on_update => $cdata->{'on_update_do'},
b3384294 979 expression => $cdata->{'expression'},
980 ) or die "Can't add constraint of type '" .
981 $cdata->{'type'} . "' to table '" . $table->name .
982 "': " . $table->error;
82968eb9 983 }
984 }
985
f62bd16c 986 return 1;
4422e22a 987}
988
9891;
990
82968eb9 991# -------------------------------------------------------------------
992# Rescue the drowning and tie your shoestrings.
993# Henry David Thoreau
994# -------------------------------------------------------------------
4422e22a 995
996=pod
997
0efb6e1b 998=head1 AUTHORS
4422e22a 999
1000Ken Y. Clark E<lt>kclark@cpan.orgE<gt>,
b8ea6076 1001Allen Day E<lt>allenday@ucla.eduE<gt>.
4422e22a 1002
1003=head1 SEE ALSO
1004
1005perl(1), Parse::RecDescent.
1006
1007=cut