Fixed handling of NULLs.
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Parser / Oracle.pm
1 package SQL::Translator::Parser::Oracle;
2
3 # -------------------------------------------------------------------
4 # $Id: Oracle.pm,v 1.26 2006-06-29 19:24:14 kycl4rk Exp $
5 # -------------------------------------------------------------------
6 # Copyright (C) 2002-4 SQLFairy Authors
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
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20 # 02111-1307  USA
21 # -------------------------------------------------------------------
22
23 =head1 NAME
24
25 SQL::Translator::Parser::Oracle - parser for Oracle
26
27 =head1 SYNOPSIS
28
29   use SQL::Translator;
30   use SQL::Translator::Parser::Oracle;
31
32   my $translator = SQL::Translator->new;
33   $translator->parser("SQL::Translator::Parser::Oracle");
34
35 =head1 DESCRIPTION
36
37 From http://www.ss64.com/ora/table_c.html:
38
39  CREATE [GLOBAL TEMPORARY] TABLE [schema.]table (tbl_defs,...)
40      [ON COMMIT {DELETE|PRESERVE} ROWS]
41          [storage_options | CLUSTER cluster_name (col1, col2,... )
42             | ORGANIZATION {HEAP [storage_options] 
43             | INDEX idx_organized_tbl_clause}]
44                [LOB_storage_clause][varray_clause][nested_storage_clause]
45                    partitioning_options
46                       [[NO]CACHE] [[NO]MONITORING] [PARALLEL parallel_clause]
47                          [ENABLE enable_clause | DISABLE disable_clause]
48                              [AS subquery]
49
50 tbl_defs:
51    column datatype [DEFAULT expr] [column_constraint(s)]
52    table_ref_constraint
53
54 storage_options:
55    PCTFREE int
56    PCTUSED int
57    INITTRANS int
58    MAXTRANS int
59    STORAGE storage_clause
60    TABLESPACE tablespace
61    [LOGGING|NOLOGGING]
62
63 idx_organized_tbl_clause:
64    storage_option(s) [PCTTHRESHOLD int]
65      [COMPRESS int|NOCOMPRESS]
66          [ [INCLUDING column_name] OVERFLOW [storage_option(s)] ]
67
68 nested_storage_clause:
69    NESTED TABLE nested_item STORE AS storage_table
70       [RETURN AS {LOCATOR|VALUE} ]
71
72 partitioning_options:
73    Partition_clause {ENABLE|DISABLE} ROW MOVEMENT
74
75 Column Constraints
76 (http://www.ss64.com/ora/clause_constraint_col.html)
77
78    CONSTRAINT constrnt_name {UNIQUE|PRIMARY KEY} constrnt_state
79
80    CONSTRAINT constrnt_name CHECK(condition) constrnt_state
81
82    CONSTRAINT constrnt_name [NOT] NULL constrnt_state
83
84    CONSTRAINT constrnt_name REFERENCES [schema.]table[(column)]
85       [ON DELETE {CASCADE|SET NULL}] constrnt_state
86
87 constrnt_state   
88     [[NOT] DEFERRABLE] [INITIALLY {IMMEDIATE|DEFERRED}]
89        [RELY | NORELY] [USING INDEX using_index_clause]
90           [ENABLE|DISABLE] [VALIDATE|NOVALIDATE]
91               [EXCEPTIONS INTO [schema.]table]
92
93 Note that probably not all of the above syntax is supported, but the grammar 
94 was altered to better handle the syntax created by DDL::Oracle.
95
96 =cut
97
98 use strict;
99 use vars qw[ $DEBUG $VERSION $GRAMMAR @EXPORT_OK ];
100 $VERSION = sprintf "%d.%02d", q$Revision: 1.26 $ =~ /(\d+)\.(\d+)/;
101 $DEBUG   = 0 unless defined $DEBUG;
102
103 use Data::Dumper;
104 use Parse::RecDescent;
105 use Exporter;
106 use base qw(Exporter);
107
108 @EXPORT_OK = qw(parse);
109
110 # Enable warnings within the Parse::RecDescent module.
111 $::RD_ERRORS = 1; # Make sure the parser dies when it encounters an error
112 $::RD_WARN   = 1; # Enable warnings. This will warn on unused rules &c.
113 $::RD_HINT   = 1; # Give out hints to help fix problems.
114
115 $GRAMMAR = q`
116
117 { my ( %tables, %indices, %constraints, $table_order, @table_comments ) }
118
119 #
120 # The "eofile" rule makes the parser fail if any "statement" rule
121 # fails.  Otherwise, the first successful match by a "statement" 
122 # won't cause the failure needed to know that the parse, as a whole,
123 # failed. -ky
124 #
125 startrule : statement(s) eofile 
126     { 
127         $return = {
128             tables      => \%tables,
129             indices     => \%indices,
130             constraints => \%constraints,
131         };
132     }
133
134 eofile : /^\Z/
135
136 statement : remark
137         | run
138     | prompt
139     | create
140     | table_comment
141     | comment_on_table
142     | comment_on_column
143     | alter
144     | drop
145     | <error>
146
147 alter : /alter/i WORD /[^;]+/ ';'
148     { @table_comments = () }
149
150 drop : /drop/i TABLE ';'
151
152 drop : /drop/i WORD(s) ';'
153     { @table_comments = () }
154
155 create : create_table table_name '(' create_definition(s /,/) ')' table_option(s?) ';'
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         if ( @table_comments ) {
162             $tables{ $table_name }{'comments'} = [ @table_comments ];
163             @table_comments = ();
164         }
165
166         my $i = 1;
167         my @constraints;
168         for my $definition ( @{ $item[4] } ) {
169             if ( $definition->{'type'} eq 'field' ) {
170                 my $field_name = $definition->{'name'};
171                 $tables{ $table_name }{'fields'}{ $field_name } = 
172                     { %$definition, order => $i };
173                 $i++;
174                                 
175                 for my $constraint ( @{ $definition->{'constraints'} || [] } ) {
176                     $constraint->{'fields'} = [ $field_name ];
177                     push @{ $tables{ $table_name }{'constraints'} }, 
178                         $constraint;
179                 }
180             }
181             elsif ( $definition->{'type'} eq 'constraint' ) {
182                 $definition->{'type'} = $definition->{'constraint_type'};
183                 push @{ $tables{ $table_name }{'constraints'} }, $definition;
184             }
185             else {
186                 push @{ $tables{ $table_name }{'indices'} }, $definition;
187             }
188         }
189
190         for my $option ( @{ $item[6] } ) {
191             push @{ $tables{ $table_name }{'table_options'} }, $option;
192         }
193
194         1;
195     }
196
197 create : create_index index_name /on/i table_name index_expr table_option(?) ';'
198     {
199         my $table_name = $item[4];
200         if ( $item[1] ) {
201             push @{ $constraints{ $table_name } }, {
202                 name   => $item[2],
203                 type   => 'unique',
204                 fields => $item[5],
205             };
206         }
207         else {
208             push @{ $indices{ $table_name } }, {
209                 name   => $item[2],
210                 type   => 'normal',
211                 fields => $item[5],
212             };
213         }
214     }
215
216 index_expr: parens_word_list
217         { $item[1] }
218         | '(' WORD parens_word_list ')'
219         {
220                 my $arg_list = join(",", @{$item[3]});
221                 $return = "$item[2]($arg_list)";
222         }
223
224 # Create anything else (e.g., domain, function, etc.)
225 create : ...!create_table ...!create_index /create/i WORD /[^;]+/ ';'
226     { @table_comments = () }
227
228 create_index : /create/i UNIQUE(?) /index/i
229         { $return = $item[2] }
230
231 index_name : NAME '.' NAME
232     { $item[3] }
233     | NAME 
234     { $item[1] }
235
236 global_temporary: /global/i /temporary/i
237
238 table_name : NAME '.' NAME
239     { $item[3] }
240     | NAME 
241     { $item[1] }
242
243 create_definition : field
244     | table_constraint
245     | <error>
246
247 table_comment : comment
248     {
249         my $comment = $item[1];
250         $return     = $comment;
251         push @table_comments, $comment;
252     }
253
254 comment : /^\s*(?:#|-{2}).*\n/
255     {
256         my $comment =  $item[1];
257         $comment    =~ s/^\s*(#|-{2})\s*//;
258         $comment    =~ s/\s*$//;
259         $return     = $comment;
260     }
261
262 comment : /\/\*/ /[^\*]+/ /\*\// 
263     {
264         my $comment = $item[2];
265         $comment    =~ s/^\s*|\s*$//g;
266         $return = $comment;
267     }
268
269 remark : /^REM\s+.*\n/
270
271 run : /^(RUN|\/)\s+.*\n/
272
273 prompt : /prompt/i /(table|index|sequence|trigger)/i ';'
274
275 prompt : /prompt\s+create\s+.*\n/i
276
277 comment_on_table : /comment/i /on/i /table/i table_name /is/i comment_phrase ';'
278     {
279         push @{ $tables{ $item{'table_name'} }{'comments'} }, $item{'comment_phrase'};
280     }
281
282 comment_on_column : /comment/i /on/i /column/i column_name /is/i comment_phrase ';'
283     {
284         my $table_name = $item[4]->{'table'};
285         my $field_name = $item[4]->{'field'};
286         push @{ $tables{ $table_name }{'fields'}{ $field_name }{'comments'} }, 
287             $item{'comment_phrase'};
288     }
289
290 column_name : NAME '.' NAME
291     { $return = { table => $item[1], field => $item[3] } }
292
293 comment_phrase : /'.*?'/ 
294     { 
295         my $val = $item[1];
296         $val =~ s/^'|'$//g;
297         $return = $val;
298     }
299
300 field : comment(s?) field_name data_type field_meta(s?) comment(s?)
301     {
302         my ( $is_pk, $default, @constraints );
303         my $null = 1;
304         for my $meta ( @{ $item[4] } ) {
305             if ( $meta->{'type'} eq 'default' ) {
306                 $default = $meta;
307                 next;
308             }
309             elsif ( $meta->{'type'} eq 'not_null' ) {
310                 $null = 0;
311                 next;
312             }
313             elsif ( $meta->{'type'} eq 'primary_key' ) {
314                 $is_pk = 1;
315             }
316
317             push @constraints, $meta if $meta->{'supertype'} eq 'constraint';
318         }
319
320         my @comments = ( @{ $item[1] }, @{ $item[5] } );
321
322         $return = { 
323             type           => 'field',
324             name           => $item{'field_name'}, 
325             data_type      => $item{'data_type'}{'type'},
326             size           => $item{'data_type'}{'size'},
327             null           => $null,
328             default        => $default->{'value'},
329             is_primary_key => $is_pk,
330             constraints    => [ @constraints ],
331             comments       => [ @comments ],
332         } 
333     }
334     | <error>
335
336 field_name : NAME
337
338 data_type : ora_data_type data_size(?)
339     { 
340         $return  = { 
341             type => $item[1],
342             size => $item[2][0] || '',
343         } 
344     }
345     
346 data_size : '(' VALUE(s /,/) data_size_modifier(?) ')'
347     { $item[2] } 
348
349 data_size_modifier: /byte/i
350         | /char/i
351
352 column_constraint : constraint_name(?) column_constraint_type constraint_state(s?)
353     {
354         my $desc       = $item{'column_constraint_type'};
355         my $type       = $desc->{'type'};
356         my $fields     = $desc->{'fields'}     || [];
357         my $expression = $desc->{'expression'} || '';
358
359         $return              =  {
360             supertype        => 'constraint',
361             name             => $item{'constraint_name(?)'}[0] || '',
362             type             => $type,
363             expression       => $type eq 'check' ? $expression : '',
364             deferrable       => $item{'deferrable'},
365             deferred         => $item{'deferred'},
366             reference_table  => $desc->{'reference_table'},
367             reference_fields => $desc->{'reference_fields'},
368 #            match_type       => $desc->{'match_type'},
369 #            on_update        => $desc->{'on_update'},
370         } 
371     }
372
373 constraint_name : /constraint/i NAME { $item[2] }
374
375 column_constraint_type : /not\s+null/i { $return = { type => 'not_null' } }
376     | /unique/i
377         { $return = { type => 'unique' } }
378     | /primary\s+key/i 
379         { $return = { type => 'primary_key' } }
380     | /check/i '(' /[^)]+/ ')' 
381         { $return = { type => 'check', expression => $item[3] } }
382     | /references/i table_name parens_word_list(?) on_delete(?) 
383     {
384         $return              =  {
385             type             => 'foreign_key',
386             reference_table  => $item[2],
387             reference_fields => $item[3][0],
388 #            match_type       => $item[4][0],
389             on_delete     => $item[5][0],
390         }
391     }
392
393 constraint_state : deferrable { $return = { type => $item[1] } }
394     | deferred { $return = { type => $item[1] } }
395     | /(no)?rely/i { $return = { type => $item[1] } }
396 #    | /using/i /index/i using_index_clause 
397 #        { $return = { type => 'using_index', index => $item[3] } }
398     | /(dis|en)able/i { $return = { type => $item[1] } }
399     | /(no)?validate/i { $return = { type => $item[1] } }
400     | /exceptions/i /into/i table_name 
401         { $return = { type => 'exceptions_into', table => $item[3] } }
402
403 deferrable : /not/i /deferrable/i 
404     { $return = 'not_deferrable' }
405     | /deferrable/i 
406     { $return = 'deferrable' }
407
408 deferred : /initially/i /(deferred|immediate)/i { $item[2] }
409
410 ora_data_type :
411     /(n?varchar2|varchar)/i { $return = 'varchar2' }
412     |
413     /n?char/i { $return = 'character' }
414     |
415         /n?dec/i { $return = 'decimal' }
416         |
417     /number/i { $return = 'number' }
418     |
419     /integer/i { $return = 'integer' }
420     |
421     /(pls_integer|binary_integer)/i { $return = 'integer' }
422     |
423     /interval\s+day/i { $return = 'interval day' }
424     |
425     /interval\s+year/i { $return = 'interval year' }
426     |
427     /long\s+raw/i { $return = 'long raw' }
428     |
429     /(long|date|timestamp|raw|rowid|urowid|mlslabel|clob|nclob|blob|bfile|float)/i { $item[1] }
430
431 parens_value_list : '(' VALUE(s /,/) ')'
432     { $item[2] }
433
434 parens_word_list : '(' WORD(s /,/) ')'
435     { $item[2] }
436
437 field_meta : default_val
438     | column_constraint
439
440 default_val  : /default/i /(?:')?[\w\d.-]*(?:')?/ 
441     { 
442         my $val =  $item[2];
443         $val    =~ s/'//g if defined $val; 
444         $return =  {
445             supertype => 'constraint',
446             type      => 'default',
447             value     => $val,
448         }
449     }
450     | /null/i
451     {
452         $return =  {
453             supertype => 'constraint',
454             type      => 'default',
455             value     => 'NULL',
456         }
457     }
458
459 create_table : /create/i global_temporary(?) /table/i
460
461 table_option : /organization/i WORD
462     {
463         $return = { 'ORGANIZATION' => $item[2] }
464     }
465
466 table_option : /nomonitoring/i
467     {
468         $return = { 'NOMONITORING' => undef }
469     }
470
471 table_option : /parallel/i '(' key_value(s) ')'
472     {
473         $return = { 'PARALLEL' => $item[3] }
474     }
475
476 key_value : WORD VALUE
477     {
478         $return = { $item[1], $item[2] }
479     }
480
481 table_option : /[^;]+/
482
483 table_constraint : comment(s?) constraint_name(?) table_constraint_type deferrable(?) deferred(?) constraint_state(s?) comment(s?)
484     {
485         my $desc       = $item{'table_constraint_type'};
486         my $type       = $desc->{'type'};
487         my $fields     = $desc->{'fields'};
488         my $expression = $desc->{'expression'};
489         my @comments   = ( @{ $item[1] }, @{ $item[-1] } );
490
491         $return              =  {
492             name             => $item{'constraint_name(?)'}[0] || '',
493             type             => 'constraint',
494             constraint_type  => $type,
495             fields           => $type ne 'check' ? $fields : [],
496             expression       => $type eq 'check' ? $expression : '',
497             deferrable       => $item{'deferrable(?)'},
498             deferred         => $item{'deferred(?)'},
499             reference_table  => $desc->{'reference_table'},
500             reference_fields => $desc->{'reference_fields'},
501 #            match_type       => $desc->{'match_type'}[0],
502             on_delete        => $desc->{'on_delete'} || $desc->{'on_delete_do'},
503             on_update        => $desc->{'on_update'} || $desc->{'on_update_do'},
504             comments         => [ @comments ],
505         } 
506     }
507
508 table_constraint_type : /primary key/i '(' NAME(s /,/) ')'
509     { 
510         $return = {
511             type   => 'primary_key',
512             fields => $item[3],
513         }
514     }
515     |
516     /unique/i '(' NAME(s /,/) ')' 
517     { 
518         $return    =  {
519             type   => 'unique',
520             fields => $item[3],
521         }
522     }
523     |
524     /check/ '(' /(.+)/ ')'
525     {
526         $return        =  {
527             type       => 'check',
528             expression => $item[3],
529         }
530     }
531     |
532     /foreign key/i '(' NAME(s /,/) ')' /references/i table_name parens_word_list(?) on_delete(?)
533     {
534         $return              =  {
535             type             => 'foreign_key',
536             fields           => $item[3],
537             reference_table  => $item[6],
538             reference_fields => $item[7][0],
539 #            match_type       => $item[8][0],
540             on_delete     => $item[8][0],
541 #            on_update     => $item[9][0],
542         }
543     }
544
545 on_delete : /on delete/i WORD(s)
546     { join(' ', @{$item[2]}) }
547
548 UNIQUE : /unique/i { $return = 1 }
549
550 WORD : /\w+/
551
552 NAME : /\w+/ { $item[1] }
553
554 TABLE : /table/i
555
556 VALUE   : /[-+]?\.?\d+(?:[eE]\d+)?/
557     { $item[1] }
558     | /'.*?'/   # XXX doesn't handle embedded quotes
559     { $item[1] }
560     | /NULL/
561     { 'NULL' }
562
563 `;
564
565 # -------------------------------------------------------------------
566 sub parse {
567     my ( $translator, $data ) = @_;
568     my $parser = Parse::RecDescent->new($GRAMMAR);
569
570     local $::RD_TRACE = $translator->trace ? 1 : undef;
571     local $DEBUG      = $translator->debug;
572
573     unless (defined $parser) {
574         return $translator->error("Error instantiating Parse::RecDescent ".
575             "instance: Bad grammer");
576     }
577
578     my $result = $parser->startrule( $data );
579     die "Parse failed.\n" unless defined $result;
580     if ( $DEBUG ) {
581         warn "Parser results =\n", Dumper($result), "\n";
582     }
583
584     my $schema      = $translator->schema;
585     my $indices     = $result->{'indices'};
586     my $constraints = $result->{'constraints'};
587     my @tables      = sort { 
588         $result->{'tables'}{ $a }{'order'} 
589         <=> 
590         $result->{'tables'}{ $b }{'order'}
591     } keys %{ $result->{'tables'} };
592
593     for my $table_name ( @tables ) {
594         my $tdata    =  $result->{'tables'}{ $table_name };
595         next unless $tdata->{'table_name'};
596         my $table    =  $schema->add_table( 
597             name     => $tdata->{'table_name'},
598             comments => $tdata->{'comments'},
599         ) or die $schema->error;
600
601         $table->options( $tdata->{'table_options'} );
602
603         my @fields = sort { 
604             $tdata->{'fields'}->{$a}->{'order'} 
605             <=>
606             $tdata->{'fields'}->{$b}->{'order'}
607         } keys %{ $tdata->{'fields'} };
608
609         for my $fname ( @fields ) {
610             my $fdata = $tdata->{'fields'}{ $fname };
611             my $field = $table->add_field(
612                 name              => $fdata->{'name'},
613                 data_type         => $fdata->{'data_type'},
614                 size              => $fdata->{'size'},
615                 default_value     => $fdata->{'default'},
616                 is_auto_increment => $fdata->{'is_auto_inc'},
617                 is_nullable       => $fdata->{'null'},
618                 comments          => $fdata->{'comments'},
619             ) or die $table->error;
620         }
621
622         push @{ $tdata->{'indices'} }, @{ $indices->{ $table_name } || [] };
623         push @{ $tdata->{'constraints'} }, 
624              @{ $constraints->{ $table_name } || [] };
625
626         for my $idata ( @{ $tdata->{'indices'} || [] } ) {
627             my $index  =  $table->add_index(
628                 name   => $idata->{'name'},
629                 type   => uc $idata->{'type'},
630                 fields => $idata->{'fields'},
631             ) or die $table->error;
632         }
633
634         for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
635             my $constraint       =  $table->add_constraint(
636                 name             => $cdata->{'name'},
637                 type             => $cdata->{'type'},
638                 fields           => $cdata->{'fields'},
639                 reference_table  => $cdata->{'reference_table'},
640                 reference_fields => $cdata->{'reference_fields'},
641                 match_type       => $cdata->{'match_type'} || '',
642                 on_delete        => $cdata->{'on_delete'} || $cdata->{'on_delete_do'},
643                 on_update        => $cdata->{'on_update'} || $cdata->{'on_update_do'},
644             ) or die $table->error;
645         }
646     }
647
648     return 1;
649 }
650
651 1;
652
653 # -------------------------------------------------------------------
654 # Something there is that doesn't love a wall.
655 # Robert Frost
656 # -------------------------------------------------------------------
657
658 =pod
659
660 =head1 AUTHOR
661
662 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.
663
664 =head1 SEE ALSO
665
666 SQL::Translator, Parse::RecDescent, DDL::Oracle.
667
668 =cut