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