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