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