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 DBIx::Class::Schema::Loader::Utils qw/split_name slurp_file array_eq/;
11 use List::MoreUtils qw/apply uniq any/;
13 use Lingua::EN::Inflect::Phrase ();
14 use Lingua::EN::Tagger ();
15 use String::ToIdentifier::EN ();
16 use String::ToIdentifier::EN::Unicode ();
18 use Class::Inspector ();
20 our $VERSION = '0.07014';
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
30 DBIx::Class::Schema::Loader::RelBuilder - Builds relationships for DBIx::Class::Schema::Loader
34 See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
38 This class builds relationships for L<DBIx::Class::Schema::Loader>. This
39 is module is not (yet) for external use.
45 Arguments: $loader object
52 [ local_moniker1 (scalar), fk_info1 (arrayref), uniq_info1 (arrayref) ]
53 [ local_moniker2 (scalar), fk_info2 (arrayref), uniq_info2 (arrayref) ]
57 This generates the code for the relationships of each table.
59 C<local_moniker> is the moniker name of the table which had the REFERENCES
60 statements. The fk_info arrayref's contents should take the form:
64 local_table => 'some_table',
65 local_moniker => 'SomeTable',
66 local_columns => [ 'col2', 'col3' ],
67 remote_table => 'another_table_moniker',
68 remote_moniker => 'AnotherTableMoniker',
69 remote_columns => [ 'col5', 'col7' ],
72 local_table => 'some_other_table',
73 local_moniker => 'SomeOtherTable',
74 local_columns => [ 'col1', 'col4' ],
75 remote_table => 'yet_another_table_moniker',
76 remote_moniker => 'YetAnotherTableMoniker',
77 remote_columns => [ 'col1', 'col2' ],
82 The uniq_info arrayref's contents should take the form:
86 uniq_constraint_name => [ 'col1', 'col2' ],
89 another_uniq_constraint_name => [ 'col1', 'col2' ],
93 This method will return the generated relationships as a hashref keyed on the
94 class names. The values are arrayrefs of hashes containing method name and
98 'Some::Source::Class' => [
99 { method => 'belongs_to', arguments => [ 'col1', 'Another::Source::Class' ],
100 { method => 'has_many', arguments => [ 'anothers', 'Yet::Another::Source::Class', 'col15' ],
102 'Another::Source::Class' => [
110 __PACKAGE__->mk_group_accessors('simple', qw/
123 my ($class, $loader) = @_;
125 # from old POD about this constructor:
126 # C<$schema_class> should be a schema class name, where the source
127 # classes have already been set up and registered. Column info,
128 # primary key, and unique constraints will be drawn from this
129 # schema for all of the existing source monikers.
131 # Options inflect_plural and inflect_singular are optional, and
132 # are better documented in L<DBIx::Class::Schema::Loader::Base>.
136 schema => $loader->schema,
137 inflect_plural => $loader->inflect_plural,
138 inflect_singular => $loader->inflect_singular,
139 relationship_attrs => $loader->relationship_attrs,
140 rel_collision_map => $loader->rel_collision_map,
141 rel_name_map => $loader->rel_name_map,
145 weaken $self->{loader}; #< don't leak
147 bless $self => $class;
149 # validate the relationship_attrs arg
150 if( defined $self->relationship_attrs ) {
151 ref $self->relationship_attrs eq 'HASH'
152 or croak "relationship_attrs must be a hashref";
159 # pluralize a relationship name
160 sub _inflect_plural {
161 my ($self, $relname) = @_;
163 return '' if !defined $relname || $relname eq '';
168 if( ref $self->inflect_plural eq 'HASH' ) {
169 if (exists $self->inflect_plural->{$relname}) {
170 $result = $self->inflect_plural->{$relname};
174 elsif( ref $self->inflect_plural eq 'CODE' ) {
175 my $inflected = $self->inflect_plural->($relname);
177 $result = $inflected;
182 return ($result, $mapped) if $mapped;
184 return ($self->_to_PL($relname), 0);
187 # Singularize a relationship name
188 sub _inflect_singular {
189 my ($self, $relname) = @_;
191 return '' if !defined $relname || $relname eq '';
196 if( ref $self->inflect_singular eq 'HASH' ) {
197 if (exists $self->inflect_singular->{$relname}) {
198 $result = $self->inflect_singular->{$relname};
202 elsif( ref $self->inflect_singular eq 'CODE' ) {
203 my $inflected = $self->inflect_singular->($relname);
205 $result = $inflected;
210 return ($result, $mapped) if $mapped;
212 return ($self->_to_S($relname), 0);
216 my ($self, $name) = @_;
219 my $plural = Lingua::EN::Inflect::Phrase::to_PL($name);
226 my ($self, $name) = @_;
229 my $singular = Lingua::EN::Inflect::Phrase::to_S($name);
230 $singular =~ s/ /_/g;
235 sub _default_relationship_attrs { +{
245 on_delete => 'CASCADE',
246 on_update => 'CASCADE',
251 # accessor for options to be passed to each generated relationship
252 # type. take single argument, the relationship type name, and returns
253 # either a hashref (if some options are set), or nothing
254 sub _relationship_attrs {
255 my ( $self, $reltype ) = @_;
256 my $r = $self->relationship_attrs;
259 %{ $self->_default_relationship_attrs->{$reltype} || {} },
263 if( my $specific = $r->{$reltype} ) {
264 while( my ($k,$v) = each %$specific ) {
271 sub _strip_id_postfix {
272 my ($self, $name) = @_;
274 $name =~ s/_?(?:id|ref|cd|code|num)\z//i;
280 my ($self, $local_moniker, $local_cols) = @_;
282 # get our base set of attrs from _relationship_attrs, if present
283 my $attrs = $self->_relationship_attrs('belongs_to') || {};
285 # If the referring column is nullable, make 'belongs_to' an
286 # outer join, unless explicitly set by relationship_attrs
287 my $nullable = grep { $self->schema->source($local_moniker)->column_info($_)->{is_nullable} } @$local_cols;
288 $attrs->{join_type} = 'LEFT' if $nullable && !defined $attrs->{join_type};
294 my ($self, $name) = @_;
296 $name = $self->loader->_to_identifier('relationships', $name, '_');
298 $name =~ s/\W+/_/g; # if naming >= 8 to_identifier takes care of it
303 sub _normalize_name {
304 my ($self, $name) = @_;
306 $name = $self->_sanitize_name($name);
308 my @words = split_name $name, $self->loader->_get_naming_v('relationships');
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->_strip_id_postfix($self->_normalize_name($col));
322 ($remote_relname) = $self->_inflect_singular($col);
325 ($remote_relname) = $self->_inflect_singular($self->_normalize_name($remote_table));
328 return $remote_relname;
331 sub _resolve_relname_collision {
332 my ($self, $moniker, $cols, $relname) = @_;
334 return $relname if $relname eq 'id'; # this shouldn't happen, but just in case
336 my $table = $self->loader->moniker_to_table->{$moniker};
338 if ($self->loader->_is_result_class_method($relname, $table)) {
339 if (my $map = $self->rel_collision_map) {
340 for my $re (keys %$map) {
341 if (my @matches = $relname =~ /$re/) {
342 return sprintf $map->{$re}, @matches;
347 my $new_relname = $relname;
348 while ($self->loader->_is_result_class_method($new_relname, $table)) {
349 $new_relname .= '_rel'
353 Relationship '$relname' in source '$moniker' for columns '@{[ join ',', @$cols ]}' collides with an inherited method. Renaming to '$new_relname'.
354 See "RELATIONSHIP NAME COLLISIONS" in perldoc DBIx::Class::Schema::Loader::Base .
364 my ($self, $tables) = @_;
366 # make a copy to destroy
367 my @tables = @$tables;
371 while (my ($local_moniker, $rels, $uniqs) = @{ shift @tables || [] }) {
372 my $local_class = $self->schema->class($local_moniker);
375 foreach my $rel (@$rels) {
376 next if !$rel->{remote_source};
377 $counters{$rel->{remote_source}}++;
380 foreach my $rel (@$rels) {
381 my $remote_moniker = $rel->{remote_source}
384 my $remote_class = $self->schema->class($remote_moniker);
385 my $remote_obj = $self->schema->source($remote_moniker);
386 my $remote_cols = $rel->{remote_columns} || [ $remote_obj->primary_columns ];
388 my $local_cols = $rel->{local_columns};
390 if($#$local_cols != $#$remote_cols) {
391 croak "Column count mismatch: $local_moniker (@$local_cols) "
392 . "$remote_moniker (@$remote_cols)";
396 foreach my $i (0 .. $#$local_cols) {
397 $cond{$remote_cols->[$i]} = $local_cols->[$i];
400 my ( $local_relname, $remote_relname, $remote_method ) =
401 $self->_relnames_and_method( $local_moniker, $rel, \%cond, $uniqs, \%counters );
402 my $local_method = 'belongs_to';
404 ($remote_relname) = $self->_rel_name_map($remote_relname, $local_method, $local_class, $local_moniker, $local_cols, $remote_class, $remote_moniker, $remote_cols);
405 ($local_relname) = $self->_rel_name_map($local_relname, $remote_method, $remote_class, $remote_moniker, $remote_cols, $local_class, $local_moniker, $local_cols);
407 $remote_relname = $self->_resolve_relname_collision($local_moniker, $local_cols, $remote_relname);
408 $local_relname = $self->_resolve_relname_collision($remote_moniker, $remote_cols, $local_relname);
410 push(@{$all_code->{$local_class}},
411 { method => $local_method,
412 args => [ $remote_relname,
415 $self->_remote_attrs($local_moniker, $local_cols),
418 local_class => $local_class,
419 local_moniker => $local_moniker,
420 remote_moniker => $remote_moniker,
425 my %rev_cond = reverse %cond;
426 for (keys %rev_cond) {
427 $rev_cond{"foreign.$_"} = "self.".$rev_cond{$_};
428 delete $rev_cond{$_};
431 push(@{$all_code->{$remote_class}},
432 { method => $remote_method,
433 args => [ $local_relname,
436 $self->_relationship_attrs($remote_method),
439 local_class => $remote_class,
440 local_moniker => $remote_moniker,
441 remote_moniker => $local_moniker,
448 # disambiguate rels with the same name
449 foreach my $class (keys %$all_code) {
450 my $dups = $self->_duplicates($all_code->{$class});
452 $self->_disambiguate($all_code->{$class}, $dups) if $dups;
461 my ($self, $rels) = @_;
463 my @rels = map [ $_->{args}[0] => $_ ], @$rels;
465 $rel_names{$_}++ foreach map $_->[0], @rels;
467 my @dups = grep $rel_names{$_} > 1, keys %rel_names;
471 foreach my $dup (@dups) {
472 $dups{$dup} = [ map $_->[1], grep { $_->[0] eq $dup } @rels ];
483 $self->__tagger(Lingua::EN::Tagger->new) unless $self->__tagger;
485 return $self->__tagger;
489 my ($self, @cols) = @_;
493 foreach my $col (@cols) {
494 my @words = split_name $col;
496 my $tagged = $self->_tagger->get_readable(join ' ', @words);
498 push @adjectives, $tagged =~ m{\G(\w+)/JJ\s+}g;
504 sub _name_to_identifier {
505 my ($self, $name) = @_;
507 my $to_identifier = $self->loader->naming->{force_ascii} ?
508 \&String::ToIdentifier::EN::to_identifier
509 : \&String::ToIdentifier::EN::Unicode::to_identifier;
511 return join '_', map lc, split_name $to_identifier->($name, '_');
515 my ($self, $all_rels, $dups) = @_;
517 DUP: foreach my $dup (keys %$dups) {
518 my @rels = @{ $dups->{$dup} };
520 # Check if there are rels to the same table name in different
521 # schemas/databases, if so qualify them.
522 my @tables = map $self->loader->moniker_to_table->{$_->{extra}{remote_moniker}},
525 # databases are different, prepend database
526 if ($tables[0]->can('database') && (uniq map $_->database||'', @tables) > 1) {
527 # If any rels are in the same database, we have to distinguish by
528 # both schema and database.
530 $db_counts{$_}++ for map $_->database, @tables;
531 my $use_schema = any { $_ > 1 } values %db_counts;
533 foreach my $i (0..$#rels) {
535 my $table = $tables[$i];
537 $rel->{args}[0] = $self->_name_to_identifier($table->database)
538 . ($use_schema ? ('_' . $self->name_to_identifier($table->schema)) : '')
539 . '_' . $rel->{args}[0];
543 # schemas are different, prepend schema
544 elsif ((uniq map $_->schema||'', @tables) > 1) {
545 foreach my $i (0..$#rels) {
547 my $table = $tables[$i];
549 $rel->{args}[0] = $self->_name_to_identifier($table->schema)
550 . '_' . $rel->{args}[0];
555 foreach my $rel (@rels) {
556 next if $rel->{method} eq 'belongs_to';
558 my @to_cols = apply { s/^foreign\.//i }
559 keys %{ $rel->{args}[2] };
561 my @adjectives = $self->_adjectives(@to_cols);
563 # If there are no adjectives, and there is only one might_have
564 # rel to that class, we hardcode 'active'.
566 my $to_class = $rel->{args}[1];
568 if ((not @adjectives)
569 && (grep { $_->{method} eq 'might_have'
570 && $_->{args}[1] eq $to_class } @$all_rels) == 1) {
572 @adjectives = 'active';
576 my $rel_name = join '_', sort(@adjectives), $rel->{args}[0];
578 ($rel_name) = $rel->{method} eq 'might_have' ?
579 $self->_inflect_singular($rel_name)
581 $self->_inflect_plural($rel_name);
583 my ($local_class, $local_moniker, $remote_moniker)
585 {qw/local_class local_moniker remote_moniker/};
587 my @from_cols = apply { s/^self\.//i }
588 values %{ $rel->{args}[2] };
590 ($rel_name) = $self->_rel_name_map($rel_name, $rel->{method}, $local_class, $local_moniker, \@from_cols, $to_class, $remote_moniker, \@to_cols);
592 $rel_name = $self->_resolve_relname_collision($local_moniker, \@from_cols, $rel_name);
594 $rel->{args}[0] = $rel_name;
599 # Check again for duplicates, since the heuristics above may not have resolved them all.
601 if ($dups = $self->_duplicates($all_rels)) {
602 foreach my $dup (keys %$dups) {
604 my @rels = map $_->[1], sort { $a->[0] <=> $b->[0] } map [
605 ($_->{method} eq 'belongs_to' ? 3 : $_->{method} eq 'has_many' ? 2 : 1), $_
606 ], @{ $dups->{$dup} };
610 foreach my $rel (@rels[1 .. $#rels]) {
611 my $inflect_type = $rel->{method} eq 'has_many' ?
616 my $inflect_method = "_$inflect_type";
618 my $relname_new_uninflected = $rel->{args}[0] . "_$rel_num";
622 my ($local_class, $local_moniker, $remote_moniker)
624 {qw/local_class local_moniker remote_moniker/};
626 my @from_cols = apply { s/^self\.//i }
627 values %{ $rel->{args}[2] };
629 my @to_cols = apply { s/^foreign\.//i }
630 keys %{ $rel->{args}[2] };
632 my $to_class = $rel->{args}[1];
634 my ($relname_new, $inflect_mapped) =
635 $self->$inflect_method($relname_new_uninflected);
639 ($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);
641 my $mapped = $inflect_mapped || $rel_name_mapped;
643 warn <<"EOF" unless $mapped;
644 Could not find a proper name for relationship '$relname_new' in source
645 '$local_moniker' for columns '@{[ join ',', @from_cols ]}'. Supply a value in
646 '$inflect_type' or 'rel_name_map' for '$relname_new_uninflected' to name this
650 $relname_new = $self->_resolve_relname_collision($local_moniker, \@from_cols, $relname_new);
652 $rel->{args}[0] = $relname_new;
658 sub _relnames_and_method {
659 my ( $self, $local_moniker, $rel, $cond, $uniqs, $counters ) = @_;
661 my $remote_moniker = $rel->{remote_source};
662 my $remote_obj = $self->schema->source( $remote_moniker );
663 my $remote_class = $self->schema->class( $remote_moniker );
664 my $remote_relname = $self->_remote_relname( $rel->{remote_table}, $cond);
666 my $local_cols = $rel->{local_columns};
667 my $local_table = $rel->{local_table};
668 my $local_class = $self->schema->class($local_moniker);
669 my $local_source = $self->schema->source($local_moniker);
671 my $local_relname_uninflected = $self->_normalize_name($local_table);
672 my ($local_relname) = $self->_inflect_plural($self->_normalize_name($local_table));
674 my $remote_method = 'has_many';
676 # If the local columns have a UNIQUE constraint, this is a one-to-one rel
677 if (array_eq([ $local_source->primary_columns ], $local_cols) ||
678 grep { array_eq($_->[1], $local_cols) } @$uniqs) {
679 $remote_method = 'might_have';
680 ($local_relname) = $self->_inflect_singular($local_relname_uninflected);
683 # If more than one rel between this pair of tables, use the local
684 # col names to distinguish, unless the rel was created previously.
685 if ($counters->{$remote_moniker} > 1) {
686 my $relationship_exists = 0;
688 if (-f (my $existing_remote_file = $self->loader->get_dump_filename($remote_class))) {
689 my $class = "${remote_class}Temporary";
691 if (not Class::Inspector->loaded($class)) {
692 my $code = slurp_file $existing_remote_file;
694 $code =~ s/(?<=package $remote_class)/Temporary/g;
696 $code =~ s/__PACKAGE__->meta->make_immutable[^;]*;//g;
701 push @{ $self->_temp_classes }, $class;
704 if ($class->has_relationship($local_relname)) {
705 my $rel_cols = [ sort { $a cmp $b } apply { s/^foreign\.//i }
706 (keys %{ $class->relationship_info($local_relname)->{cond} }) ];
708 $relationship_exists = 1 if array_eq([ sort @$local_cols ], $rel_cols);
712 if (not $relationship_exists) {
713 my $colnames = q{_} . $self->_normalize_name(join '_', @$local_cols);
714 $remote_relname .= $colnames if keys %$cond > 1;
716 $local_relname = $self->_strip_id_postfix($self->_normalize_name($local_table . $colnames));
718 $local_relname_uninflected = $local_relname;
719 ($local_relname) = $self->_inflect_plural($local_relname);
721 # if colnames were added and this is a might_have, re-inflect
722 if ($remote_method eq 'might_have') {
723 ($local_relname) = $self->_inflect_singular($local_relname_uninflected);
728 return ($local_relname, $remote_relname, $remote_method);
732 my ($self, $relname, $method, $local_class, $local_moniker, $local_cols,
733 $remote_class, $remote_moniker, $remote_cols) = @_;
738 local_class => $local_class,
739 local_moniker => $local_moniker,
740 local_columns => $local_cols,
741 remote_class => $remote_class,
742 remote_moniker => $remote_moniker,
743 remote_columns => $remote_cols,
746 my $new_name = $relname;
748 my $map = $self->rel_name_map;
751 if ('HASH' eq ref($map)) {
752 my $name = $info->{name};
753 my $moniker = $info->{local_moniker};
754 if ($map->{$moniker} and 'HASH' eq ref($map->{$moniker})
755 and $map->{$moniker}{$name}
757 $new_name = $map->{$moniker}{$name};
760 elsif ($map->{$name} and not 'HASH' eq ref($map->{$name})) {
761 $new_name = $map->{$name};
765 elsif ('CODE' eq ref($map)) {
766 my $name = $map->($info);
773 return ($new_name, $mapped);
779 for my $class (@{ $self->_temp_classes }) {
780 Class::Unload->unload($class);
783 $self->_temp_classes([]);
788 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
792 This library is free software; you can redistribute it and/or modify it under
793 the same terms as Perl itself.
798 # vim:et sts=4 sw=4 tw=0: