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