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