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/;
21 use base qw(Exporter);
23 @EXPORT_OK = qw(parse);
25 # -------------------------------------------------------------------
28 # setting parser_args => { add_fk_index => 0 } will prevent
29 # the auto-generation of an index for each FK.
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 # -------------------------------------------------------------------
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]);
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'};
45 croak 'No DBIx::Class::Schema' unless ($dbicschema);
46 if (!ref $dbicschema) {
48 eval "require $dbicschema;"
51 croak "Can't load $dbicschema ($_)";
55 my $schema = $tr->schema;
58 $schema->name( ref($dbicschema) . " v" . ($dbicschema->schema_version || '1.x'))
59 unless ($schema->name);
61 my @monikers = sort $dbicschema->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' );
67 # limit monikers to those specified in
69 if ($ref eq 'ARRAY') {
70 $sources->{$_} = 1 for (@$limit_sources);
72 $sources = $limit_sources;
74 @monikers = grep { $sources->{$_} } @monikers;
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}++;
90 foreach my $moniker (sort keys %table_monikers)
92 my $source = $dbicschema->source($moniker);
93 my $table_name = $source->name;
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';
99 # It's possible to have multiple DBIC sources using the same table
100 next if $tables{$table_name};
102 $tables{$table_name}{source} = $source;
103 my $table = $tables{$table_name}{object} = SQL::Translator::Schema::Table->new(
107 foreach my $col ($source->columns)
109 # assuming column_info in dbic is the same as DBI (?)
110 # data_type is a number, column_type is text?
114 is_auto_increment => 0,
117 %{$source->column_info($col)}
119 if ($colinfo{is_nullable}) {
120 $colinfo{default} = '' unless exists $colinfo{default};
122 my $f = $table->add_field(%colinfo)
123 || $dbicschema->throw_exception ($table->error);
126 my @primary = $source->primary_columns;
128 $table->primary_key(@primary) if @primary;
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(
136 fields => $unique_constraints{$uniq}
141 my @rels = $source->relationships();
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;
148 foreach my $rel (sort @rels)
151 my $rel_info = $source->relationship_info($rel);
153 # Ignore any rel cond that isn't a straight hash
154 next unless ref $rel_info->{cond} eq 'HASH';
156 my $relsource = $source->related_source($rel);
158 # related sources might be excluded via a {sources} filter or might be views
159 next unless exists $table_monikers{$relsource->source_name};
161 my $rel_table = $relsource->name;
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';
167 my $reverse_rels = $source->reverse_relationship_info($rel);
168 my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
170 # Force the order of @cond to match the order of ->add_columns
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}});
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;
179 # determine if this relationship is a self.fk => foreign.pk (i.e. belongs_to)
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};
186 # it can not be multi
187 elsif ( $rel_info->{attrs}{accessor}
188 && $rel_info->{attrs}{accessor} eq 'multi' ) {
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!!?? :)
195 $fk_constraint = not $source->_compare_relationship_keys(\@keys, \@primary);
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"};
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";
209 elsif (defined $otherrelationship and $otherrelationship->{attrs}{$c eq 'update' ? 'cascade_copy' : 'cascade_delete'}) {
210 $cascade->{$c} = 'CASCADE';
215 # Constraints are added only if applicable
216 next unless $fk_constraint;
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};
223 $created_FK_rels{$rel_table}->{$key_test} = 1;
225 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
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}++;
233 $table->add_constraint(
234 type => 'foreign_key',
235 name => join('_', $table_name, 'fk', @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 ) : ()),
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;
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
253 next if join("\x00", @keys) eq join("\x00", @primary);
255 if ($add_fk_index_rel) {
256 my $index = $table->add_index(
257 name => join('_', $table_name, 'idx', @keys),
268 # attach the tables to the schema in dependency order
270 map { $_ => _resolve_deps ($_, \%tables) } (keys %tables)
275 keys %{$dependencies->{$a} || {} } <=> keys %{ $dependencies->{$b} || {} }
281 $schema->add_table ($tables{$table}{object});
282 $tables{$table}{source} -> _invoke_sqlt_deploy_hook( $tables{$table}{object} );
284 # the hook might have already removed the table
285 if ($schema->get_table($table) && $table =~ /^ \s* \( \s* SELECT \s+/ix) {
288 Custom SQL through ->name(\'( SELECT ...') is DEPRECATED, for more details see
289 "Arbitrary SQL through a custom ResultSource" in DBIx::Class::Manual::Cookbook
290 or http://search.cpan.org/dist/DBIx-Class/lib/DBIx/Class/Manual/Cookbook.pod
294 # remove the table as there is no way someone might want to
295 # actually deploy this
296 $schema->drop_table ($table);
304 keys %{ $a->deploy_depends_on || {} }
306 keys %{ $b->deploy_depends_on || {} }
308 $a->source_name cmp $b->source_name
310 map { $dbicschema->source($_) }
313 foreach my $source (@view_sources)
315 my $view_name = $source->name;
317 # FIXME - this isn't the right way to do it, but sqlt does not
318 # support quoting properly to be signaled about this
319 $view_name = $$view_name if ref $view_name eq 'SCALAR';
321 # Skip custom query sources
322 next if ref $view_name;
324 # Its possible to have multiple DBIC source using same table
325 next if $views{$view_name}++;
327 $dbicschema->throw_exception ("view $view_name is missing a view_definition")
328 unless $source->view_definition;
330 my $view = $schema->add_view (
332 fields => [ $source->columns ],
333 $source->view_definition ? ( 'sql' => $source->view_definition ) : ()
334 ) || $dbicschema->throw_exception ($schema->error);
336 $source->_invoke_sqlt_deploy_hook($view);
340 if ($dbicschema->can('sqlt_deploy_hook')) {
341 $dbicschema->sqlt_deploy_hook($schema);
348 # Quick and dirty dependency graph calculator
351 my ($table, $tables, $seen) = @_;
356 # copy and bump all deps by one (so we can reconstruct the chain)
357 my %seen = map { $_ => $seen->{$_} + 1 } (keys %$seen);
360 for my $dep (keys %{$tables->{$table}{foreign_table_deps}} ) {
364 # warn and remove the circular constraint so we don't get flooded with the same warning over and over
365 #carp sprintf ("Circular dependency detected, schema may not be deployable:\n%s\n",
366 # join (' -> ', (sort { $seen->{$b} <=> $seen->{$a} } (keys %$seen) ), $table, $dep )
368 #delete $tables->{$table}{foreign_table_deps}{$dep};
373 my $subdeps = _resolve_deps ($dep, $tables, \%seen);
374 $ret->{$_} += $subdeps->{$_} for ( keys %$subdeps );
386 SQL::Translator::Parser::DBIx::Class - Create a SQL::Translator schema
387 from a DBIx::Class::Schema instance
393 my $schema = MyApp::Schema->connect("dbi:SQLite:something.db");
394 $schema->create_ddl_dir();
402 my $schema = MyApp::Schema->connect;
403 my $trans = SQL::Translator->new (
404 parser => 'SQL::Translator::Parser::DBIx::Class',
413 producer => 'SQLite',
414 ) or die SQL::Translator->error;
415 my $out = $trans->translate() or die $trans->error;
419 This class requires L<SQL::Translator> installed to work.
421 C<SQL::Translator::Parser::DBIx::Class> reads a DBIx::Class schema,
422 interrogates the columns, and stuffs it all in an $sqlt_schema object.
424 Its primary use is in deploying database layouts described as a set
425 of L<DBIx::Class> classes, to a database. To do this, see
426 L<DBIx::Class::Schema/deploy>.
428 This can also be achieved by having DBIx::Class export the schema as a
429 set of SQL files ready for import into your database, or passed to
430 other machines that need to have your application installed but don't
431 have SQL::Translator installed. To do this see
432 L<DBIx::Class::Schema/create_ddl_dir>.
434 =head1 PARSER OPTIONS
438 Create an index for each foreign key.
439 Enabled by default, as having indexed foreign key columns is normally the
440 sensible thing to do.
446 =item Arguments: \@class_names
450 Limit the amount of parsed sources by supplying an explicit list of source names.
454 L<SQL::Translator>, L<DBIx::Class::Schema>
458 See L<DBIx::Class/CONTRIBUTORS>.
462 You may distribute this code under the same terms as Perl itself.