release 0.07020
[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
dec80986 21our $VERSION = '0.07020';
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
dc379dc6 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
c8c27020 252# accessor for options to be passed to each generated relationship
253# type. take single argument, the relationship type name, and returns
254# either a hashref (if some options are set), or nothing
255sub _relationship_attrs {
256 my ( $self, $reltype ) = @_;
1ad8e8c3 257 my $r = $self->relationship_attrs;
c8c27020 258
53ef681d 259 my %composite = (
260 %{ $self->_default_relationship_attrs->{$reltype} || {} },
261 %{ $r->{all} || {} }
262 );
263
c8c27020 264 if( my $specific = $r->{$reltype} ) {
5c06aa08 265 while( my ($k,$v) = each %$specific ) {
266 $composite{$k} = $v;
267 }
c8c27020 268 }
269 return \%composite;
270}
271
ccf9b8a6 272sub _strip_id_postfix {
273 my ($self, $name) = @_;
274
275 $name =~ s/_?(?:id|ref|cd|code|num)\z//i;
276
277 return $name;
278}
279
c39e403e 280sub _remote_attrs {
c496748b 281 my ($self, $local_moniker, $local_cols) = @_;
c39e403e 282
c496748b 283 # get our base set of attrs from _relationship_attrs, if present
284 my $attrs = $self->_relationship_attrs('belongs_to') || {};
c8c27020 285
eaf23084 286 # If any referring column is nullable, make 'belongs_to' an
c496748b 287 # outer join, unless explicitly set by relationship_attrs
eaf23084 288 my $nullable = first { $self->schema->source($local_moniker)->column_info($_)->{is_nullable} } @$local_cols;
c496748b 289 $attrs->{join_type} = 'LEFT' if $nullable && !defined $attrs->{join_type};
c39e403e 290
c496748b 291 return $attrs;
c39e403e 292}
293
414c61a0 294sub _sanitize_name {
295 my ($self, $name) = @_;
296
df35916c 297 $name = $self->loader->_to_identifier('relationships', $name, '_');
298
299 $name =~ s/\W+/_/g; # if naming >= 8 to_identifier takes care of it
414c61a0 300
301 return $name;
302}
303
19b7d71c 304sub _normalize_name {
305 my ($self, $name) = @_;
306
414c61a0 307 $name = $self->_sanitize_name($name);
308
ea3b8f03 309 my @words = split_name $name, $self->loader->_get_naming_v('relationships');
19b7d71c 310
311 return join '_', map lc, @words;
312}
313
f2fc8d01 314sub _remote_relname {
315 my ($self, $remote_table, $cond) = @_;
316
317 my $remote_relname;
318 # for single-column case, set the remote relname to the column
319 # name, to make filter accessors work, but strip trailing _id
320 if(scalar keys %{$cond} == 1) {
321 my ($col) = values %{$cond};
ccf9b8a6 322 $col = $self->_strip_id_postfix($self->_normalize_name($col));
59388920 323 ($remote_relname) = $self->_inflect_singular($col);
f2fc8d01 324 }
325 else {
59388920 326 ($remote_relname) = $self->_inflect_singular($self->_normalize_name($remote_table));
f2fc8d01 327 }
328
329 return $remote_relname;
330}
331
a7116285 332sub _resolve_relname_collision {
333 my ($self, $moniker, $cols, $relname) = @_;
334
335 return $relname if $relname eq 'id'; # this shouldn't happen, but just in case
336
c4a69b87 337 my $table = $self->loader->moniker_to_table->{$moniker};
dc379dc6 338
404aefa4 339 if ($self->loader->_is_result_class_method($relname, $table)) {
a7116285 340 if (my $map = $self->rel_collision_map) {
341 for my $re (keys %$map) {
342 if (my @matches = $relname =~ /$re/) {
343 return sprintf $map->{$re}, @matches;
344 }
345 }
346 }
347
348 my $new_relname = $relname;
404aefa4 349 while ($self->loader->_is_result_class_method($new_relname, $table)) {
a7116285 350 $new_relname .= '_rel'
351 }
352
353 warn <<"EOF";
c4a69b87 354Relationship '$relname' in source '$moniker' for columns '@{[ join ',', @$cols ]}' collides with an inherited method. Renaming to '$new_relname'.
a7116285 355See "RELATIONSHIP NAME COLLISIONS" in perldoc DBIx::Class::Schema::Loader::Base .
356EOF
357
358 return $new_relname;
359 }
360
361 return $relname;
362}
363
996be9ee 364sub generate_code {
dc379dc6 365 my ($self, $tables) = @_;
366
367 # make a copy to destroy
368 my @tables = @$tables;
996be9ee 369
370 my $all_code = {};
371
dc379dc6 372 while (my ($local_moniker, $rels, $uniqs) = @{ shift @tables || [] }) {
373 my $local_class = $self->schema->class($local_moniker);
057fbb08 374
dc379dc6 375 my %counters;
376 foreach my $rel (@$rels) {
377 next if !$rel->{remote_source};
378 $counters{$rel->{remote_source}}++;
379 }
e8ad6491 380
dc379dc6 381 foreach my $rel (@$rels) {
382 my $remote_moniker = $rel->{remote_source}
383 or next;
057fbb08 384
dc379dc6 385 my $remote_class = $self->schema->class($remote_moniker);
386 my $remote_obj = $self->schema->source($remote_moniker);
387 my $remote_cols = $rel->{remote_columns} || [ $remote_obj->primary_columns ];
057fbb08 388
dc379dc6 389 my $local_cols = $rel->{local_columns};
e8ad6491 390
dc379dc6 391 if($#$local_cols != $#$remote_cols) {
392 croak "Column count mismatch: $local_moniker (@$local_cols) "
393 . "$remote_moniker (@$remote_cols)";
394 }
996be9ee 395
dc379dc6 396 my %cond;
397 foreach my $i (0 .. $#$local_cols) {
398 $cond{$remote_cols->[$i]} = $local_cols->[$i];
399 }
400
401 my ( $local_relname, $remote_relname, $remote_method ) =
402 $self->_relnames_and_method( $local_moniker, $rel, \%cond, $uniqs, \%counters );
59388920 403 my $local_method = 'belongs_to';
404
405 ($remote_relname) = $self->_rel_name_map($remote_relname, $local_method, $local_class, $local_moniker, $local_cols, $remote_class, $remote_moniker, $remote_cols);
406 ($local_relname) = $self->_rel_name_map($local_relname, $remote_method, $remote_class, $remote_moniker, $remote_cols, $local_class, $local_moniker, $local_cols);
dc379dc6 407
59388920 408 $remote_relname = $self->_resolve_relname_collision($local_moniker, $local_cols, $remote_relname);
409 $local_relname = $self->_resolve_relname_collision($remote_moniker, $remote_cols, $local_relname);
dc379dc6 410
411 push(@{$all_code->{$local_class}},
59388920 412 { method => $local_method,
dc379dc6 413 args => [ $remote_relname,
414 $remote_class,
415 \%cond,
416 $self->_remote_attrs($local_moniker, $local_cols),
417 ],
418 extra => {
59388920 419 local_class => $local_class,
420 local_moniker => $local_moniker,
421 remote_moniker => $remote_moniker,
dc379dc6 422 },
423 }
424 );
425
426 my %rev_cond = reverse %cond;
427 for (keys %rev_cond) {
428 $rev_cond{"foreign.$_"} = "self.".$rev_cond{$_};
429 delete $rev_cond{$_};
430 }
431
432 push(@{$all_code->{$remote_class}},
433 { method => $remote_method,
434 args => [ $local_relname,
435 $local_class,
436 \%rev_cond,
437 $self->_relationship_attrs($remote_method),
438 ],
439 extra => {
59388920 440 local_class => $remote_class,
441 local_moniker => $remote_moniker,
442 remote_moniker => $local_moniker,
dc379dc6 443 },
444 }
445 );
e8ad6491 446 }
dc379dc6 447 }
448
eaf23084 449 $self->_generate_m2ms($all_code);
450
dc379dc6 451 # disambiguate rels with the same name
452 foreach my $class (keys %$all_code) {
453 my $dups = $self->_duplicates($all_code->{$class});
996be9ee 454
eaf23084 455 $self->_disambiguate($all_code, $class, $dups) if $dups;
dc379dc6 456 }
457
458 $self->_cleanup;
459
460 return $all_code;
461}
462
eaf23084 463# Find classes with only 2 FKs which are the PK and make many_to_many bridges for them.
464sub _generate_m2ms {
465 my ($self, $all_code) = @_;
466
467 while (my ($class, $rels) = each %$all_code) {
468 next unless (grep $_->{method} eq 'belongs_to', @$rels) == 2;
469
470 my $class1_local_moniker = $rels->[0]{extra}{remote_moniker};
471 my $class1_remote_moniker = $rels->[1]{extra}{remote_moniker};
472
473 my $class2_local_moniker = $rels->[1]{extra}{remote_moniker};
474 my $class2_remote_moniker = $rels->[0]{extra}{remote_moniker};
475
476 my $class1 = $rels->[0]{args}[1];
477 my $class2 = $rels->[1]{args}[1];
478
479 my $class1_to_link_table_rel = first {
480 $_->{method} eq 'has_many' && $_->{args}[1] eq $class
481 } @{ $all_code->{$class1} };
482
483 my $class1_to_link_table_rel_name = $class1_to_link_table_rel->{args}[0];
484
485 my $class2_to_link_table_rel = first {
486 $_->{method} eq 'has_many' && $_->{args}[1] eq $class
487 } @{ $all_code->{$class2} };
488
489 my $class2_to_link_table_rel_name = $class2_to_link_table_rel->{args}[0];
490
491 my $class1_link_rel = $rels->[1]{args}[0];
492 my $class2_link_rel = $rels->[0]{args}[0];
493
494 my @class1_from_cols = apply { s/^self\.//i } values %{
495 $class1_to_link_table_rel->{args}[2]
496 };
497
498 my @class1_link_cols = apply { s/^self\.//i } values %{ $rels->[1]{args}[2] };
499
500 my @class1_to_cols = apply { s/^foreign\.//i } keys %{ $rels->[1]{args}[2] };
501
502 my @class2_from_cols = apply { s/^self\.//i } values %{
503 $class2_to_link_table_rel->{args}[2]
504 };
505
506 my @class2_link_cols = apply { s/^self\.//i } values %{ $rels->[0]{args}[2] };
507
508 my @class2_to_cols = apply { s/^foreign\.//i } keys %{ $rels->[0]{args}[2] };
509
510 my @link_table_cols =
511 @{[ $self->schema->source($rels->[0]{extra}{local_moniker})->columns ]};
512
513 my @link_table_primary_cols =
514 @{[ $self->schema->source($rels->[0]{extra}{local_moniker})->primary_columns ]};
515
516 next unless @class1_link_cols + @class2_link_cols == @link_table_cols
517 && @link_table_cols == @link_table_primary_cols;
518
519 my ($class1_to_class2_relname) = $self->_rel_name_map(
520 ($self->_inflect_plural($class1_link_rel))[0],
521 'many_to_many',
522 $class1,
523 $class1_local_moniker,
524 \@class1_from_cols,
525 $class2,
526 $class1_remote_moniker,
527 \@class1_to_cols,
528 );
529
530 $class1_to_class2_relname = $self->_resolve_relname_collision(
531 $class1_local_moniker,
532 \@class1_from_cols,
533 $class1_to_class2_relname,
534 );
535
536 my ($class2_to_class1_relname) = $self->_rel_name_map(
537 ($self->_inflect_plural($class2_link_rel))[0],
538 'many_to_many',
539 $class1,
540 $class2_local_moniker,
541 \@class2_from_cols,
542 $class2,
543 $class2_remote_moniker,
544 \@class2_to_cols,
545 );
546
547 $class2_to_class1_relname = $self->_resolve_relname_collision(
548 $class2_local_moniker,
549 \@class2_from_cols,
550 $class2_to_class1_relname,
551 );
552
553 push @{$all_code->{$class1}}, {
554 method => 'many_to_many',
555 args => [
556 $class1_to_class2_relname,
557 $class1_to_link_table_rel_name,
558 $class1_link_rel,
559 ],
560 extra => {
561 local_class => $class1,
562 link_class => $class,
563 local_moniker => $class1_local_moniker,
564 remote_moniker => $class1_remote_moniker,
565 },
566 };
567
568 push @{$all_code->{$class2}}, {
569 method => 'many_to_many',
570 args => [
571 $class2_to_class1_relname,
572 $class2_to_link_table_rel_name,
573 $class2_link_rel,
574 ],
575 extra => {
576 local_class => $class2,
577 link_class => $class,
578 local_moniker => $class2_local_moniker,
579 remote_moniker => $class2_remote_moniker,
580 },
581 };
582 }
583}
584
dc379dc6 585sub _duplicates {
586 my ($self, $rels) = @_;
587
588 my @rels = map [ $_->{args}[0] => $_ ], @$rels;
589 my %rel_names;
590 $rel_names{$_}++ foreach map $_->[0], @rels;
591
592 my @dups = grep $rel_names{$_} > 1, keys %rel_names;
593
594 my %dups;
595
596 foreach my $dup (@dups) {
597 $dups{$dup} = [ map $_->[1], grep { $_->[0] eq $dup } @rels ];
598 }
599
600 return if not %dups;
601
602 return \%dups;
603}
604
605sub _tagger {
606 my $self = shift;
607
608 $self->__tagger(Lingua::EN::Tagger->new) unless $self->__tagger;
609
610 return $self->__tagger;
611}
7dba7c70 612
dc379dc6 613sub _adjectives {
614 my ($self, @cols) = @_;
a7116285 615
dc379dc6 616 my @adjectives;
617
618 foreach my $col (@cols) {
619 my @words = split_name $col;
620
621 my $tagged = $self->_tagger->get_readable(join ' ', @words);
622
623 push @adjectives, $tagged =~ m{\G(\w+)/JJ\s+}g;
624 }
625
626 return @adjectives;
627}
628
5975bbe6 629sub _name_to_identifier {
630 my ($self, $name) = @_;
631
632 my $to_identifier = $self->loader->naming->{force_ascii} ?
633 \&String::ToIdentifier::EN::to_identifier
634 : \&String::ToIdentifier::EN::Unicode::to_identifier;
635
636 return join '_', map lc, split_name $to_identifier->($name, '_');
637}
638
dc379dc6 639sub _disambiguate {
eaf23084 640 my ($self, $all_code, $in_class, $dups) = @_;
dc379dc6 641
5975bbe6 642 DUP: foreach my $dup (keys %$dups) {
dc379dc6 643 my @rels = @{ $dups->{$dup} };
644
5975bbe6 645 # Check if there are rels to the same table name in different
646 # schemas/databases, if so qualify them.
647 my @tables = map $self->loader->moniker_to_table->{$_->{extra}{remote_moniker}},
648 @rels;
649
650 # databases are different, prepend database
651 if ($tables[0]->can('database') && (uniq map $_->database||'', @tables) > 1) {
652 # If any rels are in the same database, we have to distinguish by
653 # both schema and database.
654 my %db_counts;
655 $db_counts{$_}++ for map $_->database, @tables;
656 my $use_schema = any { $_ > 1 } values %db_counts;
657
658 foreach my $i (0..$#rels) {
659 my $rel = $rels[$i];
660 my $table = $tables[$i];
661
662 $rel->{args}[0] = $self->_name_to_identifier($table->database)
663 . ($use_schema ? ('_' . $self->name_to_identifier($table->schema)) : '')
664 . '_' . $rel->{args}[0];
665 }
666 next DUP;
667 }
668 # schemas are different, prepend schema
669 elsif ((uniq map $_->schema||'', @tables) > 1) {
670 foreach my $i (0..$#rels) {
671 my $rel = $rels[$i];
672 my $table = $tables[$i];
673
674 $rel->{args}[0] = $self->_name_to_identifier($table->schema)
675 . '_' . $rel->{args}[0];
676 }
677 next DUP;
678 }
679
dc379dc6 680 foreach my $rel (@rels) {
eaf23084 681 next if $rel->{method} =~ /^(?:belongs_to|many_to_many)\z/;
dc379dc6 682
683 my @to_cols = apply { s/^foreign\.//i }
684 keys %{ $rel->{args}[2] };
685
686 my @adjectives = $self->_adjectives(@to_cols);
687
688 # If there are no adjectives, and there is only one might_have
689 # rel to that class, we hardcode 'active'.
690
691 my $to_class = $rel->{args}[1];
692
693 if ((not @adjectives)
694 && (grep { $_->{method} eq 'might_have'
eaf23084 695 && $_->{args}[1] eq $to_class } @{ $all_code->{$in_class} }) == 1) {
dc379dc6 696
697 @adjectives = 'active';
996be9ee 698 }
e8ad6491 699
dc379dc6 700 if (@adjectives) {
701 my $rel_name = join '_', sort(@adjectives), $rel->{args}[0];
702
59388920 703 ($rel_name) = $rel->{method} eq 'might_have' ?
dc379dc6 704 $self->_inflect_singular($rel_name)
705 :
706 $self->_inflect_plural($rel_name);
707
59388920 708 my ($local_class, $local_moniker, $remote_moniker)
709 = @{ $rel->{extra} }
710 {qw/local_class local_moniker remote_moniker/};
dc379dc6 711
712 my @from_cols = apply { s/^self\.//i }
713 values %{ $rel->{args}[2] };
057fbb08 714
59388920 715 ($rel_name) = $self->_rel_name_map($rel_name, $rel->{method}, $local_class, $local_moniker, \@from_cols, $to_class, $remote_moniker, \@to_cols);
716
717 $rel_name = $self->_resolve_relname_collision($local_moniker, \@from_cols, $rel_name);
dc379dc6 718
719 $rel->{args}[0] = $rel_name;
e8ad6491 720 }
dc379dc6 721 }
996be9ee 722 }
723
dc379dc6 724 # Check again for duplicates, since the heuristics above may not have resolved them all.
725
eaf23084 726 if ($dups = $self->_duplicates($all_code->{$in_class})) {
dc379dc6 727 foreach my $dup (keys %$dups) {
728 # sort by method
729 my @rels = map $_->[1], sort { $a->[0] <=> $b->[0] } map [
eaf23084 730 {
731 belongs_to => 3,
732 has_many => 2,
733 might_have => 1,
734 many_to_many => 0,
735 }->{$_->{method}}, $_
dc379dc6 736 ], @{ $dups->{$dup} };
737
738 my $rel_num = 2;
739
740 foreach my $rel (@rels[1 .. $#rels]) {
eaf23084 741 my $inflect_type = $rel->{method} =~ /^(?:many_to_many|has_many)\z/ ?
dc379dc6 742 'inflect_plural'
743 :
744 'inflect_singular';
745
746 my $inflect_method = "_$inflect_type";
747
59388920 748 my $relname_new_uninflected = $rel->{args}[0] . "_$rel_num";
dc379dc6 749
750 $rel_num++;
751
59388920 752 my ($local_class, $local_moniker, $remote_moniker)
753 = @{ $rel->{extra} }
754 {qw/local_class local_moniker remote_moniker/};
dc379dc6 755
eaf23084 756 my (@from_cols, @to_cols, $to_class);
757
758 if ($rel->{method} eq 'many_to_many') {
759 @from_cols = apply { s/^self\.//i } values %{
760 (first { $_->{args}[0] eq $rel->{args}[1] } @{ $all_code->{$local_class} })
761 ->{args}[2]
762 };
763 @to_cols = apply { s/^foreign\.//i } keys %{
764 (first { $_->{args}[0] eq $rel->{args}[2] }
765 @{ $all_code->{ $rel->{extra}{link_class} } })
766 ->{args}[2]
767 };
768 $to_class = $self->schema->source($remote_moniker)->result_class;
769 }
770 else {
771 @from_cols = apply { s/^self\.//i } values %{ $rel->{args}[2] };
772 @to_cols = apply { s/^foreign\.//i } keys %{ $rel->{args}[2] };
773 $to_class = $rel->{args}[1];
774 }
59388920 775
776 my ($relname_new, $inflect_mapped) =
777 $self->$inflect_method($relname_new_uninflected);
778
779 my $rel_name_mapped;
780
781 ($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);
782
783 my $mapped = $inflect_mapped || $rel_name_mapped;
784
785 warn <<"EOF" unless $mapped;
786Could not find a proper name for relationship '$relname_new' in source
787'$local_moniker' for columns '@{[ join ',', @from_cols ]}'. Supply a value in
eaf23084 788'$inflect_type' for '$relname_new_uninflected' or 'rel_name_map' for
789'$relname_new' to name this relationship.
dc379dc6 790EOF
791
59388920 792 $relname_new = $self->_resolve_relname_collision($local_moniker, \@from_cols, $relname_new);
aa608e1a 793
dc379dc6 794 $rel->{args}[0] = $relname_new;
795 }
796 }
797 }
996be9ee 798}
799
39ef3bfe 800sub _relnames_and_method {
057fbb08 801 my ( $self, $local_moniker, $rel, $cond, $uniqs, $counters ) = @_;
e9c09ed9 802
59388920 803 my $remote_moniker = $rel->{remote_source};
804 my $remote_obj = $self->schema->source( $remote_moniker );
805 my $remote_class = $self->schema->class( $remote_moniker );
c4a69b87 806 my $remote_relname = $self->_remote_relname( $rel->{remote_table}, $cond);
fa6f8d4e 807
59388920 808 my $local_cols = $rel->{local_columns};
c4a69b87 809 my $local_table = $rel->{local_table};
59388920 810 my $local_class = $self->schema->class($local_moniker);
811 my $local_source = $self->schema->source($local_moniker);
057fbb08 812
1ad8e8c3 813 my $local_relname_uninflected = $self->_normalize_name($local_table);
59388920 814 my ($local_relname) = $self->_inflect_plural($self->_normalize_name($local_table));
fa6f8d4e 815
057fbb08 816 my $remote_method = 'has_many';
817
818 # If the local columns have a UNIQUE constraint, this is a one-to-one rel
50b95db6 819 if (array_eq([ $local_source->primary_columns ], $local_cols) ||
eaf23084 820 first { array_eq($_->[1], $local_cols) } @$uniqs) {
59388920 821 $remote_method = 'might_have';
822 ($local_relname) = $self->_inflect_singular($local_relname_uninflected);
057fbb08 823 }
fa6f8d4e 824
1ad8e8c3 825 # If more than one rel between this pair of tables, use the local
826 # col names to distinguish, unless the rel was created previously.
827 if ($counters->{$remote_moniker} > 1) {
828 my $relationship_exists = 0;
829
404aefa4 830 if (-f (my $existing_remote_file = $self->loader->get_dump_filename($remote_class))) {
1ad8e8c3 831 my $class = "${remote_class}Temporary";
832
8c70d2c7 833 if (not Class::Inspector->loaded($class)) {
fcf328c7 834 my $code = slurp_file $existing_remote_file;
1ad8e8c3 835
836 $code =~ s/(?<=package $remote_class)/Temporary/g;
837
6e4b7bb1 838 $code =~ s/__PACKAGE__->meta->make_immutable[^;]*;//g;
1ad8e8c3 839
840 eval $code;
841 die $@ if $@;
842
843 push @{ $self->_temp_classes }, $class;
844 }
845
846 if ($class->has_relationship($local_relname)) {
847 my $rel_cols = [ sort { $a cmp $b } apply { s/^foreign\.//i }
848 (keys %{ $class->relationship_info($local_relname)->{cond} }) ];
849
50b95db6 850 $relationship_exists = 1 if array_eq([ sort @$local_cols ], $rel_cols);
1ad8e8c3 851 }
852 }
853
854 if (not $relationship_exists) {
855 my $colnames = q{_} . $self->_normalize_name(join '_', @$local_cols);
856 $remote_relname .= $colnames if keys %$cond > 1;
857
ccf9b8a6 858 $local_relname = $self->_strip_id_postfix($self->_normalize_name($local_table . $colnames));
1ad8e8c3 859
860 $local_relname_uninflected = $local_relname;
59388920 861 ($local_relname) = $self->_inflect_plural($local_relname);
1ad8e8c3 862
863 # if colnames were added and this is a might_have, re-inflect
864 if ($remote_method eq 'might_have') {
59388920 865 ($local_relname) = $self->_inflect_singular($local_relname_uninflected);
1ad8e8c3 866 }
867 }
868 }
869
59388920 870 return ($local_relname, $remote_relname, $remote_method);
871}
872
873sub _rel_name_map {
874 my ($self, $relname, $method, $local_class, $local_moniker, $local_cols,
875 $remote_class, $remote_moniker, $remote_cols) = @_;
876
877 my $info = {
878 name => $relname,
879 type => $method,
880 local_class => $local_class,
881 local_moniker => $local_moniker,
882 local_columns => $local_cols,
883 remote_class => $remote_class,
884 remote_moniker => $remote_moniker,
885 remote_columns => $remote_cols,
886 };
887
888 my $new_name = $relname;
889
890 my $map = $self->rel_name_map;
891 my $mapped = 0;
892
893 if ('HASH' eq ref($map)) {
894 my $name = $info->{name};
895 my $moniker = $info->{local_moniker};
896 if ($map->{$moniker} and 'HASH' eq ref($map->{$moniker})
897 and $map->{$moniker}{$name}
898 ) {
899 $new_name = $map->{$moniker}{$name};
900 $mapped = 1;
901 }
902 elsif ($map->{$name} and not 'HASH' eq ref($map->{$name})) {
903 $new_name = $map->{$name};
904 $mapped = 1;
905 }
906 }
907 elsif ('CODE' eq ref($map)) {
908 my $name = $map->($info);
909 if ($name) {
910 $new_name = $name;
911 $mapped = 1;
912 }
913 }
914
915 return ($new_name, $mapped);
fa6f8d4e 916}
917
dc379dc6 918sub _cleanup {
1ad8e8c3 919 my $self = shift;
920
921 for my $class (@{ $self->_temp_classes }) {
922 Class::Unload->unload($class);
923 }
924
925 $self->_temp_classes([]);
926}
927
be80bba7 928=head1 AUTHOR
929
9cc8e7e1 930See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
be80bba7 931
932=head1 LICENSE
933
934This library is free software; you can redistribute it and/or modify it under
935the same terms as Perl itself.
936
937=cut
938
996be9ee 9391;
19b7d71c 940# vim:et sts=4 sw=4 tw=0: