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