Added some documentation to PG and MySQL; the "eofile" rule to MySQL.
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Parser / PostgreSQL.pm
CommitLineData
84012a55 1package SQL::Translator::Parser::PostgreSQL;
4422e22a 2
3# -------------------------------------------------------------------
629b76f9 4# $Id: PostgreSQL.pm,v 1.6 2003-02-25 14:55:36 kycl4rk Exp $
4422e22a 5# -------------------------------------------------------------------
6# Copyright (C) 2003 Ken Y. Clark <kclark@cpan.org>,
0efb6e1b 7# Allen Day <allenday@users.sourceforge.net>,
4422e22a 8# darren chamberlain <darren@cpan.org>,
9# Chris Mungall <cjm@fruitfly.org>
10#
11# This program is free software; you can redistribute it and/or
12# modify it under the terms of the GNU General Public License as
13# published by the Free Software Foundation; version 2.
14#
15# This program is distributed in the hope that it will be useful, but
16# WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18# General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program; if not, write to the Free Software
0efb6e1b 22# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
4422e22a 23# 02111-1307 USA
24# -------------------------------------------------------------------
25
26=head1 NAME
27
84012a55 28SQL::Translator::Parser::PostgreSQL - parser for PostgreSQL
4422e22a 29
30=head1 SYNOPSIS
31
32 use SQL::Translator;
84012a55 33 use SQL::Translator::Parser::PostgreSQL;
4422e22a 34
35 my $translator = SQL::Translator->new;
84012a55 36 $translator->parser("SQL::Translator::Parser::PostgreSQL");
4422e22a 37
38=head1 DESCRIPTION
39
0efb6e1b 40The grammar was started from the MySQL parsers. Here is the description
41from PostgreSQL:
42
43Table:
629b76f9 44(http://www.postgresql.org/docs/view.php?version=7.3&idoc=1&file=sql-createtable.html)
45
46 CREATE [ [ LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (
47 { column_name data_type [ DEFAULT default_expr ]
48 [ column_constraint [, ... ] ]
49 | table_constraint } [, ... ]
50 )
51 [ INHERITS ( parent_table [, ... ] ) ]
52 [ WITH OIDS | WITHOUT OIDS ]
53
54 where column_constraint is:
55
56 [ CONSTRAINT constraint_name ]
57 { NOT NULL | NULL | UNIQUE | PRIMARY KEY |
58 CHECK (expression) |
59 REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL ]
60 [ ON DELETE action ] [ ON UPDATE action ] }
61 [ DEFERRABLE | NOT DEFERRABLE ]
62 [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
63
64 and table_constraint is:
65
66 [ CONSTRAINT constraint_name ]
67 { UNIQUE ( column_name [, ... ] ) |
68 PRIMARY KEY ( column_name [, ... ] ) |
69 CHECK ( expression ) |
70 FOREIGN KEY ( column_name [, ... ] )
71 REFERENCES reftable [ ( refcolumn [, ... ] ) ]
72 [ MATCH FULL | MATCH PARTIAL ]
73 [ ON DELETE action ] [ ON UPDATE action ] }
74 [ DEFERRABLE | NOT DEFERRABLE ]
75 [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
0efb6e1b 76
77Index:
629b76f9 78(http://www.postgresql.org/docs/view.php?version=7.3&idoc=1&file=sql-createindex.html)
0efb6e1b 79
629b76f9 80 CREATE [ UNIQUE ] INDEX index_name ON table
81 [ USING acc_method ] ( column [ ops_name ] [, ...] )
82 [ WHERE predicate ]
83 CREATE [ UNIQUE ] INDEX index_name ON table
84 [ USING acc_method ] ( func_name( column [, ... ]) [ ops_name ] )
85 [ WHERE predicate ]
4422e22a 86
87=cut
88
89use strict;
90use vars qw[ $DEBUG $VERSION $GRAMMAR @EXPORT_OK ];
629b76f9 91$VERSION = sprintf "%d.%02d", q$Revision: 1.6 $ =~ /(\d+)\.(\d+)/;
4422e22a 92$DEBUG = 0 unless defined $DEBUG;
93
94use Data::Dumper;
95use Parse::RecDescent;
96use Exporter;
97use base qw(Exporter);
98
99@EXPORT_OK = qw(parse);
100
101# Enable warnings within the Parse::RecDescent module.
102$::RD_ERRORS = 1; # Make sure the parser dies when it encounters an error
103$::RD_WARN = 1; # Enable warnings. This will warn on unused rules &c.
104$::RD_HINT = 1; # Give out hints to help fix problems.
105
106my $parser; # should we do this? There's no programmic way to
107 # change the grammar, so I think this is safe.
108
109$GRAMMAR = q!
110
0efb6e1b 111{ our ( %tables, $table_order ) }
4422e22a 112
629b76f9 113#
114# The "eofile" rule makes the parser fail if any "statement" rule
115# fails. Otherwise, the first successful match by a "statement"
116# won't cause the failure needed to know that the parse, as a whole,
117# failed. -ky
118#
0efb6e1b 119startrule : statement(s) eofile { \%tables }
4422e22a 120
0efb6e1b 121eofile : /^\Z/
122
123statement : create
124 | comment
125 | grant
126 | revoke
4422e22a 127 | drop
0efb6e1b 128 | connect
4422e22a 129 | <error>
130
0efb6e1b 131connect : /^\s*\\\connect.*\n/
132
133revoke : /revoke/i WORD(s /,/) /on/i table_name /from/i name_with_opt_quotes(s /,/) ';'
134 {
135 my $table_name = $item{'table_name'};
136 push @{ $tables{ $table_name }{'permissions'} }, {
137 type => 'revoke',
138 actions => $item[2],
139 users => $item[6],
140 }
141 }
142
143grant : /grant/i WORD(s /,/) /on/i table_name /to/i name_with_opt_quotes(s /,/) ';'
144 {
145 my $table_name = $item{'table_name'};
146 push @{ $tables{ $table_name }{'permissions'} }, {
147 type => 'grant',
148 actions => $item[2],
149 users => $item[6],
150 }
151 }
152
153drop : /drop/i /[^;]*/ ';'
4422e22a 154
ba1a1626 155create : create_table table_name '(' create_definition(s /,/) ')' table_option(s?) ';'
0efb6e1b 156 {
157 my $table_name = $item{'table_name'};
158 $tables{ $table_name }{'order'} = ++$table_order;
159 $tables{ $table_name }{'table_name'} = $table_name;
160
161 my $i = 1;
162 my @constraints;
163 for my $definition ( @{ $item[4] } ) {
164 if ( $definition->{'type'} eq 'field' ) {
165 my $field_name = $definition->{'name'};
166 $tables{ $table_name }{'fields'}{ $field_name } =
167 { %$definition, order => $i };
168 $i++;
4422e22a 169
0efb6e1b 170 if ( $definition->{'is_primary_key'} ) {
171 push @{ $tables{ $table_name }{'indices'} }, {
172 type => 'primary_key',
173 fields => [ $field_name ],
174 };
175 }
176
177 for my $constraint ( @{ $definition->{'constaints'} || [] } ) {
178 $constraint->{'fields' } = [ $field_name ];
179 push @{$tables{ $table_name }{'constraints'}}, $constraint;
180 }
181 }
182 elsif ( $definition->{'type'} eq 'constraint' ) {
183 $definition->{'type'} = $definition->{'constraint_type'};
184 push @{ $tables{ $table_name }{'constraints'} }, $definition;
185 }
186 else {
187 push @{ $tables{ $table_name }{'indices'} }, $definition;
188 }
189 }
190
191 for my $option ( @{ $item[6] } ) {
192 $tables{ $table_name }{'table_options'}{ $option->{'type'} } =
193 $option;
194 }
195
196 1;
197 }
198
199create : /create/i unique(?) /(index|key)/i index_name /on/i table_name using_method(?) '(' field_name(s /,/) ')' where_predicate(?) ';'
4422e22a 200 {
201 push @{ $tables{ $item{'table_name'} }{'indices'} },
202 {
0efb6e1b 203 name => $item{'index_name'},
204 type => $item{'unique'}[0] ? 'unique' : 'normal',
205 fields => $item[9],
206 method => $item{'using_method'}[0],
4422e22a 207 }
208 ;
209 }
210
0efb6e1b 211using_method : /using/i WORD { $item[2] }
212
213where_predicate : /where/i /[^;]+/
214
215create_definition : field
216 | index
217 | table_constraint
4422e22a 218 | <error>
219
220comment : /^\s*(?:#|-{2}).*\n/
221
0efb6e1b 222field : field_name data_type field_meta(s?)
4422e22a 223 {
0efb6e1b 224 my ( $default, @constraints );
225 for my $meta ( @{ $item[3] } ) {
226 $default = $meta if $meta->{'meta_type'} eq 'default';
227 push @constraints, $meta if $meta->{'meta_type'} eq 'constraint';
4422e22a 228 }
229
0efb6e1b 230 my $null = ( grep { $_->{'type'} eq 'not_null' } @constraints ) ? 0 : 1;
231
4422e22a 232 $return = {
233 type => 'field',
234 name => $item{'field_name'},
235 data_type => $item{'data_type'}{'type'},
236 size => $item{'data_type'}{'size'},
237 list => $item{'data_type'}{'list'},
238 null => $null,
0efb6e1b 239 default => $default->{'value'},
240 constraints => [ @constraints ],
4422e22a 241 }
242 }
243 | <error>
244
0efb6e1b 245field_meta : default_val
246 |
247 column_constraint
4422e22a 248
0efb6e1b 249column_constraint : constraint_name(?) column_constraint_type deferrable(?) deferred(?)
250 {
251 my $desc = $item{'column_constraint_type'};
252 my $type = $desc->{'type'};
253 my $fields = $desc->{'fields'} || [];
254 my $expression = $desc->{'expression'} || '';
255
256 $return = {
257 meta_type => 'constraint',
258 name => $item{'constraint_name'}[0] || '',
259 type => $type,
260 expression => $type eq 'check' ? $expression : '',
261 deferreable => $item{'deferrable'},
262 deferred => $item{'deferred'},
263 reference_table => $desc->{'reference_table'},
264 reference_fields => $desc->{'reference_fields'},
265 match_type => $desc->{'match_type'},
266 on_delete_do => $desc->{'on_delete_do'},
267 on_update_do => $desc->{'on_update_do'},
4422e22a 268 }
269 }
270
0efb6e1b 271constraint_name : /constraint/i name_with_opt_quotes { $item[2] }
272
273column_constraint_type : /not null/i { $return = { type => 'not_null' } }
274 |
275 /null/
276 { $return = { type => 'null' } }
277 |
278 /unique/
279 { $return = { type => 'unique' } }
280 |
281 /primary key/i
282 { $return = { type => 'primary_key' } }
283 |
284 /check/i '(' /[^)]+/ ')'
285 { $return = { type => 'check', expression => $item[2] } }
286 |
287 /references/i table_name parens_value_list(?) match_type(?) on_delete_do(?) on_update_do(?)
288 {
289 $return = {
290 type => 'foreign_key',
291 reference_table => $item[2],
292 reference_fields => $item[3],
293 match_type => $item[4][0],
294 on_delete_do => $item[5][0],
295 on_update_do => $item[6][0],
ba1a1626 296 }
4422e22a 297 }
298
4422e22a 299index : primary_key_index
300 | unique_index
4422e22a 301 | normal_index
302
0efb6e1b 303table_name : name_with_opt_quotes
4422e22a 304
0efb6e1b 305field_name : name_with_opt_quotes
4422e22a 306
0efb6e1b 307name_with_opt_quotes : double_quote(?) WORD double_quote(?) { $item[2] }
4422e22a 308
0efb6e1b 309double_quote: /"/
4422e22a 310
0efb6e1b 311index_name : WORD
4422e22a 312
0efb6e1b 313data_type : pg_data_type parens_value_list(?)
4422e22a 314 {
315 my $type = $item[1];
ba1a1626 316
0efb6e1b 317 #
318 # We can deduce some sizes from the data type's name.
319 #
320 my $size;
321 if ( ref $type eq 'ARRAY' ) {
322 $size = [ $type->[1] ];
323 $type = $type->[0];
4422e22a 324 }
325 else {
0efb6e1b 326 $size = $item[2][0] || '';
4422e22a 327 }
328
0efb6e1b 329 $return = {
330 type => $type,
331 size => $size,
4422e22a 332 }
333 }
334
0efb6e1b 335pg_data_type :
336 /(bigint|int8|bigserial|serial8)/ { $return = [ 'integer', 8 ] }
337 |
338 /(smallint|int2)/ { $return = [ 'integer', 2 ] }
339 |
340 /int(eger)?|int4/ { $return = [ 'integer', 4 ] }
341 |
342 /(double precision|float8?)/ { $return = [ 'float', 8 ] }
343 |
344 /(real|float4)/ { $return = [ 'real', 4 ] }
345 |
346 /serial4?/ { $return = [ 'serial', 4 ] }
347 |
348 /bigserial/ { $return = [ 'serial', 8 ] }
349 |
350 /(bit varying|varbit)/ { $return = 'varbit' }
351 |
352 /character varying/ { $return = 'varchar' }
353 |
354 /char(acter)?/ { $return = 'char' }
355 |
356 /bool(ean)?/ { $return = 'boolean' }
357 |
358 /(bytea|binary data)/ { $return = 'binary' }
359 |
360 /timestampz?/ { $return = 'timestamp' }
361 |
362 /(bit|box|cidr|circle|date|inet|interval|line|lseg|macaddr|money|numeric|decimal|path|point|polygon|text|time|varchar)/
363 { $item[1] }
364
4422e22a 365parens_value_list : '(' VALUE(s /,/) ')'
366 { $item[2] }
367
0efb6e1b 368parens_word_list : '(' WORD(s /,/) ')'
369 { $item[2] }
4422e22a 370
0efb6e1b 371field_size : '(' num_range ')' { $item{'num_range'} }
4422e22a 372
0efb6e1b 373num_range : DIGITS ',' DIGITS
4422e22a 374 { $return = $item[1].','.$item[3] }
375 | DIGITS
376 { $return = $item[1] }
377
0efb6e1b 378table_constraint : constraint_name(?) table_constraint_type deferrable(?) deferred(?)
379 {
380 my $desc = $item{'table_constraint_type'};
381 my $type = $desc->{'type'};
382 my $fields = $desc->{'fields'};
383 my $expression = $desc->{'expression'};
384
385 $return = {
386 name => $item{'constraint_name'}[0] || '',
387 type => 'constraint',
388 constraint_type => $type,
389 fields => $type ne 'check' ? $fields : [],
390 expression => $type eq 'check' ? $expression : '',
391 deferreable => $item{'deferrable'},
392 deferred => $item{'deferred'},
393 reference_table => $desc->{'reference_table'},
394 reference_fields => $desc->{'reference_fields'},
395 match_type => $desc->{'match_type'}[0],
396 on_delete_do => $desc->{'on_delete_do'}[0],
397 on_update_do => $desc->{'on_update_do'}[0],
398 }
399 }
4422e22a 400
0efb6e1b 401table_constraint_type : /primary key/i '(' name_with_opt_quotes(s /,/) ')'
402 {
403 $return = {
404 type => 'primary_key',
405 fields => $item[3],
406 }
407 }
408 |
409 /unique/i '(' name_with_opt_quotes(s /,/) ')'
410 {
411 $return = {
412 type => 'unique',
413 fields => $item[3],
414 }
415 }
416 |
417 /check/ '(' /(.+)/ ')'
418 {
419 $return = {
420 type => 'check',
421 expression => $item[3],
422 }
423 }
424 |
425 /foreign key/i '(' name_with_opt_quotes(s /,/) ')' /references/i table_name parens_word_list(?) match_type(?) on_delete_do(?) on_update_do(?)
426 {
427 $return = {
428 type => 'foreign_key',
429 fields => $item[3],
430 reference_table => $item[6],
431 reference_fields => $item[7][0],
432 match_type => $item[8][0],
433 on_delete_do => $item[9][0],
434 on_update_do => $item[10][0],
435 }
436 }
437
438deferrable : /not/i /deferrable/i
439 {
440 $return = ( $item[1] =~ /not/i ) ? 0 : 1;
441 }
4422e22a 442
0efb6e1b 443deferred : /initially/i /(deferred|immediate)/i { $item[2] }
4422e22a 444
0efb6e1b 445match_type : /match full/i { 'match_full' }
446 |
447 /match partial/i { 'match_partial' }
448
449on_delete_do : /on delete/i WORD
450 { $item[2] }
451
452on_update_do : /on update/i WORD
453 { $item[2] }
454
455create_table : /create/i /table/i
456
457create_index : /create/i /index/i
4422e22a 458
459default_val : /default/i /(?:')?[\w\d.-]*(?:')?/
460 {
0efb6e1b 461 my $val = $item[2] || '';
462 $val =~ s/'//g;
463 $return = {
464 meta_type => 'default',
465 value => $val,
466 }
4422e22a 467 }
468
0efb6e1b 469auto_inc : /auto_increment/i { 1 }
4422e22a 470
471primary_key : /primary/i /key/i { 1 }
472
4422e22a 473primary_key_index : primary_key index_name(?) '(' field_name(s /,/) ')'
474 {
475 $return = {
476 name => $item{'index_name'}[0],
477 type => 'primary_key',
478 fields => $item[4],
479 }
480 }
481
482normal_index : key index_name(?) '(' name_with_opt_paren(s /,/) ')'
483 {
484 $return = {
485 name => $item{'index_name'}[0],
486 type => 'normal',
487 fields => $item[4],
488 }
489 }
490
491unique_index : unique key(?) index_name(?) '(' name_with_opt_paren(s /,/) ')'
492 {
493 $return = {
494 name => $item{'index_name'}[0],
495 type => 'unique',
496 fields => $item[5],
497 }
498 }
499
4422e22a 500name_with_opt_paren : NAME parens_value_list(s?)
0efb6e1b 501 { $item[2][0] ? "$item[1]($item[2][0][0])" : $item[1] }
4422e22a 502
503unique : /unique/i { 1 }
504
505key : /key/i | /index/i
506
0efb6e1b 507table_option : /inherits/i '(' name_with_opt_quotes(s /,/) ')'
4422e22a 508 {
0efb6e1b 509 $return = { type => 'inherits', table_name => $item[3] }
510 }
511 |
512 /with(out)? oids/i
513 {
514 $return = { type => $item[1] =~ /out/i ? 'without_oids' : 'with_oids' }
4422e22a 515 }
516
0efb6e1b 517SEMICOLON : /\s*;\n?/
518
4422e22a 519WORD : /\w+/
520
521DIGITS : /\d+/
522
523COMMA : ','
524
525NAME : "`" /\w+/ "`"
526 { $item[2] }
527 | /\w+/
528 { $item[1] }
529
530VALUE : /[-+]?\.?\d+(?:[eE]\d+)?/
531 { $item[1] }
532 | /'.*?'/ # XXX doesn't handle embedded quotes
533 { $item[1] }
534 | /NULL/
535 { 'NULL' }
536
537!;
538
539# -------------------------------------------------------------------
540sub parse {
541 my ( $translator, $data ) = @_;
542 $parser ||= Parse::RecDescent->new($GRAMMAR);
543
544 $::RD_TRACE = $translator->trace ? 1 : undef;
545 $DEBUG = $translator->debug;
546
547 unless (defined $parser) {
548 return $translator->error("Error instantiating Parse::RecDescent ".
549 "instance: Bad grammer");
550 }
551
552 my $result = $parser->startrule($data);
553 die "Parse failed.\n" unless defined $result;
554 warn Dumper($result) if $DEBUG;
555 return $result;
556}
557
5581;
559
560#-----------------------------------------------------
561# Where man is not nature is barren.
562# William Blake
563#-----------------------------------------------------
564
565=pod
566
0efb6e1b 567=head1 AUTHORS
4422e22a 568
569Ken Y. Clark E<lt>kclark@cpan.orgE<gt>,
0efb6e1b 570Allen Day <allenday@users.sourceforge.net>.
4422e22a 571
572=head1 SEE ALSO
573
574perl(1), Parse::RecDescent.
575
576=cut