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