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/
114 my ( $class, $base ) = @_;
116 # from old POD about this constructor:
117 # C<$schema_class> should be a schema class name, where the source
118 # classes have already been set up and registered. Column info,
119 # primary key, and unique constraints will be drawn from this
120 # schema for all of the existing source monikers.
122 # Options inflect_plural and inflect_singular are optional, and
123 # are better documented in L<DBIx::Class::Schema::Loader::Base>.
127 schema => $base->schema,
128 inflect_plural => $base->inflect_plural,
129 inflect_singular => $base->inflect_singular,
130 relationship_attrs => $base->relationship_attrs,
131 rel_collision_map => $base->rel_collision_map,
135 weaken $self->{base}; #< don't leak
137 bless $self => $class;
139 # validate the relationship_attrs arg
140 if( defined $self->relationship_attrs ) {
141 ref $self->relationship_attrs eq 'HASH'
142 or croak "relationship_attrs must be a hashref";
149 # pluralize a relationship name
150 sub _inflect_plural {
151 my ($self, $relname) = @_;
153 return '' if !defined $relname || $relname eq '';
155 if( ref $self->inflect_plural eq 'HASH' ) {
156 return $self->inflect_plural->{$relname}
157 if exists $self->inflect_plural->{$relname};
159 elsif( ref $self->inflect_plural eq 'CODE' ) {
160 my $inflected = $self->inflect_plural->($relname);
161 return $inflected if $inflected;
164 return $self->_to_PL($relname);
167 # Singularize a relationship name
168 sub _inflect_singular {
169 my ($self, $relname) = @_;
171 return '' if !defined $relname || $relname eq '';
173 if( ref $self->inflect_singular eq 'HASH' ) {
174 return $self->inflect_singular->{$relname}
175 if exists $self->inflect_singular->{$relname};
177 elsif( ref $self->inflect_singular eq 'CODE' ) {
178 my $inflected = $self->inflect_singular->($relname);
179 return $inflected if $inflected;
182 return $self->_to_S($relname);
186 my ($self, $name) = @_;
189 my $plural = Lingua::EN::Inflect::Phrase::to_PL($name);
196 my ($self, $name) = @_;
199 my $singular = Lingua::EN::Inflect::Phrase::to_S($name);
200 $singular =~ s/ /_/g;
205 sub _default_relationship_attrs { +{
215 on_delete => 'CASCADE',
216 on_update => 'CASCADE',
221 # accessor for options to be passed to each generated relationship
222 # type. take single argument, the relationship type name, and returns
223 # either a hashref (if some options are set), or nothing
224 sub _relationship_attrs {
225 my ( $self, $reltype ) = @_;
226 my $r = $self->relationship_attrs;
229 %{ $self->_default_relationship_attrs->{$reltype} || {} },
233 if( my $specific = $r->{$reltype} ) {
234 while( my ($k,$v) = each %$specific ) {
242 my ($self, $a, $b) = @_;
244 return unless @$a == @$b;
246 for (my $i = 0; $i < @$a; $i++) {
247 return unless $a->[$i] eq $b->[$i];
253 my ($self, $local_moniker, $local_cols) = @_;
255 # get our base set of attrs from _relationship_attrs, if present
256 my $attrs = $self->_relationship_attrs('belongs_to') || {};
258 # If the referring column is nullable, make 'belongs_to' an
259 # outer join, unless explicitly set by relationship_attrs
260 my $nullable = grep { $self->schema->source($local_moniker)->column_info($_)->{is_nullable} } @$local_cols;
261 $attrs->{join_type} = 'LEFT' if $nullable && !defined $attrs->{join_type};
267 my ($self, $name) = @_;
270 # scalar ref for weird table name (like one containing a '.')
271 ($name = $$name) =~ s/\W+/_/g;
274 # remove 'schema.' prefix if any
275 $name =~ s/^[^.]+\.//;
281 sub _normalize_name {
282 my ($self, $name) = @_;
284 $name = $self->_sanitize_name($name);
286 my @words = split_name $name;
288 return join '_', map lc, @words;
291 sub _remote_relname {
292 my ($self, $remote_table, $cond) = @_;
295 # for single-column case, set the remote relname to the column
296 # name, to make filter accessors work, but strip trailing _id
297 if(scalar keys %{$cond} == 1) {
298 my ($col) = values %{$cond};
299 $col = $self->_normalize_name($col);
301 $remote_relname = $self->_inflect_singular($col);
304 $remote_relname = $self->_inflect_singular($self->_normalize_name($remote_table));
307 return $remote_relname;
310 sub _resolve_relname_collision {
311 my ($self, $moniker, $cols, $relname) = @_;
313 return $relname if $relname eq 'id'; # this shouldn't happen, but just in case
315 my $table = $self->base->tables->{$moniker};
317 if ($self->base->_is_result_class_method($relname, $table)) {
318 if (my $map = $self->rel_collision_map) {
319 for my $re (keys %$map) {
320 if (my @matches = $relname =~ /$re/) {
321 return sprintf $map->{$re}, @matches;
326 my $new_relname = $relname;
327 while ($self->base->_is_result_class_method($new_relname, $table)) {
328 $new_relname .= '_rel'
332 Relationship '$relname' in source '$moniker' for columns '@{[ join ',', @$cols ]}' collides with an inherited method.
333 Renaming to '$new_relname'.
334 See "RELATIONSHIP NAME COLLISIONS" in perldoc DBIx::Class::Schema::Loader::Base .
344 my ($self, $tables) = @_;
346 # make a copy to destroy
347 my @tables = @$tables;
351 while (my ($local_moniker, $rels, $uniqs) = @{ shift @tables || [] }) {
352 my $local_class = $self->schema->class($local_moniker);
355 foreach my $rel (@$rels) {
356 next if !$rel->{remote_source};
357 $counters{$rel->{remote_source}}++;
360 foreach my $rel (@$rels) {
361 my $remote_moniker = $rel->{remote_source}
364 my $remote_class = $self->schema->class($remote_moniker);
365 my $remote_obj = $self->schema->source($remote_moniker);
366 my $remote_cols = $rel->{remote_columns} || [ $remote_obj->primary_columns ];
368 my $local_cols = $rel->{local_columns};
370 if($#$local_cols != $#$remote_cols) {
371 croak "Column count mismatch: $local_moniker (@$local_cols) "
372 . "$remote_moniker (@$remote_cols)";
376 foreach my $i (0 .. $#$local_cols) {
377 $cond{$remote_cols->[$i]} = $local_cols->[$i];
380 my ( $local_relname, $remote_relname, $remote_method ) =
381 $self->_relnames_and_method( $local_moniker, $rel, \%cond, $uniqs, \%counters );
383 $remote_relname = $self->_resolve_relname_collision($local_moniker, $local_cols, $remote_relname);
384 $local_relname = $self->_resolve_relname_collision($remote_moniker, $remote_cols, $local_relname);
386 push(@{$all_code->{$local_class}},
387 { method => 'belongs_to',
388 args => [ $remote_relname,
391 $self->_remote_attrs($local_moniker, $local_cols),
394 moniker => $local_moniker,
399 my %rev_cond = reverse %cond;
400 for (keys %rev_cond) {
401 $rev_cond{"foreign.$_"} = "self.".$rev_cond{$_};
402 delete $rev_cond{$_};
405 push(@{$all_code->{$remote_class}},
406 { method => $remote_method,
407 args => [ $local_relname,
410 $self->_relationship_attrs($remote_method),
413 moniker => $remote_moniker,
420 # disambiguate rels with the same name
421 foreach my $class (keys %$all_code) {
422 my $dups = $self->_duplicates($all_code->{$class});
424 $self->_disambiguate($all_code->{$class}, $dups) if $dups;
433 my ($self, $rels) = @_;
435 my @rels = map [ $_->{args}[0] => $_ ], @$rels;
437 $rel_names{$_}++ foreach map $_->[0], @rels;
439 my @dups = grep $rel_names{$_} > 1, keys %rel_names;
443 foreach my $dup (@dups) {
444 $dups{$dup} = [ map $_->[1], grep { $_->[0] eq $dup } @rels ];
455 $self->__tagger(Lingua::EN::Tagger->new) unless $self->__tagger;
457 return $self->__tagger;
461 my ($self, @cols) = @_;
465 foreach my $col (@cols) {
466 my @words = split_name $col;
468 my $tagged = $self->_tagger->get_readable(join ' ', @words);
470 push @adjectives, $tagged =~ m{\G(\w+)/JJ\s+}g;
477 my ($self, $all_rels, $dups) = @_;
479 foreach my $dup (keys %$dups) {
480 my @rels = @{ $dups->{$dup} };
482 foreach my $rel (@rels) {
483 next if $rel->{method} eq 'belongs_to';
485 my @to_cols = apply { s/^foreign\.//i }
486 keys %{ $rel->{args}[2] };
488 my @adjectives = $self->_adjectives(@to_cols);
490 # If there are no adjectives, and there is only one might_have
491 # rel to that class, we hardcode 'active'.
493 my $to_class = $rel->{args}[1];
495 if ((not @adjectives)
496 && (grep { $_->{method} eq 'might_have'
497 && $_->{args}[1] eq $to_class } @$all_rels) == 1) {
499 @adjectives = 'active';
503 my $rel_name = join '_', sort(@adjectives), $rel->{args}[0];
505 $rel_name = $rel->{method} eq 'might_have' ?
506 $self->_inflect_singular($rel_name)
508 $self->_inflect_plural($rel_name);
510 my $moniker = $rel->{extra}{moniker};
512 my @from_cols = apply { s/^self\.//i }
513 values %{ $rel->{args}[2] };
515 $rel_name = $self->_resolve_relname_collision($moniker, \@from_cols, $rel_name);
517 $rel->{args}[0] = $rel_name;
522 # Check again for duplicates, since the heuristics above may not have resolved them all.
524 if ($dups = $self->_duplicates($all_rels)) {
525 foreach my $dup (keys %$dups) {
527 my @rels = map $_->[1], sort { $a->[0] <=> $b->[0] } map [
528 ($_->{method} eq 'belongs_to' ? 3 : $_->{method} eq 'has_many' ? 2 : 1), $_
529 ], @{ $dups->{$dup} };
533 foreach my $rel (@rels[1 .. $#rels]) {
534 my $inflect_type = $rel->{method} eq 'has_many' ?
539 my $inflect_method = "_$inflect_type";
541 my $relname_new_uninflected =
542 $self->_inflect_singular($rel->{args}[0]) . "_$rel_num";
546 my $relname_new = $self->$inflect_method($relname_new_uninflected);
548 my $moniker = $rel->{extra}{moniker};
550 my @from_cols = apply { s/^self\.//i }
551 values %{ $rel->{args}[2] };
554 Could not find a proper name for relationship '$relname_new' in source '$moniker' for columns '@{[ join ',', @from_cols ]}'.
555 Supply a value in '$inflect_type' for '$relname_new_uninflected' to name this relationship.
558 $relname_new = $self->_resolve_relname_collision($moniker, \@from_cols, $relname_new);
560 $rel->{args}[0] = $relname_new;
566 sub _relnames_and_method {
567 my ( $self, $local_moniker, $rel, $cond, $uniqs, $counters ) = @_;
569 my $remote_moniker = $rel->{remote_source};
570 my $remote_obj = $self->schema->source( $remote_moniker );
571 my $remote_class = $self->schema->class( $remote_moniker );
572 my $remote_relname = $self->_remote_relname( $remote_obj->from, $cond);
574 my $local_cols = $rel->{local_columns};
575 my $local_table = $self->schema->source($local_moniker)->from;
576 my $local_class = $self->schema->class($local_moniker);
577 my $local_source = $self->schema->source($local_moniker);
579 my $local_relname_uninflected = $self->_normalize_name($local_table);
580 my $local_relname = $self->_inflect_plural($self->_normalize_name($local_table));
582 my $remote_method = 'has_many';
584 # If the local columns have a UNIQUE constraint, this is a one-to-one rel
585 if ($self->_array_eq([ $local_source->primary_columns ], $local_cols) ||
586 grep { $self->_array_eq($_->[1], $local_cols) } @$uniqs) {
587 $remote_method = 'might_have';
588 $local_relname = $self->_inflect_singular($local_relname_uninflected);
591 # If more than one rel between this pair of tables, use the local
592 # col names to distinguish, unless the rel was created previously.
593 if ($counters->{$remote_moniker} > 1) {
594 my $relationship_exists = 0;
596 if (-f (my $existing_remote_file = $self->base->get_dump_filename($remote_class))) {
597 my $class = "${remote_class}Temporary";
599 if (not Class::Inspector->loaded($class)) {
600 my $code = read_file($existing_remote_file, binmode => ':encoding(UTF-8)');
602 $code =~ s/(?<=package $remote_class)/Temporary/g;
604 $code =~ s/__PACKAGE__->meta->make_immutable[^;]*;//g;
609 push @{ $self->_temp_classes }, $class;
612 if ($class->has_relationship($local_relname)) {
613 my $rel_cols = [ sort { $a cmp $b } apply { s/^foreign\.//i }
614 (keys %{ $class->relationship_info($local_relname)->{cond} }) ];
616 $relationship_exists = 1 if $self->_array_eq([ sort @$local_cols ], $rel_cols);
620 if (not $relationship_exists) {
621 my $colnames = q{_} . $self->_normalize_name(join '_', @$local_cols);
622 $remote_relname .= $colnames if keys %$cond > 1;
624 $local_relname = $self->_normalize_name($local_table . $colnames);
625 $local_relname =~ s/_id$//;
627 $local_relname_uninflected = $local_relname;
628 $local_relname = $self->_inflect_plural($local_relname);
630 # if colnames were added and this is a might_have, re-inflect
631 if ($remote_method eq 'might_have') {
632 $local_relname = $self->_inflect_singular($local_relname_uninflected);
637 return ( $local_relname, $remote_relname, $remote_method );
643 for my $class (@{ $self->_temp_classes }) {
644 Class::Unload->unload($class);
647 $self->_temp_classes([]);
652 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
656 This library is free software; you can redistribute it and/or modify it under
657 the same terms as Perl itself.
662 # vim:et sts=4 sw=4 tw=0: