add rel_name_map option
[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 Lingua::EN::Inflect::Phrase ();
10 use Lingua::EN::Tagger ();
11 use DBIx::Class::Schema::Loader::Utils 'split_name';
12 use File::Slurp 'read_file';
13 use Try::Tiny;
14 use Class::Unload ();
15 use Class::Inspector ();
16 use List::MoreUtils 'apply';
17 use namespace::clean;
18
19 our $VERSION = '0.07010';
20
21 # Glossary:
22 #
23 # remote_relname -- name of relationship from the local table referring to the remote table
24 # local_relname  -- name of relationship from the remote table referring to the local table
25 # remote_method  -- relationship type from remote table to local table, usually has_many
26
27 =head1 NAME
28
29 DBIx::Class::Schema::Loader::RelBuilder - Builds relationships for DBIx::Class::Schema::Loader
30
31 =head1 SYNOPSIS
32
33 See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
34
35 =head1 DESCRIPTION
36
37 This class builds relationships for L<DBIx::Class::Schema::Loader>.  This
38 is module is not (yet) for external use.
39
40 =head1 METHODS
41
42 =head2 new
43
44 Arguments: $base object
45
46 =head2 generate_code
47
48 Arguments: 
49     
50     {
51         local_moniker (scalar) => [ fk_info (arrayref), uniq_info (arrayref) ]
52         ...
53     }
54
55 This generates the code for the relationships of each table.
56
57 C<local_moniker> is the moniker name of the table which had the REFERENCES
58 statements.  The fk_info arrayref's contents should take the form:
59
60     [
61         {
62             local_columns => [ 'col2', 'col3' ],
63             remote_columns => [ 'col5', 'col7' ],
64             remote_moniker => 'AnotherTableMoniker',
65         },
66         {
67             local_columns => [ 'col1', 'col4' ],
68             remote_columns => [ 'col1', 'col2' ],
69             remote_moniker => 'YetAnotherTableMoniker',
70         },
71         # ...
72     ],
73
74 The uniq_info arrayref's contents should take the form:
75
76     [
77         [
78             uniq_constraint_name         => [ 'col1', 'col2' ],
79         ],
80         [
81             another_uniq_constraint_name => [ 'col1', 'col2' ],
82         ],
83     ],
84
85 This method will return the generated relationships as a hashref keyed on the
86 class names.  The values are arrayrefs of hashes containing method name and
87 arguments, like so:
88
89   {
90       'Some::Source::Class' => [
91           { method => 'belongs_to', arguments => [ 'col1', 'Another::Source::Class' ],
92           { method => 'has_many', arguments => [ 'anothers', 'Yet::Another::Source::Class', 'col15' ],
93       ],
94       'Another::Source::Class' => [
95           # ...
96       ],
97       # ...
98   }
99
100 =cut
101
102 __PACKAGE__->mk_group_accessors('simple', qw/
103     base
104     schema
105     inflect_plural
106     inflect_singular
107     relationship_attrs
108     rel_collision_map
109     rel_name_map
110     _temp_classes
111     __tagger
112 /);
113
114 sub new {
115     my ( $class, $base ) = @_;
116
117     # from old POD about this constructor:
118     # C<$schema_class> should be a schema class name, where the source
119     # classes have already been set up and registered.  Column info,
120     # primary key, and unique constraints will be drawn from this
121     # schema for all of the existing source monikers.
122
123     # Options inflect_plural and inflect_singular are optional, and
124     # are better documented in L<DBIx::Class::Schema::Loader::Base>.
125
126     my $self = {
127         base               => $base,
128         schema             => $base->schema,
129         inflect_plural     => $base->inflect_plural,
130         inflect_singular   => $base->inflect_singular,
131         relationship_attrs => $base->relationship_attrs,
132         rel_collision_map  => $base->rel_collision_map,
133         rel_name_map       => $base->rel_name_map,
134         _temp_classes      => [],
135     };
136
137     weaken $self->{base}; #< don't leak
138
139     bless $self => $class;
140
141     # validate the relationship_attrs arg
142     if( defined $self->relationship_attrs ) {
143         ref $self->relationship_attrs eq 'HASH'
144             or croak "relationship_attrs must be a hashref";
145     }
146
147     return $self;
148 }
149
150
151 # pluralize a relationship name
152 sub _inflect_plural {
153     my ($self, $relname) = @_;
154
155     return '' if !defined $relname || $relname eq '';
156
157     my $result;
158     my $mapped = 0;
159
160     if( ref $self->inflect_plural eq 'HASH' ) {
161         if (exists $self->inflect_plural->{$relname}) {
162             $result = $self->inflect_plural->{$relname};
163             $mapped = 1;
164         }
165     }
166     elsif( ref $self->inflect_plural eq 'CODE' ) {
167         my $inflected = $self->inflect_plural->($relname);
168         if ($inflected) {
169             $result = $inflected;
170             $mapped = 1;
171         }
172     }
173
174     return ($result, $mapped) if $mapped;
175
176     return ($self->_to_PL($relname), 0);
177 }
178
179 # Singularize a relationship name
180 sub _inflect_singular {
181     my ($self, $relname) = @_;
182
183     return '' if !defined $relname || $relname eq '';
184
185     my $result;
186     my $mapped = 0;
187
188     if( ref $self->inflect_singular eq 'HASH' ) {
189         if (exists $self->inflect_singular->{$relname}) {
190             $result = $self->inflect_singular->{$relname};
191             $mapped = 1;
192         }
193     }
194     elsif( ref $self->inflect_singular eq 'CODE' ) {
195         my $inflected = $self->inflect_singular->($relname);
196         if ($inflected) {
197             $result = $inflected;
198             $mapped = 1;
199         }
200     }
201
202     return ($result, $mapped) if $mapped;
203
204     return ($self->_to_S($relname), 0);
205 }
206
207 sub _to_PL {
208     my ($self, $name) = @_;
209
210     $name =~ s/_/ /g;
211     my $plural = Lingua::EN::Inflect::Phrase::to_PL($name);
212     $plural =~ s/ /_/g;
213
214     return $plural;
215 }
216
217 sub _to_S {
218     my ($self, $name) = @_;
219
220     $name =~ s/_/ /g;
221     my $singular = Lingua::EN::Inflect::Phrase::to_S($name);
222     $singular =~ s/ /_/g;
223
224     return $singular;
225 }
226
227 sub _default_relationship_attrs { +{
228     has_many => {
229         cascade_delete => 0,
230         cascade_copy   => 0,
231     },
232     might_have => {
233         cascade_delete => 0,
234         cascade_copy   => 0,
235     },
236     belongs_to => {
237         on_delete => 'CASCADE',
238         on_update => 'CASCADE',
239         is_deferrable => 1,
240     },
241 } }
242
243 # accessor for options to be passed to each generated relationship
244 # type.  take single argument, the relationship type name, and returns
245 # either a hashref (if some options are set), or nothing
246 sub _relationship_attrs {
247     my ( $self, $reltype ) = @_;
248     my $r = $self->relationship_attrs;
249
250     my %composite = (
251         %{ $self->_default_relationship_attrs->{$reltype} || {} },
252         %{ $r->{all} || {} }
253     );
254
255     if( my $specific = $r->{$reltype} ) {
256         while( my ($k,$v) = each %$specific ) {
257             $composite{$k} = $v;
258         }
259     }
260     return \%composite;
261 }
262
263 sub _array_eq {
264     my ($self, $a, $b) = @_;
265
266     return unless @$a == @$b;
267
268     for (my $i = 0; $i < @$a; $i++) {
269         return unless $a->[$i] eq $b->[$i];
270     }
271     return 1;
272 }
273
274 sub _remote_attrs {
275     my ($self, $local_moniker, $local_cols) = @_;
276
277     # get our base set of attrs from _relationship_attrs, if present
278     my $attrs = $self->_relationship_attrs('belongs_to') || {};
279
280     # If the referring column is nullable, make 'belongs_to' an
281     # outer join, unless explicitly set by relationship_attrs
282     my $nullable = grep { $self->schema->source($local_moniker)->column_info($_)->{is_nullable} } @$local_cols;
283     $attrs->{join_type} = 'LEFT' if $nullable && !defined $attrs->{join_type};
284
285     return $attrs;
286 }
287
288 sub _sanitize_name {
289     my ($self, $name) = @_;
290
291     if (ref $name) {
292         # scalar ref for weird table name (like one containing a '.')
293         ($name = $$name) =~ s/\W+/_/g;
294     }
295     else {
296         # remove 'schema.' prefix if any
297         $name =~ s/^[^.]+\.//;
298     }
299
300     return $name;
301 }
302
303 sub _normalize_name {
304     my ($self, $name) = @_;
305
306     $name = $self->_sanitize_name($name);
307
308     my @words = split_name $name;
309
310     return join '_', map lc, @words;
311 }
312
313 sub _remote_relname {
314     my ($self, $remote_table, $cond) = @_;
315
316     my $remote_relname;
317     # for single-column case, set the remote relname to the column
318     # name, to make filter accessors work, but strip trailing _id
319     if(scalar keys %{$cond} == 1) {
320         my ($col) = values %{$cond};
321         $col = $self->_normalize_name($col);
322         $col =~ s/_id$//;
323         ($remote_relname) = $self->_inflect_singular($col);
324     }
325     else {
326         ($remote_relname) = $self->_inflect_singular($self->_normalize_name($remote_table));
327     }
328
329     return $remote_relname;
330 }
331
332 sub _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
337     my $table = $self->base->tables->{$moniker};
338
339     if ($self->base->_is_result_class_method($relname, $table)) {
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;
349         while ($self->base->_is_result_class_method($new_relname, $table)) {
350             $new_relname .= '_rel'
351         }
352
353         warn <<"EOF";
354 Relationship '$relname' in source '$moniker' for columns '@{[ join ',', @$cols ]}' collides with an inherited method.
355 Renaming to '$new_relname'.
356 See "RELATIONSHIP NAME COLLISIONS" in perldoc DBIx::Class::Schema::Loader::Base .
357 EOF
358
359         return $new_relname;
360     }
361
362     return $relname;
363 }
364
365 sub generate_code {
366     my ($self, $tables) = @_;
367     
368     # make a copy to destroy
369     my @tables = @$tables;
370
371     my $all_code = {};
372
373     while (my ($local_moniker, $rels, $uniqs) = @{ shift @tables || [] }) {
374         my $local_class = $self->schema->class($local_moniker);
375
376         my %counters;
377         foreach my $rel (@$rels) {
378             next if !$rel->{remote_source};
379             $counters{$rel->{remote_source}}++;
380         }
381
382         foreach my $rel (@$rels) {
383             my $remote_moniker = $rel->{remote_source}
384                 or next;
385
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 ];
389
390             my $local_cols     = $rel->{local_columns};
391
392             if($#$local_cols != $#$remote_cols) {
393                 croak "Column count mismatch: $local_moniker (@$local_cols) "
394                     . "$remote_moniker (@$remote_cols)";
395             }
396
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 );
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);
408
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);
411
412             push(@{$all_code->{$local_class}},
413                 { method => $local_method,
414                   args => [ $remote_relname,
415                             $remote_class,
416                             \%cond,
417                             $self->_remote_attrs($local_moniker, $local_cols),
418                   ],
419                   extra => {
420                       local_class    => $local_class,
421                       local_moniker  => $local_moniker,
422                       remote_moniker => $remote_moniker,
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 => {
441                       local_class    => $remote_class,
442                       local_moniker  => $remote_moniker,
443                       remote_moniker => $local_moniker,
444                   },
445                 }
446             );
447         }
448     }
449
450     # disambiguate rels with the same name
451     foreach my $class (keys %$all_code) {
452         my $dups = $self->_duplicates($all_code->{$class});
453
454         $self->_disambiguate($all_code->{$class}, $dups) if $dups;
455     }
456
457     $self->_cleanup;
458
459     return $all_code;
460 }
461
462 sub _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
482 sub _tagger {
483     my $self = shift;
484
485     $self->__tagger(Lingua::EN::Tagger->new) unless $self->__tagger;
486
487     return $self->__tagger;
488 }
489
490 sub _adjectives {
491     my ($self, @cols) = @_;
492
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
506 sub _disambiguate {
507     my ($self, $all_rels, $dups) = @_;
508
509     foreach my $dup (keys %$dups) {
510         my @rels = @{ $dups->{$dup} };
511
512         foreach my $rel (@rels) {
513             next if $rel->{method} eq 'belongs_to';
514
515             my @to_cols = apply { s/^foreign\.//i }
516                 keys %{ $rel->{args}[2] };
517
518             my @adjectives = $self->_adjectives(@to_cols);
519
520             # If there are no adjectives, and there is only one might_have
521             # rel to that class, we hardcode 'active'.
522
523             my $to_class = $rel->{args}[1];
524
525             if ((not @adjectives)
526                 && (grep { $_->{method} eq 'might_have'
527                            && $_->{args}[1] eq $to_class } @$all_rels) == 1) {
528
529                 @adjectives = 'active';
530             }
531
532             if (@adjectives) {
533                 my $rel_name = join '_', sort(@adjectives), $rel->{args}[0];
534
535                 ($rel_name) = $rel->{method} eq 'might_have' ?
536                     $self->_inflect_singular($rel_name)
537                     :
538                     $self->_inflect_plural($rel_name);
539
540                 my ($local_class, $local_moniker, $remote_moniker)
541                     = @{ $rel->{extra} }
542                         {qw/local_class local_moniker remote_moniker/};
543
544                 my @from_cols = apply { s/^self\.//i }
545                     values %{ $rel->{args}[2] };
546
547                 ($rel_name) = $self->_rel_name_map($rel_name, $rel->{method}, $local_class, $local_moniker, \@from_cols, $to_class, $remote_moniker, \@to_cols);
548
549                 $rel_name = $self->_resolve_relname_collision($local_moniker, \@from_cols, $rel_name);
550
551                 $rel->{args}[0] = $rel_name;
552             }
553         }
554     }
555
556     # Check again for duplicates, since the heuristics above may not have resolved them all.
557
558     if ($dups = $self->_duplicates($all_rels)) {
559         foreach my $dup (keys %$dups) {
560             # sort by method
561             my @rels = map $_->[1], sort { $a->[0] <=> $b->[0] } map [
562                 ($_->{method} eq 'belongs_to' ? 3 : $_->{method} eq 'has_many' ? 2 : 1), $_
563             ], @{ $dups->{$dup} };
564
565             my $rel_num = 2;
566
567             foreach my $rel (@rels[1 .. $#rels]) {
568                 my $inflect_type = $rel->{method} eq 'has_many' ?
569                     'inflect_plural'
570                     :
571                     'inflect_singular';
572
573                 my $inflect_method = "_$inflect_type";
574
575                 my $relname_new_uninflected = $rel->{args}[0] . "_$rel_num";
576
577                 $rel_num++;
578
579                 my ($local_class, $local_moniker, $remote_moniker)
580                     = @{ $rel->{extra} }
581                         {qw/local_class local_moniker remote_moniker/};
582
583                 my @from_cols = apply { s/^self\.//i }
584                     values %{ $rel->{args}[2] };
585
586                 my @to_cols = apply { s/^foreign\.//i }
587                     keys %{ $rel->{args}[2] };
588
589                 my $to_class = $rel->{args}[1];
590
591                 my ($relname_new, $inflect_mapped) =
592                     $self->$inflect_method($relname_new_uninflected);
593
594                 my $rel_name_mapped;
595
596                 ($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);
597                 
598                 my $mapped = $inflect_mapped || $rel_name_mapped;
599
600                 warn <<"EOF" unless $mapped;
601 Could not find a proper name for relationship '$relname_new' in source
602 '$local_moniker' for columns '@{[ join ',', @from_cols ]}'. Supply a value in
603 '$inflect_type' or 'rel_name_map' for '$relname_new_uninflected' to name this
604 relationship.
605 EOF
606
607                 $relname_new = $self->_resolve_relname_collision($local_moniker, \@from_cols, $relname_new);
608
609                 $rel->{args}[0] = $relname_new;
610             }
611         }
612     }
613 }
614
615 sub _relnames_and_method {
616     my ( $self, $local_moniker, $rel, $cond, $uniqs, $counters ) = @_;
617
618     my $remote_moniker  = $rel->{remote_source};
619     my $remote_obj      = $self->schema->source( $remote_moniker );
620     my $remote_class    = $self->schema->class(  $remote_moniker );
621     my $remote_relname  = $self->_remote_relname( $remote_obj->from, $cond);
622
623     my $local_cols      = $rel->{local_columns};
624     my $local_table     = $self->schema->source($local_moniker)->from;
625     my $local_class     = $self->schema->class($local_moniker);
626     my $local_source    = $self->schema->source($local_moniker);
627
628     my $local_relname_uninflected = $self->_normalize_name($local_table);
629     my ($local_relname) = $self->_inflect_plural($self->_normalize_name($local_table));
630
631     my $remote_method = 'has_many';
632
633     # If the local columns have a UNIQUE constraint, this is a one-to-one rel
634     if ($self->_array_eq([ $local_source->primary_columns ], $local_cols) ||
635             grep { $self->_array_eq($_->[1], $local_cols) } @$uniqs) {
636         $remote_method   = 'might_have';
637         ($local_relname) = $self->_inflect_singular($local_relname_uninflected);
638     }
639
640     # If more than one rel between this pair of tables, use the local
641     # col names to distinguish, unless the rel was created previously.
642     if ($counters->{$remote_moniker} > 1) {
643         my $relationship_exists = 0;
644
645         if (-f (my $existing_remote_file = $self->base->get_dump_filename($remote_class))) {
646             my $class = "${remote_class}Temporary";
647
648             if (not Class::Inspector->loaded($class)) {
649                 my $code = read_file($existing_remote_file, binmode => ':encoding(UTF-8)');
650
651                 $code =~ s/(?<=package $remote_class)/Temporary/g;
652
653                 $code =~ s/__PACKAGE__->meta->make_immutable[^;]*;//g;
654
655                 eval $code;
656                 die $@ if $@;
657
658                 push @{ $self->_temp_classes }, $class;
659             }
660
661             if ($class->has_relationship($local_relname)) {
662                 my $rel_cols = [ sort { $a cmp $b } apply { s/^foreign\.//i }
663                     (keys %{ $class->relationship_info($local_relname)->{cond} }) ];
664
665                 $relationship_exists = 1 if $self->_array_eq([ sort @$local_cols ], $rel_cols);
666             }
667         }
668
669         if (not $relationship_exists) {
670             my $colnames = q{_} . $self->_normalize_name(join '_', @$local_cols);
671             $remote_relname .= $colnames if keys %$cond > 1;
672
673             $local_relname = $self->_normalize_name($local_table . $colnames);
674             $local_relname =~ s/_id$//;
675
676             $local_relname_uninflected = $local_relname;
677             ($local_relname) = $self->_inflect_plural($local_relname);
678
679             # if colnames were added and this is a might_have, re-inflect
680             if ($remote_method eq 'might_have') {
681                 ($local_relname) = $self->_inflect_singular($local_relname_uninflected);
682             }
683         }
684     }
685
686     return ($local_relname, $remote_relname, $remote_method);
687 }
688
689 sub _rel_name_map {
690     my ($self, $relname, $method, $local_class, $local_moniker, $local_cols,
691         $remote_class, $remote_moniker, $remote_cols) = @_;
692
693     my $info = {
694         name           => $relname,
695         type           => $method,
696         local_class    => $local_class,
697         local_moniker  => $local_moniker,
698         local_columns  => $local_cols,
699         remote_class   => $remote_class,
700         remote_moniker => $remote_moniker,
701         remote_columns => $remote_cols,
702     };
703
704     my $new_name = $relname;
705
706     my $map = $self->rel_name_map;
707     my $mapped = 0;
708
709     if ('HASH' eq ref($map)) {
710         my $name = $info->{name};
711         my $moniker = $info->{local_moniker};
712         if ($map->{$moniker} and 'HASH' eq ref($map->{$moniker})
713             and $map->{$moniker}{$name}
714         ) {
715             $new_name = $map->{$moniker}{$name};
716             $mapped   = 1;
717         }
718         elsif ($map->{$name} and not 'HASH' eq ref($map->{$name})) {
719             $new_name = $map->{$name};
720             $mapped   = 1;
721         }
722     }
723     elsif ('CODE' eq ref($map)) {
724         my $name = $map->($info);
725         if ($name) {
726             $new_name = $name;
727             $mapped   = 1;
728         }
729     }
730
731     return ($new_name, $mapped);
732 }
733
734 sub _cleanup {
735     my $self = shift;
736
737     for my $class (@{ $self->_temp_classes }) {
738         Class::Unload->unload($class);
739     }
740
741     $self->_temp_classes([]);
742 }
743
744 =head1 AUTHOR
745
746 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
747
748 =head1 LICENSE
749
750 This library is free software; you can redistribute it and/or modify it under
751 the same terms as Perl itself.
752
753 =cut
754
755 1;
756 # vim:et sts=4 sw=4 tw=0: