Fixed up ON DELETE parsing for FKs
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Parser / Oracle.pm
1 package SQL::Translator::Parser::Oracle;
2
3 # -------------------------------------------------------------------
4 # $Id: Oracle.pm,v 1.24 2006-05-05 16:42:17 duality72 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.24 $ =~ /(\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 my $parser; 
116
117 $GRAMMAR = q`
118
119 { my ( %tables, %indices, %constraints, $table_order, @table_comments ) }
120
121 #
122 # The "eofile" rule makes the parser fail if any "statement" rule
123 # fails.  Otherwise, the first successful match by a "statement" 
124 # won't cause the failure needed to know that the parse, as a whole,
125 # failed. -ky
126 #
127 startrule : statement(s) eofile 
128     { 
129         $return = {
130             tables      => \%tables,
131             indices     => \%indices,
132             constraints => \%constraints,
133         };
134     }
135
136 eofile : /^\Z/
137
138 statement : remark
139         | run
140     | prompt
141     | create
142     | table_comment
143     | comment_on_table
144     | comment_on_column
145     | alter
146     | drop
147     | <error>
148
149 alter : /alter/i WORD /[^;]+/ ';'
150     { @table_comments = () }
151
152 drop : /drop/i TABLE ';'
153
154 drop : /drop/i WORD(s) ';'
155     { @table_comments = () }
156
157 create : create_table table_name '(' create_definition(s /,/) ')' table_option(s?) ';'
158     {
159         my $table_name                       = $item{'table_name'};
160         $tables{ $table_name }{'order'}      = ++$table_order;
161         $tables{ $table_name }{'table_name'} = $table_name;
162
163         if ( @table_comments ) {
164             $tables{ $table_name }{'comments'} = [ @table_comments ];
165             @table_comments = ();
166         }
167
168         my $i = 1;
169         my @constraints;
170         for my $definition ( @{ $item[4] } ) {
171             if ( $definition->{'type'} eq 'field' ) {
172                 my $field_name = $definition->{'name'};
173                 $tables{ $table_name }{'fields'}{ $field_name } = 
174                     { %$definition, order => $i };
175                 $i++;
176                                 
177                 for my $constraint ( @{ $definition->{'constraints'} || [] } ) {
178                     $constraint->{'fields'} = [ $field_name ];
179                     push @{ $tables{ $table_name }{'constraints'} }, 
180                         $constraint;
181                 }
182             }
183             elsif ( $definition->{'type'} eq 'constraint' ) {
184                 $definition->{'type'} = $definition->{'constraint_type'};
185                 push @{ $tables{ $table_name }{'constraints'} }, $definition;
186             }
187             else {
188                 push @{ $tables{ $table_name }{'indices'} }, $definition;
189             }
190         }
191
192         for my $option ( @{ $item[6] } ) {
193             push @{ $tables{ $table_name }{'table_options'} }, $option;
194         }
195
196         1;
197     }
198
199 create : create_index index_name /on/i table_name index_expr table_option(?) ';'
200     {
201         my $table_name = $item[4];
202         if ( $item[1] ) {
203             push @{ $constraints{ $table_name } }, {
204                 name   => $item[2],
205                 type   => 'unique',
206                 fields => $item[5],
207             };
208         }
209         else {
210             push @{ $indices{ $table_name } }, {
211                 name   => $item[2],
212                 type   => 'normal',
213                 fields => $item[5],
214             };
215         }
216     }
217
218 index_expr: parens_word_list
219         { $item[1] }
220         | '(' WORD parens_word_list ')'
221         {
222                 my $arg_list = join(",", @{$item[3]});
223                 $return = "$item[2]($arg_list)";
224         }
225
226 # Create anything else (e.g., domain, function, etc.)
227 create : ...!create_table ...!create_index /create/i WORD /[^;]+/ ';'
228     { @table_comments = () }
229
230 create_index : /create/i UNIQUE(?) /index/i
231         { $return = $item[2] }
232
233 index_name : NAME '.' NAME
234     { $item[3] }
235     | NAME 
236     { $item[1] }
237
238 global_temporary: /global/i /temporary/i
239
240 table_name : NAME '.' NAME
241     { $item[3] }
242     | NAME 
243     { $item[1] }
244
245 create_definition : field
246     | table_constraint
247     | <error>
248
249 table_comment : comment
250     {
251         my $comment = $item[1];
252         $return     = $comment;
253         push @table_comments, $comment;
254     }
255
256 comment : /^\s*(?:#|-{2}).*\n/
257     {
258         my $comment =  $item[1];
259         $comment    =~ s/^\s*(#|-{2})\s*//;
260         $comment    =~ s/\s*$//;
261         $return     = $comment;
262     }
263
264 comment : /\/\*/ /[^\*]+/ /\*\// 
265     {
266         my $comment = $item[2];
267         $comment    =~ s/^\s*|\s*$//g;
268         $return = $comment;
269     }
270
271 remark : /^REM\s+.*\n/
272
273 run : /^(RUN|\/)\s+.*\n/
274
275 prompt : /prompt/i /(table|index|sequence|trigger)/i ';'
276
277 prompt : /prompt\s+create\s+.*\n/i
278
279 comment_on_table : /comment/i /on/i /table/i table_name /is/i comment_phrase ';'
280     {
281         push @{ $tables{ $item{'table_name'} }{'comments'} }, $item{'comment_phrase'};
282     }
283
284 comment_on_column : /comment/i /on/i /column/i column_name /is/i comment_phrase ';'
285     {
286         my $table_name = $item[4]->{'table'};
287         my $field_name = $item[4]->{'field'};
288         push @{ $tables{ $table_name }{'fields'}{ $field_name }{'comments'} }, 
289             $item{'comment_phrase'};
290     }
291
292 column_name : NAME '.' NAME
293     { $return = { table => $item[1], field => $item[3] } }
294
295 comment_phrase : /'.*?'/ 
296     { 
297         my $val = $item[1];
298         $val =~ s/^'|'$//g;
299         $return = $val;
300     }
301
302 field : comment(s?) field_name data_type field_meta(s?) comment(s?)
303     {
304         my ( $is_pk, $default, @constraints );
305         my $null = 1;
306         for my $meta ( @{ $item[4] } ) {
307             if ( $meta->{'type'} eq 'default' ) {
308                 $default = $meta;
309                 next;
310             }
311             elsif ( $meta->{'type'} eq 'not_null' ) {
312                 $null = 0;
313                 next;
314             }
315             elsif ( $meta->{'type'} eq 'primary_key' ) {
316                 $is_pk = 1;
317             }
318
319             push @constraints, $meta if $meta->{'supertype'} eq 'constraint';
320         }
321
322         my @comments = ( @{ $item[1] }, @{ $item[5] } );
323
324         $return = { 
325             type           => 'field',
326             name           => $item{'field_name'}, 
327             data_type      => $item{'data_type'}{'type'},
328             size           => $item{'data_type'}{'size'},
329             null           => $null,
330             default        => $default->{'value'},
331             is_primary_key => $is_pk,
332             constraints    => [ @constraints ],
333             comments       => [ @comments ],
334         } 
335     }
336     | <error>
337
338 field_name : NAME
339
340 data_type : ora_data_type data_size(?)
341     { 
342         $return  = { 
343             type => $item[1],
344             size => $item[2][0] || '',
345         } 
346     }
347     
348 data_size : '(' VALUE(s /,/) data_size_modifier(?) ')'
349     { $item[2] } 
350
351 data_size_modifier: /byte/i
352         | /char/i
353
354 column_constraint : constraint_name(?) column_constraint_type constraint_state(s?)
355     {
356         my $desc       = $item{'column_constraint_type'};
357         my $type       = $desc->{'type'};
358         my $fields     = $desc->{'fields'}     || [];
359         my $expression = $desc->{'expression'} || '';
360
361         $return              =  {
362             supertype        => 'constraint',
363             name             => $item{'constraint_name(?)'}[0] || '',
364             type             => $type,
365             expression       => $type eq 'check' ? $expression : '',
366             deferrable       => $item{'deferrable'},
367             deferred         => $item{'deferred'},
368             reference_table  => $desc->{'reference_table'},
369             reference_fields => $desc->{'reference_fields'},
370 #            match_type       => $desc->{'match_type'},
371 #            on_update        => $desc->{'on_update'},
372         } 
373     }
374
375 constraint_name : /constraint/i NAME { $item[2] }
376
377 column_constraint_type : /not\s+null/i { $return = { type => 'not_null' } }
378     | /null/ 
379         { $return = { type => 'null' } }
380     | /unique/ 
381         { $return = { type => 'unique' } }
382     | /primary\s+key/i 
383         { $return = { type => 'primary_key' } }
384     | /check/i '(' /[^)]+/ ')' 
385         { $return = { type => 'check', expression => $item[3] } }
386     | /references/i table_name parens_word_list(?) on_delete(?) 
387     {
388         $return              =  {
389             type             => 'foreign_key',
390             reference_table  => $item[2],
391             reference_fields => $item[3][0],
392 #            match_type       => $item[4][0],
393             on_delete     => $item[5][0],
394         }
395     }
396
397 constraint_state : deferrable { $return = { type => $item[1] } }
398     | deferred { $return = { type => $item[1] } }
399     | /(no)?rely/i { $return = { type => $item[1] } }
400 #    | /using/i /index/i using_index_clause 
401 #        { $return = { type => 'using_index', index => $item[3] } }
402     | /(dis|en)able/i { $return = { type => $item[1] } }
403     | /(no)?validate/i { $return = { type => $item[1] } }
404     | /exceptions/i /into/i table_name 
405         { $return = { type => 'exceptions_into', table => $item[3] } }
406
407 deferrable : /not/i /deferrable/i 
408     { $return = 'not_deferrable' }
409     | /deferrable/i 
410     { $return = 'deferrable' }
411
412 deferred : /initially/i /(deferred|immediate)/i { $item[2] }
413
414 ora_data_type :
415     /(n?varchar2|varchar)/i { $return = 'varchar2' }
416     |
417     /n?char/i { $return = 'character' }
418     |
419         /n?dec/i { $return = 'decimal' }
420         |
421     /number/i { $return = 'number' }
422     |
423     /integer/i { $return = 'integer' }
424     |
425     /(pls_integer|binary_integer)/i { $return = 'integer' }
426     |
427     /interval\s+day/i { $return = 'interval day' }
428     |
429     /interval\s+year/i { $return = 'interval year' }
430     |
431     /long\s+raw/i { $return = 'long raw' }
432     |
433     /(long|date|timestamp|raw|rowid|urowid|mlslabel|clob|nclob|blob|bfile|float)/i { $item[1] }
434
435 parens_value_list : '(' VALUE(s /,/) ')'
436     { $item[2] }
437
438 parens_word_list : '(' WORD(s /,/) ')'
439     { $item[2] }
440
441 field_meta : default_val
442     | column_constraint
443
444 default_val  : /default/i /(?:')?[\w\d.-]*(?:')?/ 
445     { 
446         my $val =  $item[2];
447         $val    =~ s/'//g if defined $val; 
448         $return =  {
449             supertype => 'constraint',
450             type      => 'default',
451             value     => $val,
452         }
453     }
454
455 create_table : /create/i global_temporary(?) /table/i
456
457 table_option : /organization/i WORD
458     {
459         $return = { 'ORGANIZATION' => $item[2] }
460     }
461
462 table_option : /nomonitoring/i
463     {
464         $return = { 'NOMONITORING' => undef }
465     }
466
467 table_option : /parallel/i '(' key_value(s) ')'
468     {
469         $return = { 'PARALLEL' => $item[3] }
470     }
471
472 key_value : WORD VALUE
473     {
474         $return = { $item[1], $item[2] }
475     }
476
477 table_option : /[^;]+/
478
479 table_constraint : comment(s?) constraint_name(?) table_constraint_type deferrable(?) deferred(?) constraint_state(s?) comment(s?)
480     {
481         my $desc       = $item{'table_constraint_type'};
482         my $type       = $desc->{'type'};
483         my $fields     = $desc->{'fields'};
484         my $expression = $desc->{'expression'};
485         my @comments   = ( @{ $item[1] }, @{ $item[-1] } );
486
487         $return              =  {
488             name             => $item{'constraint_name(?)'}[0] || '',
489             type             => 'constraint',
490             constraint_type  => $type,
491             fields           => $type ne 'check' ? $fields : [],
492             expression       => $type eq 'check' ? $expression : '',
493             deferrable       => $item{'deferrable(?)'},
494             deferred         => $item{'deferred(?)'},
495             reference_table  => $desc->{'reference_table'},
496             reference_fields => $desc->{'reference_fields'},
497 #            match_type       => $desc->{'match_type'}[0],
498             on_delete        => $desc->{'on_delete'} || $desc->{'on_delete_do'},
499             on_update        => $desc->{'on_update'} || $desc->{'on_update_do'},
500             comments         => [ @comments ],
501         } 
502     }
503
504 table_constraint_type : /primary key/i '(' NAME(s /,/) ')'
505     { 
506         $return = {
507             type   => 'primary_key',
508             fields => $item[3],
509         }
510     }
511     |
512     /unique/i '(' NAME(s /,/) ')' 
513     { 
514         $return    =  {
515             type   => 'unique',
516             fields => $item[3],
517         }
518     }
519     |
520     /check/ '(' /(.+)/ ')'
521     {
522         $return        =  {
523             type       => 'check',
524             expression => $item[3],
525         }
526     }
527     |
528     /foreign key/i '(' NAME(s /,/) ')' /references/i table_name parens_word_list(?) on_delete(?)
529     {
530         $return              =  {
531             type             => 'foreign_key',
532             fields           => $item[3],
533             reference_table  => $item[6],
534             reference_fields => $item[7][0],
535 #            match_type       => $item[8][0],
536             on_delete     => $item[8][0],
537 #            on_update     => $item[9][0],
538         }
539     }
540
541 on_delete : /on delete/i WORD(s)
542     { join(' ', @{$item[2]}) }
543
544 UNIQUE : /unique/i { $return = 1 }
545
546 WORD : /\w+/
547
548 NAME : /\w+/ { $item[1] }
549
550 TABLE : /table/i
551
552 VALUE   : /[-+]?\.?\d+(?:[eE]\d+)?/
553     { $item[1] }
554     | /'.*?'/   # XXX doesn't handle embedded quotes
555     { $item[1] }
556     | /NULL/
557     { 'NULL' }
558
559 `;
560
561 # -------------------------------------------------------------------
562 sub parse {
563     my ( $translator, $data ) = @_;
564     $parser ||= Parse::RecDescent->new($GRAMMAR);
565
566     local $::RD_TRACE = $translator->trace ? 1 : undef;
567     local $DEBUG      = $translator->debug;
568
569     unless (defined $parser) {
570         return $translator->error("Error instantiating Parse::RecDescent ".
571             "instance: Bad grammer");
572     }
573
574     my $result = $parser->startrule( $data );
575     die "Parse failed.\n" unless defined $result;
576     if ( $DEBUG ) {
577         warn "Parser results =\n", Dumper($result), "\n";
578     }
579
580     my $schema      = $translator->schema;
581     my $indices     = $result->{'indices'};
582     my $constraints = $result->{'constraints'};
583     my @tables      = sort { 
584         $result->{'tables'}{ $a }{'order'} 
585         <=> 
586         $result->{'tables'}{ $b }{'order'}
587     } keys %{ $result->{'tables'} };
588
589     for my $table_name ( @tables ) {
590         my $tdata    =  $result->{'tables'}{ $table_name };
591         next unless $tdata->{'table_name'};
592         my $table    =  $schema->add_table( 
593             name     => $tdata->{'table_name'},
594             comments => $tdata->{'comments'},
595         ) or die $schema->error;
596
597         $table->options( $tdata->{'table_options'} );
598
599         my @fields = sort { 
600             $tdata->{'fields'}->{$a}->{'order'} 
601             <=>
602             $tdata->{'fields'}->{$b}->{'order'}
603         } keys %{ $tdata->{'fields'} };
604
605         for my $fname ( @fields ) {
606             my $fdata = $tdata->{'fields'}{ $fname };
607             my $field = $table->add_field(
608                 name              => $fdata->{'name'},
609                 data_type         => $fdata->{'data_type'},
610                 size              => $fdata->{'size'},
611                 default_value     => $fdata->{'default'},
612                 is_auto_increment => $fdata->{'is_auto_inc'},
613                 is_nullable       => $fdata->{'null'},
614                 comments          => $fdata->{'comments'},
615             ) or die $table->error;
616         }
617
618         push @{ $tdata->{'indices'} }, @{ $indices->{ $table_name } || [] };
619         push @{ $tdata->{'constraints'} }, 
620              @{ $constraints->{ $table_name } || [] };
621
622         for my $idata ( @{ $tdata->{'indices'} || [] } ) {
623             my $index  =  $table->add_index(
624                 name   => $idata->{'name'},
625                 type   => uc $idata->{'type'},
626                 fields => $idata->{'fields'},
627             ) or die $table->error;
628         }
629
630         for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
631             my $constraint       =  $table->add_constraint(
632                 name             => $cdata->{'name'},
633                 type             => $cdata->{'type'},
634                 fields           => $cdata->{'fields'},
635                 reference_table  => $cdata->{'reference_table'},
636                 reference_fields => $cdata->{'reference_fields'},
637                 match_type       => $cdata->{'match_type'} || '',
638                 on_delete        => $cdata->{'on_delete'} || $cdata->{'on_delete_do'},
639                 on_update        => $cdata->{'on_update'} || $cdata->{'on_update_do'},
640             ) or die $table->error;
641         }
642     }
643
644     return 1;
645 }
646
647 1;
648
649 # -------------------------------------------------------------------
650 # Something there is that doesn't love a wall.
651 # Robert Frost
652 # -------------------------------------------------------------------
653
654 =pod
655
656 =head1 AUTHOR
657
658 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.
659
660 =head1 SEE ALSO
661
662 SQL::Translator, Parse::RecDescent, DDL::Oracle.
663
664 =cut