1 package SQL::Translator::Parser::DBIx::Class;
3 # AUTHOR: Jess Robinson
5 # Some mistakes the fault of Matt S Trout
7 # Others the fault of Ash Berlin
11 use vars qw($DEBUG $VERSION @EXPORT_OK);
13 $DEBUG = 0 unless defined $DEBUG;
16 use SQL::Translator::Utils qw(debug normalize_name);
17 use Carp::Clan qw/^SQL::Translator|^DBIx::Class/;
19 use base qw(Exporter);
21 @EXPORT_OK = qw(parse);
23 # -------------------------------------------------------------------
26 # setting parser_args => { add_fk_index => 0 } will prevent
27 # the auto-generation of an index for each FK.
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 # -------------------------------------------------------------------
33 # this is a hack to prevent schema leaks due to a retarded SQLT implementation
34 # DO NOT REMOVE (until SQLT2 is out, the all of this will be rewritten anyway)
35 Scalar::Util::weaken ($_[1]) if ref ($_[1]);
38 my $args = $tr->parser_args;
39 my $dbicschema = $args->{'DBIx::Class::Schema'} || $args->{"DBIx::Schema"} ||$data;
40 $dbicschema ||= $args->{'package'};
41 my $limit_sources = $args->{'sources'};
43 croak 'No DBIx::Class::Schema' unless ($dbicschema);
44 if (!ref $dbicschema) {
45 eval "use $dbicschema;";
46 croak "Can't load $dbicschema ($@)" if($@);
49 my $schema = $tr->schema;
52 $schema->name( ref($dbicschema) . " v" . ($dbicschema->schema_version || '1.x'))
53 unless ($schema->name);
55 my @monikers = sort $dbicschema->sources;
57 my $ref = ref $limit_sources || '';
58 $dbicschema->throw_exception ("'sources' parameter must be an array or hash ref")
59 unless( $ref eq 'ARRAY' || ref eq 'HASH' );
61 # limit monikers to those specified in
63 if ($ref eq 'ARRAY') {
64 $sources->{$_} = 1 for (@$limit_sources);
66 $sources = $limit_sources;
68 @monikers = grep { $sources->{$_} } @monikers;
72 my(%table_monikers, %view_monikers);
73 for my $moniker (@monikers){
74 my $source = $dbicschema->source($moniker);
75 if ( $source->isa('DBIx::Class::ResultSource::Table') ) {
76 $table_monikers{$moniker}++;
77 } elsif( $source->isa('DBIx::Class::ResultSource::View') ){
78 next if $source->is_virtual;
79 $view_monikers{$moniker}++;
84 foreach my $moniker (sort keys %table_monikers)
86 my $source = $dbicschema->source($moniker);
87 my $table_name = $source->name;
89 # FIXME - this isn't the right way to do it, but sqlt does not
90 # support quoting properly to be signaled about this
91 $table_name = $$table_name if ref $table_name eq 'SCALAR';
93 # It's possible to have multiple DBIC sources using the same table
94 next if $tables{$table_name};
96 $tables{$table_name}{source} = $source;
97 my $table = $tables{$table_name}{object} = SQL::Translator::Schema::Table->new(
101 foreach my $col ($source->columns)
103 # assuming column_info in dbic is the same as DBI (?)
104 # data_type is a number, column_type is text?
108 is_auto_increment => 0,
111 %{$source->column_info($col)}
113 if ($colinfo{is_nullable}) {
114 $colinfo{default} = '' unless exists $colinfo{default};
116 my $f = $table->add_field(%colinfo)
117 || $dbicschema->throw_exception ($table->error);
120 my @primary = $source->primary_columns;
122 $table->primary_key(@primary) if @primary;
124 my %unique_constraints = $source->unique_constraints;
125 foreach my $uniq (sort keys %unique_constraints) {
126 if (!$source->_compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
127 $table->add_constraint(
130 fields => $unique_constraints{$uniq}
135 my @rels = $source->relationships();
139 # global add_fk_index set in parser_args
140 my $add_fk_index = (exists $args->{add_fk_index} && ! $args->{add_fk_index}) ? 0 : 1;
142 foreach my $rel (sort @rels)
145 my $rel_info = $source->relationship_info($rel);
147 # Ignore any rel cond that isn't a straight hash
148 next unless ref $rel_info->{cond} eq 'HASH';
150 my $relsource = $source->related_source($rel);
152 # related sources might be excluded via a {sources} filter or might be views
153 next unless exists $table_monikers{$relsource->source_name};
155 my $rel_table = $relsource->name;
157 # FIXME - this isn't the right way to do it, but sqlt does not
158 # support quoting properly to be signaled about this
159 $rel_table = $$rel_table if ref $rel_table eq 'SCALAR';
161 my $reverse_rels = $source->reverse_relationship_info($rel);
162 my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
164 # Force the order of @cond to match the order of ->add_columns
166 my %other_columns_idx = map {'foreign.'.$_ => ++$idx } $relsource->columns;
167 my @cond = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } keys(%{$rel_info->{cond}});
169 # Get the key information, mapping off the foreign/self markers
170 my @refkeys = map {/^\w+\.(\w+)$/} @cond;
171 my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
173 # determine if this relationship is a self.fk => foreign.pk (i.e. belongs_to)
176 #first it can be specified explicitly
177 if ( exists $rel_info->{attrs}{is_foreign_key_constraint} ) {
178 $fk_constraint = $rel_info->{attrs}{is_foreign_key_constraint};
180 # it can not be multi
181 elsif ( $rel_info->{attrs}{accessor}
182 && $rel_info->{attrs}{accessor} eq 'multi' ) {
185 # if indeed single, check if all self.columns are our primary keys.
186 # this is supposed to indicate a has_one/might_have...
187 # where's the introspection!!?? :)
189 $fk_constraint = not $source->_compare_relationship_keys(\@keys, \@primary);
193 for my $c (qw/delete update/) {
194 if (exists $rel_info->{attrs}{"on_$c"}) {
195 if ($fk_constraint) {
196 $cascade->{$c} = $rel_info->{attrs}{"on_$c"};
198 elsif ( $rel_info->{attrs}{"on_$c"} ) {
199 carp "SQLT attribute 'on_$c' was supplied for relationship '$moniker/$rel', which does not appear to be a foreign constraint. "
200 . "If you are sure that SQLT must generate a constraint for this relationship, add 'is_foreign_key_constraint => 1' to the attributes.\n";
203 elsif (defined $otherrelationship and $otherrelationship->{attrs}{$c eq 'update' ? 'cascade_copy' : 'cascade_delete'}) {
204 $cascade->{$c} = 'CASCADE';
209 # Constraints are added only if applicable
210 next unless $fk_constraint;
212 # Make sure we dont create the same foreign key constraint twice
213 my $key_test = join("\x00", sort @keys);
214 next if $created_FK_rels{$rel_table}->{$key_test};
217 $created_FK_rels{$rel_table}->{$key_test} = 1;
219 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
221 # calculate dependencies: do not consider deferrable constraints and
222 # self-references for dependency calculations
223 if (! $is_deferrable and $rel_table ne $table_name) {
224 $tables{$table_name}{foreign_table_deps}{$rel_table}++;
227 $table->add_constraint(
228 type => 'foreign_key',
229 name => join('_', $table_name, 'fk', @keys),
231 reference_fields => \@refkeys,
232 reference_table => $rel_table,
233 on_delete => uc ($cascade->{delete} || ''),
234 on_update => uc ($cascade->{update} || ''),
235 (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
238 # global parser_args add_fk_index param can be overridden on the rel def
239 my $add_fk_index_rel = (exists $rel_info->{attrs}{add_fk_index}) ? $rel_info->{attrs}{add_fk_index} : $add_fk_index;
241 # Check that we do not create an index identical to the PK index
242 # (some RDBMS croak on this, and it generally doesn't make much sense)
243 # NOTE: we do not sort the key columns because the order of
244 # columns is important for indexes and two indexes with the
245 # same cols but different order are allowed and sometimes
247 next if join("\x00", @keys) eq join("\x00", @primary);
249 if ($add_fk_index_rel) {
250 my $index = $table->add_index(
251 name => join('_', $table_name, 'idx', @keys),
262 # attach the tables to the schema in dependency order
264 map { $_ => _resolve_deps ($_, \%tables) } (keys %tables)
269 keys %{$dependencies->{$a} || {} } <=> keys %{ $dependencies->{$b} || {} }
275 $schema->add_table ($tables{$table}{object});
276 $tables{$table}{source} -> _invoke_sqlt_deploy_hook( $tables{$table}{object} );
278 # the hook might have already removed the table
279 if ($schema->get_table($table) && $table =~ /^ \s* \( \s* SELECT \s+/ix) {
282 Custom SQL through ->name(\'( SELECT ...') is DEPRECATED, for more details see
283 "Arbitrary SQL through a custom ResultSource" in DBIx::Class::Manual::Cookbook
284 or http://search.cpan.org/dist/DBIx-Class/lib/DBIx/Class/Manual/Cookbook.pod
288 # remove the table as there is no way someone might want to
289 # actually deploy this
290 $schema->drop_table ($table);
297 #(exists $a->deploy_depends_on->{$b->source_name} ? 1 : 0)
299 #(exists $b->deploy_depends_on->{$a->source_name} ? 1 : 0)
301 #map { $dbicschema->source($_) } (sort keys %view_monikers);
305 keys %{ $dependencies->{$a} || {} }
307 keys %{ $dependencies->{$b} || {} }
311 map { $dbicschema->source($_) } (sort keys %view_monikers);
314 print STDERR "View monikers: ", Dumper %view_monikers;
315 print STDERR "Source name of view source: ", $_->source_name, "\n" for @view_sources;
316 print STDERR Dumper "Dependencies: ", $dependencies;
318 foreach my $source (@view_sources)
320 my $view_name = $source->name;
322 # FIXME - this isn't the right way to do it, but sqlt does not
323 # support quoting properly to be signaled about this
324 $view_name = $$view_name if ref $view_name eq 'SCALAR';
326 # Skip custom query sources
327 next if ref $view_name;
329 # Its possible to have multiple DBIC source using same table
330 next if $views{$view_name}++;
332 $dbicschema->throw_exception ("view $view_name is missing a view_definition")
333 unless $source->view_definition;
335 my $view = $schema->add_view (
337 fields => [ $source->columns ],
338 $source->view_definition ? ( 'sql' => $source->view_definition ) : ()
339 ) || $dbicschema->throw_exception ($schema->error);
341 $source->_invoke_sqlt_deploy_hook($view);
345 if ($dbicschema->can('sqlt_deploy_hook')) {
346 $dbicschema->sqlt_deploy_hook($schema);
353 # Quick and dirty dependency graph calculator
356 my ($table, $tables, $seen) = @_;
361 # copy and bump all deps by one (so we can reconstruct the chain)
362 my %seen = map { $_ => $seen->{$_} + 1 } (keys %$seen);
365 for my $dep (keys %{$tables->{$table}{foreign_table_deps}} ) {
369 # warn and remove the circular constraint so we don't get flooded with the same warning over and over
370 #carp sprintf ("Circular dependency detected, schema may not be deployable:\n%s\n",
371 # join (' -> ', (sort { $seen->{$b} <=> $seen->{$a} } (keys %$seen) ), $table, $dep )
373 #delete $tables->{$table}{foreign_table_deps}{$dep};
378 my $subdeps = _resolve_deps ($dep, $tables, \%seen);
379 $ret->{$_} += $subdeps->{$_} for ( keys %$subdeps );
391 SQL::Translator::Parser::DBIx::Class - Create a SQL::Translator schema
392 from a DBIx::Class::Schema instance
398 my $schema = MyApp::Schema->connect("dbi:SQLite:something.db");
399 $schema->create_ddl_dir();
407 my $schema = MyApp::Schema->connect;
408 my $trans = SQL::Translator->new (
409 parser => 'SQL::Translator::Parser::DBIx::Class',
418 producer => 'SQLite',
419 ) or die SQL::Translator->error;
420 my $out = $trans->translate() or die $trans->error;
424 This class requires L<SQL::Translator> installed to work.
426 C<SQL::Translator::Parser::DBIx::Class> reads a DBIx::Class schema,
427 interrogates the columns, and stuffs it all in an $sqlt_schema object.
429 Its primary use is in deploying database layouts described as a set
430 of L<DBIx::Class> classes, to a database. To do this, see
431 L<DBIx::Class::Schema/deploy>.
433 This can also be achieved by having DBIx::Class export the schema as a
434 set of SQL files ready for import into your database, or passed to
435 other machines that need to have your application installed but don't
436 have SQL::Translator installed. To do this see
437 L<DBIx::Class::Schema/create_ddl_dir>.
439 =head1 PARSER OPTIONS
443 Create an index for each foreign key.
444 Enabled by default, as having indexed foreign key columns is normally the
445 sensible thing to do.
451 =item Arguments: \@class_names
455 Limit the amount of parsed sources by supplying an explicit list of source names.
459 L<SQL::Translator>, L<DBIx::Class::Schema>
463 See L<DBIx::Class/CONTRIBUTORS>.
467 You may distribute this code under the same terms as Perl itself.