Merge branch 'current/for_cpan_index' into current/dq
[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 our ($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 DBIx::Class::Carp qw/^SQL::Translator|^DBIx::Class|^Try::Tiny/;
18 use DBIx::Class::Exception;
19 use Scalar::Util 'blessed';
20 use Try::Tiny;
21 use namespace::clean;
22
23 use base qw(Exporter);
24
25 @EXPORT_OK = qw(parse);
26
27 # -------------------------------------------------------------------
28 # parse($tr, $data)
29 #
30 # setting parser_args => { add_fk_index => 0 } will prevent
31 # the auto-generation of an index for each FK.
32 #
33 # Note that $data, in the case of this parser, is not useful.
34 # We're working with DBIx::Class Schemas, not data streams.
35 # -------------------------------------------------------------------
36 sub parse {
37     my ($tr, $data)   = @_;
38     my $args          = $tr->parser_args;
39
40     my $dbicschema = $data || $args->{dbic_schema};
41
42     for (qw(DBIx::Class::Schema DBIx::Schema package)) {
43       if (defined (my $s = delete $args->{$_} )) {
44         carp_unique("Supplying a schema via  ... parser_args => { '$_' => \$schema } is deprecated. Please use parser_args => { dbic_schema => \$schema } instead");
45
46         # move it from the deprecated to the proper $args slot
47         unless ($dbicschema) {
48           $args->{dbic_schema} = $dbicschema = $s;
49         }
50       }
51     }
52
53     DBIx::Class::Exception->throw('No DBIx::Class::Schema') unless ($dbicschema);
54
55     if (!ref $dbicschema) {
56       eval "require $dbicschema"
57         or DBIx::Class::Exception->throw("Can't load $dbicschema: $@");
58     }
59
60     if (
61       ref $args->{dbic_schema}
62         and
63       $args->{dbic_schema}->storage
64     ) {
65       # we have a storage-holding $schema instance in $args
66       # we need to dissociate it from that $storage
67       # otherwise SQLT insanity may ensue due to how some
68       # serializing producers treat $args (crazy crazy shit)
69       local $args->{dbic_schema}{storage};
70       $args->{dbic_schema} = $args->{dbic_schema}->clone;
71     }
72
73     my $schema      = $tr->schema;
74     my $table_no    = 0;
75
76     $schema->name( ref($dbicschema) . " v" . ($dbicschema->schema_version || '1.x'))
77       unless ($schema->name);
78
79     my @monikers = sort $dbicschema->sources;
80     if (my $limit_sources = $args->{'sources'}) {
81         my $ref = ref $limit_sources || '';
82         $dbicschema->throw_exception ("'sources' parameter must be an array or hash ref")
83           unless( $ref eq 'ARRAY' || ref eq 'HASH' );
84
85         # limit monikers to those specified in
86         my $sources;
87         if ($ref eq 'ARRAY') {
88             $sources->{$_} = 1 for (@$limit_sources);
89         } else {
90             $sources = $limit_sources;
91         }
92         @monikers = grep { $sources->{$_} } @monikers;
93     }
94
95
96     my(%table_monikers, %view_monikers);
97     for my $moniker (@monikers){
98       my $source = $dbicschema->source($moniker);
99        if ( $source->isa('DBIx::Class::ResultSource::Table') ) {
100          $table_monikers{$moniker}++;
101       } elsif( $source->isa('DBIx::Class::ResultSource::View') ){
102           next if $source->is_virtual;
103          $view_monikers{$moniker}++;
104       }
105     }
106
107     my %tables;
108     foreach my $moniker (sort keys %table_monikers)
109     {
110         my $source = $dbicschema->source($moniker);
111         my $table_name = $source->name;
112
113         # FIXME - this isn't the right way to do it, but sqlt does not
114         # support quoting properly to be signaled about this
115         $table_name = $$table_name if ref $table_name eq 'SCALAR';
116
117         # It's possible to have multiple DBIC sources using the same table
118         next if $tables{$table_name};
119
120         $tables{$table_name}{source} = $source;
121         my $table = $tables{$table_name}{object} = SQL::Translator::Schema::Table->new(
122                                        name => $table_name,
123                                        type => 'TABLE',
124                                        );
125         foreach my $col ($source->columns)
126         {
127             # assuming column_info in dbic is the same as DBI (?)
128             # data_type is a number, column_type is text?
129             my %colinfo = (
130               name => $col,
131               size => 0,
132               is_auto_increment => 0,
133               is_foreign_key => 0,
134               is_nullable => 0,
135               %{$source->column_info($col)}
136             );
137             if ($colinfo{is_nullable}) {
138               $colinfo{default} = '' unless exists $colinfo{default};
139             }
140             my $f = $table->add_field(%colinfo)
141               || $dbicschema->throw_exception ($table->error);
142         }
143
144         my @primary = $source->primary_columns;
145
146         $table->primary_key(@primary) if @primary;
147
148         my %unique_constraints = $source->unique_constraints;
149         foreach my $uniq (sort keys %unique_constraints) {
150             if (!$source->_compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
151                 $table->add_constraint(
152                             type             => 'unique',
153                             name             => $uniq,
154                             fields           => $unique_constraints{$uniq}
155                 );
156             }
157         }
158
159         my @rels = $source->relationships();
160
161         my %created_FK_rels;
162
163         # global add_fk_index set in parser_args
164         my $add_fk_index = (exists $args->{add_fk_index} && ! $args->{add_fk_index}) ? 0 : 1;
165
166         foreach my $rel (sort @rels)
167         {
168
169             my $rel_info = $source->relationship_info($rel);
170
171             # Ignore any rel cond that isn't a straight hash or DQ expr
172
173             my $rel_cond = do {
174               if (ref($rel_info->{cond}) eq 'HASH') {
175                 # strip foreign. and self.
176                 +{ map {/^\w+\.(\w+)$/} %{$rel_info->{cond}} };
177               } elsif (
178                 blessed($rel_info->{cond})
179                 and $rel_info->{cond}->isa('Data::Query::ExprBuilder')
180               ) {
181                 $source->_join_condition_to_hashref($rel_info->{cond}{expr});
182               } else {
183                 undef;
184               }
185             };
186
187             # non-equality join DQ expr will also have produced undef
188
189             next unless $rel_cond;
190
191             my $relsource = try { $source->related_source($rel) };
192             unless ($relsource) {
193               carp "Ignoring relationship '$rel' - related resultsource '$rel_info->{class}' is not registered with this schema\n";
194               next;
195             };
196
197             # related sources might be excluded via a {sources} filter or might be views
198             next unless exists $table_monikers{$relsource->source_name};
199
200             my $rel_table = $relsource->name;
201
202             # FIXME - this isn't the right way to do it, but sqlt does not
203             # support quoting properly to be signaled about this
204             $rel_table = $$rel_table if ref $rel_table eq 'SCALAR';
205
206             my $reverse_rels = $source->reverse_relationship_info($rel);
207             my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
208
209             # Force the order of @cond to match the order of ->add_columns
210             my $idx;
211             my %other_columns_idx = map { $_ => ++$idx } $relsource->columns;
212             my @refkeys = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } keys(%{$rel_cond});
213
214             my @keys = @{$rel_cond}{@refkeys};
215
216             # determine if this relationship is a self.fk => foreign.pk (i.e. belongs_to)
217             my $fk_constraint;
218
219             #first it can be specified explicitly
220             if ( exists $rel_info->{attrs}{is_foreign_key_constraint} ) {
221                 $fk_constraint = $rel_info->{attrs}{is_foreign_key_constraint};
222             }
223             # it can not be multi
224             elsif ( $rel_info->{attrs}{accessor}
225                     && $rel_info->{attrs}{accessor} eq 'multi' ) {
226                 $fk_constraint = 0;
227             }
228             # if indeed single, check if all self.columns are our primary keys.
229             # this is supposed to indicate a has_one/might_have...
230             # where's the introspection!!?? :)
231             else {
232                 $fk_constraint = not $source->_compare_relationship_keys(\@keys, \@primary);
233             }
234
235             my $cascade;
236             for my $c (qw/delete update/) {
237                 if (exists $rel_info->{attrs}{"on_$c"}) {
238                     if ($fk_constraint) {
239                         $cascade->{$c} = $rel_info->{attrs}{"on_$c"};
240                     }
241                     elsif ( $rel_info->{attrs}{"on_$c"} ) {
242                         carp "SQLT attribute 'on_$c' was supplied for relationship '$moniker/$rel', which does not appear to be a foreign constraint. "
243                             . "If you are sure that SQLT must generate a constraint for this relationship, add 'is_foreign_key_constraint => 1' to the attributes.\n";
244                     }
245                 }
246                 elsif (defined $otherrelationship and $otherrelationship->{attrs}{$c eq 'update' ? 'cascade_copy' : 'cascade_delete'}) {
247                     $cascade->{$c} = 'CASCADE';
248                 }
249             }
250
251             if($rel_table) {
252                 # Constraints are added only if applicable
253                 next unless $fk_constraint;
254
255                 # Make sure we don't create the same foreign key constraint twice
256                 my $key_test = join("\x00", sort @keys);
257                 next if $created_FK_rels{$rel_table}->{$key_test};
258
259                 if (scalar(@keys)) {
260                   $created_FK_rels{$rel_table}->{$key_test} = 1;
261
262                   my $is_deferrable = $rel_info->{attrs}{is_deferrable};
263
264                   # calculate dependencies: do not consider deferrable constraints and
265                   # self-references for dependency calculations
266                   if (! $is_deferrable and $rel_table ne $table_name) {
267                     $tables{$table_name}{foreign_table_deps}{$rel_table}++;
268                   }
269
270                   $table->add_constraint(
271                     type             => 'foreign_key',
272                     name             => join('_', $table_name, 'fk', @keys),
273                     fields           => \@keys,
274                     reference_fields => \@refkeys,
275                     reference_table  => $rel_table,
276                     on_delete        => uc ($cascade->{delete} || ''),
277                     on_update        => uc ($cascade->{update} || ''),
278                     (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
279                   );
280
281                   # global parser_args add_fk_index param can be overridden on the rel def
282                   my $add_fk_index_rel = (exists $rel_info->{attrs}{add_fk_index}) ? $rel_info->{attrs}{add_fk_index} : $add_fk_index;
283
284                   # Check that we do not create an index identical to the PK index
285                   # (some RDBMS croak on this, and it generally doesn't make much sense)
286                   # NOTE: we do not sort the key columns because the order of
287                   # columns is important for indexes and two indexes with the
288                   # same cols but different order are allowed and sometimes
289                   # needed
290                   next if join("\x00", @keys) eq join("\x00", @primary);
291
292                   if ($add_fk_index_rel) {
293                       my $index = $table->add_index(
294                           name   => join('_', $table_name, 'idx', @keys),
295                           fields => \@keys,
296                           type   => 'NORMAL',
297                       );
298                   }
299               }
300             }
301         }
302
303     }
304
305     # attach the tables to the schema in dependency order
306     my $dependencies = {
307       map { $_ => _resolve_deps ($_, \%tables) } (keys %tables)
308     };
309
310     for my $table (sort
311       {
312         keys %{$dependencies->{$a} || {} } <=> keys %{ $dependencies->{$b} || {} }
313           ||
314         $a cmp $b
315       }
316       (keys %tables)
317     ) {
318       $schema->add_table ($tables{$table}{object});
319       $tables{$table}{source} -> _invoke_sqlt_deploy_hook( $tables{$table}{object} );
320
321       # the hook might have already removed the table
322       if ($schema->get_table($table) && $table =~ /^ \s* \( \s* SELECT \s+/ix) {
323         carp <<'EOW';
324
325 Custom SQL through ->name(\'( SELECT ...') is DEPRECATED, for more details see
326 "Arbitrary SQL through a custom ResultSource" in DBIx::Class::Manual::Cookbook
327 or http://search.cpan.org/dist/DBIx-Class/lib/DBIx/Class/Manual/Cookbook.pod
328
329 EOW
330
331         # remove the table as there is no way someone might want to
332         # actually deploy this
333         $schema->drop_table ($table);
334       }
335     }
336
337     my %views;
338     my @views = map { $dbicschema->source($_) } keys %view_monikers;
339
340     my $view_dependencies = {
341         map {
342             $_ => _resolve_deps( $dbicschema->source($_), \%view_monikers )
343           } ( keys %view_monikers )
344     };
345
346     my @view_sources =
347       sort {
348         keys %{ $view_dependencies->{ $a->source_name }   || {} } <=>
349           keys %{ $view_dependencies->{ $b->source_name } || {} }
350           || $a->source_name cmp $b->source_name
351       }
352       map { $dbicschema->source($_) }
353       keys %view_monikers;
354
355     foreach my $source (@view_sources)
356     {
357         my $view_name = $source->name;
358
359         # FIXME - this isn't the right way to do it, but sqlt does not
360         # support quoting properly to be signaled about this
361         $view_name = $$view_name if ref $view_name eq 'SCALAR';
362
363         # Skip custom query sources
364         next if ref $view_name;
365
366         # Its possible to have multiple DBIC source using same table
367         next if $views{$view_name}++;
368
369         $dbicschema->throw_exception ("view $view_name is missing a view_definition")
370             unless $source->view_definition;
371
372         my $view = $schema->add_view (
373           name => $view_name,
374           fields => [ $source->columns ],
375           $source->view_definition ? ( 'sql' => $source->view_definition ) : ()
376         ) || $dbicschema->throw_exception ($schema->error);
377
378         $source->_invoke_sqlt_deploy_hook($view);
379     }
380
381
382     if ($dbicschema->can('sqlt_deploy_hook')) {
383       $dbicschema->sqlt_deploy_hook($schema);
384     }
385
386     return 1;
387 }
388
389 #
390 # Quick and dirty dependency graph calculator
391 #
392 sub _resolve_deps {
393     my ( $question, $answers, $seen ) = @_;
394     my $ret = {};
395     $seen ||= {};
396     my @deps;
397
398     # copy and bump all deps by one (so we can reconstruct the chain)
399     my %seen = map { $_ => $seen->{$_} + 1 } ( keys %$seen );
400     if ( blessed($question)
401         && $question->isa('DBIx::Class::ResultSource::View') )
402     {
403         $seen{ $question->result_class } = 1;
404         @deps = keys %{ $question->{deploy_depends_on} };
405     }
406     else {
407         $seen{$question} = 1;
408         @deps = keys %{ $answers->{$question}{foreign_table_deps} };
409     }
410
411     for my $dep (@deps) {
412         if ( $seen->{$dep} ) {
413             return {};
414         }
415         my $next_dep;
416
417         if ( blessed($question)
418             && $question->isa('DBIx::Class::ResultSource::View') )
419         {
420             no warnings 'uninitialized';
421             my ($next_dep_source_name) =
422               grep {
423                 $question->schema->source($_)->result_class eq $dep
424                   && !( $question->schema->source($_)
425                     ->isa('DBIx::Class::ResultSource::Table') )
426               } @{ [ $question->schema->sources ] };
427             return {} unless $next_dep_source_name;
428             $next_dep = $question->schema->source($next_dep_source_name);
429         }
430         else {
431             $next_dep = $dep;
432         }
433         my $subdeps = _resolve_deps( $next_dep, $answers, \%seen );
434         $ret->{$_} += $subdeps->{$_} for ( keys %$subdeps );
435         ++$ret->{$dep};
436     }
437     return $ret;
438 }
439
440 1;
441
442 =head1 NAME
443
444 SQL::Translator::Parser::DBIx::Class - Create a SQL::Translator schema
445 from a DBIx::Class::Schema instance
446
447 =head1 SYNOPSIS
448
449  ## Via DBIx::Class
450  use MyApp::Schema;
451  my $schema = MyApp::Schema->connect("dbi:SQLite:something.db");
452  $schema->create_ddl_dir();
453  ## or
454  $schema->deploy();
455
456  ## Standalone
457  use MyApp::Schema;
458  use SQL::Translator;
459
460  my $schema = MyApp::Schema->connect;
461  my $trans  = SQL::Translator->new (
462       parser      => 'SQL::Translator::Parser::DBIx::Class',
463       parser_args => {
464           dbic_schema => $schema,
465           add_fk_index => 0,
466           sources => [qw/
467             Artist
468             CD
469           /],
470       },
471       producer    => 'SQLite',
472      ) or die SQL::Translator->error;
473  my $out = $trans->translate() or die $trans->error;
474
475 =head1 DESCRIPTION
476
477 This class requires L<SQL::Translator> installed to work.
478
479 C<SQL::Translator::Parser::DBIx::Class> reads a DBIx::Class schema,
480 interrogates the columns, and stuffs it all in an $sqlt_schema object.
481
482 Its primary use is in deploying database layouts described as a set
483 of L<DBIx::Class> classes, to a database. To do this, see
484 L<DBIx::Class::Schema/deploy>.
485
486 This can also be achieved by having DBIx::Class export the schema as a
487 set of SQL files ready for import into your database, or passed to
488 other machines that need to have your application installed but don't
489 have SQL::Translator installed. To do this see
490 L<DBIx::Class::Schema/create_ddl_dir>.
491
492 =head1 PARSER OPTIONS
493
494 =head2 dbic_schema
495
496 The DBIx::Class schema (either an instance or a class name) to be parsed.
497 This argument is in fact optional - instead one can supply it later at
498 translation time as an argument to L<SQL::Translator/translate>. In
499 other words both of the following invocations are valid and will produce
500 conceptually identical output:
501
502   my $yaml = SQL::Translator->new(
503     parser => 'SQL::Translator::Parser::DBIx::Class',
504     parser_args => {
505       dbic_schema => $schema,
506     },
507     producer => 'SQL::Translator::Producer::YAML',
508   )->translate;
509
510   my $yaml = SQL::Translator->new(
511     parser => 'SQL::Translator::Parser::DBIx::Class',
512     producer => 'SQL::Translator::Producer::YAML',
513   )->translate(data => $schema);
514
515 =head2 add_fk_index
516
517 Create an index for each foreign key.
518 Enabled by default, as having indexed foreign key columns is normally the
519 sensible thing to do.
520
521 =head2 sources
522
523 =over 4
524
525 =item Arguments: \@class_names
526
527 =back
528
529 Limit the amount of parsed sources by supplying an explicit list of source names.
530
531 =head1 SEE ALSO
532
533 L<SQL::Translator>, L<DBIx::Class::Schema>
534
535 =head1 AUTHORS
536
537 See L<DBIx::Class/CONTRIBUTORS>.
538
539 =head1 LICENSE
540
541 You may distribute this code under the same terms as Perl itself.
542
543 =cut