set cascade_update => 0 on might_have relationships
[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 DBIx::Class::Schema::Loader::Utils 'split_name';
11 use File::Slurp 'slurp';
12 use Try::Tiny;
13 use Class::Unload ();
14 use Class::Inspector ();
15 use List::MoreUtils 'apply';
16 use namespace::clean;
17
18 our $VERSION = '0.07010';
19
20 # Glossary:
21 #
22 # remote_relname -- name of relationship from the local table referring to the remote table
23 # local_relname  -- name of relationship from the remote table referring to the local table
24 # remote_method  -- relationship type from remote table to local table, usually has_many
25
26 =head1 NAME
27
28 DBIx::Class::Schema::Loader::RelBuilder - Builds relationships for DBIx::Class::Schema::Loader
29
30 =head1 SYNOPSIS
31
32 See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
33
34 =head1 DESCRIPTION
35
36 This class builds relationships for L<DBIx::Class::Schema::Loader>.  This
37 is module is not (yet) for external use.
38
39 =head1 METHODS
40
41 =head2 new
42
43 Arguments: $base object
44
45 =head2 generate_code
46
47 Arguments: local_moniker (scalar), fk_info (arrayref)
48
49 This generates the code for the relationships of a given table.
50
51 C<local_moniker> is the moniker name of the table which had the REFERENCES
52 statements.  The fk_info arrayref's contents should take the form:
53
54     [
55         {
56             local_columns => [ 'col2', 'col3' ],
57             remote_columns => [ 'col5', 'col7' ],
58             remote_moniker => 'AnotherTableMoniker',
59         },
60         {
61             local_columns => [ 'col1', 'col4' ],
62             remote_columns => [ 'col1', 'col2' ],
63             remote_moniker => 'YetAnotherTableMoniker',
64         },
65         # ...
66     ],
67
68 This method will return the generated relationships as a hashref keyed on the
69 class names.  The values are arrayrefs of hashes containing method name and
70 arguments, like so:
71
72   {
73       'Some::Source::Class' => [
74           { method => 'belongs_to', arguments => [ 'col1', 'Another::Source::Class' ],
75           { method => 'has_many', arguments => [ 'anothers', 'Yet::Another::Source::Class', 'col15' ],
76       ],
77       'Another::Source::Class' => [
78           # ...
79       ],
80       # ...
81   }
82
83 =cut
84
85 __PACKAGE__->mk_group_accessors('simple', qw/
86     base
87     schema
88     inflect_plural
89     inflect_singular
90     relationship_attrs
91     rel_collision_map
92     _temp_classes
93 /);
94
95 sub new {
96     my ( $class, $base ) = @_;
97
98     # from old POD about this constructor:
99     # C<$schema_class> should be a schema class name, where the source
100     # classes have already been set up and registered.  Column info,
101     # primary key, and unique constraints will be drawn from this
102     # schema for all of the existing source monikers.
103
104     # Options inflect_plural and inflect_singular are optional, and
105     # are better documented in L<DBIx::Class::Schema::Loader::Base>.
106
107     my $self = {
108         base               => $base,
109         schema             => $base->schema,
110         inflect_plural     => $base->inflect_plural,
111         inflect_singular   => $base->inflect_singular,
112         relationship_attrs => $base->relationship_attrs,
113         rel_collision_map  => $base->rel_collision_map,
114         _temp_classes      => [],
115     };
116
117     weaken $self->{base}; #< don't leak
118
119     bless $self => $class;
120
121     # validate the relationship_attrs arg
122     if( defined $self->relationship_attrs ) {
123         ref $self->relationship_attrs eq 'HASH'
124             or croak "relationship_attrs must be a hashref";
125     }
126
127     return $self;
128 }
129
130
131 # pluralize a relationship name
132 sub _inflect_plural {
133     my ($self, $relname) = @_;
134
135     return '' if !defined $relname || $relname eq '';
136
137     if( ref $self->inflect_plural eq 'HASH' ) {
138         return $self->inflect_plural->{$relname}
139             if exists $self->inflect_plural->{$relname};
140     }
141     elsif( ref $self->inflect_plural eq 'CODE' ) {
142         my $inflected = $self->inflect_plural->($relname);
143         return $inflected if $inflected;
144     }
145
146     return $self->_to_PL($relname);
147 }
148
149 # Singularize a relationship name
150 sub _inflect_singular {
151     my ($self, $relname) = @_;
152
153     return '' if !defined $relname || $relname eq '';
154
155     if( ref $self->inflect_singular eq 'HASH' ) {
156         return $self->inflect_singular->{$relname}
157             if exists $self->inflect_singular->{$relname};
158     }
159     elsif( ref $self->inflect_singular eq 'CODE' ) {
160         my $inflected = $self->inflect_singular->($relname);
161         return $inflected if $inflected;
162     }
163
164     return $self->_to_S($relname);
165 }
166
167 sub _to_PL {
168     my ($self, $name) = @_;
169
170     $name =~ s/_/ /g;
171     my $plural = Lingua::EN::Inflect::Phrase::to_PL($name);
172     $plural =~ s/ /_/g;
173
174     return $plural;
175 }
176
177 sub _to_S {
178     my ($self, $name) = @_;
179
180     $name =~ s/_/ /g;
181     my $singular = Lingua::EN::Inflect::Phrase::to_S($name);
182     $singular =~ s/ /_/g;
183
184     return $singular;
185 }
186
187 sub _default_relationship_attrs { +{
188     has_many => {
189         cascade_delete => 0,
190         cascade_copy   => 0,
191     },
192     might_have => {
193         cascade_delete => 0,
194         cascade_copy   => 0,
195         cascade_update => 0,
196     },
197     belongs_to => {
198         on_delete => 'CASCADE',
199         on_update => 'CASCADE',
200         is_deferrable => 1,
201     },
202 } }
203
204 # accessor for options to be passed to each generated relationship
205 # type.  take single argument, the relationship type name, and returns
206 # either a hashref (if some options are set), or nothing
207 sub _relationship_attrs {
208     my ( $self, $reltype ) = @_;
209     my $r = $self->relationship_attrs;
210
211     my %composite = (
212         %{ $self->_default_relationship_attrs->{$reltype} || {} },
213         %{ $r->{all} || {} }
214     );
215
216     if( my $specific = $r->{$reltype} ) {
217         while( my ($k,$v) = each %$specific ) {
218             $composite{$k} = $v;
219         }
220     }
221     return \%composite;
222 }
223
224 sub _array_eq {
225     my ($self, $a, $b) = @_;
226
227     return unless @$a == @$b;
228
229     for (my $i = 0; $i < @$a; $i++) {
230         return unless $a->[$i] eq $b->[$i];
231     }
232     return 1;
233 }
234
235 sub _remote_attrs {
236     my ($self, $local_moniker, $local_cols) = @_;
237
238     # get our base set of attrs from _relationship_attrs, if present
239     my $attrs = $self->_relationship_attrs('belongs_to') || {};
240
241     # If the referring column is nullable, make 'belongs_to' an
242     # outer join, unless explicitly set by relationship_attrs
243     my $nullable = grep { $self->schema->source($local_moniker)->column_info($_)->{is_nullable} } @$local_cols;
244     $attrs->{join_type} = 'LEFT' if $nullable && !defined $attrs->{join_type};
245
246     return $attrs;
247 }
248
249 sub _sanitize_name {
250     my ($self, $name) = @_;
251
252     if (ref $name) {
253         # scalar ref for weird table name (like one containing a '.')
254         ($name = $$name) =~ s/\W+/_/g;
255     }
256     else {
257         # remove 'schema.' prefix if any
258         $name =~ s/^[^.]+\.//;
259     }
260
261     return $name;
262 }
263
264 sub _normalize_name {
265     my ($self, $name) = @_;
266
267     $name = $self->_sanitize_name($name);
268
269     my @words = split_name $name;
270
271     return join '_', map lc, @words;
272 }
273
274 sub _remote_relname {
275     my ($self, $remote_table, $cond) = @_;
276
277     my $remote_relname;
278     # for single-column case, set the remote relname to the column
279     # name, to make filter accessors work, but strip trailing _id
280     if(scalar keys %{$cond} == 1) {
281         my ($col) = values %{$cond};
282         $col = $self->_normalize_name($col);
283         $col =~ s/_id$//;
284         $remote_relname = $self->_inflect_singular($col);
285     }
286     else {
287         $remote_relname = $self->_inflect_singular($self->_normalize_name($remote_table));
288     }
289
290     return $remote_relname;
291 }
292
293 sub _resolve_relname_collision {
294     my ($self, $moniker, $cols, $relname) = @_;
295
296     return $relname if $relname eq 'id'; # this shouldn't happen, but just in case
297
298     if ($self->base->_is_result_class_method($relname)) {
299         if (my $map = $self->rel_collision_map) {
300             for my $re (keys %$map) {
301                 if (my @matches = $relname =~ /$re/) {
302                     return sprintf $map->{$re}, @matches;
303                 }
304             }
305         }
306
307         my $new_relname = $relname;
308         while ($self->base->_is_result_class_method($new_relname)) {
309             $new_relname .= '_rel'
310         }
311
312         warn <<"EOF";
313 Relationship '$relname' in source '$moniker' for columns '@{[ join ',', @$cols ]}' collides with an inherited method.
314 Renaming to '$new_relname'.
315 See "RELATIONSHIP NAME COLLISIONS" in perldoc DBIx::Class::Schema::Loader::Base .
316 EOF
317
318         return $new_relname;
319     }
320
321     return $relname;
322 }
323
324 sub generate_code {
325     my ($self, $local_moniker, $rels, $uniqs) = @_;
326
327     my $all_code = {};
328
329     my $local_class = $self->schema->class($local_moniker);
330
331     my %counters;
332     foreach my $rel (@$rels) {
333         next if !$rel->{remote_source};
334         $counters{$rel->{remote_source}}++;
335     }
336
337     foreach my $rel (@$rels) {
338         my $remote_moniker = $rel->{remote_source}
339             or next;
340
341         my $remote_class   = $self->schema->class($remote_moniker);
342         my $remote_obj     = $self->schema->source($remote_moniker);
343         my $remote_cols    = $rel->{remote_columns} || [ $remote_obj->primary_columns ];
344
345         my $local_cols     = $rel->{local_columns};
346
347         if($#$local_cols != $#$remote_cols) {
348             croak "Column count mismatch: $local_moniker (@$local_cols) "
349                 . "$remote_moniker (@$remote_cols)";
350         }
351
352         my %cond;
353         foreach my $i (0 .. $#$local_cols) {
354             $cond{$remote_cols->[$i]} = $local_cols->[$i];
355         }
356
357         my ( $local_relname, $remote_relname, $remote_method ) =
358             $self->_relnames_and_method( $local_moniker, $rel, \%cond,  $uniqs, \%counters );
359
360         $remote_relname = $self->_resolve_relname_collision($local_moniker,  $local_cols,  $remote_relname);
361         $local_relname  = $self->_resolve_relname_collision($remote_moniker, $remote_cols, $local_relname);
362
363         push(@{$all_code->{$local_class}},
364             { method => 'belongs_to',
365               args => [ $remote_relname,
366                         $remote_class,
367                         \%cond,
368                         $self->_remote_attrs($local_moniker, $local_cols),
369               ],
370             }
371         );
372
373         my %rev_cond = reverse %cond;
374         for (keys %rev_cond) {
375             $rev_cond{"foreign.$_"} = "self.".$rev_cond{$_};
376             delete $rev_cond{$_};
377         }
378
379         push(@{$all_code->{$remote_class}},
380             { method => $remote_method,
381               args => [ $local_relname,
382                         $local_class,
383                         \%rev_cond,
384                         $self->_relationship_attrs($remote_method),
385               ],
386             }
387         );
388     }
389
390     return $all_code;
391 }
392
393 sub _relnames_and_method {
394     my ( $self, $local_moniker, $rel, $cond, $uniqs, $counters ) = @_;
395
396     my $remote_moniker = $rel->{remote_source};
397     my $remote_obj     = $self->schema->source( $remote_moniker );
398     my $remote_class   = $self->schema->class(  $remote_moniker );
399     my $remote_relname = $self->_remote_relname( $remote_obj->from, $cond);
400
401     my $local_cols     = $rel->{local_columns};
402     my $local_table    = $self->schema->source($local_moniker)->from;
403     my $local_class    = $self->schema->class($local_moniker);
404     my $local_source   = $self->schema->source($local_moniker);
405
406     my $local_relname_uninflected = $self->_normalize_name($local_table);
407     my $local_relname = $self->_inflect_plural($self->_normalize_name($local_table));
408
409     my $remote_method = 'has_many';
410
411     # If the local columns have a UNIQUE constraint, this is a one-to-one rel
412     if ($self->_array_eq([ $local_source->primary_columns ], $local_cols) ||
413             grep { $self->_array_eq($_->[1], $local_cols) } @$uniqs) {
414         $remote_method = 'might_have';
415         $local_relname = $self->_inflect_singular($local_relname_uninflected);
416     }
417
418     # If more than one rel between this pair of tables, use the local
419     # col names to distinguish, unless the rel was created previously.
420     if ($counters->{$remote_moniker} > 1) {
421         my $relationship_exists = 0;
422
423         if (-f (my $existing_remote_file = $self->base->get_dump_filename($remote_class))) {
424             my $class = "${remote_class}Temporary";
425
426             if (not Class::Inspector->loaded($class)) {
427                 my $code = slurp $existing_remote_file;
428
429                 $code =~ s/(?<=package $remote_class)/Temporary/g;
430
431                 $code =~ s/__PACKAGE__->meta->make_immutable[^;]*;//g;
432
433                 eval $code;
434                 die $@ if $@;
435
436                 push @{ $self->_temp_classes }, $class;
437             }
438
439             if ($class->has_relationship($local_relname)) {
440                 my $rel_cols = [ sort { $a cmp $b } apply { s/^foreign\.//i }
441                     (keys %{ $class->relationship_info($local_relname)->{cond} }) ];
442
443                 $relationship_exists = 1 if $self->_array_eq([ sort @$local_cols ], $rel_cols);
444             }
445         }
446
447         if (not $relationship_exists) {
448             my $colnames = q{_} . $self->_normalize_name(join '_', @$local_cols);
449             $remote_relname .= $colnames if keys %$cond > 1;
450
451             $local_relname = $self->_normalize_name($local_table . $colnames);
452             $local_relname =~ s/_id$//;
453
454             $local_relname_uninflected = $local_relname;
455             $local_relname = $self->_inflect_plural($local_relname);
456
457             # if colnames were added and this is a might_have, re-inflect
458             if ($remote_method eq 'might_have') {
459                 $local_relname = $self->_inflect_singular($local_relname_uninflected);
460             }
461         }
462     }
463
464     return ( $local_relname, $remote_relname, $remote_method );
465 }
466
467 sub cleanup {
468     my $self = shift;
469
470     for my $class (@{ $self->_temp_classes }) {
471         Class::Unload->unload($class);
472     }
473
474     $self->_temp_classes([]);
475 }
476
477 =head1 AUTHOR
478
479 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
480
481 =head1 LICENSE
482
483 This library is free software; you can redistribute it and/or modify it under
484 the same terms as Perl itself.
485
486 =cut
487
488 1;
489 # vim:et sts=4 sw=4 tw=0: