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 our ($DEBUG, $VERSION, @EXPORT_OK);
13 $DEBUG = 0 unless defined $DEBUG;
16 use SQL::Translator::Utils qw(debug normalize_name);
17 use DBIx::Class::Carp qw/^SQL::Translator|^DBIx::Class|^Try::Tiny/;
18 use DBIx::Class::Exception;
19 use Scalar::Util qw/weaken blessed/;
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 # -------------------------------------------------------------------
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 # this is a hack to prevent schema leaks due to a retarded SQLT implementation
44 # DO NOT REMOVE (until SQLT2 is out, the all of this will be rewritten anyway)
46 for $_[1], $dbicschema, @{$args}{qw/DBIx::Schema DBIx::Class::Schema package/};
48 DBIx::Class::Exception->throw('No DBIx::Class::Schema') unless ($dbicschema);
49 if (!ref $dbicschema) {
50 eval "require $dbicschema"
51 or DBIx::Class::Exception->throw("Can't load $dbicschema: $@");
54 my $schema = $tr->schema;
57 $schema->name( ref($dbicschema) . " v" . ($dbicschema->schema_version || '1.x'))
58 unless ($schema->name);
60 my @monikers = sort $dbicschema->sources;
62 my $ref = ref $limit_sources || '';
63 $dbicschema->throw_exception ("'sources' parameter must be an array or hash ref")
64 unless( $ref eq 'ARRAY' || ref eq 'HASH' );
66 # limit monikers to those specified in
68 if ($ref eq 'ARRAY') {
69 $sources->{$_} = 1 for (@$limit_sources);
71 $sources = $limit_sources;
73 @monikers = grep { $sources->{$_} } @monikers;
77 my(%table_monikers, %view_monikers);
78 for my $moniker (@monikers){
79 my $source = $dbicschema->source($moniker);
80 if ( $source->isa('DBIx::Class::ResultSource::Table') ) {
81 $table_monikers{$moniker}++;
82 } elsif( $source->isa('DBIx::Class::ResultSource::View') ){
83 next if $source->is_virtual;
84 $view_monikers{$moniker}++;
89 foreach my $moniker (sort keys %table_monikers)
91 my $source = $dbicschema->source($moniker);
92 my $table_name = $source->name;
94 # FIXME - this isn't the right way to do it, but sqlt does not
95 # support quoting properly to be signaled about this
96 $table_name = $$table_name if ref $table_name eq 'SCALAR';
98 # It's possible to have multiple DBIC sources using the same table
99 next if $tables{$table_name};
101 $tables{$table_name}{source} = $source;
102 my $table = $tables{$table_name}{object} = SQL::Translator::Schema::Table->new(
106 foreach my $col ($source->columns)
108 # assuming column_info in dbic is the same as DBI (?)
109 # data_type is a number, column_type is text?
113 is_auto_increment => 0,
116 %{$source->column_info($col)}
118 if ($colinfo{is_nullable}) {
119 $colinfo{default} = '' unless exists $colinfo{default};
121 my $f = $table->add_field(%colinfo)
122 || $dbicschema->throw_exception ($table->error);
125 my @primary = $source->primary_columns;
127 $table->primary_key(@primary) if @primary;
129 my %unique_constraints = $source->unique_constraints;
130 foreach my $uniq (sort keys %unique_constraints) {
131 if (!$source->_compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
132 $table->add_constraint(
135 fields => $unique_constraints{$uniq}
140 my @rels = $source->relationships();
144 # global add_fk_index set in parser_args
145 my $add_fk_index = (exists $args->{add_fk_index} && ! $args->{add_fk_index}) ? 0 : 1;
147 foreach my $rel (sort @rels)
150 my $rel_info = $source->relationship_info($rel);
152 # Ignore any rel cond that isn't a straight hash
153 next unless ref $rel_info->{cond} eq 'HASH';
155 my $relsource = try { $source->related_source($rel) };
156 unless ($relsource) {
157 warn "Ignoring relationship '$rel' - related resultsource '$rel_info->{class}' is not registered with this schema\n";
161 # related sources might be excluded via a {sources} filter or might be views
162 next unless exists $table_monikers{$relsource->source_name};
164 my $rel_table = $relsource->name;
166 # FIXME - this isn't the right way to do it, but sqlt does not
167 # support quoting properly to be signaled about this
168 $rel_table = $$rel_table if ref $rel_table eq 'SCALAR';
170 my $reverse_rels = $source->reverse_relationship_info($rel);
171 my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
173 # Force the order of @cond to match the order of ->add_columns
175 my %other_columns_idx = map {'foreign.'.$_ => ++$idx } $relsource->columns;
176 my @cond = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } keys(%{$rel_info->{cond}});
178 # Get the key information, mapping off the foreign/self markers
179 my @refkeys = map {/^\w+\.(\w+)$/} @cond;
180 my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
182 # determine if this relationship is a self.fk => foreign.pk (i.e. belongs_to)
185 #first it can be specified explicitly
186 if ( exists $rel_info->{attrs}{is_foreign_key_constraint} ) {
187 $fk_constraint = $rel_info->{attrs}{is_foreign_key_constraint};
189 # it can not be multi
190 elsif ( $rel_info->{attrs}{accessor}
191 && $rel_info->{attrs}{accessor} eq 'multi' ) {
194 # if indeed single, check if all self.columns are our primary keys.
195 # this is supposed to indicate a has_one/might_have...
196 # where's the introspection!!?? :)
198 $fk_constraint = not $source->_compare_relationship_keys(\@keys, \@primary);
202 for my $c (qw/delete update/) {
203 if (exists $rel_info->{attrs}{"on_$c"}) {
204 if ($fk_constraint) {
205 $cascade->{$c} = $rel_info->{attrs}{"on_$c"};
207 elsif ( $rel_info->{attrs}{"on_$c"} ) {
208 carp "SQLT attribute 'on_$c' was supplied for relationship '$moniker/$rel', which does not appear to be a foreign constraint. "
209 . "If you are sure that SQLT must generate a constraint for this relationship, add 'is_foreign_key_constraint => 1' to the attributes.\n";
212 elsif (defined $otherrelationship and $otherrelationship->{attrs}{$c eq 'update' ? 'cascade_copy' : 'cascade_delete'}) {
213 $cascade->{$c} = 'CASCADE';
218 # Constraints are added only if applicable
219 next unless $fk_constraint;
221 # Make sure we dont create the same foreign key constraint twice
222 my $key_test = join("\x00", sort @keys);
223 next if $created_FK_rels{$rel_table}->{$key_test};
226 $created_FK_rels{$rel_table}->{$key_test} = 1;
228 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
230 # calculate dependencies: do not consider deferrable constraints and
231 # self-references for dependency calculations
232 if (! $is_deferrable and $rel_table ne $table_name) {
233 $tables{$table_name}{foreign_table_deps}{$rel_table}++;
236 $table->add_constraint(
237 type => 'foreign_key',
238 name => join('_', $table_name, 'fk', @keys),
240 reference_fields => \@refkeys,
241 reference_table => $rel_table,
242 on_delete => uc ($cascade->{delete} || ''),
243 on_update => uc ($cascade->{update} || ''),
244 (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
247 # global parser_args add_fk_index param can be overridden on the rel def
248 my $add_fk_index_rel = (exists $rel_info->{attrs}{add_fk_index}) ? $rel_info->{attrs}{add_fk_index} : $add_fk_index;
250 # Check that we do not create an index identical to the PK index
251 # (some RDBMS croak on this, and it generally doesn't make much sense)
252 # NOTE: we do not sort the key columns because the order of
253 # columns is important for indexes and two indexes with the
254 # same cols but different order are allowed and sometimes
256 next if join("\x00", @keys) eq join("\x00", @primary);
258 if ($add_fk_index_rel) {
259 my $index = $table->add_index(
260 name => join('_', $table_name, 'idx', @keys),
271 # attach the tables to the schema in dependency order
272 my $dependencies = _get_deps($dbicschema, 'Table');
276 keys %{$dependencies->{$a} || {} } <=> keys %{ $dependencies->{$b} || {} }
282 $schema->add_table ($tables{$table}{object});
283 $tables{$table}{source} -> _invoke_sqlt_deploy_hook( $tables{$table}{object} );
285 # the hook might have already removed the table
286 if ($schema->get_table($table) && $table =~ /^ \s* \( \s* SELECT \s+/ix) {
289 Custom SQL through ->name(\'( SELECT ...') is DEPRECATED, for more details see
290 "Arbitrary SQL through a custom ResultSource" in DBIx::Class::Manual::Cookbook
291 or http://search.cpan.org/dist/DBIx-Class/lib/DBIx/Class/Manual/Cookbook.pod
295 # remove the table as there is no way someone might want to
296 # actually deploy this
297 $schema->drop_table ($table);
302 my @views = map { $dbicschema->source($_) } keys %view_monikers;
304 my $view_dependencies = _get_deps($dbicschema, 'View');
308 keys %{ $view_dependencies->{ $a->source_name } || {} } <=>
309 keys %{ $view_dependencies->{ $b->source_name } || {} }
310 || $a->source_name cmp $b->source_name
312 map { $dbicschema->source($_) }
315 foreach my $source (@view_sources)
317 my $view_name = $source->name;
319 # FIXME - this isn't the right way to do it, but sqlt does not
320 # support quoting properly to be signaled about this
321 $view_name = $$view_name if ref $view_name eq 'SCALAR';
323 # Skip custom query sources
324 next if ref $view_name;
326 # Its possible to have multiple DBIC source using same table
327 next if $views{$view_name}++;
329 $dbicschema->throw_exception ("view $view_name is missing a view_definition")
330 unless $source->view_definition;
332 my $view = $schema->add_view (
334 fields => [ $source->columns ],
335 $source->view_definition ? ( 'sql' => $source->view_definition ) : ()
336 ) || $dbicschema->throw_exception ($schema->error);
338 $source->_invoke_sqlt_deploy_hook($view);
342 if ($dbicschema->can('sqlt_deploy_hook')) {
343 $dbicschema->sqlt_deploy_hook($schema);
355 grep { $_->[1]->isa("DBIx::Class::ResultSource::$type") }
356 map +[$_, $schema->source($_)],
359 my %s_dep = %{$schema->source_tree({ limit_sources => \%sources })};
361 for my $s (keys %s_dep) {
362 $t_deps{$schema->source($s)->name} = {
364 $schema->source($_)->name => 1,
375 SQL::Translator::Parser::DBIx::Class - Create a SQL::Translator schema
376 from a DBIx::Class::Schema instance
382 my $schema = MyApp::Schema->connect("dbi:SQLite:something.db");
383 $schema->create_ddl_dir();
391 my $schema = MyApp::Schema->connect;
392 my $trans = SQL::Translator->new (
393 parser => 'SQL::Translator::Parser::DBIx::Class',
402 producer => 'SQLite',
403 ) or die SQL::Translator->error;
404 my $out = $trans->translate() or die $trans->error;
408 This class requires L<SQL::Translator> installed to work.
410 C<SQL::Translator::Parser::DBIx::Class> reads a DBIx::Class schema,
411 interrogates the columns, and stuffs it all in an $sqlt_schema object.
413 Its primary use is in deploying database layouts described as a set
414 of L<DBIx::Class> classes, to a database. To do this, see
415 L<DBIx::Class::Schema/deploy>.
417 This can also be achieved by having DBIx::Class export the schema as a
418 set of SQL files ready for import into your database, or passed to
419 other machines that need to have your application installed but don't
420 have SQL::Translator installed. To do this see
421 L<DBIx::Class::Schema/create_ddl_dir>.
423 =head1 PARSER OPTIONS
427 Create an index for each foreign key.
428 Enabled by default, as having indexed foreign key columns is normally the
429 sensible thing to do.
435 =item Arguments: \@class_names
439 Limit the amount of parsed sources by supplying an explicit list of source names.
443 L<SQL::Translator>, L<DBIx::Class::Schema>
447 See L<DBIx::Class/CONTRIBUTORS>.
451 You may distribute this code under the same terms as Perl itself.