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