Fix RT52812
[dbsrgits/DBIx-Class.git] / lib / SQL / Translator / Parser / DBIx / Class.pm
CommitLineData
392cebac 1package SQL::Translator::Parser::DBIx::Class;
b02b20b5 2
3# AUTHOR: Jess Robinson
4
1d996af5 5# Some mistakes the fault of Matt S Trout
6
c385ecea 7# Others the fault of Ash Berlin
8
b02b20b5 9use strict;
10use warnings;
4a9f6cdc 11use vars qw($DEBUG $VERSION @EXPORT_OK);
12$VERSION = '1.10';
b02b20b5 13$DEBUG = 0 unless defined $DEBUG;
b02b20b5 14
15use Exporter;
b02b20b5 16use SQL::Translator::Utils qw(debug normalize_name);
48850f9a 17use Carp::Clan qw/^SQL::Translator|^DBIx::Class/;
b02b20b5 18
19use base qw(Exporter);
20
21@EXPORT_OK = qw(parse);
22
23# -------------------------------------------------------------------
24# parse($tr, $data)
25#
0e2c6809 26# setting parser_args => { add_fk_index => 0 } will prevent
27# the auto-generation of an index for each FK.
28#
880a1a0c 29# Note that $data, in the case of this parser, is not useful.
b02b20b5 30# We're working with DBIx::Class Schemas, not data streams.
31# -------------------------------------------------------------------
32sub parse {
499adf63 33 my ($tr, $data) = @_;
34 my $args = $tr->parser_args;
b7e303a8 35 my $dbicschema = $args->{'DBIx::Class::Schema'} || $args->{"DBIx::Schema"} ||$data;
36 $dbicschema ||= $args->{'package'};
499adf63 37 my $limit_sources = $args->{'sources'};
48850f9a 38
eb0bc670 39 croak 'No DBIx::Class::Schema' unless ($dbicschema);
b7e303a8 40 if (!ref $dbicschema) {
41 eval "use $dbicschema;";
eb0bc670 42 croak "Can't load $dbicschema ($@)" if($@);
b02b20b5 43 }
44
45 my $schema = $tr->schema;
46 my $table_no = 0;
47
b1f9d92e 48 $schema->name( ref($dbicschema) . " v" . ($dbicschema->schema_version || '1.x'))
b7e303a8 49 unless ($schema->name);
38e48163 50
b7e303a8 51 my @monikers = sort $dbicschema->sources;
499adf63 52 if ($limit_sources) {
53 my $ref = ref $limit_sources || '';
eb0bc670 54 $dbicschema->throw_exception ("'sources' parameter must be an array or hash ref")
55 unless( $ref eq 'ARRAY' || ref eq 'HASH' );
499adf63 56
57 # limit monikers to those specified in
58 my $sources;
59 if ($ref eq 'ARRAY') {
60 $sources->{$_} = 1 for (@$limit_sources);
61 } else {
62 $sources = $limit_sources;
63 }
64 @monikers = grep { $sources->{$_} } @monikers;
65 }
66
67
a7f4b74c 68 my(%table_monikers, %view_monikers);
1d521afd 69 for my $moniker (@monikers){
70 my $source = $dbicschema->source($moniker);
5f5e87cf 71 if ( $source->isa('DBIx::Class::ResultSource::Table') ) {
a7f4b74c 72 $table_monikers{$moniker}++;
5f5e87cf 73 } elsif( $source->isa('DBIx::Class::ResultSource::View') ){
bccd177f 74 next if $source->is_virtual;
a7f4b74c 75 $view_monikers{$moniker}++;
1d521afd 76 }
77 }
499adf63 78
48850f9a 79 my %tables;
a7f4b74c 80 foreach my $moniker (sort keys %table_monikers)
b02b20b5 81 {
b7e303a8 82 my $source = $dbicschema->source($moniker);
48850f9a 83 my $table_name = $source->name;
39be4120 84
4678e9da 85 # FIXME - this isn't the right way to do it, but sqlt does not
86 # support quoting properly to be signaled about this
a8fcfb9f 87 $table_name = $$table_name if ref $table_name eq 'SCALAR';
b02b20b5 88
e3d5a547 89 # It's possible to have multiple DBIC sources using the same table
48850f9a 90 next if $tables{$table_name};
38e48163 91
48850f9a 92 $tables{$table_name}{source} = $source;
93 my $table = $tables{$table_name}{object} = SQL::Translator::Schema::Table->new(
94 name => $table_name,
b02b20b5 95 type => 'TABLE',
48850f9a 96 );
b02b20b5 97 foreach my $col ($source->columns)
98 {
d6c79cb3 99 # assuming column_info in dbic is the same as DBI (?)
b02b20b5 100 # data_type is a number, column_type is text?
101 my %colinfo = (
102 name => $col,
b02b20b5 103 size => 0,
104 is_auto_increment => 0,
105 is_foreign_key => 0,
106 is_nullable => 0,
107 %{$source->column_info($col)}
108 );
0009fa49 109 if ($colinfo{is_nullable}) {
110 $colinfo{default} = '' unless exists $colinfo{default};
111 }
eb0bc670 112 my $f = $table->add_field(%colinfo)
113 || $dbicschema->throw_exception ($table->error);
b02b20b5 114 }
115 $table->primary_key($source->primary_columns);
116
7b90bb13 117 my @primary = $source->primary_columns;
118 my %unique_constraints = $source->unique_constraints;
b7e303a8 119 foreach my $uniq (sort keys %unique_constraints) {
6d0ee587 120 if (!$source->_compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
7b90bb13 121 $table->add_constraint(
122 type => 'unique',
a7e65bb5 123 name => $uniq,
7b90bb13 124 fields => $unique_constraints{$uniq}
125 );
126 }
127 }
128
b02b20b5 129 my @rels = $source->relationships();
499adf63 130
131 my %created_FK_rels;
48850f9a 132
2581038c 133 # global add_fk_index set in parser_args
a7f4b74c 134 my $add_fk_index = (exists $args->{add_fk_index} && ! $args->{add_fk_index}) ? 0 : 1;
499adf63 135
454a5a42 136 foreach my $rel (sort @rels)
b02b20b5 137 {
a7f4b74c 138
b02b20b5 139 my $rel_info = $source->relationship_info($rel);
637ca936 140
637ca936 141 # Ignore any rel cond that isn't a straight hash
142 next unless ref $rel_info->{cond} eq 'HASH';
143
a7f4b74c 144 my $relsource = $source->related_source($rel);
145
146 # related sources might be excluded via a {sources} filter or might be views
147 next unless exists $table_monikers{$relsource->source_name};
148
149 my $rel_table = $relsource->name;
4678e9da 150
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';
de60a93d 154
e377d723 155 my $reverse_rels = $source->reverse_relationship_info($rel);
156 my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
157
d1b264d3 158 # Force the order of @cond to match the order of ->add_columns
159 my $idx;
a7f4b74c 160 my %other_columns_idx = map {'foreign.'.$_ => ++$idx } $relsource->columns;
d1b264d3 161 my @cond = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } keys(%{$rel_info->{cond}});
48850f9a 162
637ca936 163 # Get the key information, mapping off the foreign/self markers
637ca936 164 my @refkeys = map {/^\w+\.(\w+)$/} @cond;
165 my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
166
e377d723 167 # determine if this relationship is a self.fk => foreign.pk (i.e. belongs_to)
168 my $fk_constraint;
de60a93d 169
e377d723 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};
173 }
174 # it can not be multi
069e49b6 175 elsif ( $rel_info->{attrs}{accessor}
176 && $rel_info->{attrs}{accessor} eq 'multi' ) {
e377d723 177 $fk_constraint = 0;
178 }
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!!?? :)
182 else {
6d0ee587 183 $fk_constraint = not $source->_compare_relationship_keys(\@keys, \@primary);
e377d723 184 }
de60a93d 185
e377d723 186 my $cascade;
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"};
191 }
db79c254 192 elsif ( $rel_info->{attrs}{"on_$c"} ) {
48850f9a 193 carp "SQLT attribute 'on_$c' was supplied for relationship '$moniker/$rel', which does not appear to be a foreign constraint. "
e377d723 194 . "If you are sure that SQLT must generate a constraint for this relationship, add 'is_foreign_key_constraint => 1' to the attributes.\n";
195 }
196 }
197 elsif (defined $otherrelationship and $otherrelationship->{attrs}{$c eq 'update' ? 'cascade_copy' : 'cascade_delete'}) {
198 $cascade->{$c} = 'CASCADE';
de60a93d 199 }
e377d723 200 }
201
202 if($rel_table)
203 {
204 # Constraints are added only if applicable
205 next unless $fk_constraint;
206
207 # Make sure we dont create the same foreign key constraint twice
e3d5a547 208 my $key_test = join("\x00", sort @keys);
e377d723 209 next if $created_FK_rels{$rel_table}->{$key_test};
de60a93d 210
48850f9a 211 if (scalar(@keys)) {
212
213 $created_FK_rels{$rel_table}->{$key_test} = 1;
13de943d 214
48850f9a 215 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
216
a7f4b74c 217 # calculate dependencies: do not consider deferrable constraints and
218 # self-references for dependency calculations
48850f9a 219 if (! $is_deferrable and $rel_table ne $table_name) {
220 $tables{$table_name}{foreign_table_deps}{$rel_table}++;
221 }
a7f4b74c 222
7b5d0b84 223 $table->add_constraint(
0d865134 224 type => 'foreign_key',
48850f9a 225 name => join('_', $table_name, 'fk', @keys),
0d865134 226 fields => \@keys,
227 reference_fields => \@refkeys,
228 reference_table => $rel_table,
555b3385 229 on_delete => uc ($cascade->{delete} || ''),
230 on_update => uc ($cascade->{update} || ''),
e394339b 231 (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
7b5d0b84 232 );
48850f9a 233
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;
236
2581038c 237 if ($add_fk_index_rel) {
0e2c6809 238 my $index = $table->add_index(
48850f9a 239 name => join('_', $table_name, 'idx', @keys),
0e2c6809 240 fields => \@keys,
241 type => 'NORMAL',
242 );
243 }
244 }
b02b20b5 245 }
246 }
48850f9a 247
b02b20b5 248 }
d6c79cb3 249
48850f9a 250 # attach the tables to the schema in dependency order
251 my $dependencies = {
252 map { $_ => _resolve_deps ($_, \%tables) } (keys %tables)
253 };
254 for my $table (sort
255 {
256 keys %{$dependencies->{$a} || {} } <=> keys %{ $dependencies->{$b} || {} }
257 ||
258 $a cmp $b
259 }
260 (keys %tables)
261 ) {
262 $schema->add_table ($tables{$table}{object});
263 $tables{$table}{source} -> _invoke_sqlt_deploy_hook( $tables{$table}{object} );
48850f9a 264
7adc2091 265 # the hook might have already removed the table
266 if ($schema->get_table($table) && $table =~ /^ \s* \( \s* SELECT \s+/ix) {
267 warn <<'EOW';
a8fcfb9f 268
7adc2091 269Custom SQL through ->name(\'( SELECT ...') is DEPRECATED, for more details see
270"Arbitrary SQL through a custom ResultSource" in DBIx::Class::Manual::Cookbook
271or http://search.cpan.org/dist/DBIx-Class/lib/DBIx/Class/Manual/Cookbook.pod
39be4120 272
7adc2091 273EOW
39be4120 274
7adc2091 275 # remove the table as there is no way someone might want to
276 # actually deploy this
277 $schema->drop_table ($table);
39be4120 278 }
279 }
48850f9a 280
281 my %views;
a7f4b74c 282 foreach my $moniker (sort keys %view_monikers)
1d521afd 283 {
284 my $source = $dbicschema->source($moniker);
48850f9a 285 my $view_name = $source->name;
4678e9da 286
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';
48850f9a 290
1d521afd 291 # Skip custom query sources
48850f9a 292 next if ref $view_name;
1d521afd 293
294 # Its possible to have multiple DBIC source using same table
48850f9a 295 next if $views{$view_name}++;
1d521afd 296
ab7e74aa 297 $dbicschema->throw_exception ("view $view_name is missing a view_definition")
298 unless $source->view_definition;
8f1617e2 299
48850f9a 300 my $view = $schema->add_view (
301 name => $view_name,
1d521afd 302 fields => [ $source->columns ],
f534e33b 303 $source->view_definition ? ( 'sql' => $source->view_definition ) : ()
eb0bc670 304 ) || $dbicschema->throw_exception ($schema->error);
a99b214b 305
306 $source->_invoke_sqlt_deploy_hook($view);
1d521afd 307 }
308
48850f9a 309
b7e303a8 310 if ($dbicschema->can('sqlt_deploy_hook')) {
311 $dbicschema->sqlt_deploy_hook($schema);
d6c79cb3 312 }
313
637ca936 314 return 1;
75d07914 315}
b02b20b5 316
48850f9a 317#
318# Quick and dirty dependency graph calculator
319#
320sub _resolve_deps {
321 my ($table, $tables, $seen) = @_;
322
323 my $ret = {};
324 $seen ||= {};
325
326 # copy and bump all deps by one (so we can reconstruct the chain)
327 my %seen = map { $_ => $seen->{$_} + 1 } (keys %$seen);
328 $seen{$table} = 1;
329
330 for my $dep (keys %{$tables->{$table}{foreign_table_deps}} ) {
331
332 if ($seen->{$dep}) {
333
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 )
337 #);
338 #delete $tables->{$table}{foreign_table_deps}{$dep};
339
340 return {};
341 }
342
343 my $subdeps = _resolve_deps ($dep, $tables, \%seen);
344 $ret->{$_} += $subdeps->{$_} for ( keys %$subdeps );
345
346 ++$ret->{$dep};
347 }
348
349 return $ret;
350}
351
0da8b7da 3521;
7232ce07 353
354=head1 NAME
355
356SQL::Translator::Parser::DBIx::Class - Create a SQL::Translator schema
357from a DBIx::Class::Schema instance
358
359=head1 SYNOPSIS
360
f26d4b95 361 ## Via DBIx::Class
362 use MyApp::Schema;
363 my $schema = MyApp::Schema->connect("dbi:SQLite:something.db");
364 $schema->create_ddl_dir();
365 ## or
366 $schema->deploy();
367
368 ## Standalone
7232ce07 369 use MyApp::Schema;
370 use SQL::Translator;
d4daee7b 371
7232ce07 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;
379
380=head1 DESCRIPTION
381
f26d4b95 382This class requires L<SQL::Translator> installed to work.
383
7232ce07 384C<SQL::Translator::Parser::DBIx::Class> reads a DBIx::Class schema,
385interrogates the columns, and stuffs it all in an $sqlt_schema object.
386
faaba25f 387Its primary use is in deploying database layouts described as a set
db2b2eb6 388of L<DBIx::Class> classes, to a database. To do this, see
389L<DBIx::Class::Schema/deploy>.
f26d4b95 390
391This can also be achieved by having DBIx::Class export the schema as a
392set of SQL files ready for import into your database, or passed to
393other machines that need to have your application installed but don't
db2b2eb6 394have SQL::Translator installed. To do this see
395L<DBIx::Class::Schema/create_ddl_dir>.
f26d4b95 396
7232ce07 397=head1 SEE ALSO
398
f26d4b95 399L<SQL::Translator>, L<DBIx::Class::Schema>
7232ce07 400
401=head1 AUTHORS
402
403Jess Robinson
404
405Matt S Trout
406
407Ash Berlin