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