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