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