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