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