missed sql key
[dbsrgits/DBIx-Class.git] / lib / SQL / Translator / Parser / DBIx / Class.pm
1 package # hide from PAUSE
2     SQL::Translator::Parser::DBIx::Class;
3
4 # AUTHOR: Jess Robinson
5
6 # Some mistakes the fault of Matt S Trout
7
8 # Others the fault of Ash Berlin
9
10 use strict;
11 use warnings;
12 use vars qw($DEBUG @EXPORT_OK);
13 $DEBUG = 0 unless defined $DEBUG;
14
15 use Exporter;
16 use Data::Dumper;
17 use SQL::Translator::Utils qw(debug normalize_name);
18
19 use base qw(Exporter);
20
21 @EXPORT_OK = qw(parse);
22
23 # -------------------------------------------------------------------
24 # parse($tr, $data)
25 #
26 # setting parser_args => { add_fk_index => 0 } will prevent
27 # the auto-generation of an index for each FK.
28 #
29 # Note that $data, in the case of this parser, is not useful.
30 # We're working with DBIx::Class Schemas, not data streams.
31 # -------------------------------------------------------------------
32 sub parse {
33     my ($tr, $data)   = @_;
34     my $args          = $tr->parser_args;
35     my $dbicschema    = $args->{'DBIx::Class::Schema'} ||  $args->{"DBIx::Schema"} ||$data;
36     $dbicschema     ||= $args->{'package'};
37     my $limit_sources = $args->{'sources'};
38     
39     die 'No DBIx::Class::Schema' unless ($dbicschema);
40     if (!ref $dbicschema) {
41       eval "use $dbicschema;";
42       die "Can't load $dbicschema ($@)" if($@);
43     }
44
45     my $schema      = $tr->schema;
46     my $table_no    = 0;
47
48     $schema->name( ref($dbicschema) . " v" . ($dbicschema->VERSION || '1.x'))
49       unless ($schema->name);
50
51     my %seen_tables;
52
53     my @monikers = sort $dbicschema->sources;
54     if ($limit_sources) {
55         my $ref = ref $limit_sources || '';
56         die "'sources' parameter must be an array or hash ref" unless $ref eq 'ARRAY' || ref eq 'HASH';
57
58         # limit monikers to those specified in 
59         my $sources;
60         if ($ref eq 'ARRAY') {
61             $sources->{$_} = 1 for (@$limit_sources);
62         } else {
63             $sources = $limit_sources;
64         }
65         @monikers = grep { $sources->{$_} } @monikers;
66     }
67
68     my(@table_monikers, @view_monikers);
69     for my $moniker (@monikers){
70       my $source = $dbicschema->source($moniker);
71       next if $source->is_virtual;
72        if ( $source->isa('DBIx::Class::ResultSource::Table') ) {
73          push(@table_monikers, $moniker);
74       } elsif( $source->isa('DBIx::Class::ResultSource::View') ){
75          push(@view_monikers, $moniker);
76       }
77     }
78
79     foreach my $moniker (sort @table_monikers)
80     {
81         my $source = $dbicschema->source($moniker);
82         
83         # Skip custom query sources
84         next if ref($source->name);
85
86         # Its possible to have multiple DBIC source using same table
87         next if $seen_tables{$source->name}++;
88
89         my $table = $schema->add_table(
90                                        name => $source->name,
91                                        type => 'TABLE',
92                                        ) || die $schema->error;
93         my $colcount = 0;
94         foreach my $col ($source->columns)
95         {
96             # assuming column_info in dbic is the same as DBI (?)
97             # data_type is a number, column_type is text?
98             my %colinfo = (
99               name => $col,
100               size => 0,
101               is_auto_increment => 0,
102               is_foreign_key => 0,
103               is_nullable => 0,
104               %{$source->column_info($col)}
105             );
106             if ($colinfo{is_nullable}) {
107               $colinfo{default} = '' unless exists $colinfo{default};
108             }
109             my $f = $table->add_field(%colinfo) || die $table->error;
110         }
111         $table->primary_key($source->primary_columns);
112
113         my @primary = $source->primary_columns;
114         my %unique_constraints = $source->unique_constraints;
115         foreach my $uniq (sort keys %unique_constraints) {
116             if (!$source->compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
117                 $table->add_constraint(
118                             type             => 'unique',
119                             name             => $uniq,
120                             fields           => $unique_constraints{$uniq}
121                 );
122             }
123         }
124
125         my @rels = $source->relationships();
126
127         my %created_FK_rels;
128         
129         # global add_fk_index set in parser_args
130         my $add_fk_index = (exists $args->{add_fk_index} && ($args->{add_fk_index} == 0)) ? 0 : 1;
131
132         foreach my $rel (sort @rels)
133         {
134             my $rel_info = $source->relationship_info($rel);
135
136             # Ignore any rel cond that isn't a straight hash
137             next unless ref $rel_info->{cond} eq 'HASH';
138
139             my $othertable = $source->related_source($rel);
140             my $rel_table = $othertable->name;
141
142             my $reverse_rels = $source->reverse_relationship_info($rel);
143             my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
144
145             # Force the order of @cond to match the order of ->add_columns
146             my $idx;
147             my %other_columns_idx = map {'foreign.'.$_ => ++$idx } $othertable->columns;            
148             my @cond = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } keys(%{$rel_info->{cond}}); 
149       
150             # Get the key information, mapping off the foreign/self markers
151             my @refkeys = map {/^\w+\.(\w+)$/} @cond;
152             my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
153
154             # determine if this relationship is a self.fk => foreign.pk (i.e. belongs_to)
155             my $fk_constraint;
156
157             #first it can be specified explicitly
158             if ( exists $rel_info->{attrs}{is_foreign_key_constraint} ) {
159                 $fk_constraint = $rel_info->{attrs}{is_foreign_key_constraint};
160             }
161             # it can not be multi
162             elsif ( $rel_info->{attrs}{accessor} eq 'multi' ) {
163                 $fk_constraint = 0;
164             }
165             # if indeed single, check if all self.columns are our primary keys.
166             # this is supposed to indicate a has_one/might_have...
167             # where's the introspection!!?? :)
168             else {
169                 $fk_constraint = not $source->compare_relationship_keys(\@keys, \@primary);
170             }
171
172             my $cascade;
173             for my $c (qw/delete update/) {
174                 if (exists $rel_info->{attrs}{"on_$c"}) {
175                     if ($fk_constraint) {
176                         $cascade->{$c} = $rel_info->{attrs}{"on_$c"};
177                     }
178                     else {
179                         warn "SQLT attribute 'on_$c' was supplied for relationship '$moniker/$rel', which does not appear to be a foreign constraint. "
180                             . "If you are sure that SQLT must generate a constraint for this relationship, add 'is_foreign_key_constraint => 1' to the attributes.\n";
181                     }
182                 }
183                 elsif (defined $otherrelationship and $otherrelationship->{attrs}{$c eq 'update' ? 'cascade_copy' : 'cascade_delete'}) {
184                     $cascade->{$c} = 'CASCADE';
185                 }
186             }
187
188             if($rel_table)
189             {
190                 # Constraints are added only if applicable
191                 next unless $fk_constraint;
192
193                 # Make sure we dont create the same foreign key constraint twice
194                 my $key_test = join("\x00", @keys);
195                 next if $created_FK_rels{$rel_table}->{$key_test};
196
197                 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
198                 
199                 # global parser_args add_fk_index param can be overridden on the rel def
200                 my $add_fk_index_rel = (exists $rel_info->{attrs}{add_fk_index}) ? $rel_info->{attrs}{add_fk_index} : $add_fk_index;
201
202
203                 $created_FK_rels{$rel_table}->{$key_test} = 1;
204                 if (scalar(@keys)) {
205                   $table->add_constraint(
206                                     type             => 'foreign_key',
207                                     name             => join('_', $table->name, 'fk', @keys),
208                                     fields           => \@keys,
209                                     reference_fields => \@refkeys,
210                                     reference_table  => $rel_table,
211                                     on_delete        => uc ($cascade->{delete} || ''),
212                                     on_update        => uc ($cascade->{update} || ''),
213                                     (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
214                   );
215                     
216                   if ($add_fk_index_rel) {
217                       my $index = $table->add_index(
218                                                     name   => join('_', $table->name, 'idx', @keys),
219                                                     fields => \@keys,
220                                                     type   => 'NORMAL',
221                                                     );
222                   }
223               }
224             }
225         }
226                 
227         if ($source->result_class->can('sqlt_deploy_hook')) {
228           $source->result_class->sqlt_deploy_hook($table);
229         }
230     }
231
232     foreach my $moniker (sort @view_monikers)
233     {
234         my $source = $dbicschema->source($moniker);
235         # Skip custom query sources
236         next if ref($source->name);
237
238         # Its possible to have multiple DBIC source using same table
239         next if $seen_tables{$source->name}++;
240
241         my $view = $schema->add_view(
242           name => $source->name,
243           fields => [ $source->columns ],
244           $source->view_definition ? ( 'sql' => $source->view_definition ) : ()
245         );
246         if ($source->result_class->can('sqlt_deploy_hook')) {
247           $source->result_class->sqlt_deploy_hook($view);
248         }
249     }
250
251
252     if ($dbicschema->can('sqlt_deploy_hook')) {
253       $dbicschema->sqlt_deploy_hook($schema);
254     }
255
256     return 1;
257 }
258
259 1;