fix clasing test dbs
[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 'slurp';
13 use Try::Tiny;
14 use Class::Unload ();
15 use Class::Inspector ();
16 use List::MoreUtils 'apply';
17 use Encode 'decode';
18 use namespace::clean;
19
20 our $VERSION = '0.07010';
21
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
28 =head1 NAME
29
30 DBIx::Class::Schema::Loader::RelBuilder - Builds relationships for DBIx::Class::Schema::Loader
31
32 =head1 SYNOPSIS
33
34 See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
35
36 =head1 DESCRIPTION
37
38 This class builds relationships for L<DBIx::Class::Schema::Loader>.  This
39 is module is not (yet) for external use.
40
41 =head1 METHODS
42
43 =head2 new
44
45 Arguments: $base object
46
47 =head2 generate_code
48
49 Arguments: 
50     
51     {
52         local_moniker (scalar) => [ fk_info (arrayref), uniq_info (arrayref) ]
53         ...
54     }
55
56 This generates the code for the relationships of each table.
57
58 C<local_moniker> is the moniker name of the table which had the REFERENCES
59 statements.  The fk_info arrayref's contents should take the form:
60
61     [
62         {
63             local_columns => [ 'col2', 'col3' ],
64             remote_columns => [ 'col5', 'col7' ],
65             remote_moniker => 'AnotherTableMoniker',
66         },
67         {
68             local_columns => [ 'col1', 'col4' ],
69             remote_columns => [ 'col1', 'col2' ],
70             remote_moniker => 'YetAnotherTableMoniker',
71         },
72         # ...
73     ],
74
75 The uniq_info arrayref's contents should take the form:
76
77     [
78         [
79             uniq_constraint_name         => [ 'col1', 'col2' ],
80         ],
81         [
82             another_uniq_constraint_name => [ 'col1', 'col2' ],
83         ],
84     ],
85
86 This method will return the generated relationships as a hashref keyed on the
87 class names.  The values are arrayrefs of hashes containing method name and
88 arguments, like so:
89
90   {
91       'Some::Source::Class' => [
92           { method => 'belongs_to', arguments => [ 'col1', 'Another::Source::Class' ],
93           { method => 'has_many', arguments => [ 'anothers', 'Yet::Another::Source::Class', 'col15' ],
94       ],
95       'Another::Source::Class' => [
96           # ...
97       ],
98       # ...
99   }
100
101 =cut
102
103 __PACKAGE__->mk_group_accessors('simple', qw/
104     base
105     schema
106     inflect_plural
107     inflect_singular
108     relationship_attrs
109     rel_collision_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         _temp_classes      => [],
134     };
135
136     weaken $self->{base}; #< don't leak
137
138     bless $self => $class;
139
140     # validate the relationship_attrs arg
141     if( defined $self->relationship_attrs ) {
142         ref $self->relationship_attrs eq 'HASH'
143             or croak "relationship_attrs must be a hashref";
144     }
145
146     return $self;
147 }
148
149
150 # pluralize a relationship name
151 sub _inflect_plural {
152     my ($self, $relname) = @_;
153
154     return '' if !defined $relname || $relname eq '';
155
156     if( ref $self->inflect_plural eq 'HASH' ) {
157         return $self->inflect_plural->{$relname}
158             if exists $self->inflect_plural->{$relname};
159     }
160     elsif( ref $self->inflect_plural eq 'CODE' ) {
161         my $inflected = $self->inflect_plural->($relname);
162         return $inflected if $inflected;
163     }
164
165     return $self->_to_PL($relname);
166 }
167
168 # Singularize a relationship name
169 sub _inflect_singular {
170     my ($self, $relname) = @_;
171
172     return '' if !defined $relname || $relname eq '';
173
174     if( ref $self->inflect_singular eq 'HASH' ) {
175         return $self->inflect_singular->{$relname}
176             if exists $self->inflect_singular->{$relname};
177     }
178     elsif( ref $self->inflect_singular eq 'CODE' ) {
179         my $inflected = $self->inflect_singular->($relname);
180         return $inflected if $inflected;
181     }
182
183     return $self->_to_S($relname);
184 }
185
186 sub _to_PL {
187     my ($self, $name) = @_;
188
189     $name =~ s/_/ /g;
190     my $plural = Lingua::EN::Inflect::Phrase::to_PL($name);
191     $plural =~ s/ /_/g;
192
193     return $plural;
194 }
195
196 sub _to_S {
197     my ($self, $name) = @_;
198
199     $name =~ s/_/ /g;
200     my $singular = Lingua::EN::Inflect::Phrase::to_S($name);
201     $singular =~ s/ /_/g;
202
203     return $singular;
204 }
205
206 sub _default_relationship_attrs { +{
207     has_many => {
208         cascade_delete => 0,
209         cascade_copy   => 0,
210     },
211     might_have => {
212         cascade_delete => 0,
213         cascade_copy   => 0,
214     },
215     belongs_to => {
216         on_delete => 'CASCADE',
217         on_update => 'CASCADE',
218         is_deferrable => 1,
219     },
220 } }
221
222 # accessor for options to be passed to each generated relationship
223 # type.  take single argument, the relationship type name, and returns
224 # either a hashref (if some options are set), or nothing
225 sub _relationship_attrs {
226     my ( $self, $reltype ) = @_;
227     my $r = $self->relationship_attrs;
228
229     my %composite = (
230         %{ $self->_default_relationship_attrs->{$reltype} || {} },
231         %{ $r->{all} || {} }
232     );
233
234     if( my $specific = $r->{$reltype} ) {
235         while( my ($k,$v) = each %$specific ) {
236             $composite{$k} = $v;
237         }
238     }
239     return \%composite;
240 }
241
242 sub _array_eq {
243     my ($self, $a, $b) = @_;
244
245     return unless @$a == @$b;
246
247     for (my $i = 0; $i < @$a; $i++) {
248         return unless $a->[$i] eq $b->[$i];
249     }
250     return 1;
251 }
252
253 sub _remote_attrs {
254     my ($self, $local_moniker, $local_cols) = @_;
255
256     # get our base set of attrs from _relationship_attrs, if present
257     my $attrs = $self->_relationship_attrs('belongs_to') || {};
258
259     # If the referring column is nullable, make 'belongs_to' an
260     # outer join, unless explicitly set by relationship_attrs
261     my $nullable = grep { $self->schema->source($local_moniker)->column_info($_)->{is_nullable} } @$local_cols;
262     $attrs->{join_type} = 'LEFT' if $nullable && !defined $attrs->{join_type};
263
264     return $attrs;
265 }
266
267 sub _sanitize_name {
268     my ($self, $name) = @_;
269
270     if (ref $name) {
271         # scalar ref for weird table name (like one containing a '.')
272         ($name = $$name) =~ s/\W+/_/g;
273     }
274     else {
275         # remove 'schema.' prefix if any
276         $name =~ s/^[^.]+\.//;
277     }
278
279     return $name;
280 }
281
282 sub _normalize_name {
283     my ($self, $name) = @_;
284
285     $name = $self->_sanitize_name($name);
286
287     my @words = split_name $name;
288
289     return join '_', map lc, @words;
290 }
291
292 sub _remote_relname {
293     my ($self, $remote_table, $cond) = @_;
294
295     my $remote_relname;
296     # for single-column case, set the remote relname to the column
297     # name, to make filter accessors work, but strip trailing _id
298     if(scalar keys %{$cond} == 1) {
299         my ($col) = values %{$cond};
300         $col = $self->_normalize_name($col);
301         $col =~ s/_id$//;
302         $remote_relname = $self->_inflect_singular($col);
303     }
304     else {
305         $remote_relname = $self->_inflect_singular($self->_normalize_name($remote_table));
306     }
307
308     return $remote_relname;
309 }
310
311 sub _resolve_relname_collision {
312     my ($self, $moniker, $cols, $relname) = @_;
313
314     return $relname if $relname eq 'id'; # this shouldn't happen, but just in case
315
316     my $table = $self->base->tables->{$moniker};
317
318     if ($self->base->_is_result_class_method($relname, $table)) {
319         if (my $map = $self->rel_collision_map) {
320             for my $re (keys %$map) {
321                 if (my @matches = $relname =~ /$re/) {
322                     return sprintf $map->{$re}, @matches;
323                 }
324             }
325         }
326
327         my $new_relname = $relname;
328         while ($self->base->_is_result_class_method($new_relname, $table)) {
329             $new_relname .= '_rel'
330         }
331
332         warn <<"EOF";
333 Relationship '$relname' in source '$moniker' for columns '@{[ join ',', @$cols ]}' collides with an inherited method.
334 Renaming to '$new_relname'.
335 See "RELATIONSHIP NAME COLLISIONS" in perldoc DBIx::Class::Schema::Loader::Base .
336 EOF
337
338         return $new_relname;
339     }
340
341     return $relname;
342 }
343
344 sub generate_code {
345     my ($self, $tables) = @_;
346     
347     # make a copy to destroy
348     my @tables = @$tables;
349
350     my $all_code = {};
351
352     while (my ($local_moniker, $rels, $uniqs) = @{ shift @tables || [] }) {
353         my $local_class = $self->schema->class($local_moniker);
354
355         my %counters;
356         foreach my $rel (@$rels) {
357             next if !$rel->{remote_source};
358             $counters{$rel->{remote_source}}++;
359         }
360
361         foreach my $rel (@$rels) {
362             my $remote_moniker = $rel->{remote_source}
363                 or next;
364
365             my $remote_class   = $self->schema->class($remote_moniker);
366             my $remote_obj     = $self->schema->source($remote_moniker);
367             my $remote_cols    = $rel->{remote_columns} || [ $remote_obj->primary_columns ];
368
369             my $local_cols     = $rel->{local_columns};
370
371             if($#$local_cols != $#$remote_cols) {
372                 croak "Column count mismatch: $local_moniker (@$local_cols) "
373                     . "$remote_moniker (@$remote_cols)";
374             }
375
376             my %cond;
377             foreach my $i (0 .. $#$local_cols) {
378                 $cond{$remote_cols->[$i]} = $local_cols->[$i];
379             }
380
381             my ( $local_relname, $remote_relname, $remote_method ) =
382                 $self->_relnames_and_method( $local_moniker, $rel, \%cond,  $uniqs, \%counters );
383
384             $remote_relname = $self->_resolve_relname_collision($local_moniker,  $local_cols,  $remote_relname);
385             $local_relname  = $self->_resolve_relname_collision($remote_moniker, $remote_cols, $local_relname);
386
387             push(@{$all_code->{$local_class}},
388                 { method => 'belongs_to',
389                   args => [ $remote_relname,
390                             $remote_class,
391                             \%cond,
392                             $self->_remote_attrs($local_moniker, $local_cols),
393                   ],
394                   extra => {
395                       moniker => $local_moniker,
396                   },
397                 }
398             );
399
400             my %rev_cond = reverse %cond;
401             for (keys %rev_cond) {
402                 $rev_cond{"foreign.$_"} = "self.".$rev_cond{$_};
403                 delete $rev_cond{$_};
404             }
405
406             push(@{$all_code->{$remote_class}},
407                 { method => $remote_method,
408                   args => [ $local_relname,
409                             $local_class,
410                             \%rev_cond,
411                             $self->_relationship_attrs($remote_method),
412                   ],
413                   extra => {
414                       moniker => $remote_moniker,
415                   },
416                 }
417             );
418         }
419     }
420
421     # disambiguate rels with the same name
422     foreach my $class (keys %$all_code) {
423         my $dups = $self->_duplicates($all_code->{$class});
424
425         $self->_disambiguate($all_code->{$class}, $dups) if $dups;
426     }
427
428     $self->_cleanup;
429
430     return $all_code;
431 }
432
433 sub _duplicates {
434     my ($self, $rels) = @_;
435
436     my @rels = map [ $_->{args}[0] => $_ ], @$rels;
437     my %rel_names;
438     $rel_names{$_}++ foreach map $_->[0], @rels;
439
440     my @dups = grep $rel_names{$_} > 1, keys %rel_names;
441
442     my %dups;
443
444     foreach my $dup (@dups) {
445         $dups{$dup} = [ map $_->[1], grep { $_->[0] eq $dup } @rels ];
446     }
447
448     return if not %dups;
449
450     return \%dups;
451 }
452
453 sub _tagger {
454     my $self = shift;
455
456     $self->__tagger(Lingua::EN::Tagger->new) unless $self->__tagger;
457
458     return $self->__tagger;
459 }
460
461 sub _adjectives {
462     my ($self, @cols) = @_;
463
464     my @adjectives;
465
466     foreach my $col (@cols) {
467         my @words = split_name $col;
468
469         my $tagged = $self->_tagger->get_readable(join ' ', @words);
470
471         push @adjectives, $tagged =~ m{\G(\w+)/JJ\s+}g;
472     }
473
474     return @adjectives;
475 }
476
477 sub _disambiguate {
478     my ($self, $all_rels, $dups) = @_;
479
480     foreach my $dup (keys %$dups) {
481         my @rels = @{ $dups->{$dup} };
482
483         foreach my $rel (@rels) {
484             next if $rel->{method} eq 'belongs_to';
485
486             my @to_cols = apply { s/^foreign\.//i }
487                 keys %{ $rel->{args}[2] };
488
489             my @adjectives = $self->_adjectives(@to_cols);
490
491             # If there are no adjectives, and there is only one might_have
492             # rel to that class, we hardcode 'active'.
493
494             my $to_class = $rel->{args}[1];
495
496             if ((not @adjectives)
497                 && (grep { $_->{method} eq 'might_have'
498                            && $_->{args}[1] eq $to_class } @$all_rels) == 1) {
499
500                 @adjectives = 'active';
501             }
502
503             if (@adjectives) {
504                 my $rel_name = join '_', sort(@adjectives), $rel->{args}[0];
505
506                 $rel_name = $rel->{method} eq 'might_have' ?
507                     $self->_inflect_singular($rel_name)
508                     :
509                     $self->_inflect_plural($rel_name);
510
511                 my $moniker = $rel->{extra}{moniker};
512
513                 my @from_cols = apply { s/^self\.//i }
514                     values %{ $rel->{args}[2] };
515
516                 $rel_name = $self->_resolve_relname_collision($moniker, \@from_cols, $rel_name);
517
518                 $rel->{args}[0] = $rel_name;
519             }
520         }
521     }
522
523     # Check again for duplicates, since the heuristics above may not have resolved them all.
524
525     if ($dups = $self->_duplicates($all_rels)) {
526         foreach my $dup (keys %$dups) {
527             # sort by method
528             my @rels = map $_->[1], sort { $a->[0] <=> $b->[0] } map [
529                 ($_->{method} eq 'belongs_to' ? 3 : $_->{method} eq 'has_many' ? 2 : 1), $_
530             ], @{ $dups->{$dup} };
531
532             my $rel_num = 2;
533
534             foreach my $rel (@rels[1 .. $#rels]) {
535                 my $inflect_type = $rel->{method} eq 'has_many' ?
536                     'inflect_plural'
537                     :
538                     'inflect_singular';
539
540                 my $inflect_method = "_$inflect_type";
541
542                 my $relname_new_uninflected =
543                     $self->_inflect_singular($rel->{args}[0]) . "_$rel_num";
544
545                 $rel_num++;
546
547                 my $relname_new = $self->$inflect_method($relname_new_uninflected);
548
549                 my $moniker = $rel->{extra}{moniker};
550
551                 my @from_cols = apply { s/^self\.//i }
552                     values %{ $rel->{args}[2] };
553
554                 warn <<"EOF";
555 Could not find a proper name for relationship '$relname_new' in source '$moniker' for columns '@{[ join ',', @from_cols ]}'.
556 Supply a value in '$inflect_type' for '$relname_new_uninflected' to name this relationship.
557 EOF
558
559                 $relname_new = $self->_resolve_relname_collision($moniker, \@from_cols, $relname_new);
560
561                 $rel->{args}[0] = $relname_new;
562             }
563         }
564     }
565 }
566
567 sub _relnames_and_method {
568     my ( $self, $local_moniker, $rel, $cond, $uniqs, $counters ) = @_;
569
570     my $remote_moniker = $rel->{remote_source};
571     my $remote_obj     = $self->schema->source( $remote_moniker );
572     my $remote_class   = $self->schema->class(  $remote_moniker );
573     my $remote_relname = $self->_remote_relname( $remote_obj->from, $cond);
574
575     my $local_cols     = $rel->{local_columns};
576     my $local_table    = $self->schema->source($local_moniker)->from;
577     my $local_class    = $self->schema->class($local_moniker);
578     my $local_source   = $self->schema->source($local_moniker);
579
580     my $local_relname_uninflected = $self->_normalize_name($local_table);
581     my $local_relname = $self->_inflect_plural($self->_normalize_name($local_table));
582
583     my $remote_method = 'has_many';
584
585     # If the local columns have a UNIQUE constraint, this is a one-to-one rel
586     if ($self->_array_eq([ $local_source->primary_columns ], $local_cols) ||
587             grep { $self->_array_eq($_->[1], $local_cols) } @$uniqs) {
588         $remote_method = 'might_have';
589         $local_relname = $self->_inflect_singular($local_relname_uninflected);
590     }
591
592     # If more than one rel between this pair of tables, use the local
593     # col names to distinguish, unless the rel was created previously.
594     if ($counters->{$remote_moniker} > 1) {
595         my $relationship_exists = 0;
596
597         if (-f (my $existing_remote_file = $self->base->get_dump_filename($remote_class))) {
598             my $class = "${remote_class}Temporary";
599
600             if (not Class::Inspector->loaded($class)) {
601                 my $code = decode 'UTF-8', scalar slurp $existing_remote_file;
602
603                 $code =~ s/(?<=package $remote_class)/Temporary/g;
604
605                 $code =~ s/__PACKAGE__->meta->make_immutable[^;]*;//g;
606
607                 eval $code;
608                 die $@ if $@;
609
610                 push @{ $self->_temp_classes }, $class;
611             }
612
613             if ($class->has_relationship($local_relname)) {
614                 my $rel_cols = [ sort { $a cmp $b } apply { s/^foreign\.//i }
615                     (keys %{ $class->relationship_info($local_relname)->{cond} }) ];
616
617                 $relationship_exists = 1 if $self->_array_eq([ sort @$local_cols ], $rel_cols);
618             }
619         }
620
621         if (not $relationship_exists) {
622             my $colnames = q{_} . $self->_normalize_name(join '_', @$local_cols);
623             $remote_relname .= $colnames if keys %$cond > 1;
624
625             $local_relname = $self->_normalize_name($local_table . $colnames);
626             $local_relname =~ s/_id$//;
627
628             $local_relname_uninflected = $local_relname;
629             $local_relname = $self->_inflect_plural($local_relname);
630
631             # if colnames were added and this is a might_have, re-inflect
632             if ($remote_method eq 'might_have') {
633                 $local_relname = $self->_inflect_singular($local_relname_uninflected);
634             }
635         }
636     }
637
638     return ( $local_relname, $remote_relname, $remote_method );
639 }
640
641 sub _cleanup {
642     my $self = shift;
643
644     for my $class (@{ $self->_temp_classes }) {
645         Class::Unload->unload($class);
646     }
647
648     $self->_temp_classes([]);
649 }
650
651 =head1 AUTHOR
652
653 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
654
655 =head1 LICENSE
656
657 This library is free software; you can redistribute it and/or modify it under
658 the same terms as Perl itself.
659
660 =cut
661
662 1;
663 # vim:et sts=4 sw=4 tw=0: