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