release 0.07027
[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';
50b95db6 9use DBIx::Class::Schema::Loader::Utils qw/split_name slurp_file array_eq/;
1ad8e8c3 10use Try::Tiny;
eaf23084 11use List::Util 'first';
5975bbe6 12use List::MoreUtils qw/apply uniq any/;
1ad8e8c3 13use namespace::clean;
c4a69b87 14use Lingua::EN::Inflect::Phrase ();
15use Lingua::EN::Tagger ();
5975bbe6 16use String::ToIdentifier::EN ();
17use String::ToIdentifier::EN::Unicode ();
c4a69b87 18use Class::Unload ();
19use Class::Inspector ();
996be9ee 20
ef73d2ad 21our $VERSION = '0.07027';
32f784fc 22
6e4b7bb1 23# Glossary:
24#
25# remote_relname -- name of relationship from the local table referring to the remote table
26# local_relname -- name of relationship from the remote table referring to the local table
27# remote_method -- relationship type from remote table to local table, usually has_many
28
996be9ee 29=head1 NAME
30
31DBIx::Class::Schema::Loader::RelBuilder - Builds relationships for DBIx::Class::Schema::Loader
32
33=head1 SYNOPSIS
34
19b7d71c 35See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
996be9ee 36
37=head1 DESCRIPTION
38
39This class builds relationships for L<DBIx::Class::Schema::Loader>. This
40is module is not (yet) for external use.
41
42=head1 METHODS
43
44=head2 new
45
404aefa4 46Arguments: $loader object
996be9ee 47
48=head2 generate_code
49
9dedee1f 50Arguments:
51
c4a69b87 52 [
53 [ local_moniker1 (scalar), fk_info1 (arrayref), uniq_info1 (arrayref) ]
54 [ local_moniker2 (scalar), fk_info2 (arrayref), uniq_info2 (arrayref) ]
dc379dc6 55 ...
c4a69b87 56 ]
e8ad6491 57
dc379dc6 58This generates the code for the relationships of each table.
e8ad6491 59
60C<local_moniker> is the moniker name of the table which had the REFERENCES
61statements. The fk_info arrayref's contents should take the form:
62
63 [
64 {
c4a69b87 65 local_table => 'some_table',
66 local_moniker => 'SomeTable',
67 local_columns => [ 'col2', 'col3' ],
68 remote_table => 'another_table_moniker',
e8ad6491 69 remote_moniker => 'AnotherTableMoniker',
c4a69b87 70 remote_columns => [ 'col5', 'col7' ],
e8ad6491 71 },
72 {
c4a69b87 73 local_table => 'some_other_table',
74 local_moniker => 'SomeOtherTable',
75 local_columns => [ 'col1', 'col4' ],
76 remote_table => 'yet_another_table_moniker',
e8ad6491 77 remote_moniker => 'YetAnotherTableMoniker',
c4a69b87 78 remote_columns => [ 'col1', 'col2' ],
e8ad6491 79 },
80 # ...
81 ],
82
dc379dc6 83The uniq_info arrayref's contents should take the form:
84
85 [
86 [
87 uniq_constraint_name => [ 'col1', 'col2' ],
88 ],
89 [
90 another_uniq_constraint_name => [ 'col1', 'col2' ],
91 ],
92 ],
93
e8ad6491 94This method will return the generated relationships as a hashref keyed on the
95class names. The values are arrayrefs of hashes containing method name and
96arguments, like so:
996be9ee 97
98 {
99 'Some::Source::Class' => [
b97c2c1e 100 { method => 'belongs_to', arguments => [ 'col1', 'Another::Source::Class' ],
101 { method => 'has_many', arguments => [ 'anothers', 'Yet::Another::Source::Class', 'col15' ],
996be9ee 102 ],
103 'Another::Source::Class' => [
104 # ...
105 ],
106 # ...
107 }
8f9d7ce5 108
996be9ee 109=cut
110
1ad8e8c3 111__PACKAGE__->mk_group_accessors('simple', qw/
404aefa4 112 loader
1ad8e8c3 113 schema
114 inflect_plural
115 inflect_singular
116 relationship_attrs
a7116285 117 rel_collision_map
59388920 118 rel_name_map
1ad8e8c3 119 _temp_classes
dc379dc6 120 __tagger
1ad8e8c3 121/);
4c7b5f46 122
996be9ee 123sub new {
404aefa4 124 my ($class, $loader) = @_;
4c7b5f46 125
126 # from old POD about this constructor:
127 # C<$schema_class> should be a schema class name, where the source
128 # classes have already been set up and registered. Column info,
129 # primary key, and unique constraints will be drawn from this
130 # schema for all of the existing source monikers.
131
132 # Options inflect_plural and inflect_singular are optional, and
133 # are better documented in L<DBIx::Class::Schema::Loader::Base>.
996be9ee 134
135 my $self = {
404aefa4 136 loader => $loader,
137 schema => $loader->schema,
138 inflect_plural => $loader->inflect_plural,
139 inflect_singular => $loader->inflect_singular,
140 relationship_attrs => $loader->relationship_attrs,
141 rel_collision_map => $loader->rel_collision_map,
142 rel_name_map => $loader->rel_name_map,
1ad8e8c3 143 _temp_classes => [],
996be9ee 144 };
145
404aefa4 146 weaken $self->{loader}; #< don't leak
1ad8e8c3 147
148 bless $self => $class;
4c7b5f46 149
c8c27020 150 # validate the relationship_attrs arg
1ad8e8c3 151 if( defined $self->relationship_attrs ) {
5c06aa08 152 ref $self->relationship_attrs eq 'HASH'
153 or croak "relationship_attrs must be a hashref";
c8c27020 154 }
996be9ee 155
1ad8e8c3 156 return $self;
996be9ee 157}
158
159
160# pluralize a relationship name
161sub _inflect_plural {
ecf930e6 162 my ($self, $relname) = @_;
996be9ee 163
39ef3bfe 164 return '' if !defined $relname || $relname eq '';
165
59388920 166 my $result;
167 my $mapped = 0;
168
1ad8e8c3 169 if( ref $self->inflect_plural eq 'HASH' ) {
59388920 170 if (exists $self->inflect_plural->{$relname}) {
171 $result = $self->inflect_plural->{$relname};
172 $mapped = 1;
173 }
996be9ee 174 }
1ad8e8c3 175 elsif( ref $self->inflect_plural eq 'CODE' ) {
176 my $inflected = $self->inflect_plural->($relname);
59388920 177 if ($inflected) {
178 $result = $inflected;
179 $mapped = 1;
180 }
996be9ee 181 }
182
59388920 183 return ($result, $mapped) if $mapped;
184
185 return ($self->_to_PL($relname), 0);
996be9ee 186}
187
188# Singularize a relationship name
189sub _inflect_singular {
ecf930e6 190 my ($self, $relname) = @_;
996be9ee 191
39ef3bfe 192 return '' if !defined $relname || $relname eq '';
193
59388920 194 my $result;
195 my $mapped = 0;
196
1ad8e8c3 197 if( ref $self->inflect_singular eq 'HASH' ) {
59388920 198 if (exists $self->inflect_singular->{$relname}) {
199 $result = $self->inflect_singular->{$relname};
200 $mapped = 1;
201 }
996be9ee 202 }
1ad8e8c3 203 elsif( ref $self->inflect_singular eq 'CODE' ) {
204 my $inflected = $self->inflect_singular->($relname);
59388920 205 if ($inflected) {
206 $result = $inflected;
207 $mapped = 1;
208 }
996be9ee 209 }
210
59388920 211 return ($result, $mapped) if $mapped;
212
213 return ($self->_to_S($relname), 0);
c496748b 214}
215
216sub _to_PL {
217 my ($self, $name) = @_;
218
219 $name =~ s/_/ /g;
39b22ca9 220 my $plural = Lingua::EN::Inflect::Phrase::to_PL($name);
c496748b 221 $plural =~ s/ /_/g;
222
223 return $plural;
224}
225
c496748b 226sub _to_S {
227 my ($self, $name) = @_;
228
39b22ca9 229 $name =~ s/_/ /g;
230 my $singular = Lingua::EN::Inflect::Phrase::to_S($name);
231 $singular =~ s/ /_/g;
232
233 return $singular;
996be9ee 234}
235
53ef681d 236sub _default_relationship_attrs { +{
237 has_many => {
238 cascade_delete => 0,
239 cascade_copy => 0,
240 },
241 might_have => {
242 cascade_delete => 0,
243 cascade_copy => 0,
244 },
245 belongs_to => {
246 on_delete => 'CASCADE',
247 on_update => 'CASCADE',
aa0867ee 248 is_deferrable => 1,
53ef681d 249 },
250} }
251
9dedee1f 252# Accessor for options to be passed to each generated relationship type. takes
253# the relationship type name and optionally any attributes from the database
254# (such as FK ON DELETE/UPDATE and DEFERRABLE clauses), and returns a
255# hashref or undef if nothing is set.
256#
257# The attributes from the database override the default attributes, which in
258# turn are overridden by user supplied attributes.
c8c27020 259sub _relationship_attrs {
9dedee1f 260 my ( $self, $reltype, $db_attrs ) = @_;
1ad8e8c3 261 my $r = $self->relationship_attrs;
c8c27020 262
53ef681d 263 my %composite = (
264 %{ $self->_default_relationship_attrs->{$reltype} || {} },
9dedee1f 265 %{ $db_attrs || {} },
266 %{ $r->{all} || {} },
267 %{ $r->{$reltype} || {} },
53ef681d 268 );
269
9dedee1f 270 return %composite ? \%composite : undef;
c8c27020 271}
272
ccf9b8a6 273sub _strip_id_postfix {
274 my ($self, $name) = @_;
275
276 $name =~ s/_?(?:id|ref|cd|code|num)\z//i;
277
278 return $name;
279}
280
c39e403e 281sub _remote_attrs {
9dedee1f 282 my ($self, $local_moniker, $local_cols, $fk_attrs) = @_;
c39e403e 283
9dedee1f 284 # get our set of attrs from _relationship_attrs, which uses the FK attrs if available
285 my $attrs = $self->_relationship_attrs('belongs_to', $fk_attrs) || {};
c8c27020 286
eaf23084 287 # If any referring column is nullable, make 'belongs_to' an
c496748b 288 # outer join, unless explicitly set by relationship_attrs
eaf23084 289 my $nullable = first { $self->schema->source($local_moniker)->column_info($_)->{is_nullable} } @$local_cols;
c496748b 290 $attrs->{join_type} = 'LEFT' if $nullable && !defined $attrs->{join_type};
c39e403e 291
c496748b 292 return $attrs;
c39e403e 293}
294
414c61a0 295sub _sanitize_name {
296 my ($self, $name) = @_;
297
df35916c 298 $name = $self->loader->_to_identifier('relationships', $name, '_');
299
300 $name =~ s/\W+/_/g; # if naming >= 8 to_identifier takes care of it
414c61a0 301
302 return $name;
303}
304
19b7d71c 305sub _normalize_name {
306 my ($self, $name) = @_;
307
414c61a0 308 $name = $self->_sanitize_name($name);
309
ea3b8f03 310 my @words = split_name $name, $self->loader->_get_naming_v('relationships');
19b7d71c 311
312 return join '_', map lc, @words;
313}
314
f2fc8d01 315sub _remote_relname {
316 my ($self, $remote_table, $cond) = @_;
317
318 my $remote_relname;
319 # for single-column case, set the remote relname to the column
320 # name, to make filter accessors work, but strip trailing _id
321 if(scalar keys %{$cond} == 1) {
322 my ($col) = values %{$cond};
ccf9b8a6 323 $col = $self->_strip_id_postfix($self->_normalize_name($col));
59388920 324 ($remote_relname) = $self->_inflect_singular($col);
f2fc8d01 325 }
326 else {
59388920 327 ($remote_relname) = $self->_inflect_singular($self->_normalize_name($remote_table));
f2fc8d01 328 }
329
330 return $remote_relname;
331}
332
a7116285 333sub _resolve_relname_collision {
334 my ($self, $moniker, $cols, $relname) = @_;
335
336 return $relname if $relname eq 'id'; # this shouldn't happen, but just in case
337
c4a69b87 338 my $table = $self->loader->moniker_to_table->{$moniker};
dc379dc6 339
404aefa4 340 if ($self->loader->_is_result_class_method($relname, $table)) {
a7116285 341 if (my $map = $self->rel_collision_map) {
342 for my $re (keys %$map) {
343 if (my @matches = $relname =~ /$re/) {
344 return sprintf $map->{$re}, @matches;
345 }
346 }
347 }
348
349 my $new_relname = $relname;
404aefa4 350 while ($self->loader->_is_result_class_method($new_relname, $table)) {
a7116285 351 $new_relname .= '_rel'
352 }
353
354 warn <<"EOF";
c4a69b87 355Relationship '$relname' in source '$moniker' for columns '@{[ join ',', @$cols ]}' collides with an inherited method. Renaming to '$new_relname'.
a7116285 356See "RELATIONSHIP NAME COLLISIONS" in perldoc DBIx::Class::Schema::Loader::Base .
357EOF
358
359 return $new_relname;
360 }
361
362 return $relname;
363}
364
996be9ee 365sub generate_code {
dc379dc6 366 my ($self, $tables) = @_;
9dedee1f 367
dc379dc6 368 # make a copy to destroy
369 my @tables = @$tables;
996be9ee 370
371 my $all_code = {};
372
dc379dc6 373 while (my ($local_moniker, $rels, $uniqs) = @{ shift @tables || [] }) {
374 my $local_class = $self->schema->class($local_moniker);
057fbb08 375
dc379dc6 376 my %counters;
377 foreach my $rel (@$rels) {
378 next if !$rel->{remote_source};
379 $counters{$rel->{remote_source}}++;
380 }
e8ad6491 381
dc379dc6 382 foreach my $rel (@$rels) {
383 my $remote_moniker = $rel->{remote_source}
384 or next;
057fbb08 385
dc379dc6 386 my $remote_class = $self->schema->class($remote_moniker);
387 my $remote_obj = $self->schema->source($remote_moniker);
388 my $remote_cols = $rel->{remote_columns} || [ $remote_obj->primary_columns ];
057fbb08 389
dc379dc6 390 my $local_cols = $rel->{local_columns};
e8ad6491 391
dc379dc6 392 if($#$local_cols != $#$remote_cols) {
393 croak "Column count mismatch: $local_moniker (@$local_cols) "
394 . "$remote_moniker (@$remote_cols)";
395 }
996be9ee 396
dc379dc6 397 my %cond;
398 foreach my $i (0 .. $#$local_cols) {
399 $cond{$remote_cols->[$i]} = $local_cols->[$i];
400 }
401
402 my ( $local_relname, $remote_relname, $remote_method ) =
403 $self->_relnames_and_method( $local_moniker, $rel, \%cond, $uniqs, \%counters );
59388920 404 my $local_method = 'belongs_to';
405
406 ($remote_relname) = $self->_rel_name_map($remote_relname, $local_method, $local_class, $local_moniker, $local_cols, $remote_class, $remote_moniker, $remote_cols);
407 ($local_relname) = $self->_rel_name_map($local_relname, $remote_method, $remote_class, $remote_moniker, $remote_cols, $local_class, $local_moniker, $local_cols);
dc379dc6 408
59388920 409 $remote_relname = $self->_resolve_relname_collision($local_moniker, $local_cols, $remote_relname);
410 $local_relname = $self->_resolve_relname_collision($remote_moniker, $remote_cols, $local_relname);
dc379dc6 411
412 push(@{$all_code->{$local_class}},
59388920 413 { method => $local_method,
dc379dc6 414 args => [ $remote_relname,
415 $remote_class,
416 \%cond,
9dedee1f 417 $self->_remote_attrs($local_moniker, $local_cols, $rel->{attrs}),
dc379dc6 418 ],
419 extra => {
59388920 420 local_class => $local_class,
421 local_moniker => $local_moniker,
422 remote_moniker => $remote_moniker,
dc379dc6 423 },
424 }
425 );
426
427 my %rev_cond = reverse %cond;
428 for (keys %rev_cond) {
429 $rev_cond{"foreign.$_"} = "self.".$rev_cond{$_};
430 delete $rev_cond{$_};
431 }
432
433 push(@{$all_code->{$remote_class}},
434 { method => $remote_method,
435 args => [ $local_relname,
436 $local_class,
437 \%rev_cond,
438 $self->_relationship_attrs($remote_method),
439 ],
440 extra => {
59388920 441 local_class => $remote_class,
442 local_moniker => $remote_moniker,
443 remote_moniker => $local_moniker,
dc379dc6 444 },
445 }
446 );
e8ad6491 447 }
dc379dc6 448 }
449
eaf23084 450 $self->_generate_m2ms($all_code);
451
dc379dc6 452 # disambiguate rels with the same name
453 foreach my $class (keys %$all_code) {
454 my $dups = $self->_duplicates($all_code->{$class});
996be9ee 455
eaf23084 456 $self->_disambiguate($all_code, $class, $dups) if $dups;
dc379dc6 457 }
458
459 $self->_cleanup;
460
461 return $all_code;
462}
463
eaf23084 464# Find classes with only 2 FKs which are the PK and make many_to_many bridges for them.
465sub _generate_m2ms {
466 my ($self, $all_code) = @_;
467
468 while (my ($class, $rels) = each %$all_code) {
469 next unless (grep $_->{method} eq 'belongs_to', @$rels) == 2;
470
471 my $class1_local_moniker = $rels->[0]{extra}{remote_moniker};
472 my $class1_remote_moniker = $rels->[1]{extra}{remote_moniker};
473
474 my $class2_local_moniker = $rels->[1]{extra}{remote_moniker};
475 my $class2_remote_moniker = $rels->[0]{extra}{remote_moniker};
476
477 my $class1 = $rels->[0]{args}[1];
478 my $class2 = $rels->[1]{args}[1];
479
480 my $class1_to_link_table_rel = first {
481 $_->{method} eq 'has_many' && $_->{args}[1] eq $class
482 } @{ $all_code->{$class1} };
483
484 my $class1_to_link_table_rel_name = $class1_to_link_table_rel->{args}[0];
485
486 my $class2_to_link_table_rel = first {
487 $_->{method} eq 'has_many' && $_->{args}[1] eq $class
488 } @{ $all_code->{$class2} };
489
490 my $class2_to_link_table_rel_name = $class2_to_link_table_rel->{args}[0];
491
492 my $class1_link_rel = $rels->[1]{args}[0];
493 my $class2_link_rel = $rels->[0]{args}[0];
494
495 my @class1_from_cols = apply { s/^self\.//i } values %{
496 $class1_to_link_table_rel->{args}[2]
497 };
498
499 my @class1_link_cols = apply { s/^self\.//i } values %{ $rels->[1]{args}[2] };
500
501 my @class1_to_cols = apply { s/^foreign\.//i } keys %{ $rels->[1]{args}[2] };
502
503 my @class2_from_cols = apply { s/^self\.//i } values %{
504 $class2_to_link_table_rel->{args}[2]
505 };
506
507 my @class2_link_cols = apply { s/^self\.//i } values %{ $rels->[0]{args}[2] };
508
509 my @class2_to_cols = apply { s/^foreign\.//i } keys %{ $rels->[0]{args}[2] };
510
511 my @link_table_cols =
512 @{[ $self->schema->source($rels->[0]{extra}{local_moniker})->columns ]};
513
514 my @link_table_primary_cols =
515 @{[ $self->schema->source($rels->[0]{extra}{local_moniker})->primary_columns ]};
516
517 next unless @class1_link_cols + @class2_link_cols == @link_table_cols
518 && @link_table_cols == @link_table_primary_cols;
519
520 my ($class1_to_class2_relname) = $self->_rel_name_map(
521 ($self->_inflect_plural($class1_link_rel))[0],
522 'many_to_many',
523 $class1,
524 $class1_local_moniker,
525 \@class1_from_cols,
526 $class2,
527 $class1_remote_moniker,
528 \@class1_to_cols,
529 );
530
531 $class1_to_class2_relname = $self->_resolve_relname_collision(
532 $class1_local_moniker,
533 \@class1_from_cols,
534 $class1_to_class2_relname,
535 );
536
537 my ($class2_to_class1_relname) = $self->_rel_name_map(
538 ($self->_inflect_plural($class2_link_rel))[0],
539 'many_to_many',
540 $class1,
541 $class2_local_moniker,
542 \@class2_from_cols,
543 $class2,
544 $class2_remote_moniker,
545 \@class2_to_cols,
546 );
547
548 $class2_to_class1_relname = $self->_resolve_relname_collision(
549 $class2_local_moniker,
550 \@class2_from_cols,
551 $class2_to_class1_relname,
552 );
553
554 push @{$all_code->{$class1}}, {
555 method => 'many_to_many',
556 args => [
557 $class1_to_class2_relname,
558 $class1_to_link_table_rel_name,
559 $class1_link_rel,
560 ],
561 extra => {
562 local_class => $class1,
563 link_class => $class,
564 local_moniker => $class1_local_moniker,
565 remote_moniker => $class1_remote_moniker,
566 },
567 };
568
569 push @{$all_code->{$class2}}, {
570 method => 'many_to_many',
571 args => [
572 $class2_to_class1_relname,
573 $class2_to_link_table_rel_name,
574 $class2_link_rel,
575 ],
576 extra => {
577 local_class => $class2,
578 link_class => $class,
579 local_moniker => $class2_local_moniker,
580 remote_moniker => $class2_remote_moniker,
581 },
582 };
583 }
584}
585
dc379dc6 586sub _duplicates {
587 my ($self, $rels) = @_;
588
589 my @rels = map [ $_->{args}[0] => $_ ], @$rels;
590 my %rel_names;
591 $rel_names{$_}++ foreach map $_->[0], @rels;
592
593 my @dups = grep $rel_names{$_} > 1, keys %rel_names;
594
595 my %dups;
596
597 foreach my $dup (@dups) {
598 $dups{$dup} = [ map $_->[1], grep { $_->[0] eq $dup } @rels ];
599 }
600
601 return if not %dups;
602
603 return \%dups;
604}
605
606sub _tagger {
607 my $self = shift;
608
609 $self->__tagger(Lingua::EN::Tagger->new) unless $self->__tagger;
610
611 return $self->__tagger;
612}
7dba7c70 613
dc379dc6 614sub _adjectives {
615 my ($self, @cols) = @_;
a7116285 616
dc379dc6 617 my @adjectives;
618
619 foreach my $col (@cols) {
620 my @words = split_name $col;
621
622 my $tagged = $self->_tagger->get_readable(join ' ', @words);
623
624 push @adjectives, $tagged =~ m{\G(\w+)/JJ\s+}g;
625 }
626
627 return @adjectives;
628}
629
5975bbe6 630sub _name_to_identifier {
631 my ($self, $name) = @_;
632
633 my $to_identifier = $self->loader->naming->{force_ascii} ?
634 \&String::ToIdentifier::EN::to_identifier
635 : \&String::ToIdentifier::EN::Unicode::to_identifier;
636
637 return join '_', map lc, split_name $to_identifier->($name, '_');
638}
639
dc379dc6 640sub _disambiguate {
eaf23084 641 my ($self, $all_code, $in_class, $dups) = @_;
dc379dc6 642
5975bbe6 643 DUP: foreach my $dup (keys %$dups) {
dc379dc6 644 my @rels = @{ $dups->{$dup} };
645
5975bbe6 646 # Check if there are rels to the same table name in different
647 # schemas/databases, if so qualify them.
648 my @tables = map $self->loader->moniker_to_table->{$_->{extra}{remote_moniker}},
649 @rels;
650
651 # databases are different, prepend database
652 if ($tables[0]->can('database') && (uniq map $_->database||'', @tables) > 1) {
653 # If any rels are in the same database, we have to distinguish by
654 # both schema and database.
655 my %db_counts;
656 $db_counts{$_}++ for map $_->database, @tables;
657 my $use_schema = any { $_ > 1 } values %db_counts;
658
659 foreach my $i (0..$#rels) {
660 my $rel = $rels[$i];
661 my $table = $tables[$i];
662
663 $rel->{args}[0] = $self->_name_to_identifier($table->database)
664 . ($use_schema ? ('_' . $self->name_to_identifier($table->schema)) : '')
665 . '_' . $rel->{args}[0];
666 }
667 next DUP;
668 }
669 # schemas are different, prepend schema
670 elsif ((uniq map $_->schema||'', @tables) > 1) {
671 foreach my $i (0..$#rels) {
672 my $rel = $rels[$i];
673 my $table = $tables[$i];
674
675 $rel->{args}[0] = $self->_name_to_identifier($table->schema)
676 . '_' . $rel->{args}[0];
677 }
678 next DUP;
679 }
680
dc379dc6 681 foreach my $rel (@rels) {
eaf23084 682 next if $rel->{method} =~ /^(?:belongs_to|many_to_many)\z/;
dc379dc6 683
684 my @to_cols = apply { s/^foreign\.//i }
685 keys %{ $rel->{args}[2] };
686
687 my @adjectives = $self->_adjectives(@to_cols);
688
689 # If there are no adjectives, and there is only one might_have
690 # rel to that class, we hardcode 'active'.
691
692 my $to_class = $rel->{args}[1];
693
694 if ((not @adjectives)
695 && (grep { $_->{method} eq 'might_have'
eaf23084 696 && $_->{args}[1] eq $to_class } @{ $all_code->{$in_class} }) == 1) {
dc379dc6 697
698 @adjectives = 'active';
996be9ee 699 }
e8ad6491 700
dc379dc6 701 if (@adjectives) {
702 my $rel_name = join '_', sort(@adjectives), $rel->{args}[0];
703
59388920 704 ($rel_name) = $rel->{method} eq 'might_have' ?
dc379dc6 705 $self->_inflect_singular($rel_name)
706 :
707 $self->_inflect_plural($rel_name);
708
59388920 709 my ($local_class, $local_moniker, $remote_moniker)
710 = @{ $rel->{extra} }
711 {qw/local_class local_moniker remote_moniker/};
dc379dc6 712
713 my @from_cols = apply { s/^self\.//i }
714 values %{ $rel->{args}[2] };
057fbb08 715
59388920 716 ($rel_name) = $self->_rel_name_map($rel_name, $rel->{method}, $local_class, $local_moniker, \@from_cols, $to_class, $remote_moniker, \@to_cols);
717
718 $rel_name = $self->_resolve_relname_collision($local_moniker, \@from_cols, $rel_name);
dc379dc6 719
720 $rel->{args}[0] = $rel_name;
e8ad6491 721 }
dc379dc6 722 }
996be9ee 723 }
724
dc379dc6 725 # Check again for duplicates, since the heuristics above may not have resolved them all.
726
eaf23084 727 if ($dups = $self->_duplicates($all_code->{$in_class})) {
dc379dc6 728 foreach my $dup (keys %$dups) {
729 # sort by method
730 my @rels = map $_->[1], sort { $a->[0] <=> $b->[0] } map [
eaf23084 731 {
732 belongs_to => 3,
733 has_many => 2,
734 might_have => 1,
735 many_to_many => 0,
736 }->{$_->{method}}, $_
dc379dc6 737 ], @{ $dups->{$dup} };
738
739 my $rel_num = 2;
740
741 foreach my $rel (@rels[1 .. $#rels]) {
eaf23084 742 my $inflect_type = $rel->{method} =~ /^(?:many_to_many|has_many)\z/ ?
dc379dc6 743 'inflect_plural'
744 :
745 'inflect_singular';
746
747 my $inflect_method = "_$inflect_type";
748
59388920 749 my $relname_new_uninflected = $rel->{args}[0] . "_$rel_num";
dc379dc6 750
751 $rel_num++;
752
59388920 753 my ($local_class, $local_moniker, $remote_moniker)
754 = @{ $rel->{extra} }
755 {qw/local_class local_moniker remote_moniker/};
dc379dc6 756
eaf23084 757 my (@from_cols, @to_cols, $to_class);
758
759 if ($rel->{method} eq 'many_to_many') {
760 @from_cols = apply { s/^self\.//i } values %{
761 (first { $_->{args}[0] eq $rel->{args}[1] } @{ $all_code->{$local_class} })
762 ->{args}[2]
763 };
764 @to_cols = apply { s/^foreign\.//i } keys %{
765 (first { $_->{args}[0] eq $rel->{args}[2] }
766 @{ $all_code->{ $rel->{extra}{link_class} } })
767 ->{args}[2]
768 };
769 $to_class = $self->schema->source($remote_moniker)->result_class;
770 }
771 else {
772 @from_cols = apply { s/^self\.//i } values %{ $rel->{args}[2] };
773 @to_cols = apply { s/^foreign\.//i } keys %{ $rel->{args}[2] };
774 $to_class = $rel->{args}[1];
775 }
59388920 776
777 my ($relname_new, $inflect_mapped) =
778 $self->$inflect_method($relname_new_uninflected);
779
780 my $rel_name_mapped;
781
782 ($relname_new, $rel_name_mapped) = $self->_rel_name_map($relname_new, $rel->{method}, $local_class, $local_moniker, \@from_cols, $to_class, $remote_moniker, \@to_cols);
9dedee1f 783
59388920 784 my $mapped = $inflect_mapped || $rel_name_mapped;
785
786 warn <<"EOF" unless $mapped;
787Could not find a proper name for relationship '$relname_new' in source
788'$local_moniker' for columns '@{[ join ',', @from_cols ]}'. Supply a value in
eaf23084 789'$inflect_type' for '$relname_new_uninflected' or 'rel_name_map' for
790'$relname_new' to name this relationship.
dc379dc6 791EOF
792
59388920 793 $relname_new = $self->_resolve_relname_collision($local_moniker, \@from_cols, $relname_new);
aa608e1a 794
dc379dc6 795 $rel->{args}[0] = $relname_new;
796 }
797 }
798 }
996be9ee 799}
800
39ef3bfe 801sub _relnames_and_method {
057fbb08 802 my ( $self, $local_moniker, $rel, $cond, $uniqs, $counters ) = @_;
e9c09ed9 803
59388920 804 my $remote_moniker = $rel->{remote_source};
805 my $remote_obj = $self->schema->source( $remote_moniker );
806 my $remote_class = $self->schema->class( $remote_moniker );
c4a69b87 807 my $remote_relname = $self->_remote_relname( $rel->{remote_table}, $cond);
fa6f8d4e 808
59388920 809 my $local_cols = $rel->{local_columns};
c4a69b87 810 my $local_table = $rel->{local_table};
59388920 811 my $local_class = $self->schema->class($local_moniker);
812 my $local_source = $self->schema->source($local_moniker);
057fbb08 813
1ad8e8c3 814 my $local_relname_uninflected = $self->_normalize_name($local_table);
59388920 815 my ($local_relname) = $self->_inflect_plural($self->_normalize_name($local_table));
fa6f8d4e 816
057fbb08 817 my $remote_method = 'has_many';
818
819 # If the local columns have a UNIQUE constraint, this is a one-to-one rel
50b95db6 820 if (array_eq([ $local_source->primary_columns ], $local_cols) ||
eaf23084 821 first { array_eq($_->[1], $local_cols) } @$uniqs) {
59388920 822 $remote_method = 'might_have';
823 ($local_relname) = $self->_inflect_singular($local_relname_uninflected);
057fbb08 824 }
fa6f8d4e 825
1ad8e8c3 826 # If more than one rel between this pair of tables, use the local
827 # col names to distinguish, unless the rel was created previously.
828 if ($counters->{$remote_moniker} > 1) {
829 my $relationship_exists = 0;
830
404aefa4 831 if (-f (my $existing_remote_file = $self->loader->get_dump_filename($remote_class))) {
1ad8e8c3 832 my $class = "${remote_class}Temporary";
833
8c70d2c7 834 if (not Class::Inspector->loaded($class)) {
fcf328c7 835 my $code = slurp_file $existing_remote_file;
1ad8e8c3 836
837 $code =~ s/(?<=package $remote_class)/Temporary/g;
838
6e4b7bb1 839 $code =~ s/__PACKAGE__->meta->make_immutable[^;]*;//g;
1ad8e8c3 840
841 eval $code;
842 die $@ if $@;
843
844 push @{ $self->_temp_classes }, $class;
845 }
846
847 if ($class->has_relationship($local_relname)) {
848 my $rel_cols = [ sort { $a cmp $b } apply { s/^foreign\.//i }
849 (keys %{ $class->relationship_info($local_relname)->{cond} }) ];
850
50b95db6 851 $relationship_exists = 1 if array_eq([ sort @$local_cols ], $rel_cols);
1ad8e8c3 852 }
853 }
854
855 if (not $relationship_exists) {
856 my $colnames = q{_} . $self->_normalize_name(join '_', @$local_cols);
857 $remote_relname .= $colnames if keys %$cond > 1;
858
ccf9b8a6 859 $local_relname = $self->_strip_id_postfix($self->_normalize_name($local_table . $colnames));
1ad8e8c3 860
861 $local_relname_uninflected = $local_relname;
59388920 862 ($local_relname) = $self->_inflect_plural($local_relname);
1ad8e8c3 863
864 # if colnames were added and this is a might_have, re-inflect
865 if ($remote_method eq 'might_have') {
59388920 866 ($local_relname) = $self->_inflect_singular($local_relname_uninflected);
1ad8e8c3 867 }
868 }
869 }
870
59388920 871 return ($local_relname, $remote_relname, $remote_method);
872}
873
874sub _rel_name_map {
875 my ($self, $relname, $method, $local_class, $local_moniker, $local_cols,
876 $remote_class, $remote_moniker, $remote_cols) = @_;
877
878 my $info = {
879 name => $relname,
880 type => $method,
881 local_class => $local_class,
882 local_moniker => $local_moniker,
883 local_columns => $local_cols,
884 remote_class => $remote_class,
885 remote_moniker => $remote_moniker,
886 remote_columns => $remote_cols,
887 };
888
889 my $new_name = $relname;
890
891 my $map = $self->rel_name_map;
892 my $mapped = 0;
893
894 if ('HASH' eq ref($map)) {
895 my $name = $info->{name};
896 my $moniker = $info->{local_moniker};
897 if ($map->{$moniker} and 'HASH' eq ref($map->{$moniker})
898 and $map->{$moniker}{$name}
899 ) {
900 $new_name = $map->{$moniker}{$name};
901 $mapped = 1;
902 }
903 elsif ($map->{$name} and not 'HASH' eq ref($map->{$name})) {
904 $new_name = $map->{$name};
905 $mapped = 1;
906 }
907 }
908 elsif ('CODE' eq ref($map)) {
909 my $name = $map->($info);
910 if ($name) {
911 $new_name = $name;
912 $mapped = 1;
913 }
914 }
915
916 return ($new_name, $mapped);
fa6f8d4e 917}
918
dc379dc6 919sub _cleanup {
1ad8e8c3 920 my $self = shift;
921
922 for my $class (@{ $self->_temp_classes }) {
923 Class::Unload->unload($class);
924 }
925
926 $self->_temp_classes([]);
927}
928
be80bba7 929=head1 AUTHOR
930
9cc8e7e1 931See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
be80bba7 932
933=head1 LICENSE
934
935This library is free software; you can redistribute it and/or modify it under
936the same terms as Perl itself.
937
938=cut
939
996be9ee 9401;
19b7d71c 941# vim:et sts=4 sw=4 tw=0: