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