Don't call the PK setter if no PK
[dbsrgits/DBIx-Class.git] / lib / SQL / Translator / Parser / DBIx / Class.pm
1 package SQL::Translator::Parser::DBIx::Class;
2
3 # AUTHOR: Jess Robinson
4
5 # Some mistakes the fault of Matt S Trout
6
7 # Others the fault of Ash Berlin
8
9 use strict;
10 use warnings;
11 use vars qw($DEBUG $VERSION @EXPORT_OK);
12 $VERSION = '1.10';
13 $DEBUG = 0 unless defined $DEBUG;
14
15 use Exporter;
16 use SQL::Translator::Utils qw(debug normalize_name);
17 use Carp::Clan qw/^SQL::Translator|^DBIx::Class/;
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     croak 'No DBIx::Class::Schema' unless ($dbicschema);
40     if (!ref $dbicschema) {
41       eval "use $dbicschema;";
42       croak "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->schema_version || '1.x'))
49       unless ($schema->name);
50
51     my @monikers = sort $dbicschema->sources;
52     if ($limit_sources) {
53         my $ref = ref $limit_sources || '';
54         $dbicschema->throw_exception ("'sources' parameter must be an array or hash ref")
55           unless( $ref eq 'ARRAY' || ref eq 'HASH' );
56
57         # limit monikers to those specified in 
58         my $sources;
59         if ($ref eq 'ARRAY') {
60             $sources->{$_} = 1 for (@$limit_sources);
61         } else {
62             $sources = $limit_sources;
63         }
64         @monikers = grep { $sources->{$_} } @monikers;
65     }
66
67
68     my(%table_monikers, %view_monikers);
69     for my $moniker (@monikers){
70       my $source = $dbicschema->source($moniker);
71        if ( $source->isa('DBIx::Class::ResultSource::Table') ) {
72          $table_monikers{$moniker}++;
73       } elsif( $source->isa('DBIx::Class::ResultSource::View') ){
74           next if $source->is_virtual;
75          $view_monikers{$moniker}++;
76       }
77     }
78
79     my %tables;
80     foreach my $moniker (sort keys %table_monikers)
81     {
82         my $source = $dbicschema->source($moniker);
83         my $table_name = $source->name;
84
85         # FIXME - this isn't the right way to do it, but sqlt does not
86         # support quoting properly to be signaled about this
87         $table_name = $$table_name if ref $table_name eq 'SCALAR';
88
89         # It's possible to have multiple DBIC sources using the same table
90         next if $tables{$table_name};
91
92         $tables{$table_name}{source} = $source;
93         my $table = $tables{$table_name}{object} = SQL::Translator::Schema::Table->new(
94                                        name => $table_name,
95                                        type => 'TABLE',
96                                        );
97         foreach my $col ($source->columns)
98         {
99             # assuming column_info in dbic is the same as DBI (?)
100             # data_type is a number, column_type is text?
101             my %colinfo = (
102               name => $col,
103               size => 0,
104               is_auto_increment => 0,
105               is_foreign_key => 0,
106               is_nullable => 0,
107               %{$source->column_info($col)}
108             );
109             if ($colinfo{is_nullable}) {
110               $colinfo{default} = '' unless exists $colinfo{default};
111             }
112             my $f = $table->add_field(%colinfo)
113               || $dbicschema->throw_exception ($table->error);
114         }
115
116         my @primary = $source->primary_columns;
117
118         $table->primary_key(@primary) if @primary;
119
120         my %unique_constraints = $source->unique_constraints;
121         foreach my $uniq (sort keys %unique_constraints) {
122             if (!$source->_compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
123                 $table->add_constraint(
124                             type             => 'unique',
125                             name             => $uniq,
126                             fields           => $unique_constraints{$uniq}
127                 );
128             }
129         }
130
131         my @rels = $source->relationships();
132
133         my %created_FK_rels;
134
135         # global add_fk_index set in parser_args
136         my $add_fk_index = (exists $args->{add_fk_index} && ! $args->{add_fk_index}) ? 0 : 1;
137
138         foreach my $rel (sort @rels)
139         {
140
141             my $rel_info = $source->relationship_info($rel);
142
143             # Ignore any rel cond that isn't a straight hash
144             next unless ref $rel_info->{cond} eq 'HASH';
145
146             my $relsource = $source->related_source($rel);
147
148             # related sources might be excluded via a {sources} filter or might be views
149             next unless exists $table_monikers{$relsource->source_name};
150
151             my $rel_table = $relsource->name;
152
153             # FIXME - this isn't the right way to do it, but sqlt does not
154             # support quoting properly to be signaled about this
155             $rel_table = $$rel_table if ref $rel_table eq 'SCALAR';
156
157             my $reverse_rels = $source->reverse_relationship_info($rel);
158             my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
159
160             # Force the order of @cond to match the order of ->add_columns
161             my $idx;
162             my %other_columns_idx = map {'foreign.'.$_ => ++$idx } $relsource->columns;
163             my @cond = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } keys(%{$rel_info->{cond}}); 
164
165             # Get the key information, mapping off the foreign/self markers
166             my @refkeys = map {/^\w+\.(\w+)$/} @cond;
167             my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
168
169             # determine if this relationship is a self.fk => foreign.pk (i.e. belongs_to)
170             my $fk_constraint;
171
172             #first it can be specified explicitly
173             if ( exists $rel_info->{attrs}{is_foreign_key_constraint} ) {
174                 $fk_constraint = $rel_info->{attrs}{is_foreign_key_constraint};
175             }
176             # it can not be multi
177             elsif ( $rel_info->{attrs}{accessor}
178                     && $rel_info->{attrs}{accessor} eq 'multi' ) {
179                 $fk_constraint = 0;
180             }
181             # if indeed single, check if all self.columns are our primary keys.
182             # this is supposed to indicate a has_one/might_have...
183             # where's the introspection!!?? :)
184             else {
185                 $fk_constraint = not $source->_compare_relationship_keys(\@keys, \@primary);
186             }
187
188             my $cascade;
189             for my $c (qw/delete update/) {
190                 if (exists $rel_info->{attrs}{"on_$c"}) {
191                     if ($fk_constraint) {
192                         $cascade->{$c} = $rel_info->{attrs}{"on_$c"};
193                     }
194                     elsif ( $rel_info->{attrs}{"on_$c"} ) {
195                         carp "SQLT attribute 'on_$c' was supplied for relationship '$moniker/$rel', which does not appear to be a foreign constraint. "
196                             . "If you are sure that SQLT must generate a constraint for this relationship, add 'is_foreign_key_constraint => 1' to the attributes.\n";
197                     }
198                 }
199                 elsif (defined $otherrelationship and $otherrelationship->{attrs}{$c eq 'update' ? 'cascade_copy' : 'cascade_delete'}) {
200                     $cascade->{$c} = 'CASCADE';
201                 }
202             }
203
204             if($rel_table)
205             {
206                 # Constraints are added only if applicable
207                 next unless $fk_constraint;
208
209                 # Make sure we dont create the same foreign key constraint twice
210                 my $key_test = join("\x00", sort @keys);
211                 next if $created_FK_rels{$rel_table}->{$key_test};
212
213                 if (scalar(@keys)) {
214
215                   $created_FK_rels{$rel_table}->{$key_test} = 1;
216
217                   my $is_deferrable = $rel_info->{attrs}{is_deferrable};
218
219                   # calculate dependencies: do not consider deferrable constraints and
220                   # self-references for dependency calculations
221                   if (! $is_deferrable and $rel_table ne $table_name) {
222                     $tables{$table_name}{foreign_table_deps}{$rel_table}++;
223                   }
224
225                   $table->add_constraint(
226                                     type             => 'foreign_key',
227                                     name             => join('_', $table_name, 'fk', @keys),
228                                     fields           => \@keys,
229                                     reference_fields => \@refkeys,
230                                     reference_table  => $rel_table,
231                                     on_delete        => uc ($cascade->{delete} || ''),
232                                     on_update        => uc ($cascade->{update} || ''),
233                                     (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
234                   );
235
236                   # global parser_args add_fk_index param can be overridden on the rel def
237                   my $add_fk_index_rel = (exists $rel_info->{attrs}{add_fk_index}) ? $rel_info->{attrs}{add_fk_index} : $add_fk_index;
238
239                   if ($add_fk_index_rel) {
240                       my $index = $table->add_index(
241                                                     name   => join('_', $table_name, 'idx', @keys),
242                                                     fields => \@keys,
243                                                     type   => 'NORMAL',
244                                                     );
245                   }
246               }
247             }
248         }
249
250     }
251
252     # attach the tables to the schema in dependency order
253     my $dependencies = {
254       map { $_ => _resolve_deps ($_, \%tables) } (keys %tables)
255     };
256     for my $table (sort
257       {
258         keys %{$dependencies->{$a} || {} } <=> keys %{ $dependencies->{$b} || {} }
259           ||
260         $a cmp $b
261       }
262       (keys %tables)
263     ) {
264       $schema->add_table ($tables{$table}{object});
265       $tables{$table}{source} -> _invoke_sqlt_deploy_hook( $tables{$table}{object} );
266
267       # the hook might have already removed the table
268       if ($schema->get_table($table) && $table =~ /^ \s* \( \s* SELECT \s+/ix) {
269         warn <<'EOW';
270
271 Custom SQL through ->name(\'( SELECT ...') is DEPRECATED, for more details see
272 "Arbitrary SQL through a custom ResultSource" in DBIx::Class::Manual::Cookbook
273 or http://search.cpan.org/dist/DBIx-Class/lib/DBIx/Class/Manual/Cookbook.pod
274
275 EOW
276
277         # remove the table as there is no way someone might want to
278         # actually deploy this
279         $schema->drop_table ($table);
280       }
281     }
282
283     my %views;
284     foreach my $moniker (sort keys %view_monikers)
285     {
286         my $source = $dbicschema->source($moniker);
287         my $view_name = $source->name;
288
289         # FIXME - this isn't the right way to do it, but sqlt does not
290         # support quoting properly to be signaled about this
291         $view_name = $$view_name if ref $view_name eq 'SCALAR';
292
293         # Skip custom query sources
294         next if ref $view_name;
295
296         # Its possible to have multiple DBIC source using same table
297         next if $views{$view_name}++;
298
299         $dbicschema->throw_exception ("view $view_name is missing a view_definition")
300             unless $source->view_definition;
301
302         my $view = $schema->add_view (
303           name => $view_name,
304           fields => [ $source->columns ],
305           $source->view_definition ? ( 'sql' => $source->view_definition ) : ()
306         ) || $dbicschema->throw_exception ($schema->error);
307
308         $source->_invoke_sqlt_deploy_hook($view);
309     }
310
311
312     if ($dbicschema->can('sqlt_deploy_hook')) {
313       $dbicschema->sqlt_deploy_hook($schema);
314     }
315
316     return 1;
317 }
318
319 #
320 # Quick and dirty dependency graph calculator
321 #
322 sub _resolve_deps {
323   my ($table, $tables, $seen) = @_;
324
325   my $ret = {};
326   $seen ||= {};
327
328   # copy and bump all deps by one (so we can reconstruct the chain)
329   my %seen = map { $_ => $seen->{$_} + 1 } (keys %$seen);
330   $seen{$table} = 1;
331
332   for my $dep (keys %{$tables->{$table}{foreign_table_deps}} ) {
333
334     if ($seen->{$dep}) {
335
336       # warn and remove the circular constraint so we don't get flooded with the same warning over and over
337       #carp sprintf ("Circular dependency detected, schema may not be deployable:\n%s\n",
338       #  join (' -> ', (sort { $seen->{$b} <=> $seen->{$a} } (keys %$seen) ), $table, $dep )
339       #);
340       #delete $tables->{$table}{foreign_table_deps}{$dep};
341
342       return {};
343     }
344
345     my $subdeps = _resolve_deps ($dep, $tables, \%seen);
346     $ret->{$_} += $subdeps->{$_} for ( keys %$subdeps );
347
348     ++$ret->{$dep};
349   }
350
351   return $ret;
352 }
353
354 1;
355
356 =head1 NAME
357
358 SQL::Translator::Parser::DBIx::Class - Create a SQL::Translator schema
359 from a DBIx::Class::Schema instance
360
361 =head1 SYNOPSIS
362
363  ## Via DBIx::Class
364  use MyApp::Schema;
365  my $schema = MyApp::Schema->connect("dbi:SQLite:something.db");
366  $schema->create_ddl_dir();
367  ## or
368  $schema->deploy();
369
370  ## Standalone
371  use MyApp::Schema;
372  use SQL::Translator;
373
374  my $schema = MyApp::Schema->connect;
375  my $trans  = SQL::Translator->new (
376       parser      => 'SQL::Translator::Parser::DBIx::Class',
377       parser_args => { package => $schema },
378       producer    => 'SQLite',
379      ) or die SQL::Translator->error;
380  my $out = $trans->translate() or die $trans->error;
381
382 =head1 DESCRIPTION
383
384 This class requires L<SQL::Translator> installed to work.
385
386 C<SQL::Translator::Parser::DBIx::Class> reads a DBIx::Class schema,
387 interrogates the columns, and stuffs it all in an $sqlt_schema object.
388
389 Its primary use is in deploying database layouts described as a set
390 of L<DBIx::Class> classes, to a database. To do this, see
391 L<DBIx::Class::Schema/deploy>.
392
393 This can also be achieved by having DBIx::Class export the schema as a
394 set of SQL files ready for import into your database, or passed to
395 other machines that need to have your application installed but don't
396 have SQL::Translator installed. To do this see
397 L<DBIx::Class::Schema/create_ddl_dir>.
398
399 =head1 SEE ALSO
400
401 L<SQL::Translator>, L<DBIx::Class::Schema>
402
403 =head1 AUTHORS
404
405 Jess Robinson
406
407 Matt S Trout
408
409 Ash Berlin