1 package DBIx::Class::Schema::Loader::RelBuilder;
5 use base 'Class::Accessor::Grouped';
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';
15 use Class::Inspector ();
16 use List::MoreUtils 'apply';
19 our $VERSION = '0.07010';
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
29 DBIx::Class::Schema::Loader::RelBuilder - Builds relationships for DBIx::Class::Schema::Loader
33 See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
37 This class builds relationships for L<DBIx::Class::Schema::Loader>. This
38 is module is not (yet) for external use.
44 Arguments: $base object
51 local_moniker (scalar) => [ fk_info (arrayref), uniq_info (arrayref) ]
55 This generates the code for the relationships of each table.
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:
62 local_columns => [ 'col2', 'col3' ],
63 remote_columns => [ 'col5', 'col7' ],
64 remote_moniker => 'AnotherTableMoniker',
67 local_columns => [ 'col1', 'col4' ],
68 remote_columns => [ 'col1', 'col2' ],
69 remote_moniker => 'YetAnotherTableMoniker',
74 The uniq_info arrayref's contents should take the form:
78 uniq_constraint_name => [ 'col1', 'col2' ],
81 another_uniq_constraint_name => [ 'col1', 'col2' ],
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
90 'Some::Source::Class' => [
91 { method => 'belongs_to', arguments => [ 'col1', 'Another::Source::Class' ],
92 { method => 'has_many', arguments => [ 'anothers', 'Yet::Another::Source::Class', 'col15' ],
94 'Another::Source::Class' => [
102 __PACKAGE__->mk_group_accessors('simple', qw/
115 my ( $class, $base ) = @_;
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.
123 # Options inflect_plural and inflect_singular are optional, and
124 # are better documented in L<DBIx::Class::Schema::Loader::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,
137 weaken $self->{base}; #< don't leak
139 bless $self => $class;
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";
151 # pluralize a relationship name
152 sub _inflect_plural {
153 my ($self, $relname) = @_;
155 return '' if !defined $relname || $relname eq '';
160 if( ref $self->inflect_plural eq 'HASH' ) {
161 if (exists $self->inflect_plural->{$relname}) {
162 $result = $self->inflect_plural->{$relname};
166 elsif( ref $self->inflect_plural eq 'CODE' ) {
167 my $inflected = $self->inflect_plural->($relname);
169 $result = $inflected;
174 return ($result, $mapped) if $mapped;
176 return ($self->_to_PL($relname), 0);
179 # Singularize a relationship name
180 sub _inflect_singular {
181 my ($self, $relname) = @_;
183 return '' if !defined $relname || $relname eq '';
188 if( ref $self->inflect_singular eq 'HASH' ) {
189 if (exists $self->inflect_singular->{$relname}) {
190 $result = $self->inflect_singular->{$relname};
194 elsif( ref $self->inflect_singular eq 'CODE' ) {
195 my $inflected = $self->inflect_singular->($relname);
197 $result = $inflected;
202 return ($result, $mapped) if $mapped;
204 return ($self->_to_S($relname), 0);
208 my ($self, $name) = @_;
211 my $plural = Lingua::EN::Inflect::Phrase::to_PL($name);
218 my ($self, $name) = @_;
221 my $singular = Lingua::EN::Inflect::Phrase::to_S($name);
222 $singular =~ s/ /_/g;
227 sub _default_relationship_attrs { +{
237 on_delete => 'CASCADE',
238 on_update => 'CASCADE',
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;
251 %{ $self->_default_relationship_attrs->{$reltype} || {} },
255 if( my $specific = $r->{$reltype} ) {
256 while( my ($k,$v) = each %$specific ) {
264 my ($self, $a, $b) = @_;
266 return unless @$a == @$b;
268 for (my $i = 0; $i < @$a; $i++) {
269 return unless $a->[$i] eq $b->[$i];
275 my ($self, $local_moniker, $local_cols) = @_;
277 # get our base set of attrs from _relationship_attrs, if present
278 my $attrs = $self->_relationship_attrs('belongs_to') || {};
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};
289 my ($self, $name) = @_;
292 # scalar ref for weird table name (like one containing a '.')
293 ($name = $$name) =~ s/\W+/_/g;
296 # remove 'schema.' prefix if any
297 $name =~ s/^[^.]+\.//;
303 sub _normalize_name {
304 my ($self, $name) = @_;
306 $name = $self->_sanitize_name($name);
308 my @words = split_name $name;
310 return join '_', map lc, @words;
313 sub _remote_relname {
314 my ($self, $remote_table, $cond) = @_;
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);
323 ($remote_relname) = $self->_inflect_singular($col);
326 ($remote_relname) = $self->_inflect_singular($self->_normalize_name($remote_table));
329 return $remote_relname;
332 sub _resolve_relname_collision {
333 my ($self, $moniker, $cols, $relname) = @_;
335 return $relname if $relname eq 'id'; # this shouldn't happen, but just in case
337 my $table = $self->base->tables->{$moniker};
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;
348 my $new_relname = $relname;
349 while ($self->base->_is_result_class_method($new_relname, $table)) {
350 $new_relname .= '_rel'
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 .
366 my ($self, $tables) = @_;
368 # make a copy to destroy
369 my @tables = @$tables;
373 while (my ($local_moniker, $rels, $uniqs) = @{ shift @tables || [] }) {
374 my $local_class = $self->schema->class($local_moniker);
377 foreach my $rel (@$rels) {
378 next if !$rel->{remote_source};
379 $counters{$rel->{remote_source}}++;
382 foreach my $rel (@$rels) {
383 my $remote_moniker = $rel->{remote_source}
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 ];
390 my $local_cols = $rel->{local_columns};
392 if($#$local_cols != $#$remote_cols) {
393 croak "Column count mismatch: $local_moniker (@$local_cols) "
394 . "$remote_moniker (@$remote_cols)";
398 foreach my $i (0 .. $#$local_cols) {
399 $cond{$remote_cols->[$i]} = $local_cols->[$i];
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';
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);
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);
412 push(@{$all_code->{$local_class}},
413 { method => $local_method,
414 args => [ $remote_relname,
417 $self->_remote_attrs($local_moniker, $local_cols),
420 local_class => $local_class,
421 local_moniker => $local_moniker,
422 remote_moniker => $remote_moniker,
427 my %rev_cond = reverse %cond;
428 for (keys %rev_cond) {
429 $rev_cond{"foreign.$_"} = "self.".$rev_cond{$_};
430 delete $rev_cond{$_};
433 push(@{$all_code->{$remote_class}},
434 { method => $remote_method,
435 args => [ $local_relname,
438 $self->_relationship_attrs($remote_method),
441 local_class => $remote_class,
442 local_moniker => $remote_moniker,
443 remote_moniker => $local_moniker,
450 # disambiguate rels with the same name
451 foreach my $class (keys %$all_code) {
452 my $dups = $self->_duplicates($all_code->{$class});
454 $self->_disambiguate($all_code->{$class}, $dups) if $dups;
463 my ($self, $rels) = @_;
465 my @rels = map [ $_->{args}[0] => $_ ], @$rels;
467 $rel_names{$_}++ foreach map $_->[0], @rels;
469 my @dups = grep $rel_names{$_} > 1, keys %rel_names;
473 foreach my $dup (@dups) {
474 $dups{$dup} = [ map $_->[1], grep { $_->[0] eq $dup } @rels ];
485 $self->__tagger(Lingua::EN::Tagger->new) unless $self->__tagger;
487 return $self->__tagger;
491 my ($self, @cols) = @_;
495 foreach my $col (@cols) {
496 my @words = split_name $col;
498 my $tagged = $self->_tagger->get_readable(join ' ', @words);
500 push @adjectives, $tagged =~ m{\G(\w+)/JJ\s+}g;
507 my ($self, $all_rels, $dups) = @_;
509 foreach my $dup (keys %$dups) {
510 my @rels = @{ $dups->{$dup} };
512 foreach my $rel (@rels) {
513 next if $rel->{method} eq 'belongs_to';
515 my @to_cols = apply { s/^foreign\.//i }
516 keys %{ $rel->{args}[2] };
518 my @adjectives = $self->_adjectives(@to_cols);
520 # If there are no adjectives, and there is only one might_have
521 # rel to that class, we hardcode 'active'.
523 my $to_class = $rel->{args}[1];
525 if ((not @adjectives)
526 && (grep { $_->{method} eq 'might_have'
527 && $_->{args}[1] eq $to_class } @$all_rels) == 1) {
529 @adjectives = 'active';
533 my $rel_name = join '_', sort(@adjectives), $rel->{args}[0];
535 ($rel_name) = $rel->{method} eq 'might_have' ?
536 $self->_inflect_singular($rel_name)
538 $self->_inflect_plural($rel_name);
540 my ($local_class, $local_moniker, $remote_moniker)
542 {qw/local_class local_moniker remote_moniker/};
544 my @from_cols = apply { s/^self\.//i }
545 values %{ $rel->{args}[2] };
547 ($rel_name) = $self->_rel_name_map($rel_name, $rel->{method}, $local_class, $local_moniker, \@from_cols, $to_class, $remote_moniker, \@to_cols);
549 $rel_name = $self->_resolve_relname_collision($local_moniker, \@from_cols, $rel_name);
551 $rel->{args}[0] = $rel_name;
556 # Check again for duplicates, since the heuristics above may not have resolved them all.
558 if ($dups = $self->_duplicates($all_rels)) {
559 foreach my $dup (keys %$dups) {
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} };
567 foreach my $rel (@rels[1 .. $#rels]) {
568 my $inflect_type = $rel->{method} eq 'has_many' ?
573 my $inflect_method = "_$inflect_type";
575 my $relname_new_uninflected = $rel->{args}[0] . "_$rel_num";
579 my ($local_class, $local_moniker, $remote_moniker)
581 {qw/local_class local_moniker remote_moniker/};
583 my @from_cols = apply { s/^self\.//i }
584 values %{ $rel->{args}[2] };
586 my @to_cols = apply { s/^foreign\.//i }
587 keys %{ $rel->{args}[2] };
589 my $to_class = $rel->{args}[1];
591 my ($relname_new, $inflect_mapped) =
592 $self->$inflect_method($relname_new_uninflected);
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);
598 my $mapped = $inflect_mapped || $rel_name_mapped;
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
607 $relname_new = $self->_resolve_relname_collision($local_moniker, \@from_cols, $relname_new);
609 $rel->{args}[0] = $relname_new;
615 sub _relnames_and_method {
616 my ( $self, $local_moniker, $rel, $cond, $uniqs, $counters ) = @_;
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);
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);
628 my $local_relname_uninflected = $self->_normalize_name($local_table);
629 my ($local_relname) = $self->_inflect_plural($self->_normalize_name($local_table));
631 my $remote_method = 'has_many';
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);
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;
645 if (-f (my $existing_remote_file = $self->base->get_dump_filename($remote_class))) {
646 my $class = "${remote_class}Temporary";
648 if (not Class::Inspector->loaded($class)) {
649 my $code = read_file($existing_remote_file, binmode => ':encoding(UTF-8)');
651 $code =~ s/(?<=package $remote_class)/Temporary/g;
653 $code =~ s/__PACKAGE__->meta->make_immutable[^;]*;//g;
658 push @{ $self->_temp_classes }, $class;
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} }) ];
665 $relationship_exists = 1 if $self->_array_eq([ sort @$local_cols ], $rel_cols);
669 if (not $relationship_exists) {
670 my $colnames = q{_} . $self->_normalize_name(join '_', @$local_cols);
671 $remote_relname .= $colnames if keys %$cond > 1;
673 $local_relname = $self->_normalize_name($local_table . $colnames);
674 $local_relname =~ s/_id$//;
676 $local_relname_uninflected = $local_relname;
677 ($local_relname) = $self->_inflect_plural($local_relname);
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);
686 return ($local_relname, $remote_relname, $remote_method);
690 my ($self, $relname, $method, $local_class, $local_moniker, $local_cols,
691 $remote_class, $remote_moniker, $remote_cols) = @_;
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,
704 my $new_name = $relname;
706 my $map = $self->rel_name_map;
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}
715 $new_name = $map->{$moniker}{$name};
718 elsif ($map->{$name} and not 'HASH' eq ref($map->{$name})) {
719 $new_name = $map->{$name};
723 elsif ('CODE' eq ref($map)) {
724 my $name = $map->($info);
731 return ($new_name, $mapped);
737 for my $class (@{ $self->_temp_classes }) {
738 Class::Unload->unload($class);
741 $self->_temp_classes([]);
746 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
750 This library is free software; you can redistribute it and/or modify it under
751 the same terms as Perl itself.
756 # vim:et sts=4 sw=4 tw=0: