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