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