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|^Try::Tiny/;
18 use Scalar::Util 'weaken';
23 use base qw(Exporter);
25 @EXPORT_OK = qw(parse);
27 # -------------------------------------------------------------------
30 # setting parser_args => { add_fk_index => 0 } will prevent
31 # the auto-generation of an index for each FK.
33 # Note that $data, in the case of this parser, is not useful.
34 # We're working with DBIx::Class Schemas, not data streams.
35 # -------------------------------------------------------------------
37 # this is a hack to prevent schema leaks due to a retarded SQLT implementation
38 # DO NOT REMOVE (until SQLT2 is out, the all of this will be rewritten anyway)
39 weaken $_[1] if ref ($_[1]);
42 my $args = $tr->parser_args;
43 my $dbicschema = $args->{'DBIx::Class::Schema'} || $args->{"DBIx::Schema"} ||$data;
44 $dbicschema ||= $args->{'package'};
45 my $limit_sources = $args->{'sources'};
47 croak 'No DBIx::Class::Schema' unless ($dbicschema);
48 if (!ref $dbicschema) {
50 eval "require $dbicschema;"
53 croak "Can't load $dbicschema ($_)";
57 my $schema = $tr->schema;
60 $schema->name( ref($dbicschema) . " v" . ($dbicschema->schema_version || '1.x'))
61 unless ($schema->name);
63 my @monikers = sort $dbicschema->sources;
65 my $ref = ref $limit_sources || '';
66 $dbicschema->throw_exception ("'sources' parameter must be an array or hash ref")
67 unless( $ref eq 'ARRAY' || ref eq 'HASH' );
69 # limit monikers to those specified in
71 if ($ref eq 'ARRAY') {
72 $sources->{$_} = 1 for (@$limit_sources);
74 $sources = $limit_sources;
76 @monikers = grep { $sources->{$_} } @monikers;
80 my(%table_monikers, %view_monikers);
81 for my $moniker (@monikers){
82 my $source = $dbicschema->source($moniker);
83 if ( $source->isa('DBIx::Class::ResultSource::Table') ) {
84 $table_monikers{$moniker}++;
85 } elsif( $source->isa('DBIx::Class::ResultSource::View') ){
86 next if $source->is_virtual;
87 $view_monikers{$moniker}++;
92 foreach my $moniker (sort keys %table_monikers)
94 my $source = $dbicschema->source($moniker);
95 my $table_name = $source->name;
97 # FIXME - this isn't the right way to do it, but sqlt does not
98 # support quoting properly to be signaled about this
99 $table_name = $$table_name if ref $table_name eq 'SCALAR';
101 # It's possible to have multiple DBIC sources using the same table
102 next if $tables{$table_name};
104 $tables{$table_name}{source} = $source;
105 my $table = $tables{$table_name}{object} = SQL::Translator::Schema::Table->new(
109 foreach my $col ($source->columns)
111 # assuming column_info in dbic is the same as DBI (?)
112 # data_type is a number, column_type is text?
116 is_auto_increment => 0,
119 %{$source->column_info($col)}
121 if ($colinfo{is_nullable}) {
122 $colinfo{default} = '' unless exists $colinfo{default};
124 my $f = $table->add_field(%colinfo)
125 || $dbicschema->throw_exception ($table->error);
128 my @primary = $source->primary_columns;
130 $table->primary_key(@primary) if @primary;
132 my %unique_constraints = $source->unique_constraints;
133 foreach my $uniq (sort keys %unique_constraints) {
134 if (!$source->_compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
135 $table->add_constraint(
138 fields => $unique_constraints{$uniq}
143 my @rels = $source->relationships();
147 # global add_fk_index set in parser_args
148 my $add_fk_index = (exists $args->{add_fk_index} && ! $args->{add_fk_index}) ? 0 : 1;
150 foreach my $rel (sort @rels)
153 my $rel_info = $source->relationship_info($rel);
155 # Ignore any rel cond that isn't a straight hash
156 next unless ref $rel_info->{cond} eq 'HASH';
158 my $relsource = $source->related_source($rel);
160 # related sources might be excluded via a {sources} filter or might be views
161 next unless exists $table_monikers{$relsource->source_name};
163 my $rel_table = $relsource->name;
165 # FIXME - this isn't the right way to do it, but sqlt does not
166 # support quoting properly to be signaled about this
167 $rel_table = $$rel_table if ref $rel_table eq 'SCALAR';
169 my $reverse_rels = $source->reverse_relationship_info($rel);
170 my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
172 # Force the order of @cond to match the order of ->add_columns
174 my %other_columns_idx = map {'foreign.'.$_ => ++$idx } $relsource->columns;
175 my @cond = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } keys(%{$rel_info->{cond}});
177 # Get the key information, mapping off the foreign/self markers
178 my @refkeys = map {/^\w+\.(\w+)$/} @cond;
179 my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
181 # determine if this relationship is a self.fk => foreign.pk (i.e. belongs_to)
184 #first it can be specified explicitly
185 if ( exists $rel_info->{attrs}{is_foreign_key_constraint} ) {
186 $fk_constraint = $rel_info->{attrs}{is_foreign_key_constraint};
188 # it can not be multi
189 elsif ( $rel_info->{attrs}{accessor}
190 && $rel_info->{attrs}{accessor} eq 'multi' ) {
193 # if indeed single, check if all self.columns are our primary keys.
194 # this is supposed to indicate a has_one/might_have...
195 # where's the introspection!!?? :)
197 $fk_constraint = not $source->_compare_relationship_keys(\@keys, \@primary);
201 for my $c (qw/delete update/) {
202 if (exists $rel_info->{attrs}{"on_$c"}) {
203 if ($fk_constraint) {
204 $cascade->{$c} = $rel_info->{attrs}{"on_$c"};
206 elsif ( $rel_info->{attrs}{"on_$c"} ) {
207 carp "SQLT attribute 'on_$c' was supplied for relationship '$moniker/$rel', which does not appear to be a foreign constraint. "
208 . "If you are sure that SQLT must generate a constraint for this relationship, add 'is_foreign_key_constraint => 1' to the attributes.\n";
211 elsif (defined $otherrelationship and $otherrelationship->{attrs}{$c eq 'update' ? 'cascade_copy' : 'cascade_delete'}) {
212 $cascade->{$c} = 'CASCADE';
217 # Constraints are added only if applicable
218 next unless $fk_constraint;
220 # Make sure we dont create the same foreign key constraint twice
221 my $key_test = join("\x00", sort @keys);
222 next if $created_FK_rels{$rel_table}->{$key_test};
225 $created_FK_rels{$rel_table}->{$key_test} = 1;
227 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
229 # calculate dependencies: do not consider deferrable constraints and
230 # self-references for dependency calculations
231 if (! $is_deferrable and $rel_table ne $table_name) {
232 $tables{$table_name}{foreign_table_deps}{$rel_table}++;
235 $table->add_constraint(
236 type => 'foreign_key',
237 name => join('_', $table_name, 'fk', @keys),
239 reference_fields => \@refkeys,
240 reference_table => $rel_table,
241 on_delete => uc ($cascade->{delete} || ''),
242 on_update => uc ($cascade->{update} || ''),
243 (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
246 # global parser_args add_fk_index param can be overridden on the rel def
247 my $add_fk_index_rel = (exists $rel_info->{attrs}{add_fk_index}) ? $rel_info->{attrs}{add_fk_index} : $add_fk_index;
249 # Check that we do not create an index identical to the PK index
250 # (some RDBMS croak on this, and it generally doesn't make much sense)
251 # NOTE: we do not sort the key columns because the order of
252 # columns is important for indexes and two indexes with the
253 # same cols but different order are allowed and sometimes
255 next if join("\x00", @keys) eq join("\x00", @primary);
257 if ($add_fk_index_rel) {
258 my $index = $table->add_index(
259 name => join('_', $table_name, 'idx', @keys),
270 # attach the tables to the schema in dependency order
272 map { $_ => _resolve_deps ($_, \%tables) } (keys %tables)
277 keys %{$dependencies->{$a} || {} } <=> keys %{ $dependencies->{$b} || {} }
283 $schema->add_table ($tables{$table}{object});
284 $tables{$table}{source} -> _invoke_sqlt_deploy_hook( $tables{$table}{object} );
286 # the hook might have already removed the table
287 if ($schema->get_table($table) && $table =~ /^ \s* \( \s* SELECT \s+/ix) {
290 Custom SQL through ->name(\'( SELECT ...') is DEPRECATED, for more details see
291 "Arbitrary SQL through a custom ResultSource" in DBIx::Class::Manual::Cookbook
292 or http://search.cpan.org/dist/DBIx-Class/lib/DBIx/Class/Manual/Cookbook.pod
296 # remove the table as there is no way someone might want to
297 # actually deploy this
298 $schema->drop_table ($table);
303 my @views = map { $dbicschema->source($_) } keys %view_monikers;
304 my $view_dependencies;
306 ### This is a loop instead of a map because
307 ### passing an object to the sub failed--gave
308 ### $view->name instead of the $view!
310 for my $view (@views) {
311 $view_dependencies->{ $view->name } =
312 _resolve_view_deps ( { view => $view }, \%view_monikers );
317 keys %{ $view_dependencies->{ $a->name } || {} } <=>
318 keys %{ $view_dependencies->{ $b->name } || {} }
319 || $a->source_name cmp $b->source_name
321 map { $dbicschema->source($_) }
324 foreach my $source (@view_sources)
326 my $view_name = $source->name;
328 # FIXME - this isn't the right way to do it, but sqlt does not
329 # support quoting properly to be signaled about this
330 $view_name = $$view_name if ref $view_name eq 'SCALAR';
332 # Skip custom query sources
333 next if ref $view_name;
335 # Its possible to have multiple DBIC source using same table
336 next if $views{$view_name}++;
338 $dbicschema->throw_exception ("view $view_name is missing a view_definition")
339 unless $source->view_definition;
341 my $view = $schema->add_view (
343 fields => [ $source->columns ],
344 $source->view_definition ? ( 'sql' => $source->view_definition ) : ()
345 ) || $dbicschema->throw_exception ($schema->error);
347 $source->_invoke_sqlt_deploy_hook($view);
351 if ($dbicschema->can('sqlt_deploy_hook')) {
352 $dbicschema->sqlt_deploy_hook($schema);
359 # Quick and dirty dependency graph calculator
362 my ($table, $tables, $seen) = @_;
367 # copy and bump all deps by one (so we can reconstruct the chain)
368 my %seen = map { $_ => $seen->{$_} + 1 } (keys %$seen);
371 for my $dep (keys %{$tables->{$table}{foreign_table_deps}} ) {
375 # warn and remove the circular constraint so we don't get flooded with the same warning over and over
376 #carp sprintf ("Circular dependency detected, schema may not be deployable:\n%s\n",
377 # join (' -> ', (sort { $seen->{$b} <=> $seen->{$a} } (keys %$seen) ), $table, $dep )
379 #delete $tables->{$table}{foreign_table_deps}{$dep};
384 my $subdeps = _resolve_deps ($dep, $tables, \%seen);
385 $ret->{$_} += $subdeps->{$_} for ( keys %$subdeps );
393 sub _resolve_view_deps {
394 my ( $view0, $monikers, $seen ) = @_;
395 my $view = $view0->{view};
399 # copy and bump all deps by one (so we can reconstruct the chain)
400 my %seen = map { $_ => $seen->{$_} + 1 } ( keys %$seen );
401 $seen{ $view->source_name } = 1;
403 for my $dep ( keys %{ $view->{deploy_depends_on} } ) {
404 if ( $seen->{$dep} ) {
407 my ($new_source_name) =
408 grep { $view->schema->source($_)->name eq $dep }
409 @{ [ $view->schema->sources ] };
410 my $subdeps = _resolve_view_deps(
411 { view => $view->schema->source($new_source_name) },
412 $monikers, \%seen, );
413 $ret->{$_} += $subdeps->{$_} for ( keys %$subdeps );
424 SQL::Translator::Parser::DBIx::Class - Create a SQL::Translator schema
425 from a DBIx::Class::Schema instance
431 my $schema = MyApp::Schema->connect("dbi:SQLite:something.db");
432 $schema->create_ddl_dir();
440 my $schema = MyApp::Schema->connect;
441 my $trans = SQL::Translator->new (
442 parser => 'SQL::Translator::Parser::DBIx::Class',
451 producer => 'SQLite',
452 ) or die SQL::Translator->error;
453 my $out = $trans->translate() or die $trans->error;
457 This class requires L<SQL::Translator> installed to work.
459 C<SQL::Translator::Parser::DBIx::Class> reads a DBIx::Class schema,
460 interrogates the columns, and stuffs it all in an $sqlt_schema object.
462 Its primary use is in deploying database layouts described as a set
463 of L<DBIx::Class> classes, to a database. To do this, see
464 L<DBIx::Class::Schema/deploy>.
466 This can also be achieved by having DBIx::Class export the schema as a
467 set of SQL files ready for import into your database, or passed to
468 other machines that need to have your application installed but don't
469 have SQL::Translator installed. To do this see
470 L<DBIx::Class::Schema/create_ddl_dir>.
472 =head1 PARSER OPTIONS
476 Create an index for each foreign key.
477 Enabled by default, as having indexed foreign key columns is normally the
478 sensible thing to do.
484 =item Arguments: \@class_names
488 Limit the amount of parsed sources by supplying an explicit list of source names.
492 L<SQL::Translator>, L<DBIx::Class::Schema>
496 See L<DBIx::Class/CONTRIBUTORS>.
500 You may distribute this code under the same terms as Perl itself.