fix clasing test dbs
[dbsrgits/DBIx-Class-Schema-Loader.git] / lib / DBIx / Class / Schema / Loader / RelBuilder.pm
CommitLineData
996be9ee 1package DBIx::Class::Schema::Loader::RelBuilder;
2
3use strict;
4use warnings;
1ad8e8c3 5use base 'Class::Accessor::Grouped';
942bd5e0 6use mro 'c3';
fa994d3c 7use Carp::Clan qw/^DBIx::Class/;
1ad8e8c3 8use Scalar::Util 'weaken';
39b22ca9 9use Lingua::EN::Inflect::Phrase ();
dc379dc6 10use Lingua::EN::Tagger ();
cc4f11a2 11use DBIx::Class::Schema::Loader::Utils 'split_name';
1ad8e8c3 12use File::Slurp 'slurp';
13use Try::Tiny;
14use Class::Unload ();
8c70d2c7 15use Class::Inspector ();
1ad8e8c3 16use List::MoreUtils 'apply';
af15ea33 17use Encode 'decode';
1ad8e8c3 18use namespace::clean;
996be9ee 19
4295c4b4 20our $VERSION = '0.07010';
32f784fc 21
6e4b7bb1 22# Glossary:
23#
24# remote_relname -- name of relationship from the local table referring to the remote table
25# local_relname -- name of relationship from the remote table referring to the local table
26# remote_method -- relationship type from remote table to local table, usually has_many
27
996be9ee 28=head1 NAME
29
30DBIx::Class::Schema::Loader::RelBuilder - Builds relationships for DBIx::Class::Schema::Loader
31
32=head1 SYNOPSIS
33
19b7d71c 34See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
996be9ee 35
36=head1 DESCRIPTION
37
38This class builds relationships for L<DBIx::Class::Schema::Loader>. This
39is module is not (yet) for external use.
40
41=head1 METHODS
42
43=head2 new
44
4c7b5f46 45Arguments: $base object
996be9ee 46
47=head2 generate_code
48
dc379dc6 49Arguments:
50
51 {
52 local_moniker (scalar) => [ fk_info (arrayref), uniq_info (arrayref) ]
53 ...
54 }
e8ad6491 55
dc379dc6 56This generates the code for the relationships of each table.
e8ad6491 57
58C<local_moniker> is the moniker name of the table which had the REFERENCES
59statements. The fk_info arrayref's contents should take the form:
60
61 [
62 {
63 local_columns => [ 'col2', 'col3' ],
64 remote_columns => [ 'col5', 'col7' ],
65 remote_moniker => 'AnotherTableMoniker',
66 },
67 {
68 local_columns => [ 'col1', 'col4' ],
69 remote_columns => [ 'col1', 'col2' ],
70 remote_moniker => 'YetAnotherTableMoniker',
71 },
72 # ...
73 ],
74
dc379dc6 75The uniq_info arrayref's contents should take the form:
76
77 [
78 [
79 uniq_constraint_name => [ 'col1', 'col2' ],
80 ],
81 [
82 another_uniq_constraint_name => [ 'col1', 'col2' ],
83 ],
84 ],
85
e8ad6491 86This method will return the generated relationships as a hashref keyed on the
87class names. The values are arrayrefs of hashes containing method name and
88arguments, like so:
996be9ee 89
90 {
91 'Some::Source::Class' => [
b97c2c1e 92 { method => 'belongs_to', arguments => [ 'col1', 'Another::Source::Class' ],
93 { method => 'has_many', arguments => [ 'anothers', 'Yet::Another::Source::Class', 'col15' ],
996be9ee 94 ],
95 'Another::Source::Class' => [
96 # ...
97 ],
98 # ...
99 }
8f9d7ce5 100
996be9ee 101=cut
102
1ad8e8c3 103__PACKAGE__->mk_group_accessors('simple', qw/
104 base
105 schema
106 inflect_plural
107 inflect_singular
108 relationship_attrs
a7116285 109 rel_collision_map
1ad8e8c3 110 _temp_classes
dc379dc6 111 __tagger
1ad8e8c3 112/);
4c7b5f46 113
996be9ee 114sub new {
4c7b5f46 115 my ( $class, $base ) = @_;
116
117 # from old POD about this constructor:
118 # C<$schema_class> should be a schema class name, where the source
119 # classes have already been set up and registered. Column info,
120 # primary key, and unique constraints will be drawn from this
121 # schema for all of the existing source monikers.
122
123 # Options inflect_plural and inflect_singular are optional, and
124 # are better documented in L<DBIx::Class::Schema::Loader::Base>.
996be9ee 125
126 my $self = {
4c7b5f46 127 base => $base,
128 schema => $base->schema,
129 inflect_plural => $base->inflect_plural,
130 inflect_singular => $base->inflect_singular,
131 relationship_attrs => $base->relationship_attrs,
a7116285 132 rel_collision_map => $base->rel_collision_map,
1ad8e8c3 133 _temp_classes => [],
996be9ee 134 };
135
1ad8e8c3 136 weaken $self->{base}; #< don't leak
137
138 bless $self => $class;
4c7b5f46 139
c8c27020 140 # validate the relationship_attrs arg
1ad8e8c3 141 if( defined $self->relationship_attrs ) {
142 ref $self->relationship_attrs eq 'HASH'
c8c27020 143 or croak "relationship_attrs must be a hashref";
144 }
996be9ee 145
1ad8e8c3 146 return $self;
996be9ee 147}
148
149
150# pluralize a relationship name
151sub _inflect_plural {
ecf930e6 152 my ($self, $relname) = @_;
996be9ee 153
39ef3bfe 154 return '' if !defined $relname || $relname eq '';
155
1ad8e8c3 156 if( ref $self->inflect_plural eq 'HASH' ) {
157 return $self->inflect_plural->{$relname}
158 if exists $self->inflect_plural->{$relname};
996be9ee 159 }
1ad8e8c3 160 elsif( ref $self->inflect_plural eq 'CODE' ) {
161 my $inflected = $self->inflect_plural->($relname);
996be9ee 162 return $inflected if $inflected;
163 }
164
ecf930e6 165 return $self->_to_PL($relname);
996be9ee 166}
167
168# Singularize a relationship name
169sub _inflect_singular {
ecf930e6 170 my ($self, $relname) = @_;
996be9ee 171
39ef3bfe 172 return '' if !defined $relname || $relname eq '';
173
1ad8e8c3 174 if( ref $self->inflect_singular eq 'HASH' ) {
175 return $self->inflect_singular->{$relname}
176 if exists $self->inflect_singular->{$relname};
996be9ee 177 }
1ad8e8c3 178 elsif( ref $self->inflect_singular eq 'CODE' ) {
179 my $inflected = $self->inflect_singular->($relname);
996be9ee 180 return $inflected if $inflected;
181 }
182
ecf930e6 183 return $self->_to_S($relname);
c496748b 184}
185
186sub _to_PL {
187 my ($self, $name) = @_;
188
189 $name =~ s/_/ /g;
39b22ca9 190 my $plural = Lingua::EN::Inflect::Phrase::to_PL($name);
c496748b 191 $plural =~ s/ /_/g;
192
193 return $plural;
194}
195
c496748b 196sub _to_S {
197 my ($self, $name) = @_;
198
39b22ca9 199 $name =~ s/_/ /g;
200 my $singular = Lingua::EN::Inflect::Phrase::to_S($name);
201 $singular =~ s/ /_/g;
202
203 return $singular;
996be9ee 204}
205
53ef681d 206sub _default_relationship_attrs { +{
207 has_many => {
208 cascade_delete => 0,
209 cascade_copy => 0,
210 },
211 might_have => {
212 cascade_delete => 0,
213 cascade_copy => 0,
214 },
215 belongs_to => {
216 on_delete => 'CASCADE',
217 on_update => 'CASCADE',
aa0867ee 218 is_deferrable => 1,
53ef681d 219 },
220} }
221
c8c27020 222# accessor for options to be passed to each generated relationship
223# type. take single argument, the relationship type name, and returns
224# either a hashref (if some options are set), or nothing
225sub _relationship_attrs {
226 my ( $self, $reltype ) = @_;
1ad8e8c3 227 my $r = $self->relationship_attrs;
c8c27020 228
53ef681d 229 my %composite = (
230 %{ $self->_default_relationship_attrs->{$reltype} || {} },
231 %{ $r->{all} || {} }
232 );
233
c8c27020 234 if( my $specific = $r->{$reltype} ) {
235 while( my ($k,$v) = each %$specific ) {
236 $composite{$k} = $v;
237 }
238 }
239 return \%composite;
240}
241
26f1c8c9 242sub _array_eq {
ecf930e6 243 my ($self, $a, $b) = @_;
26f1c8c9 244
245 return unless @$a == @$b;
246
247 for (my $i = 0; $i < @$a; $i++) {
248 return unless $a->[$i] eq $b->[$i];
249 }
250 return 1;
251}
252
c39e403e 253sub _remote_attrs {
c496748b 254 my ($self, $local_moniker, $local_cols) = @_;
c39e403e 255
c496748b 256 # get our base set of attrs from _relationship_attrs, if present
257 my $attrs = $self->_relationship_attrs('belongs_to') || {};
c8c27020 258
c496748b 259 # If the referring column is nullable, make 'belongs_to' an
260 # outer join, unless explicitly set by relationship_attrs
1ad8e8c3 261 my $nullable = grep { $self->schema->source($local_moniker)->column_info($_)->{is_nullable} } @$local_cols;
c496748b 262 $attrs->{join_type} = 'LEFT' if $nullable && !defined $attrs->{join_type};
c39e403e 263
c496748b 264 return $attrs;
c39e403e 265}
266
414c61a0 267sub _sanitize_name {
268 my ($self, $name) = @_;
269
270 if (ref $name) {
271 # scalar ref for weird table name (like one containing a '.')
272 ($name = $$name) =~ s/\W+/_/g;
273 }
274 else {
275 # remove 'schema.' prefix if any
276 $name =~ s/^[^.]+\.//;
277 }
278
279 return $name;
280}
281
19b7d71c 282sub _normalize_name {
283 my ($self, $name) = @_;
284
414c61a0 285 $name = $self->_sanitize_name($name);
286
cc4f11a2 287 my @words = split_name $name;
19b7d71c 288
289 return join '_', map lc, @words;
290}
291
f2fc8d01 292sub _remote_relname {
293 my ($self, $remote_table, $cond) = @_;
294
295 my $remote_relname;
296 # for single-column case, set the remote relname to the column
297 # name, to make filter accessors work, but strip trailing _id
298 if(scalar keys %{$cond} == 1) {
299 my ($col) = values %{$cond};
19b7d71c 300 $col = $self->_normalize_name($col);
f2fc8d01 301 $col =~ s/_id$//;
302 $remote_relname = $self->_inflect_singular($col);
303 }
304 else {
19b7d71c 305 $remote_relname = $self->_inflect_singular($self->_normalize_name($remote_table));
f2fc8d01 306 }
307
308 return $remote_relname;
309}
310
a7116285 311sub _resolve_relname_collision {
312 my ($self, $moniker, $cols, $relname) = @_;
313
314 return $relname if $relname eq 'id'; # this shouldn't happen, but just in case
315
dc379dc6 316 my $table = $self->base->tables->{$moniker};
317
318 if ($self->base->_is_result_class_method($relname, $table)) {
a7116285 319 if (my $map = $self->rel_collision_map) {
320 for my $re (keys %$map) {
321 if (my @matches = $relname =~ /$re/) {
322 return sprintf $map->{$re}, @matches;
323 }
324 }
325 }
326
327 my $new_relname = $relname;
dc379dc6 328 while ($self->base->_is_result_class_method($new_relname, $table)) {
a7116285 329 $new_relname .= '_rel'
330 }
331
332 warn <<"EOF";
333Relationship '$relname' in source '$moniker' for columns '@{[ join ',', @$cols ]}' collides with an inherited method.
334Renaming to '$new_relname'.
335See "RELATIONSHIP NAME COLLISIONS" in perldoc DBIx::Class::Schema::Loader::Base .
336EOF
337
338 return $new_relname;
339 }
340
341 return $relname;
342}
343
996be9ee 344sub generate_code {
dc379dc6 345 my ($self, $tables) = @_;
346
347 # make a copy to destroy
348 my @tables = @$tables;
996be9ee 349
350 my $all_code = {};
351
dc379dc6 352 while (my ($local_moniker, $rels, $uniqs) = @{ shift @tables || [] }) {
353 my $local_class = $self->schema->class($local_moniker);
057fbb08 354
dc379dc6 355 my %counters;
356 foreach my $rel (@$rels) {
357 next if !$rel->{remote_source};
358 $counters{$rel->{remote_source}}++;
359 }
e8ad6491 360
dc379dc6 361 foreach my $rel (@$rels) {
362 my $remote_moniker = $rel->{remote_source}
363 or next;
057fbb08 364
dc379dc6 365 my $remote_class = $self->schema->class($remote_moniker);
366 my $remote_obj = $self->schema->source($remote_moniker);
367 my $remote_cols = $rel->{remote_columns} || [ $remote_obj->primary_columns ];
057fbb08 368
dc379dc6 369 my $local_cols = $rel->{local_columns};
e8ad6491 370
dc379dc6 371 if($#$local_cols != $#$remote_cols) {
372 croak "Column count mismatch: $local_moniker (@$local_cols) "
373 . "$remote_moniker (@$remote_cols)";
374 }
996be9ee 375
dc379dc6 376 my %cond;
377 foreach my $i (0 .. $#$local_cols) {
378 $cond{$remote_cols->[$i]} = $local_cols->[$i];
379 }
380
381 my ( $local_relname, $remote_relname, $remote_method ) =
382 $self->_relnames_and_method( $local_moniker, $rel, \%cond, $uniqs, \%counters );
383
384 $remote_relname = $self->_resolve_relname_collision($local_moniker, $local_cols, $remote_relname);
385 $local_relname = $self->_resolve_relname_collision($remote_moniker, $remote_cols, $local_relname);
386
387 push(@{$all_code->{$local_class}},
388 { method => 'belongs_to',
389 args => [ $remote_relname,
390 $remote_class,
391 \%cond,
392 $self->_remote_attrs($local_moniker, $local_cols),
393 ],
394 extra => {
395 moniker => $local_moniker,
396 },
397 }
398 );
399
400 my %rev_cond = reverse %cond;
401 for (keys %rev_cond) {
402 $rev_cond{"foreign.$_"} = "self.".$rev_cond{$_};
403 delete $rev_cond{$_};
404 }
405
406 push(@{$all_code->{$remote_class}},
407 { method => $remote_method,
408 args => [ $local_relname,
409 $local_class,
410 \%rev_cond,
411 $self->_relationship_attrs($remote_method),
412 ],
413 extra => {
414 moniker => $remote_moniker,
415 },
416 }
417 );
e8ad6491 418 }
dc379dc6 419 }
420
421 # disambiguate rels with the same name
422 foreach my $class (keys %$all_code) {
423 my $dups = $self->_duplicates($all_code->{$class});
996be9ee 424
dc379dc6 425 $self->_disambiguate($all_code->{$class}, $dups) if $dups;
426 }
427
428 $self->_cleanup;
429
430 return $all_code;
431}
432
433sub _duplicates {
434 my ($self, $rels) = @_;
435
436 my @rels = map [ $_->{args}[0] => $_ ], @$rels;
437 my %rel_names;
438 $rel_names{$_}++ foreach map $_->[0], @rels;
439
440 my @dups = grep $rel_names{$_} > 1, keys %rel_names;
441
442 my %dups;
443
444 foreach my $dup (@dups) {
445 $dups{$dup} = [ map $_->[1], grep { $_->[0] eq $dup } @rels ];
446 }
447
448 return if not %dups;
449
450 return \%dups;
451}
452
453sub _tagger {
454 my $self = shift;
455
456 $self->__tagger(Lingua::EN::Tagger->new) unless $self->__tagger;
457
458 return $self->__tagger;
459}
7dba7c70 460
dc379dc6 461sub _adjectives {
462 my ($self, @cols) = @_;
a7116285 463
dc379dc6 464 my @adjectives;
465
466 foreach my $col (@cols) {
467 my @words = split_name $col;
468
469 my $tagged = $self->_tagger->get_readable(join ' ', @words);
470
471 push @adjectives, $tagged =~ m{\G(\w+)/JJ\s+}g;
472 }
473
474 return @adjectives;
475}
476
477sub _disambiguate {
478 my ($self, $all_rels, $dups) = @_;
479
480 foreach my $dup (keys %$dups) {
481 my @rels = @{ $dups->{$dup} };
482
483 foreach my $rel (@rels) {
484 next if $rel->{method} eq 'belongs_to';
485
486 my @to_cols = apply { s/^foreign\.//i }
487 keys %{ $rel->{args}[2] };
488
489 my @adjectives = $self->_adjectives(@to_cols);
490
491 # If there are no adjectives, and there is only one might_have
492 # rel to that class, we hardcode 'active'.
493
494 my $to_class = $rel->{args}[1];
495
496 if ((not @adjectives)
497 && (grep { $_->{method} eq 'might_have'
498 && $_->{args}[1] eq $to_class } @$all_rels) == 1) {
499
500 @adjectives = 'active';
996be9ee 501 }
e8ad6491 502
dc379dc6 503 if (@adjectives) {
504 my $rel_name = join '_', sort(@adjectives), $rel->{args}[0];
505
506 $rel_name = $rel->{method} eq 'might_have' ?
507 $self->_inflect_singular($rel_name)
508 :
509 $self->_inflect_plural($rel_name);
510
511 my $moniker = $rel->{extra}{moniker};
512
513 my @from_cols = apply { s/^self\.//i }
514 values %{ $rel->{args}[2] };
057fbb08 515
dc379dc6 516 $rel_name = $self->_resolve_relname_collision($moniker, \@from_cols, $rel_name);
517
518 $rel->{args}[0] = $rel_name;
e8ad6491 519 }
dc379dc6 520 }
996be9ee 521 }
522
dc379dc6 523 # Check again for duplicates, since the heuristics above may not have resolved them all.
524
525 if ($dups = $self->_duplicates($all_rels)) {
526 foreach my $dup (keys %$dups) {
527 # sort by method
528 my @rels = map $_->[1], sort { $a->[0] <=> $b->[0] } map [
529 ($_->{method} eq 'belongs_to' ? 3 : $_->{method} eq 'has_many' ? 2 : 1), $_
530 ], @{ $dups->{$dup} };
531
532 my $rel_num = 2;
533
534 foreach my $rel (@rels[1 .. $#rels]) {
535 my $inflect_type = $rel->{method} eq 'has_many' ?
536 'inflect_plural'
537 :
538 'inflect_singular';
539
540 my $inflect_method = "_$inflect_type";
541
542 my $relname_new_uninflected =
543 $self->_inflect_singular($rel->{args}[0]) . "_$rel_num";
544
545 $rel_num++;
546
547 my $relname_new = $self->$inflect_method($relname_new_uninflected);
548
549 my $moniker = $rel->{extra}{moniker};
550
551 my @from_cols = apply { s/^self\.//i }
552 values %{ $rel->{args}[2] };
553
554 warn <<"EOF";
555Could not find a proper name for relationship '$relname_new' in source '$moniker' for columns '@{[ join ',', @from_cols ]}'.
556Supply a value in '$inflect_type' for '$relname_new_uninflected' to name this relationship.
557EOF
558
aa608e1a 559 $relname_new = $self->_resolve_relname_collision($moniker, \@from_cols, $relname_new);
560
dc379dc6 561 $rel->{args}[0] = $relname_new;
562 }
563 }
564 }
996be9ee 565}
566
39ef3bfe 567sub _relnames_and_method {
057fbb08 568 my ( $self, $local_moniker, $rel, $cond, $uniqs, $counters ) = @_;
e9c09ed9 569
057fbb08 570 my $remote_moniker = $rel->{remote_source};
1ad8e8c3 571 my $remote_obj = $self->schema->source( $remote_moniker );
572 my $remote_class = $self->schema->class( $remote_moniker );
ecf930e6 573 my $remote_relname = $self->_remote_relname( $remote_obj->from, $cond);
fa6f8d4e 574
1ad8e8c3 575 my $local_cols = $rel->{local_columns};
576 my $local_table = $self->schema->source($local_moniker)->from;
577 my $local_class = $self->schema->class($local_moniker);
578 my $local_source = $self->schema->source($local_moniker);
057fbb08 579
1ad8e8c3 580 my $local_relname_uninflected = $self->_normalize_name($local_table);
581 my $local_relname = $self->_inflect_plural($self->_normalize_name($local_table));
fa6f8d4e 582
057fbb08 583 my $remote_method = 'has_many';
584
585 # If the local columns have a UNIQUE constraint, this is a one-to-one rel
ecf930e6 586 if ($self->_array_eq([ $local_source->primary_columns ], $local_cols) ||
587 grep { $self->_array_eq($_->[1], $local_cols) } @$uniqs) {
057fbb08 588 $remote_method = 'might_have';
c496748b 589 $local_relname = $self->_inflect_singular($local_relname_uninflected);
057fbb08 590 }
fa6f8d4e 591
1ad8e8c3 592 # If more than one rel between this pair of tables, use the local
593 # col names to distinguish, unless the rel was created previously.
594 if ($counters->{$remote_moniker} > 1) {
595 my $relationship_exists = 0;
596
6e4b7bb1 597 if (-f (my $existing_remote_file = $self->base->get_dump_filename($remote_class))) {
1ad8e8c3 598 my $class = "${remote_class}Temporary";
599
8c70d2c7 600 if (not Class::Inspector->loaded($class)) {
af15ea33 601 my $code = decode 'UTF-8', scalar slurp $existing_remote_file;
1ad8e8c3 602
603 $code =~ s/(?<=package $remote_class)/Temporary/g;
604
6e4b7bb1 605 $code =~ s/__PACKAGE__->meta->make_immutable[^;]*;//g;
1ad8e8c3 606
607 eval $code;
608 die $@ if $@;
609
610 push @{ $self->_temp_classes }, $class;
611 }
612
613 if ($class->has_relationship($local_relname)) {
614 my $rel_cols = [ sort { $a cmp $b } apply { s/^foreign\.//i }
615 (keys %{ $class->relationship_info($local_relname)->{cond} }) ];
616
617 $relationship_exists = 1 if $self->_array_eq([ sort @$local_cols ], $rel_cols);
618 }
619 }
620
621 if (not $relationship_exists) {
622 my $colnames = q{_} . $self->_normalize_name(join '_', @$local_cols);
623 $remote_relname .= $colnames if keys %$cond > 1;
624
625 $local_relname = $self->_normalize_name($local_table . $colnames);
626 $local_relname =~ s/_id$//;
627
628 $local_relname_uninflected = $local_relname;
629 $local_relname = $self->_inflect_plural($local_relname);
630
631 # if colnames were added and this is a might_have, re-inflect
632 if ($remote_method eq 'might_have') {
633 $local_relname = $self->_inflect_singular($local_relname_uninflected);
634 }
635 }
636 }
637
057fbb08 638 return ( $local_relname, $remote_relname, $remote_method );
fa6f8d4e 639}
640
dc379dc6 641sub _cleanup {
1ad8e8c3 642 my $self = shift;
643
644 for my $class (@{ $self->_temp_classes }) {
645 Class::Unload->unload($class);
646 }
647
648 $self->_temp_classes([]);
649}
650
be80bba7 651=head1 AUTHOR
652
9cc8e7e1 653See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
be80bba7 654
655=head1 LICENSE
656
657This library is free software; you can redistribute it and/or modify it under
658the same terms as Perl itself.
659
660=cut
661
996be9ee 6621;
19b7d71c 663# vim:et sts=4 sw=4 tw=0: