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