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