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