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 # -------------------------------------------------------------------
34 my $args = $tr->parser_args;
35 my $dbicschema = $args->{'DBIx::Class::Schema'} || $args->{"DBIx::Schema"} ||$data;
36 $dbicschema ||= $args->{'package'};
37 my $limit_sources = $args->{'sources'};
39 croak 'No DBIx::Class::Schema' unless ($dbicschema);
40 if (!ref $dbicschema) {
41 eval "use $dbicschema;";
42 croak "Can't load $dbicschema ($@)" if($@);
45 my $schema = $tr->schema;
48 $schema->name( ref($dbicschema) . " v" . ($dbicschema->schema_version || '1.x'))
49 unless ($schema->name);
51 my @monikers = sort $dbicschema->sources;
53 my $ref = ref $limit_sources || '';
54 $dbicschema->throw_exception ("'sources' parameter must be an array or hash ref")
55 unless( $ref eq 'ARRAY' || ref eq 'HASH' );
57 # limit monikers to those specified in
59 if ($ref eq 'ARRAY') {
60 $sources->{$_} = 1 for (@$limit_sources);
62 $sources = $limit_sources;
64 @monikers = grep { $sources->{$_} } @monikers;
68 my(%table_monikers, %view_monikers);
69 for my $moniker (@monikers){
70 my $source = $dbicschema->source($moniker);
71 if ( $source->isa('DBIx::Class::ResultSource::Table') ) {
72 $table_monikers{$moniker}++;
73 } elsif( $source->isa('DBIx::Class::ResultSource::View') ){
74 next if $source->is_virtual;
75 $view_monikers{$moniker}++;
80 foreach my $moniker (sort keys %table_monikers)
82 my $source = $dbicschema->source($moniker);
83 my $table_name = $source->name;
85 # FIXME - this isn't the right way to do it, but sqlt does not
86 # support quoting properly to be signaled about this
87 $table_name = $$table_name if ref $table_name eq 'SCALAR';
89 # It's possible to have multiple DBIC sources using the same table
90 next if $tables{$table_name};
92 $tables{$table_name}{source} = $source;
93 my $table = $tables{$table_name}{object} = SQL::Translator::Schema::Table->new(
97 foreach my $col ($source->columns)
99 # assuming column_info in dbic is the same as DBI (?)
100 # data_type is a number, column_type is text?
104 is_auto_increment => 0,
107 %{$source->column_info($col)}
109 if ($colinfo{is_nullable}) {
110 $colinfo{default} = '' unless exists $colinfo{default};
112 my $f = $table->add_field(%colinfo)
113 || $dbicschema->throw_exception ($table->error);
116 my @primary = $source->primary_columns;
118 $table->primary_key(@primary) if @primary;
120 my %unique_constraints = $source->unique_constraints;
121 foreach my $uniq (sort keys %unique_constraints) {
122 if (!$source->_compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
123 $table->add_constraint(
126 fields => $unique_constraints{$uniq}
131 my @rels = $source->relationships();
135 # global add_fk_index set in parser_args
136 my $add_fk_index = (exists $args->{add_fk_index} && ! $args->{add_fk_index}) ? 0 : 1;
138 foreach my $rel (sort @rels)
141 my $rel_info = $source->relationship_info($rel);
143 # Ignore any rel cond that isn't a straight hash
144 next unless ref $rel_info->{cond} eq 'HASH';
146 my $relsource = $source->related_source($rel);
148 # related sources might be excluded via a {sources} filter or might be views
149 next unless exists $table_monikers{$relsource->source_name};
151 my $rel_table = $relsource->name;
153 # FIXME - this isn't the right way to do it, but sqlt does not
154 # support quoting properly to be signaled about this
155 $rel_table = $$rel_table if ref $rel_table eq 'SCALAR';
157 my $reverse_rels = $source->reverse_relationship_info($rel);
158 my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
160 # Force the order of @cond to match the order of ->add_columns
162 my %other_columns_idx = map {'foreign.'.$_ => ++$idx } $relsource->columns;
163 my @cond = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } keys(%{$rel_info->{cond}});
165 # Get the key information, mapping off the foreign/self markers
166 my @refkeys = map {/^\w+\.(\w+)$/} @cond;
167 my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
169 # determine if this relationship is a self.fk => foreign.pk (i.e. belongs_to)
172 #first it can be specified explicitly
173 if ( exists $rel_info->{attrs}{is_foreign_key_constraint} ) {
174 $fk_constraint = $rel_info->{attrs}{is_foreign_key_constraint};
176 # it can not be multi
177 elsif ( $rel_info->{attrs}{accessor}
178 && $rel_info->{attrs}{accessor} eq 'multi' ) {
181 # if indeed single, check if all self.columns are our primary keys.
182 # this is supposed to indicate a has_one/might_have...
183 # where's the introspection!!?? :)
185 $fk_constraint = not $source->_compare_relationship_keys(\@keys, \@primary);
189 for my $c (qw/delete update/) {
190 if (exists $rel_info->{attrs}{"on_$c"}) {
191 if ($fk_constraint) {
192 $cascade->{$c} = $rel_info->{attrs}{"on_$c"};
194 elsif ( $rel_info->{attrs}{"on_$c"} ) {
195 carp "SQLT attribute 'on_$c' was supplied for relationship '$moniker/$rel', which does not appear to be a foreign constraint. "
196 . "If you are sure that SQLT must generate a constraint for this relationship, add 'is_foreign_key_constraint => 1' to the attributes.\n";
199 elsif (defined $otherrelationship and $otherrelationship->{attrs}{$c eq 'update' ? 'cascade_copy' : 'cascade_delete'}) {
200 $cascade->{$c} = 'CASCADE';
206 # Constraints are added only if applicable
207 next unless $fk_constraint;
209 # Make sure we dont create the same foreign key constraint twice
210 my $key_test = join("\x00", sort @keys);
211 next if $created_FK_rels{$rel_table}->{$key_test};
215 $created_FK_rels{$rel_table}->{$key_test} = 1;
217 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
219 # calculate dependencies: do not consider deferrable constraints and
220 # self-references for dependency calculations
221 if (! $is_deferrable and $rel_table ne $table_name) {
222 $tables{$table_name}{foreign_table_deps}{$rel_table}++;
225 $table->add_constraint(
226 type => 'foreign_key',
227 name => join('_', $table_name, 'fk', @keys),
229 reference_fields => \@refkeys,
230 reference_table => $rel_table,
231 on_delete => uc ($cascade->{delete} || ''),
232 on_update => uc ($cascade->{update} || ''),
233 (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
236 # global parser_args add_fk_index param can be overridden on the rel def
237 my $add_fk_index_rel = (exists $rel_info->{attrs}{add_fk_index}) ? $rel_info->{attrs}{add_fk_index} : $add_fk_index;
239 if ($add_fk_index_rel) {
240 my $index = $table->add_index(
241 name => join('_', $table_name, 'idx', @keys),
252 # attach the tables to the schema in dependency order
254 map { $_ => _resolve_deps ($_, \%tables) } (keys %tables)
258 keys %{$dependencies->{$a} || {} } <=> keys %{ $dependencies->{$b} || {} }
264 $schema->add_table ($tables{$table}{object});
265 $tables{$table}{source} -> _invoke_sqlt_deploy_hook( $tables{$table}{object} );
267 # the hook might have already removed the table
268 if ($schema->get_table($table) && $table =~ /^ \s* \( \s* SELECT \s+/ix) {
271 Custom SQL through ->name(\'( SELECT ...') is DEPRECATED, for more details see
272 "Arbitrary SQL through a custom ResultSource" in DBIx::Class::Manual::Cookbook
273 or http://search.cpan.org/dist/DBIx-Class/lib/DBIx/Class/Manual/Cookbook.pod
277 # remove the table as there is no way someone might want to
278 # actually deploy this
279 $schema->drop_table ($table);
284 foreach my $moniker (sort keys %view_monikers)
286 my $source = $dbicschema->source($moniker);
287 my $view_name = $source->name;
289 # FIXME - this isn't the right way to do it, but sqlt does not
290 # support quoting properly to be signaled about this
291 $view_name = $$view_name if ref $view_name eq 'SCALAR';
293 # Skip custom query sources
294 next if ref $view_name;
296 # Its possible to have multiple DBIC source using same table
297 next if $views{$view_name}++;
299 $dbicschema->throw_exception ("view $view_name is missing a view_definition")
300 unless $source->view_definition;
302 my $view = $schema->add_view (
304 fields => [ $source->columns ],
305 $source->view_definition ? ( 'sql' => $source->view_definition ) : ()
306 ) || $dbicschema->throw_exception ($schema->error);
308 $source->_invoke_sqlt_deploy_hook($view);
312 if ($dbicschema->can('sqlt_deploy_hook')) {
313 $dbicschema->sqlt_deploy_hook($schema);
320 # Quick and dirty dependency graph calculator
323 my ($table, $tables, $seen) = @_;
328 # copy and bump all deps by one (so we can reconstruct the chain)
329 my %seen = map { $_ => $seen->{$_} + 1 } (keys %$seen);
332 for my $dep (keys %{$tables->{$table}{foreign_table_deps}} ) {
336 # warn and remove the circular constraint so we don't get flooded with the same warning over and over
337 #carp sprintf ("Circular dependency detected, schema may not be deployable:\n%s\n",
338 # join (' -> ', (sort { $seen->{$b} <=> $seen->{$a} } (keys %$seen) ), $table, $dep )
340 #delete $tables->{$table}{foreign_table_deps}{$dep};
345 my $subdeps = _resolve_deps ($dep, $tables, \%seen);
346 $ret->{$_} += $subdeps->{$_} for ( keys %$subdeps );
358 SQL::Translator::Parser::DBIx::Class - Create a SQL::Translator schema
359 from a DBIx::Class::Schema instance
365 my $schema = MyApp::Schema->connect("dbi:SQLite:something.db");
366 $schema->create_ddl_dir();
374 my $schema = MyApp::Schema->connect;
375 my $trans = SQL::Translator->new (
376 parser => 'SQL::Translator::Parser::DBIx::Class',
377 parser_args => { package => $schema },
378 producer => 'SQLite',
379 ) or die SQL::Translator->error;
380 my $out = $trans->translate() or die $trans->error;
384 This class requires L<SQL::Translator> installed to work.
386 C<SQL::Translator::Parser::DBIx::Class> reads a DBIx::Class schema,
387 interrogates the columns, and stuffs it all in an $sqlt_schema object.
389 Its primary use is in deploying database layouts described as a set
390 of L<DBIx::Class> classes, to a database. To do this, see
391 L<DBIx::Class::Schema/deploy>.
393 This can also be achieved by having DBIx::Class export the schema as a
394 set of SQL files ready for import into your database, or passed to
395 other machines that need to have your application installed but don't
396 have SQL::Translator installed. To do this see
397 L<DBIx::Class::Schema/create_ddl_dir>.
401 L<SQL::Translator>, L<DBIx::Class::Schema>