i forget what i did, but i found more bugs. we need to be able to support 'varchar'
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Parser / PostgreSQL.pm
1 package SQL::Translator::Parser::PostgreSQL;
2
3 # -------------------------------------------------------------------
4 # $Id: PostgreSQL.pm,v 1.4 2003-02-25 03:24:56 allenday Exp $
5 # -------------------------------------------------------------------
6 # Copyright (C) 2003 Ken Y. Clark <kclark@cpan.org>,
7 #                    darren chamberlain <darren@cpan.org>,
8 #                    Chris Mungall <cjm@fruitfly.org>
9 #
10 # This program is free software; you can redistribute it and/or
11 # modify it under the terms of the GNU General Public License as
12 # published by the Free Software Foundation; version 2.
13 #
14 # This program is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 # General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program; if not, write to the Free Software
21 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 
22 # 02111-1307  USA
23 # -------------------------------------------------------------------
24
25 =head1 NAME
26
27 SQL::Translator::Parser::PostgreSQL - parser for PostgreSQL
28
29 =head1 SYNOPSIS
30
31   use SQL::Translator;
32   use SQL::Translator::Parser::PostgreSQL;
33
34   my $translator = SQL::Translator->new;
35   $translator->parser("SQL::Translator::Parser::PostgreSQL");
36
37 =head1 DESCRIPTION
38
39 The grammar is influenced heavily by Tim Bunce's "mysql2ora" grammar.
40
41 =cut
42
43 use strict;
44 use vars qw[ $DEBUG $VERSION $GRAMMAR @EXPORT_OK ];
45 $VERSION = sprintf "%d.%02d", q$Revision: 1.4 $ =~ /(\d+)\.(\d+)/;
46 $DEBUG   = 0 unless defined $DEBUG;
47
48 use Data::Dumper;
49 use Parse::RecDescent;
50 use Exporter;
51 use base qw(Exporter);
52
53 @EXPORT_OK = qw(parse);
54
55 # Enable warnings within the Parse::RecDescent module.
56 $::RD_ERRORS = 1; # Make sure the parser dies when it encounters an error
57 $::RD_WARN   = 1; # Enable warnings. This will warn on unused rules &c.
58 $::RD_HINT   = 1; # Give out hints to help fix problems.
59
60 my $parser; # should we do this?  There's no programmic way to 
61             # change the grammar, so I think this is safe.
62
63 $GRAMMAR = q!
64
65 { our ( %tables, $table_order, $current_table ) }
66
67 startrule : statement(s) { \%tables }
68
69 statement : comment
70   | drop
71   | create
72   | <error>
73
74 drop : /drop/i WORD(s) ';'
75
76 create : create_table table_name '(' create_definition(s /,/) ')' table_option(s?) ';'
77   {
78    my $table_name                       = $item{'table_name'};
79    $current_table                       = $item{'table_name'};
80    $tables{ $table_name }{'order'}      = ++$table_order;
81    $tables{ $table_name }{'table_name'} = $table_name;
82
83    my $i = 1;
84    for my $definition ( @{ $item[4] } ) {
85          if ( $definition->{'type'} eq 'field' ) {
86            my $field_name = $definition->{'name'};
87            $tables{ $table_name }{'fields'}{ $field_name } = 
88                  { %$definition, order => $i };
89            $i++;
90                                 
91            if ( $definition->{'is_primary_key'} ) {
92                  push @{ $tables{ $table_name }{'indices'} },
93                    {
94                         type   => 'primary_key',
95                         fields => [ $field_name ],
96                    }
97                          ;
98            }
99          }
100          else {
101            push @{ $tables{ $table_name }{'indices'} },
102                  $definition;
103          }
104    }
105
106    for my $opt ( @{ $item{'table_option'} } ) {
107          if ( my ( $key, $val ) = each %$opt ) {
108            $tables{ $table_name }{'table_options'}{ $key } = $val;
109          }
110    }
111   }
112
113   create : /CREATE/i unique(?) /(INDEX|KEY)/i index_name /on/i table_name '(' field_name(s /,/) ')' ';'
114     {
115         push @{ $tables{ $item{'table_name'} }{'indices'} },
116             {
117                 name   => $item[4],
118                 type   => $item[2] ? 'unique' : 'normal',
119                 fields => $item[8],
120             }
121         ;
122     }
123
124 create_definition : index
125     | field
126     | <error>
127
128 comment : /^\s*(?:#|-{2}).*\n/
129
130 blank : /\s*/
131
132 field : field_name data_type field_qualifier(s?)
133     {
134         my %qualifiers = map { %$_ } @{ $item{'field_qualifier'} || [] };
135         my $null = defined $item{'not_null'} ? $item{'not_null'} : 1;
136         delete $qualifiers{'not_null'};
137         if ( my @type_quals = @{ $item{'data_type'}{'qualifiers'} || [] } ) {
138             $qualifiers{ $_ } = 1 for @type_quals;
139         }
140
141         $return = { 
142             type           => 'field',
143             name           => $item{'field_name'}, 
144             data_type      => $item{'data_type'}{'type'},
145             size           => $item{'data_type'}{'size'},
146             list           => $item{'data_type'}{'list'},
147             null           => $null,
148             %qualifiers,
149         } 
150     }
151     | <error>
152
153 field_qualifier : not_null
154     { 
155         $return = { 
156              null => $item{'not_null'},
157         } 
158     }
159
160 field_qualifier : default_val
161     { 
162         $return = { 
163              default => $item{'default_val'},
164         } 
165     }
166
167 field_qualifier : auto_inc
168     { 
169         $return = { 
170              is_auto_inc => $item{'auto_inc'},
171         } 
172     }
173
174 field_qualifier : ',' primary_key '(' field_name ')'
175     { 
176         $return = { 
177              is_primary_key => $item{'primary_key'},
178         } 
179     }
180
181 field_qualifier : ',' foreign_key '(' field_name ')' foreign_key_reference foreign_table_name '(' foreign_field_name ')'
182     { 
183         $return = {
184              is_foreign_key => $item{'foreign_key'},
185                          foreign_table => $item{'foreign_table_name'},
186                          foreign_field => $item{'foreign_field_name'},
187                          name => $item{'field_name'},
188         }
189     }
190
191 field_qualifier : unsigned
192     { 
193         $return = { 
194              is_unsigned => $item{'unsigned'},
195         } 
196     }
197
198 index : primary_key_index
199     | unique_index
200     | fulltext_index
201     | normal_index
202
203 table_name   : WORD
204
205 foreign_table_name   : WORD
206
207 field_name   : WORD
208
209 foreign_field_name   : WORD
210
211 index_name   : WORD
212
213 data_type    : WORD parens_value_list(s?) type_qualifier(s?)
214     { 
215         my $type = $item[1];
216
217         my $size; # field size, applicable only to non-set fields
218         my $list; # set list, applicable only to sets (duh)
219
220
221         if(uc($type) =~ /^SERIAL$/){
222             $type = 'int';
223         } elsif ( uc($type) =~ /^(SET|ENUM)$/ ) {
224             $size = undef;
225             $list = $item[2][0];
226         }
227         else {
228             $size = $item[2][0];
229             $list = [];
230         }
231
232         if(uc($type) =~ /^VARCHAR$/ and not defined($size)){ $size = [255] }
233
234         $return        = { 
235             type       => $type,
236             size       => $size,
237             list       => $list,
238             qualifiers => $item[3],
239         } 
240     }
241
242 parens_value_list : '(' VALUE(s /,/) ')'
243     { $item[2] }
244
245 type_qualifier : /(BINARY|UNSIGNED|ZEROFILL)/i
246     { lc $item[1] }
247
248 field_type   : WORD
249
250 field_size   : '(' num_range ')' { $item{'num_range'} }
251
252 num_range    : DIGITS ',' DIGITS
253     { $return = $item[1].','.$item[3] }
254     | DIGITS
255     { $return = $item[1] }
256
257 create_table : /create/i /table/i
258
259 create_index : /create/i /index/i
260
261 not_null     : /not/i /null/i { $return = 0 }
262
263 unsigned     : /unsigned/i { $return = 0 }
264
265 default_val  : /default/i /(?:')?[\w\d.-]*(?:')?/ 
266     { 
267         $item[2] =~ s/'//g; 
268         $return  =  $item[2];
269     }
270
271 auto_inc : /auto_increment/i { 1 } #see data_type
272
273 primary_key : /primary/i /key/i { 1 }
274
275 foreign_key : /foreign/i /key/i { 1 }
276
277 foreign_key_reference : /references/i { 1 }
278
279 primary_key_index : primary_key index_name(?) '(' field_name(s /,/) ')'
280     { 
281         $return    = { 
282             name   => $item{'index_name'}[0],
283             type   => 'primary_key',
284             fields => $item[4],
285         } 
286     }
287
288 normal_index : key index_name(?) '(' name_with_opt_paren(s /,/) ')'
289     { 
290         $return    = { 
291             name   => $item{'index_name'}[0],
292             type   => 'normal',
293             fields => $item[4],
294         } 
295     }
296
297 unique_index : unique key(?) index_name(?) '(' name_with_opt_paren(s /,/) ')'
298     { 
299         $return    = { 
300             name   => $item{'index_name'}[0],
301             type   => 'unique',
302             fields => $item[5],
303         } 
304     }
305
306 fulltext_index : fulltext key(?) index_name(?) '(' name_with_opt_paren(s /,/) ')'
307     { 
308         $return    = { 
309             name   => $item{'index_name'}[0],
310             type   => 'fulltext',
311             fields => $item[5],
312         } 
313     }
314
315 name_with_opt_paren : NAME parens_value_list(s?)
316     {
317         if($item[2][0]) {
318           "$item[1]($item[2][0][0])"
319         } else {
320           $item[1];
321         }
322     }
323
324 fulltext : /fulltext/i { 1 }
325
326 unique : /unique/i { 1 }
327
328 key : /key/i | /index/i
329
330 table_option : /[^\s;]*/ 
331     { 
332         $return = { split /=/, $item[1] }
333     }
334
335 WORD : /\w+/
336
337 DIGITS : /\d+/
338
339 COMMA : ','
340
341 NAME    : "`" /\w+/ "`"
342     { $item[2] }
343     | /\w+/
344     { $item[1] }
345
346 VALUE   : /[-+]?\.?\d+(?:[eE]\d+)?/
347     { $item[1] }
348     | /'.*?'/   # XXX doesn't handle embedded quotes
349     { $item[1] }
350     | /NULL/
351     { 'NULL' }
352
353 !;
354
355 #        $item[2][0] ? "$item[1]($item[2][0][0])" : $item[1];
356
357 # -------------------------------------------------------------------
358 sub parse {
359     my ( $translator, $data ) = @_;
360     $parser ||= Parse::RecDescent->new($GRAMMAR);
361
362     $::RD_TRACE  = $translator->trace ? 1 : undef;
363     $DEBUG       = $translator->debug;
364
365     unless (defined $parser) {
366         return $translator->error("Error instantiating Parse::RecDescent ".
367             "instance: Bad grammer");
368     }
369
370     my $result = $parser->startrule($data);
371     die "Parse failed.\n" unless defined $result;
372     warn Dumper($result) if $DEBUG;
373     return $result;
374 }
375
376 1;
377
378 #-----------------------------------------------------
379 # Where man is not nature is barren.
380 # William Blake
381 #-----------------------------------------------------
382
383 =pod
384
385 =head1 AUTHOR
386
387 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>,
388 Chris Mungall
389
390 =head1 SEE ALSO
391
392 perl(1), Parse::RecDescent.
393
394 =cut