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