Finish ViewDeps: fix a join in test class, put attribs on Parser, add resultset tests...
[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;
ebed3aaf 14
b02b20b5 15use Exporter;
b02b20b5 16use SQL::Translator::Utils qw(debug normalize_name);
9780718f 17use Carp::Clan qw/^SQL::Translator|^DBIx::Class|^Try::Tiny/;
3bf702eb 18use Scalar::Util ();
9780718f 19use Try::Tiny;
b02b20b5 20
21use base qw(Exporter);
22
23@EXPORT_OK = qw(parse);
24
25# -------------------------------------------------------------------
26# parse($tr, $data)
27#
0e2c6809 28# setting parser_args => { add_fk_index => 0 } will prevent
29# the auto-generation of an index for each FK.
30#
880a1a0c 31# Note that $data, in the case of this parser, is not useful.
b02b20b5 32# We're working with DBIx::Class Schemas, not data streams.
33# -------------------------------------------------------------------
34sub parse {
3bf702eb 35 # this is a hack to prevent schema leaks due to a retarded SQLT implementation
2ad89bf5 36 # DO NOT REMOVE (until SQLT2 is out, the all of this will be rewritten anyway)
02730621 37 Scalar::Util::weaken ($_[1]) if ref ($_[1]);
3bf702eb 38
499adf63 39 my ($tr, $data) = @_;
40 my $args = $tr->parser_args;
b7e303a8 41 my $dbicschema = $args->{'DBIx::Class::Schema'} || $args->{"DBIx::Schema"} ||$data;
42 $dbicschema ||= $args->{'package'};
499adf63 43 my $limit_sources = $args->{'sources'};
48850f9a 44
eb0bc670 45 croak 'No DBIx::Class::Schema' unless ($dbicschema);
b7e303a8 46 if (!ref $dbicschema) {
9780718f 47 try {
48 eval "require $dbicschema;"
49 }
50 catch {
51 croak "Can't load $dbicschema ($_)";
52 }
b02b20b5 53 }
54
55 my $schema = $tr->schema;
56 my $table_no = 0;
57
b1f9d92e 58 $schema->name( ref($dbicschema) . " v" . ($dbicschema->schema_version || '1.x'))
b7e303a8 59 unless ($schema->name);
38e48163 60
b7e303a8 61 my @monikers = sort $dbicschema->sources;
499adf63 62 if ($limit_sources) {
63 my $ref = ref $limit_sources || '';
eb0bc670 64 $dbicschema->throw_exception ("'sources' parameter must be an array or hash ref")
65 unless( $ref eq 'ARRAY' || ref eq 'HASH' );
499adf63 66
67 # limit monikers to those specified in
68 my $sources;
69 if ($ref eq 'ARRAY') {
70 $sources->{$_} = 1 for (@$limit_sources);
71 } else {
72 $sources = $limit_sources;
73 }
74 @monikers = grep { $sources->{$_} } @monikers;
75 }
76
77
a7f4b74c 78 my(%table_monikers, %view_monikers);
1d521afd 79 for my $moniker (@monikers){
80 my $source = $dbicschema->source($moniker);
5f5e87cf 81 if ( $source->isa('DBIx::Class::ResultSource::Table') ) {
a7f4b74c 82 $table_monikers{$moniker}++;
5f5e87cf 83 } elsif( $source->isa('DBIx::Class::ResultSource::View') ){
bccd177f 84 next if $source->is_virtual;
a7f4b74c 85 $view_monikers{$moniker}++;
1d521afd 86 }
87 }
499adf63 88
48850f9a 89 my %tables;
a7f4b74c 90 foreach my $moniker (sort keys %table_monikers)
b02b20b5 91 {
b7e303a8 92 my $source = $dbicschema->source($moniker);
48850f9a 93 my $table_name = $source->name;
39be4120 94
4678e9da 95 # FIXME - this isn't the right way to do it, but sqlt does not
96 # support quoting properly to be signaled about this
a8fcfb9f 97 $table_name = $$table_name if ref $table_name eq 'SCALAR';
b02b20b5 98
e3d5a547 99 # It's possible to have multiple DBIC sources using the same table
48850f9a 100 next if $tables{$table_name};
38e48163 101
48850f9a 102 $tables{$table_name}{source} = $source;
103 my $table = $tables{$table_name}{object} = SQL::Translator::Schema::Table->new(
104 name => $table_name,
b02b20b5 105 type => 'TABLE',
48850f9a 106 );
b02b20b5 107 foreach my $col ($source->columns)
108 {
d6c79cb3 109 # assuming column_info in dbic is the same as DBI (?)
b02b20b5 110 # data_type is a number, column_type is text?
111 my %colinfo = (
112 name => $col,
b02b20b5 113 size => 0,
114 is_auto_increment => 0,
115 is_foreign_key => 0,
116 is_nullable => 0,
117 %{$source->column_info($col)}
118 );
0009fa49 119 if ($colinfo{is_nullable}) {
120 $colinfo{default} = '' unless exists $colinfo{default};
121 }
eb0bc670 122 my $f = $table->add_field(%colinfo)
123 || $dbicschema->throw_exception ($table->error);
b02b20b5 124 }
b02b20b5 125
7b90bb13 126 my @primary = $source->primary_columns;
36e9e24f 127
128 $table->primary_key(@primary) if @primary;
129
7b90bb13 130 my %unique_constraints = $source->unique_constraints;
b7e303a8 131 foreach my $uniq (sort keys %unique_constraints) {
6d0ee587 132 if (!$source->_compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
7b90bb13 133 $table->add_constraint(
134 type => 'unique',
a7e65bb5 135 name => $uniq,
7b90bb13 136 fields => $unique_constraints{$uniq}
137 );
138 }
139 }
140
b02b20b5 141 my @rels = $source->relationships();
499adf63 142
143 my %created_FK_rels;
48850f9a 144
2581038c 145 # global add_fk_index set in parser_args
a7f4b74c 146 my $add_fk_index = (exists $args->{add_fk_index} && ! $args->{add_fk_index}) ? 0 : 1;
499adf63 147
454a5a42 148 foreach my $rel (sort @rels)
b02b20b5 149 {
a7f4b74c 150
b02b20b5 151 my $rel_info = $source->relationship_info($rel);
637ca936 152
637ca936 153 # Ignore any rel cond that isn't a straight hash
154 next unless ref $rel_info->{cond} eq 'HASH';
155
a7f4b74c 156 my $relsource = $source->related_source($rel);
157
158 # related sources might be excluded via a {sources} filter or might be views
159 next unless exists $table_monikers{$relsource->source_name};
160
161 my $rel_table = $relsource->name;
4678e9da 162
163 # FIXME - this isn't the right way to do it, but sqlt does not
164 # support quoting properly to be signaled about this
165 $rel_table = $$rel_table if ref $rel_table eq 'SCALAR';
de60a93d 166
e377d723 167 my $reverse_rels = $source->reverse_relationship_info($rel);
168 my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
169
d1b264d3 170 # Force the order of @cond to match the order of ->add_columns
171 my $idx;
a7f4b74c 172 my %other_columns_idx = map {'foreign.'.$_ => ++$idx } $relsource->columns;
d1b264d3 173 my @cond = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } keys(%{$rel_info->{cond}});
48850f9a 174
637ca936 175 # Get the key information, mapping off the foreign/self markers
637ca936 176 my @refkeys = map {/^\w+\.(\w+)$/} @cond;
177 my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
178
e377d723 179 # determine if this relationship is a self.fk => foreign.pk (i.e. belongs_to)
180 my $fk_constraint;
de60a93d 181
e377d723 182 #first it can be specified explicitly
183 if ( exists $rel_info->{attrs}{is_foreign_key_constraint} ) {
184 $fk_constraint = $rel_info->{attrs}{is_foreign_key_constraint};
185 }
186 # it can not be multi
069e49b6 187 elsif ( $rel_info->{attrs}{accessor}
188 && $rel_info->{attrs}{accessor} eq 'multi' ) {
e377d723 189 $fk_constraint = 0;
190 }
191 # if indeed single, check if all self.columns are our primary keys.
192 # this is supposed to indicate a has_one/might_have...
193 # where's the introspection!!?? :)
194 else {
6d0ee587 195 $fk_constraint = not $source->_compare_relationship_keys(\@keys, \@primary);
e377d723 196 }
de60a93d 197
e377d723 198 my $cascade;
199 for my $c (qw/delete update/) {
200 if (exists $rel_info->{attrs}{"on_$c"}) {
201 if ($fk_constraint) {
202 $cascade->{$c} = $rel_info->{attrs}{"on_$c"};
203 }
db79c254 204 elsif ( $rel_info->{attrs}{"on_$c"} ) {
48850f9a 205 carp "SQLT attribute 'on_$c' was supplied for relationship '$moniker/$rel', which does not appear to be a foreign constraint. "
e377d723 206 . "If you are sure that SQLT must generate a constraint for this relationship, add 'is_foreign_key_constraint => 1' to the attributes.\n";
207 }
208 }
209 elsif (defined $otherrelationship and $otherrelationship->{attrs}{$c eq 'update' ? 'cascade_copy' : 'cascade_delete'}) {
210 $cascade->{$c} = 'CASCADE';
de60a93d 211 }
e377d723 212 }
213
cae467a7 214 if($rel_table) {
e377d723 215 # Constraints are added only if applicable
216 next unless $fk_constraint;
217
218 # Make sure we dont create the same foreign key constraint twice
e3d5a547 219 my $key_test = join("\x00", sort @keys);
e377d723 220 next if $created_FK_rels{$rel_table}->{$key_test};
de60a93d 221
48850f9a 222 if (scalar(@keys)) {
48850f9a 223 $created_FK_rels{$rel_table}->{$key_test} = 1;
13de943d 224
48850f9a 225 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
226
a7f4b74c 227 # calculate dependencies: do not consider deferrable constraints and
228 # self-references for dependency calculations
48850f9a 229 if (! $is_deferrable and $rel_table ne $table_name) {
230 $tables{$table_name}{foreign_table_deps}{$rel_table}++;
231 }
7b5d0b84 232
7b5d0b84 233 $table->add_constraint(
cae467a7 234 type => 'foreign_key',
235 name => join('_', $table_name, 'fk', @keys),
236 fields => \@keys,
237 reference_fields => \@refkeys,
238 reference_table => $rel_table,
239 on_delete => uc ($cascade->{delete} || ''),
240 on_update => uc ($cascade->{update} || ''),
241 (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
7b5d0b84 242 );
48850f9a 243
244 # global parser_args add_fk_index param can be overridden on the rel def
245 my $add_fk_index_rel = (exists $rel_info->{attrs}{add_fk_index}) ? $rel_info->{attrs}{add_fk_index} : $add_fk_index;
246
c49ff507 247 # Check that we do not create an index identical to the PK index
248 # (some RDBMS croak on this, and it generally doesn't make much sense)
249 # NOTE: we do not sort the key columns because the order of
5930bfc2 250 # columns is important for indexes and two indexes with the
251 # same cols but different order are allowed and sometimes
252 # needed
c49ff507 253 next if join("\x00", @keys) eq join("\x00", @primary);
48850f9a 254
2581038c 255 if ($add_fk_index_rel) {
0e2c6809 256 my $index = $table->add_index(
5930bfc2 257 name => join('_', $table_name, 'idx', @keys),
258 fields => \@keys,
259 type => 'NORMAL',
260 );
0e2c6809 261 }
262 }
b02b20b5 263 }
264 }
48850f9a 265
b02b20b5 266 }
d6c79cb3 267
48850f9a 268 # attach the tables to the schema in dependency order
269 my $dependencies = {
270 map { $_ => _resolve_deps ($_, \%tables) } (keys %tables)
271 };
9485509b 272
48850f9a 273 for my $table (sort
274 {
275 keys %{$dependencies->{$a} || {} } <=> keys %{ $dependencies->{$b} || {} }
276 ||
277 $a cmp $b
278 }
279 (keys %tables)
280 ) {
281 $schema->add_table ($tables{$table}{object});
282 $tables{$table}{source} -> _invoke_sqlt_deploy_hook( $tables{$table}{object} );
48850f9a 283
7adc2091 284 # the hook might have already removed the table
285 if ($schema->get_table($table) && $table =~ /^ \s* \( \s* SELECT \s+/ix) {
286 warn <<'EOW';
a8fcfb9f 287
7adc2091 288Custom SQL through ->name(\'( SELECT ...') is DEPRECATED, for more details see
289"Arbitrary SQL through a custom ResultSource" in DBIx::Class::Manual::Cookbook
290or http://search.cpan.org/dist/DBIx-Class/lib/DBIx/Class/Manual/Cookbook.pod
39be4120 291
7adc2091 292EOW
39be4120 293
7adc2091 294 # remove the table as there is no way someone might want to
295 # actually deploy this
296 $schema->drop_table ($table);
39be4120 297 }
298 }
48850f9a 299
300 my %views;
9485509b 301
ebed3aaf 302 my @view_sources =
303 sort {
7364d776 304 keys %{ $a->deploy_depends_on || {} }
ebed3aaf 305 <=>
7364d776 306 keys %{ $b->deploy_depends_on || {} }
ebed3aaf 307 ||
7364d776 308 $a->source_name cmp $b->source_name
ebed3aaf 309 }
310 map { $dbicschema->source($_) }
311 keys %view_monikers;
1999a918 312
943538a0 313 foreach my $source (@view_sources)
1d521afd 314 {
48850f9a 315 my $view_name = $source->name;
4678e9da 316
317 # FIXME - this isn't the right way to do it, but sqlt does not
318 # support quoting properly to be signaled about this
319 $view_name = $$view_name if ref $view_name eq 'SCALAR';
48850f9a 320
1d521afd 321 # Skip custom query sources
48850f9a 322 next if ref $view_name;
1d521afd 323
324 # Its possible to have multiple DBIC source using same table
48850f9a 325 next if $views{$view_name}++;
1d521afd 326
ab7e74aa 327 $dbicschema->throw_exception ("view $view_name is missing a view_definition")
328 unless $source->view_definition;
8f1617e2 329
48850f9a 330 my $view = $schema->add_view (
331 name => $view_name,
1d521afd 332 fields => [ $source->columns ],
f534e33b 333 $source->view_definition ? ( 'sql' => $source->view_definition ) : ()
eb0bc670 334 ) || $dbicschema->throw_exception ($schema->error);
a99b214b 335
336 $source->_invoke_sqlt_deploy_hook($view);
1d521afd 337 }
338
48850f9a 339
b7e303a8 340 if ($dbicschema->can('sqlt_deploy_hook')) {
341 $dbicschema->sqlt_deploy_hook($schema);
d6c79cb3 342 }
343
637ca936 344 return 1;
75d07914 345}
b02b20b5 346
48850f9a 347#
348# Quick and dirty dependency graph calculator
349#
350sub _resolve_deps {
351 my ($table, $tables, $seen) = @_;
352
353 my $ret = {};
354 $seen ||= {};
355
356 # copy and bump all deps by one (so we can reconstruct the chain)
357 my %seen = map { $_ => $seen->{$_} + 1 } (keys %$seen);
358 $seen{$table} = 1;
359
360 for my $dep (keys %{$tables->{$table}{foreign_table_deps}} ) {
361
362 if ($seen->{$dep}) {
363
364 # warn and remove the circular constraint so we don't get flooded with the same warning over and over
365 #carp sprintf ("Circular dependency detected, schema may not be deployable:\n%s\n",
366 # join (' -> ', (sort { $seen->{$b} <=> $seen->{$a} } (keys %$seen) ), $table, $dep )
367 #);
368 #delete $tables->{$table}{foreign_table_deps}{$dep};
369
370 return {};
371 }
372
373 my $subdeps = _resolve_deps ($dep, $tables, \%seen);
374 $ret->{$_} += $subdeps->{$_} for ( keys %$subdeps );
375
376 ++$ret->{$dep};
377 }
378
379 return $ret;
380}
381
0da8b7da 3821;
7232ce07 383
384=head1 NAME
385
386SQL::Translator::Parser::DBIx::Class - Create a SQL::Translator schema
387from a DBIx::Class::Schema instance
388
389=head1 SYNOPSIS
390
f26d4b95 391 ## Via DBIx::Class
392 use MyApp::Schema;
393 my $schema = MyApp::Schema->connect("dbi:SQLite:something.db");
394 $schema->create_ddl_dir();
395 ## or
396 $schema->deploy();
397
398 ## Standalone
7232ce07 399 use MyApp::Schema;
400 use SQL::Translator;
d4daee7b 401
7232ce07 402 my $schema = MyApp::Schema->connect;
403 my $trans = SQL::Translator->new (
404 parser => 'SQL::Translator::Parser::DBIx::Class',
37cb0de1 405 parser_args => {
406 package => $schema,
cae467a7 407 add_fk_index => 0,
37cb0de1 408 sources => [qw/
409 Artist
410 CD
411 /],
412 },
7232ce07 413 producer => 'SQLite',
414 ) or die SQL::Translator->error;
415 my $out = $trans->translate() or die $trans->error;
416
417=head1 DESCRIPTION
418
f26d4b95 419This class requires L<SQL::Translator> installed to work.
420
7232ce07 421C<SQL::Translator::Parser::DBIx::Class> reads a DBIx::Class schema,
422interrogates the columns, and stuffs it all in an $sqlt_schema object.
423
faaba25f 424Its primary use is in deploying database layouts described as a set
db2b2eb6 425of L<DBIx::Class> classes, to a database. To do this, see
426L<DBIx::Class::Schema/deploy>.
f26d4b95 427
428This can also be achieved by having DBIx::Class export the schema as a
429set of SQL files ready for import into your database, or passed to
430other machines that need to have your application installed but don't
db2b2eb6 431have SQL::Translator installed. To do this see
432L<DBIx::Class::Schema/create_ddl_dir>.
f26d4b95 433
cae467a7 434=head1 PARSER OPTIONS
435
436=head2 add_fk_index
437
438Create an index for each foreign key.
ad91ed74 439Enabled by default, as having indexed foreign key columns is normally the
440sensible thing to do.
cae467a7 441
442=head2 sources
443
444=over 4
445
f0ac764e 446=item Arguments: \@class_names
cae467a7 447
448=back
ad91ed74 449
450Limit the amount of parsed sources by supplying an explicit list of source names.
cae467a7 451
7232ce07 452=head1 SEE ALSO
453
f26d4b95 454L<SQL::Translator>, L<DBIx::Class::Schema>
7232ce07 455
339f7f5d 456=head1 AUTHOR
7232ce07 457
339f7f5d 458Jess Robinson
459
460=head2 CONTRIBUTORS
461
462Matt Trout
463Ash Berlin
464Amiri Barksdale
7232ce07 465
827a808f 466=head1 LICENSE
7232ce07 467
827a808f 468You may distribute this code under the same terms as Perl itself.
7232ce07 469
827a808f 470=cut