f2e5bfa591c63e4226702e29b7d93cf239385269
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Parser / DB2.pm
1 package SQL::Translator::Parser::DB2;
2
3 =head1 NAME
4
5 SQL::Translator::Parser::DB2 - parser for DB2
6
7 =head1 SYNOPSIS
8
9   use SQL::Translator;
10   use SQL::Translator::Parser::DB2;
11
12   my $translator = SQL::Translator->new;
13   $translator->parser("SQL::Translator::Parser::DB2");
14
15 =head1 DESCRIPTION
16
17 This is a grammar for parsing CREATE statements for DB2
18
19 =cut
20
21 use warnings;
22 use strict;
23
24 use base qw(Exporter);
25 our @EXPORT_OK = qw(parse);
26
27 our $DEBUG;
28
29 use Data::Dumper;
30 use SQL::Translator::Utils qw/ddl_parser_instance/;
31
32 our $GRAMMAR = <<'END_OF_GRAMMAR';
33
34 {
35     my ( %tables, $table_order, @table_comments, @views, @triggers );
36 }
37
38 #
39 # The "eofile" rule makes the parser fail if any "statement" rule
40 # fails.  Otherwise, the first successful match by a "statement"
41 # won't cause the failure needed to know that the parse, as a whole,
42 # failed. -ky
43 #
44 startrule : statement(s) eofile {
45     $return      = {
46         tables   => \%tables,
47         views    => \@views,
48         triggers => \@triggers,
49     }
50 }
51
52 eofile : /^\Z/
53
54 statement :
55     comment
56     | create
57     | <error>
58
59 comment : /^\s*-{2}.*\n/
60     {
61         my $comment =  $item[1];
62         $comment    =~ s/^\s*(-{2})\s*//;
63         $comment    =~ s/\s*$//;
64         $return     = $comment;
65     }
66
67
68 create: CREATE TRIGGER trigger_name before type /ON/i table_name reference_b(?) /FOR EACH ROW/i 'MODE DB2SQL' triggered_action
69 {
70     my $table_name = $item{'table_name'}{'name'};
71     $return =  {
72         table      => $table_name,
73         schema     => $item{'trigger_name'}{'schema'},
74         name       => $item{'trigger_name'}{'name'},
75         when       => 'before',
76         db_event   => $item{'type'}->{'event'},
77         fields     => $item{'type'}{'fields'},
78         condition  => $item{'triggered_action'}{'condition'},
79         reference  => $item{'reference_b'},
80         granularity => $item[9],
81         action     => $item{'triggered_action'}{'statement'}
82     };
83
84     push @triggers, $return;
85 }
86
87 create: CREATE TRIGGER trigger_name after type /ON/i table_name reference_a(?) /FOR EACH ROW|FOR EACH STATEMENT/i 'MODE DB2SQL' triggered_action
88 {
89     my $table_name = $item{'table_name'}{'name'};
90     $return = {
91         table      => $table_name,
92         schema     => $item{'trigger_name'}{'schema'},
93         name       => $item{'trigger_name'}{'name'},
94         when       => 'after',
95         db_event   => $item{'type'}{'event'},
96         fields     => $item{'type'}{'fields'},
97         condition  => $item{'triggered_action'}{'condition'},
98         reference  => $item{'reference_a'},
99         granularity => $item[9],
100         action     => $item{'triggered_action'}{'statement'}
101     };
102
103     push @triggers, $return;
104 }
105
106 create: CREATE /FEDERATED|/i VIEW view_name column_list(?) /AS/i with_expression(?) SQL_procedure_statement
107 {
108     $return = {
109         name   => $item{view_name}{name},
110         sql    => $item{SQL_procedure_statement},
111         with   => $item{'with_expression(?)'},
112         fields => $item{'column_list(?)'}
113     };
114     push @views, $return;
115 }
116
117 # create: CREATE /FEDERATED/i VIEW view_name col_list_or_of(?) /AS/i with_expression(?) fullselect options(?)
118
119 # col_list_or_of: column_list | /OF/i ( root_view_definition | subview_definition )
120
121 with_expression: /WITH/i common_table_expression(s /,/)
122 {
123     $return = $item{'common_table_expression'};
124 }
125
126 SQL_procedure_statement: /[^;]*/ /(;|\z)/ { $return = $item[1] . $item[2] }
127
128 column_list: '(' column_name(s /,/) ')'
129 {
130     $return = join(' ', '(', @{$item[2]}, ')');
131 }
132
133 CREATE: /create/i
134
135 TRIGGER: /trigger/i
136
137 VIEW: /view/i
138
139 INNER: /inner/i
140
141 LEFT: /left/i
142
143 RIGHT: /right/i
144
145 FULL: /full/i
146
147 OUTER: /outer/i
148
149 WHERE: /where/i
150
151 trigger_name: SCHEMA '.' NAME
152     { $return = { schema => $item[1], name => $item[3] } }
153     | NAME
154     { $return = { name => $item[1] } }
155
156 table_name: SCHEMA '.' NAME
157     { $return = { schema => $item[1], name => $item[3] } }
158     | NAME
159     { $return = { name => $item[1] } }
160
161 view_name: SCHEMA '.' NAME
162     { $return = { schema => $item[1], name => $item[3] } }
163     | NAME
164     { $return = { name => $item[1] } }
165
166 column_name: NAME
167
168 identifier: NAME
169
170 correlation_name: NAME
171
172 numeric_constant: /\d+/
173
174 SCHEMA: /\w+/
175
176 SCHEMA: /\w{1,128}/
177
178 NAME: /\w+/
179
180 NAME: /\w{1,18}/
181
182 options: /WITH/i ( /CASCADED/i | /LOCAL/i ) /CHECK\s+OPTION/i
183
184 # root_view_definition: /MODE\s+DB2SQL/i '(' oid_column ( /,/ with_options )(?) ')'
185
186 # subview_definition: /MODE\s+DB2SQL/i under_clause ( '(' with_options ')' )(?) /EXTEND/i(?)
187
188 # oid_column: /REF\s+IS/i oid_column_name /USER\s+GENERATED\s+UNCHECKED/i(?)
189
190 # with_options: ( column_name /WITH\s+OPTIONS/i ( /SCOPE/i ( typed_table_name | typed_view_name ) | /READ\s+ONLY/i )(s /,/) )(s /,/)
191
192 # under_clause: /UNDER/i superview_name /INHERIT\s+SELECT\s+PRIVILEGES/i
193
194 common_table_expression: table_name column_list /AS/i get_bracketed
195 {
196     $return = { name  => $item{table_name}{name},
197                 query => $item[4]
198                 };
199 }
200
201 get_bracketed:
202 {
203     extract_bracketed($text, '(');
204 }
205
206 common_table_expression: table_name column_list /AS/i '(' fullselect ')'
207
208 # fullselect: ( subselect | '(' fullselect ')' | values_clause ) ( ( /UNION/i | /UNION/i /ALL/i | /EXCEPT/i | /EXCEPT/i /ALL/i | /INTERSECT/i | /INTERSECT/i /ALL/i ) ( subselect | '(' fullselect ')' | values_clause ) )(s)
209
210 # values_clause: /VALUES/i values_row(s /,/)
211
212 # values_row: ( expression | /NULL/i ) | '(' ( expression | /NULL/i )(s /,/) ')'
213
214 # subselect:  select_clause from_clause where_clause(?) group_by_clause(?) having_clause(?)
215
216 # select_clause: SELECT ( /ALL/i | /DISTINCT )(?) ( '*' | ( expression ( /AS|/i new_column_name )(?) | exposed_name '.*' )(s /,/) )
217
218 # from_clause: /FROM/i table_name(s /,/)
219
220 # from_clause: /FROM/i table_reference(s /,/)
221
222 # table_reference:
223 #     (
224 #       ( nickname
225 #       | table_name
226 #       | view_name
227 #       )
228 #     | ( /ONLY/i
229 #       | /OUTER/i
230 #       ) '('
231 #       ( table_name
232 #       | view_name
233 #       ) ')'
234 #     ) correlation_clause(?)
235 #   | TABLE '(' function_name '(' expression(s? /,/) ')' ')'  correlation_clause
236 #   | TABLE(?) '(' fullselect ')' correlation_clause
237 #   | joined_table
238
239
240 # correlation_clause: /AS/i(?) correlation_name column_list(?)
241
242 # joined_table:
243 #    table_reference ( INNER
244 #                     | outer
245 #                     )(?) JOIN table_reference ON join_condition
246 #   | '(' joined_table ')'
247
248 # outer: ( LEFT | RIGHT | FULL ) OUTER(?)
249
250 where_clause: WHERE search_condition
251
252 # group_by_clause: /GROUP\s+BY/i ( grouping_expression
253 #                                | grouping_sets
254 #                                | super_groups
255 #                                )(s /,/)
256
257 # grouping_expression: expression
258
259 # orderby_clause: /ORDER\s+BY/i ( sort_key ( /ASC/i | /DESC/i)(?) )(s /,/)
260
261 # sort_key: simple_column_name | simple_integer | sort_key_expression
262
263 # # Name of one of the selected columns!
264 # simple_column_name: NAME
265
266 # simple_integer: /\d+/
267 #   { $item[1] <= $numberofcolumns && $item[1] > 1 }
268
269 # sort_key_expression: expression
270 #   { expression from select columns list, grouping_expression, column function.. }
271
272 # grouping_sets: /GROUPING\s+SETS/i '(' (
273 #                                         ( grouping_expression
274 #                                         | super_groups
275 #                                         )
276 #                                       | '(' ( grouping_expression
277 #                                             | super_groups
278 #                                             )(s /,/) ')'
279 #                                       )(s /,/) ')'
280
281 # super_groups: /ROLLUP/i '(' grouping_expression_list ')'
282 #            | /CUBE/i '(' grouping_expression_list ')'
283 #            | grand_total
284
285 # grouping_expression_list:  ( grouping_expression
286 #                            | '(' grouping_expression(s /,/) ')'
287 #                            )(s /,/)
288
289 # grand_total: '(' ')'
290
291 # having_clause: /HAVING/i search_condition
292
293 when_clause: /WHEN/i '(' search_condition ')' {$return = $item[3]}
294
295 triggered_action: when_clause(?) SQL_procedure_statement
296 { $return = { 'condition' => $item[1][0],
297               'statement' => $item{'SQL_procedure_statement'} };
298 }
299
300 before: /NO CASCADE BEFORE/i
301
302 after: /AFTER/i
303
304 type: /UPDATE/i /OF/i column_name(s /,/)
305 { $return = { event  => 'update_on',
306               fields => $item[3] }
307 }
308
309 type: ( /INSERT/i | /DELETE/i | /UPDATE/i )
310 { $return = { event => $item[1] } }
311
312 reference_b: /REFERENCING/i old_new_corr(0..2)
313 { $return = join(' ', $item[1], join(' ', @{$item[2]}) ) }
314
315 reference_a: /REFERENCING/i old_new_corr(0..2) old_new_table(0..2)
316 { $return = join(' ', $item[1], join(' ', @{$item[2]}), join(' ', @{$item[3]})  ) }
317
318 old_new_corr: /OLD/i /(AS)?/i correlation_name
319 { $return = join(' ', @item[1..3] ) }
320 | /NEW/i /(AS)?/i correlation_name
321 { $return = join(' ', @item[1..3] ) }
322
323 old_new_table: /OLD_TABLE/i /(AS)?/i identifier
324 { $return = join(' ', @item[1..3] ) }
325 | /NEW_TABLE/i /(AS)?/i identifier
326 { $return = join(' ', @item[1..3] ) }
327
328 # Just parsing simple search conditions for now.
329 search_condition: /[^)]+/
330
331 expression: (
332               ( '+'
333               | '-'
334               )(?)
335               ( function
336               | '(' expression ')'
337               | constant
338               | column_name
339               | host_variable
340               | special_register
341               | '(' scalar_fullselect ')'
342               | labeled_duration
343               | case_expression
344               | cast_specification
345 #              | dereference_operation
346               | OLAP_function
347               | method_invocation
348               | subtype_treatment
349               | sequence_reference
350               )
351             )(s /operator/)
352
353 operator: ( /CONCAT/i | '||' ) | '/' | '*' | '+' | '-'
354
355 function: ( /SYSIBM\.|/i sysibm_function
356           | /SYSFUN\.|/i sysfun_function
357           | userdefined_function
358           ) '(' func_args(s /,/)  ')'
359
360 constant: int_const | float_const | dec_const | char_const | hex_const | grastr_const
361
362 func_args: expression
363
364 sysibm_function: ( /ABS/i | /ABSVAL/i )
365                 | /AVG/i
366                 | /BIGINT/i
367                 | /BLOB/i
368                 | /CHAR/i
369                 | /CLOB/i
370                 | /COALESCE/i
371                 | ( /CONCAT/ | '||' )
372                 | ( /CORRELATION/i | /CORR/ )
373                 | /COUNT/i
374                 | /COUNT_BIG/i
375                 | (/COVARIANCE/i | /COVAR/i )
376                 | /DATE/i
377                 | /DAY/i
378                 | /DAYS/i
379                 | /DBCLOB/i
380                 | ( /DECIMAL/i | /DEC/i )
381                 | /DECRYPT_BIN/i
382                 | /DECRYPT_CHAR/i
383                 | /DEREF/i
384                 | /DIGITS/i
385                 | /DLCOMMENT/i
386                 | /DLLINKTYPE/i
387                 | /DLURLCOMPLETE/i
388                 | /DLURLPATH/i
389                 | /DLURLPATHONLY/i
390                 | /DLURLSCHEME/i
391                 | /DLURLSERVER/i
392                 | /DLVALUE/i
393                 | ( /DOUBLE/i | /DOUBLE_PRECISION/i )
394                 | /ENCRYPT/i
395                 | /EVENT_MON_STATE/i
396                 | /FLOAT/i
397                 | /GETHINT/i
398                 | /GENERATE_UNIQUE/i
399                 | /GRAPHIC/i
400                 | /GROUPING/i
401                 | /HEX/i
402                 | /HOUR/i
403                 | /IDENTITY_VAL_LOCAL/i
404                 | ( /INTEGER/i | /INT/ )
405                 | ( /LCASE/i | /LOWER/ )
406                 | /LENGTH/i
407                 | /LONG_VARCHAR/i
408                 | /LONG_VARGRAPHIC/i
409                 | /LTRIM/i
410                 | /MAX/i
411                 | /MICROSECOND/i
412                 | /MIN/i
413                 | /MINUTE/i
414                 | /MONTH/i
415                 | /MULTIPLY_ACT/i
416                 | /NODENUMBER/i
417                 | /NULLIF/i
418                 | /PARTITON/i
419                 | /POSSTR/i
420                 | /RAISE_ERROR/i
421                 | /REAL/i
422                 | /REC2XML/i
423                 | /REGR_AVGX/i
424                 | /REGR_AVGY/i
425                 | /REGR_COUNT/i
426                 | ( /REGR_INTERCEPT/i | /REGR_ICPT/i )
427                 | /REGR_R2/i
428                 | /REGR_SLOPE/i
429                 | /REGR_SXX/i
430                 | /REGR_SXY/i
431                 | /REGR_SYY/i
432                 | /RTRIM/i
433                 | /SECOND/i
434                 | /SMALLINT/i
435                 | /STDDEV/i
436                 | /SUBSTR/i
437                 | /SUM/i
438                 | /TABLE_NAME/i
439                 | /TABLE_SCHEMA/i
440                 | /TIME/i
441                 | /TIMESTAMP/i
442                 | /TRANSLATE/i
443                 | /TYPE_ID/i
444                 | /TYPE_NAME/i
445                 | /TYPE_SCHEMA/i
446                 | ( /UCASE/i | /UPPER/i )
447                 | /VALUE/i
448                 | /VARCHAR/i
449                 | /VARGRAPHIC/i
450                 | ( /VARIANCE/i | /VAR/i )
451                 | /YEAR/i
452
453 sysfun: ( /ABS/i | /ABSVAL/i )
454                 | /ACOS/i
455                 | /ASCII/i
456                 | /ASIN/i
457                 | /ATAN/i
458                 | /ATAN2/i
459                 | ( /CEIL/i | /CEILING/i )
460                 | /CHAR/i
461                 | /CHR/i
462                 | /COS/i
463                 | /COT/i
464                 | /DAYNAME/i
465                 | /DAYOFWEEK/i
466                 | /DAYOFWEEK_ISO/i
467                 | /DAYOFYEAR/i
468                 | /DEGREES/i
469                 | /DIFFERENCE/i
470                 | /DOUBLE/i
471                 | /EXP/i
472                 | /FLOOR/i
473                 | /GET_ROUTINE_SAR/i
474                 | /INSERT/i
475                 | /JULIAN_DAY/i
476                 | /LCASE/i
477                 | /LEFT/i
478                 | /LN/i
479                 | /LOCATE/i
480                 | /LOG/i
481                 | /LOG10/i
482                 | /LTRIM/i
483                 | /MIDNIGHT_SECONDS/i
484                 | /MOD/i
485                 | /MONTHNAME/i
486                 | /POWER/i
487                 | /PUT_ROUTINE_SAR/i
488                 | /QUARTER/i
489                 | /RADIANS/i
490                 | /RAND/i
491                 | /REPEAT/i
492                 | /REPLACE/i
493                 | /RIGHT/i
494                 | /ROUND/i
495                 | /RTRIM/I
496                 | /SIGN/i
497                 | /SIN/i
498                 | /SOUNDEX/i
499                 | /SPACE/i
500                 | /SQLCACHE_SNAPSHOT/i
501                 | /SQRT/i
502                 | /TAN/i
503                 | /TIMESTAMP_ISO/i
504                 | /TIMESTAMPDIFF/i
505                 | ( /TRUNCATE/i | /TRUNC/i )
506                 | /UCASE/i
507                 | /WEEK/i
508                 | /WEEK_ISO/i
509
510 scalar_fullselect: '(' fullselect ')'
511
512 labeled_duration: ld_type ld_duration
513
514 ld_type: function
515        | '(' expression ')'
516        | constant
517        | column_name
518        | host_variable
519
520 ld_duration: /YEARS?/i
521            | /MONTHS?/i
522            | /DAYS?/i
523            | /HOURS?/i
524            | /MINUTES?/i
525            | /SECONDS?/i
526            | /MICROSECONDS?/i
527
528 case_expression: /CASE/i ( searched_when_clause
529                          | simple_when_clause
530                          )
531                          ( /ELSE\s+NULL/i
532                          | /ELSE/i result_expression
533                          )(?) /END/i
534
535 searched_when_clause: ( /WHEN/i search_condition /THEN/i
536                         ( result_expression
537                         | /NULL/i
538                         )
539                       )(s)
540
541 simple_when_clause: expression ( /WHEN/i search_condition /THEN/i
542                                  ( result_expression
543                                  | /NULL/i
544                                  )
545                                )(s)
546
547 result_expression: expression
548
549 cast_specification: /CAST/i '(' ( expression
550                                 | /NULL/i
551                                 | parameter_marker
552                                 ) /AS/i data_type
553                                   ( /SCOPE/ ( typed_table_name
554                                             | typed_view_name
555                                             )
556                                   )(?) ')'
557
558 dereference_operation: scoped_reference_expression '->' name1
559                       (  '(' expression(s) ')' )(?)
560 #                         ( '(' expression(s /,/) ')' )(?)
561
562
563
564 scoped_reference_expression: expression
565 { # scoped, reference
566 }
567
568 name1: NAME
569
570 OLAP_function: ranking_function
571              | numbering_function
572              | aggregation_function
573
574 ranking_function: ( /RANK/ '()'
575                   | /DENSE_RANK|DENSERANK/i '()'
576                   ) /OVER/i '(' window_partition_clause(?) window_order_clause ')'
577
578 numbering_function: /ROW_NUMBER|ROWNUMBER/i '()' /OVER/i '(' window_partition_clause(?)
579                       ( window_order_clause window_aggregation_group_clause(?)
580                       )(?)
581                       ( /RANGE\s+BETWEEN\s+UNBOUNDED\s+PRECEDING\s+AND\s+UNBBOUNDED\s+FOLLOWING/i
582                       | window_aggregation_group_clause
583                       )(?) ')'
584
585 window_partition_clause: /PARTITION\s+BY/i partitioning_expression(s /,/)
586
587 window_order_clause: /ORDER\s+BY/i
588                       ( sort_key_expression
589                         ( asc_option
590                         | desc_option
591                         )(?)
592                       )(s /,/)
593
594 asc_option: /ASC/i ( /NULLS\s+FIRST/i | /NULLS\s+LAST/i )(?)
595
596 desc_option: /DESC/i ( /NULLS\s+FIRST/i | /NULLS\s+LAST/i )(?)
597
598 window_aggregation_group_clause: ( /ROWS/i
599                                  | /RANGE/i
600                                  )
601                                  ( group_start
602                                  | group_between
603                                  | group_end
604                                  )
605
606 group_start: /UNBOUNDED\s+PRECEDING/i
607            | unsigned_constant /PRECEDING/i
608            | /CURRENT\s+ROW/i
609
610 group_between: /BETWEEN/i group_bound1 /AND/i group_bound2
611
612 group_bound1: /UNBOUNDED\s+PRECEDING/i
613            | unsigned_constant /PRECEDING/i
614            | unsigned_constant /FOLLOWING/i
615            | /CURRENT\s+ROW/i
616
617 group_bound2: /UNBOUNDED\s+PRECEDING/i
618            | unsigned_constant /PRECEDING/i
619            | unsigned_constant /FOLLOWING/i
620            | /CURRENT\s+ROW/i
621
622 group_end: /UNBOUNDED\s+PRECEDING/i
623            | unsigned_constant /FOLLOWING/i
624
625 method_invocation: subject_expression '..' method_name
626                     ( '(' expression(s) ')'
627 #                    ( '(' expression(s /,/) ')'
628                     )(?)
629
630 subject_expression: expression
631 { # with static result type that is a used-defined struct type
632 }
633
634 method_name: NAME
635 { # must be a method of subject_expression
636 }
637
638 subtype_treatment: /TREAT/i '(' expression /AS/i data_type ')'
639
640 sequence_reference: nextval_expression
641                   | prevval_expression
642
643 nextval_expression: /NEXTVAL\s+FOR/i sequence_name
644
645 prevval_expression: /PREVVAL\s+FOR/i sequence_name
646
647 sequence_name: NAME
648
649
650 search_condition: /NOT|/i ( predicate ( /SELECTIVITY/i numeric_constant )(?) | '(' search_condition ')' ) cond(s?)
651
652 cond: ( /AND/i | /OR/i ) /NOT|/i ( predicate ( /SELECTIVITY/i numeric_constant )(?) | '(' search_condition ')' )
653
654 predicate: basic_p | quantified_p | between_p | exists_p | in_p | like_p | null_p | type_p
655
656 basic_p: expression /(=|<>|<|>|<=|=>|\^=|\^<|\^>|\!=)/ expression
657
658 quantified_p: expression1 /(=|<>|<|>|<=|=>|\^=|\^<|\^>|\!=)/ /SOME|ANY|ALL/i '(' fullselect ')'
659
660 END_OF_GRAMMAR
661
662 sub parse {
663     my ( $translator, $data ) = @_;
664
665     # Enable warnings within the Parse::RecDescent module.
666     local $::RD_ERRORS = 1 unless defined $::RD_ERRORS; # Make sure the parser dies when it encounters an error
667     local $::RD_WARN   = 1 unless defined $::RD_WARN; # Enable warnings. This will warn on unused rules &c.
668     local $::RD_HINT   = 1 unless defined $::RD_HINT; # Give out hints to help fix problems.
669
670     local $::RD_TRACE  = $translator->trace ? 1 : undef;
671     local $DEBUG       = $translator->debug;
672
673     my $parser = ddl_parser_instance('DB2');
674
675     my $result = $parser->startrule($data);
676     return $translator->error( "Parse failed." ) unless defined $result;
677     warn Dumper( $result ) if $DEBUG;
678
679     my $schema = $translator->schema;
680     my @tables =
681         map   { $_->[1] }
682         sort  { $a->[0] <=> $b->[0] }
683         map   { [ $result->{'tables'}{ $_ }->{'order'}, $_ ] }
684         keys %{ $result->{'tables'} };
685
686     for my $table_name ( @tables ) {
687         my $tdata =  $result->{'tables'}{ $table_name };
688         my $table =  $schema->add_table(
689             name  => $tdata->{'name'},
690         ) or die $schema->error;
691
692         $table->comments( $tdata->{'comments'} );
693
694         for my $fdata ( @{ $tdata->{'fields'} } ) {
695             my $field = $table->add_field(
696                 name              => $fdata->{'name'},
697                 data_type         => $fdata->{'data_type'},
698                 size              => $fdata->{'size'},
699                 default_value     => $fdata->{'default'},
700                 is_auto_increment => $fdata->{'is_auto_inc'},
701                 is_nullable       => $fdata->{'is_nullable'},
702                 comments          => $fdata->{'comments'},
703             ) or die $table->error;
704
705             $table->primary_key( $field->name ) if $fdata->{'is_primary_key'};
706
707             for my $cdata ( @{ $fdata->{'constraints'} } ) {
708                 next unless $cdata->{'type'} eq 'foreign_key';
709                 $cdata->{'fields'} ||= [ $field->name ];
710                 push @{ $tdata->{'constraints'} }, $cdata;
711             }
712         }
713
714         for my $idata ( @{ $tdata->{'indices'} || [] } ) {
715             my $index  =  $table->add_index(
716                 name   => $idata->{'name'},
717                 type   => uc $idata->{'type'},
718                 fields => $idata->{'fields'},
719             ) or die $table->error;
720         }
721
722         for my $cdata ( @{ $tdata->{'constraints'} || [] } ) {
723             my $constraint       =  $table->add_constraint(
724                 name             => $cdata->{'name'},
725                 type             => $cdata->{'type'},
726                 fields           => $cdata->{'fields'},
727                 reference_table  => $cdata->{'reference_table'},
728                 reference_fields => $cdata->{'reference_fields'},
729                 match_type       => $cdata->{'match_type'} || '',
730                 on_delete        => $cdata->{'on_delete'} || $cdata->{'on_delete_do'},
731                 on_update        => $cdata->{'on_update'} || $cdata->{'on_update_do'},
732             ) or die $table->error;
733         }
734     }
735
736     for my $def ( @{ $result->{'views'} || [] } ) {
737         my $view = $schema->add_view(
738             name => $def->{'name'},
739             sql  => $def->{'sql'},
740         );
741     }
742
743     for my $def ( @{ $result->{'triggers'} || [] } ) {
744         my $trig                = $schema->add_trigger(
745             name                => $def->{'name'},
746             perform_action_when => $def->{'when'},
747             database_event      => $def->{'db_event'},
748             action              => $def->{'action'},
749             fields              => $def->{'fields'},
750             on_table            => $def->{'table'}
751                                                        );
752         $trig->extra( reference => $def->{'reference'},
753                       condition => $def->{'condition'},
754                       granularity => $def->{'granularity'} );
755     }
756
757     return 1;
758 }
759
760 1;
761
762 =pod
763
764 =head1 AUTHOR
765
766 Jess Robinson <cpan@desert-island.me.uk>
767
768 =head1 SEE ALSO
769
770 perl(1), Parse::RecDescent, SQL::Translator::Schema.
771
772 =cut