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);
115 $table->primary_key($source->primary_columns);
117 my @primary = $source->primary_columns;
118 my %unique_constraints = $source->unique_constraints;
119 foreach my $uniq (sort keys %unique_constraints) {
120 if (!$source->_compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
121 $table->add_constraint(
124 fields => $unique_constraints{$uniq}
129 my @rels = $source->relationships();
133 # global add_fk_index set in parser_args
134 my $add_fk_index = (exists $args->{add_fk_index} && ! $args->{add_fk_index}) ? 0 : 1;
136 foreach my $rel (sort @rels)
139 my $rel_info = $source->relationship_info($rel);
141 # Ignore any rel cond that isn't a straight hash
142 next unless ref $rel_info->{cond} eq 'HASH';
144 my $relsource = $source->related_source($rel);
146 # related sources might be excluded via a {sources} filter or might be views
147 next unless exists $table_monikers{$relsource->source_name};
149 my $rel_table = $relsource->name;
151 # FIXME - this isn't the right way to do it, but sqlt does not
152 # support quoting properly to be signaled about this
153 $rel_table = $$rel_table if ref $rel_table eq 'SCALAR';
155 my $reverse_rels = $source->reverse_relationship_info($rel);
156 my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
158 # Force the order of @cond to match the order of ->add_columns
160 my %other_columns_idx = map {'foreign.'.$_ => ++$idx } $relsource->columns;
161 my @cond = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } keys(%{$rel_info->{cond}});
163 # Get the key information, mapping off the foreign/self markers
164 my @refkeys = map {/^\w+\.(\w+)$/} @cond;
165 my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
167 # determine if this relationship is a self.fk => foreign.pk (i.e. belongs_to)
170 #first it can be specified explicitly
171 if ( exists $rel_info->{attrs}{is_foreign_key_constraint} ) {
172 $fk_constraint = $rel_info->{attrs}{is_foreign_key_constraint};
174 # it can not be multi
175 elsif ( $rel_info->{attrs}{accessor}
176 && $rel_info->{attrs}{accessor} eq 'multi' ) {
179 # if indeed single, check if all self.columns are our primary keys.
180 # this is supposed to indicate a has_one/might_have...
181 # where's the introspection!!?? :)
183 $fk_constraint = not $source->_compare_relationship_keys(\@keys, \@primary);
187 for my $c (qw/delete update/) {
188 if (exists $rel_info->{attrs}{"on_$c"}) {
189 if ($fk_constraint) {
190 $cascade->{$c} = $rel_info->{attrs}{"on_$c"};
192 elsif ( $rel_info->{attrs}{"on_$c"} ) {
193 carp "SQLT attribute 'on_$c' was supplied for relationship '$moniker/$rel', which does not appear to be a foreign constraint. "
194 . "If you are sure that SQLT must generate a constraint for this relationship, add 'is_foreign_key_constraint => 1' to the attributes.\n";
197 elsif (defined $otherrelationship and $otherrelationship->{attrs}{$c eq 'update' ? 'cascade_copy' : 'cascade_delete'}) {
198 $cascade->{$c} = 'CASCADE';
204 # Constraints are added only if applicable
205 next unless $fk_constraint;
207 # Make sure we dont create the same foreign key constraint twice
208 my $key_test = join("\x00", sort @keys);
209 next if $created_FK_rels{$rel_table}->{$key_test};
213 $created_FK_rels{$rel_table}->{$key_test} = 1;
215 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
217 # calculate dependencies: do not consider deferrable constraints and
218 # self-references for dependency calculations
219 if (! $is_deferrable and $rel_table ne $table_name) {
220 $tables{$table_name}{foreign_table_deps}{$rel_table}++;
223 $table->add_constraint(
224 type => 'foreign_key',
225 name => join('_', $table_name, 'fk', @keys),
227 reference_fields => \@refkeys,
228 reference_table => $rel_table,
229 on_delete => uc ($cascade->{delete} || ''),
230 on_update => uc ($cascade->{update} || ''),
231 (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
234 # global parser_args add_fk_index param can be overridden on the rel def
235 my $add_fk_index_rel = (exists $rel_info->{attrs}{add_fk_index}) ? $rel_info->{attrs}{add_fk_index} : $add_fk_index;
237 if ($add_fk_index_rel) {
238 my $index = $table->add_index(
239 name => join('_', $table_name, 'idx', @keys),
250 # attach the tables to the schema in dependency order
252 map { $_ => _resolve_deps ($_, \%tables) } (keys %tables)
256 keys %{$dependencies->{$a} || {} } <=> keys %{ $dependencies->{$b} || {} }
262 $schema->add_table ($tables{$table}{object});
263 $tables{$table}{source} -> _invoke_sqlt_deploy_hook( $tables{$table}{object} );
265 # the hook might have already removed the table
266 if ($schema->get_table($table) && $table =~ /^ \s* \( \s* SELECT \s+/ix) {
269 Custom SQL through ->name(\'( SELECT ...') is DEPRECATED, for more details see
270 "Arbitrary SQL through a custom ResultSource" in DBIx::Class::Manual::Cookbook
271 or http://search.cpan.org/dist/DBIx-Class/lib/DBIx/Class/Manual/Cookbook.pod
275 # remove the table as there is no way someone might want to
276 # actually deploy this
277 $schema->drop_table ($table);
282 foreach my $moniker (sort keys %view_monikers)
284 my $source = $dbicschema->source($moniker);
285 my $view_name = $source->name;
287 # FIXME - this isn't the right way to do it, but sqlt does not
288 # support quoting properly to be signaled about this
289 $view_name = $$view_name if ref $view_name eq 'SCALAR';
291 # Skip custom query sources
292 next if ref $view_name;
294 # Its possible to have multiple DBIC source using same table
295 next if $views{$view_name}++;
297 $dbicschema->throw_exception ("view $view_name is missing a view_definition")
298 unless $source->view_definition;
300 my $view = $schema->add_view (
302 fields => [ $source->columns ],
303 $source->view_definition ? ( 'sql' => $source->view_definition ) : ()
304 ) || $dbicschema->throw_exception ($schema->error);
306 $source->_invoke_sqlt_deploy_hook($view);
310 if ($dbicschema->can('sqlt_deploy_hook')) {
311 $dbicschema->sqlt_deploy_hook($schema);
318 # Quick and dirty dependency graph calculator
321 my ($table, $tables, $seen) = @_;
326 # copy and bump all deps by one (so we can reconstruct the chain)
327 my %seen = map { $_ => $seen->{$_} + 1 } (keys %$seen);
330 for my $dep (keys %{$tables->{$table}{foreign_table_deps}} ) {
334 # warn and remove the circular constraint so we don't get flooded with the same warning over and over
335 #carp sprintf ("Circular dependency detected, schema may not be deployable:\n%s\n",
336 # join (' -> ', (sort { $seen->{$b} <=> $seen->{$a} } (keys %$seen) ), $table, $dep )
338 #delete $tables->{$table}{foreign_table_deps}{$dep};
343 my $subdeps = _resolve_deps ($dep, $tables, \%seen);
344 $ret->{$_} += $subdeps->{$_} for ( keys %$subdeps );
356 SQL::Translator::Parser::DBIx::Class - Create a SQL::Translator schema
357 from a DBIx::Class::Schema instance
363 my $schema = MyApp::Schema->connect("dbi:SQLite:something.db");
364 $schema->create_ddl_dir();
372 my $schema = MyApp::Schema->connect;
373 my $trans = SQL::Translator->new (
374 parser => 'SQL::Translator::Parser::DBIx::Class',
375 parser_args => { package => $schema },
376 producer => 'SQLite',
377 ) or die SQL::Translator->error;
378 my $out = $trans->translate() or die $trans->error;
382 This class requires L<SQL::Translator> installed to work.
384 C<SQL::Translator::Parser::DBIx::Class> reads a DBIx::Class schema,
385 interrogates the columns, and stuffs it all in an $sqlt_schema object.
387 Its primary use is in deploying database layouts described as a set
388 of L<DBIx::Class> classes, to a database. To do this, see
389 L<DBIx::Class::Schema/deploy>.
391 This can also be achieved by having DBIx::Class export the schema as a
392 set of SQL files ready for import into your database, or passed to
393 other machines that need to have your application installed but don't
394 have SQL::Translator installed. To do this see
395 L<DBIx::Class::Schema/create_ddl_dir>.
399 L<SQL::Translator>, L<DBIx::Class::Schema>