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 push(@table_monikers, $moniker);
73 } elsif( $source->isa('DBIx::Class::ResultSource::View') ){
74 next if $source->is_virtual;
75 push(@view_monikers, $moniker);
80 foreach my $moniker (sort @table_monikers)
82 my $source = $dbicschema->source($moniker);
83 my $table_name = $source->name;
85 # sqlt currently does not do quoting right anyway
86 $table_name = $$table_name if ref $table_name eq 'SCALAR';
88 # Its possible to have multiple DBIC sources using the same table
89 next if $tables{$table_name};
91 $tables{$table_name}{source} = $source;
92 my $table = $tables{$table_name}{object} = SQL::Translator::Schema::Table->new(
96 foreach my $col ($source->columns)
98 # assuming column_info in dbic is the same as DBI (?)
99 # data_type is a number, column_type is text?
103 is_auto_increment => 0,
106 %{$source->column_info($col)}
108 if ($colinfo{is_nullable}) {
109 $colinfo{default} = '' unless exists $colinfo{default};
111 my $f = $table->add_field(%colinfo)
112 || $dbicschema->throw_exception ($table->error);
114 $table->primary_key($source->primary_columns);
116 my @primary = $source->primary_columns;
117 my %unique_constraints = $source->unique_constraints;
118 foreach my $uniq (sort keys %unique_constraints) {
119 if (!$source->_compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
120 $table->add_constraint(
123 fields => $unique_constraints{$uniq}
128 my @rels = $source->relationships();
132 # global add_fk_index set in parser_args
133 my $add_fk_index = (exists $args->{add_fk_index} && ($args->{add_fk_index} == 0)) ? 0 : 1;
135 foreach my $rel (sort @rels)
137 my $rel_info = $source->relationship_info($rel);
139 # Ignore any rel cond that isn't a straight hash
140 next unless ref $rel_info->{cond} eq 'HASH';
142 my $othertable = $source->related_source($rel);
143 my $rel_table = $othertable->name;
144 $rel_table = $$rel_table if ref $rel_table eq 'SCALAR'; #sqlt currently does not do quoting right anyway
146 my $reverse_rels = $source->reverse_relationship_info($rel);
147 my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
149 # Force the order of @cond to match the order of ->add_columns
151 my %other_columns_idx = map {'foreign.'.$_ => ++$idx } $othertable->columns;
152 my @cond = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } keys(%{$rel_info->{cond}});
154 # Get the key information, mapping off the foreign/self markers
155 my @refkeys = map {/^\w+\.(\w+)$/} @cond;
156 my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
158 # determine if this relationship is a self.fk => foreign.pk (i.e. belongs_to)
161 #first it can be specified explicitly
162 if ( exists $rel_info->{attrs}{is_foreign_key_constraint} ) {
163 $fk_constraint = $rel_info->{attrs}{is_foreign_key_constraint};
165 # it can not be multi
166 elsif ( $rel_info->{attrs}{accessor}
167 && $rel_info->{attrs}{accessor} eq 'multi' ) {
170 # if indeed single, check if all self.columns are our primary keys.
171 # this is supposed to indicate a has_one/might_have...
172 # where's the introspection!!?? :)
174 $fk_constraint = not $source->_compare_relationship_keys(\@keys, \@primary);
178 for my $c (qw/delete update/) {
179 if (exists $rel_info->{attrs}{"on_$c"}) {
180 if ($fk_constraint) {
181 $cascade->{$c} = $rel_info->{attrs}{"on_$c"};
184 carp "SQLT attribute 'on_$c' was supplied for relationship '$moniker/$rel', which does not appear to be a foreign constraint. "
185 . "If you are sure that SQLT must generate a constraint for this relationship, add 'is_foreign_key_constraint => 1' to the attributes.\n";
188 elsif (defined $otherrelationship and $otherrelationship->{attrs}{$c eq 'update' ? 'cascade_copy' : 'cascade_delete'}) {
189 $cascade->{$c} = 'CASCADE';
195 # Constraints are added only if applicable
196 next unless $fk_constraint;
198 # Make sure we dont create the same foreign key constraint twice
199 my $key_test = join("\x00", @keys);
200 next if $created_FK_rels{$rel_table}->{$key_test};
204 $created_FK_rels{$rel_table}->{$key_test} = 1;
206 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
208 # do not consider deferrable constraints and self-references
209 # for dependency calculations
210 if (! $is_deferrable and $rel_table ne $table_name) {
211 $tables{$table_name}{foreign_table_deps}{$rel_table}++;
214 $table->add_constraint(
215 type => 'foreign_key',
216 name => join('_', $table_name, 'fk', @keys),
218 reference_fields => \@refkeys,
219 reference_table => $rel_table,
220 on_delete => uc ($cascade->{delete} || ''),
221 on_update => uc ($cascade->{update} || ''),
222 (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
225 # global parser_args add_fk_index param can be overridden on the rel def
226 my $add_fk_index_rel = (exists $rel_info->{attrs}{add_fk_index}) ? $rel_info->{attrs}{add_fk_index} : $add_fk_index;
228 if ($add_fk_index_rel) {
229 my $index = $table->add_index(
230 name => join('_', $table_name, 'idx', @keys),
241 # attach the tables to the schema in dependency order
243 map { $_ => _resolve_deps ($_, \%tables) } (keys %tables)
247 keys %{$dependencies->{$a} || {} } <=> keys %{ $dependencies->{$b} || {} }
253 $schema->add_table ($tables{$table}{object});
254 $tables{$table}{source} -> _invoke_sqlt_deploy_hook( $tables{$table}{object} );
256 # the hook might have already removed the table
257 if ($schema->get_table($table) && $table =~ /^ \s* \( \s* SELECT \s+/ix) {
260 Custom SQL through ->name(\'( SELECT ...') is DEPRECATED, for more details see
261 "Arbitrary SQL through a custom ResultSource" in DBIx::Class::Manual::Cookbook
262 or http://search.cpan.org/dist/DBIx-Class/lib/DBIx/Class/Manual/Cookbook.pod
266 # remove the table as there is no way someone might want to
267 # actually deploy this
268 $schema->drop_table ($table);
273 foreach my $moniker (sort @view_monikers)
275 my $source = $dbicschema->source($moniker);
276 my $view_name = $source->name;
277 $view_name = $$view_name if ref $view_name eq 'SCALAR'; #sqlt currently does not do quoting right anyway
279 # Skip custom query sources
280 next if ref $view_name;
282 # Its possible to have multiple DBIC source using same table
283 next if $views{$view_name}++;
285 my $view = $schema->add_view (
287 fields => [ $source->columns ],
288 $source->view_definition ? ( 'sql' => $source->view_definition ) : ()
289 ) || $dbicschema->throw_exception ($schema->error);
291 $source->_invoke_sqlt_deploy_hook($view);
295 if ($dbicschema->can('sqlt_deploy_hook')) {
296 $dbicschema->sqlt_deploy_hook($schema);
303 # Quick and dirty dependency graph calculator
306 my ($table, $tables, $seen) = @_;
311 # copy and bump all deps by one (so we can reconstruct the chain)
312 my %seen = map { $_ => $seen->{$_} + 1 } (keys %$seen);
315 for my $dep (keys %{$tables->{$table}{foreign_table_deps}} ) {
319 # warn and remove the circular constraint so we don't get flooded with the same warning over and over
320 #carp sprintf ("Circular dependency detected, schema may not be deployable:\n%s\n",
321 # join (' -> ', (sort { $seen->{$b} <=> $seen->{$a} } (keys %$seen) ), $table, $dep )
323 #delete $tables->{$table}{foreign_table_deps}{$dep};
328 my $subdeps = _resolve_deps ($dep, $tables, \%seen);
329 $ret->{$_} += $subdeps->{$_} for ( keys %$subdeps );
341 SQL::Translator::Parser::DBIx::Class - Create a SQL::Translator schema
342 from a DBIx::Class::Schema instance
348 my $schema = MyApp::Schema->connect("dbi:SQLite:something.db");
349 $schema->create_ddl_dir();
357 my $schema = MyApp::Schema->connect;
358 my $trans = SQL::Translator->new (
359 parser => 'SQL::Translator::Parser::DBIx::Class',
360 parser_args => { package => $schema },
361 producer => 'SQLite',
362 ) or die SQL::Translator->error;
363 my $out = $trans->translate() or die $trans->error;
367 This class requires L<SQL::Translator> installed to work.
369 C<SQL::Translator::Parser::DBIx::Class> reads a DBIx::Class schema,
370 interrogates the columns, and stuffs it all in an $sqlt_schema object.
372 Its primary use is in deploying database layouts described as a set
373 of L<DBIx::Class> classes, to a database. To do this, see
374 L<DBIx::Class::Schema/deploy>.
376 This can also be achieved by having DBIx::Class export the schema as a
377 set of SQL files ready for import into your database, or passed to
378 other machines that need to have your application installed but don't
379 have SQL::Translator installed. To do this see
380 L<DBIx::Class::Schema/create_ddl_dir>.
384 L<SQL::Translator>, L<DBIx::Class::Schema>