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 DBIx::Class::Schema::Loader::Utils 'split_name';
11 use File::Slurp 'slurp';
14 use Class::Inspector ();
15 use List::MoreUtils 'apply';
18 our $VERSION = '0.07008';
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
28 DBIx::Class::Schema::Loader::RelBuilder - Builds relationships for DBIx::Class::Schema::Loader
32 See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
36 This class builds relationships for L<DBIx::Class::Schema::Loader>. This
37 is module is not (yet) for external use.
43 Arguments: $base object
47 Arguments: local_moniker (scalar), fk_info (arrayref)
49 This generates the code for the relationships of a given table.
51 C<local_moniker> is the moniker name of the table which had the REFERENCES
52 statements. The fk_info arrayref's contents should take the form:
56 local_columns => [ 'col2', 'col3' ],
57 remote_columns => [ 'col5', 'col7' ],
58 remote_moniker => 'AnotherTableMoniker',
61 local_columns => [ 'col1', 'col4' ],
62 remote_columns => [ 'col1', 'col2' ],
63 remote_moniker => 'YetAnotherTableMoniker',
68 This method will return the generated relationships as a hashref keyed on the
69 class names. The values are arrayrefs of hashes containing method name and
73 'Some::Source::Class' => [
74 { method => 'belongs_to', arguments => [ 'col1', 'Another::Source::Class' ],
75 { method => 'has_many', arguments => [ 'anothers', 'Yet::Another::Source::Class', 'col15' ],
77 'Another::Source::Class' => [
85 __PACKAGE__->mk_group_accessors('simple', qw/
96 my ( $class, $base ) = @_;
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.
104 # Options inflect_plural and inflect_singular are optional, and
105 # are better documented in L<DBIx::Class::Schema::Loader::Base>.
109 schema => $base->schema,
110 inflect_plural => $base->inflect_plural,
111 inflect_singular => $base->inflect_singular,
112 relationship_attrs => $base->relationship_attrs,
113 rel_collision_map => $base->rel_collision_map,
117 weaken $self->{base}; #< don't leak
119 bless $self => $class;
121 # validate the relationship_attrs arg
122 if( defined $self->relationship_attrs ) {
123 ref $self->relationship_attrs eq 'HASH'
124 or croak "relationship_attrs must be a hashref";
131 # pluralize a relationship name
132 sub _inflect_plural {
133 my ($self, $relname) = @_;
135 return '' if !defined $relname || $relname eq '';
137 if( ref $self->inflect_plural eq 'HASH' ) {
138 return $self->inflect_plural->{$relname}
139 if exists $self->inflect_plural->{$relname};
141 elsif( ref $self->inflect_plural eq 'CODE' ) {
142 my $inflected = $self->inflect_plural->($relname);
143 return $inflected if $inflected;
146 return $self->_to_PL($relname);
149 # Singularize a relationship name
150 sub _inflect_singular {
151 my ($self, $relname) = @_;
153 return '' if !defined $relname || $relname eq '';
155 if( ref $self->inflect_singular eq 'HASH' ) {
156 return $self->inflect_singular->{$relname}
157 if exists $self->inflect_singular->{$relname};
159 elsif( ref $self->inflect_singular eq 'CODE' ) {
160 my $inflected = $self->inflect_singular->($relname);
161 return $inflected if $inflected;
164 return $self->_to_S($relname);
168 my ($self, $name) = @_;
171 my $plural = Lingua::EN::Inflect::Phrase::to_PL($name);
178 my ($self, $name) = @_;
181 my $singular = Lingua::EN::Inflect::Phrase::to_S($name);
182 $singular =~ s/ /_/g;
187 sub _default_relationship_attrs { +{
197 on_delete => 'CASCADE',
198 on_update => 'CASCADE',
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
206 sub _relationship_attrs {
207 my ( $self, $reltype ) = @_;
208 my $r = $self->relationship_attrs;
211 %{ $self->_default_relationship_attrs->{$reltype} || {} },
215 if( my $specific = $r->{$reltype} ) {
216 while( my ($k,$v) = each %$specific ) {
224 my ($self, $a, $b) = @_;
226 return unless @$a == @$b;
228 for (my $i = 0; $i < @$a; $i++) {
229 return unless $a->[$i] eq $b->[$i];
235 my ($self, $local_moniker, $local_cols) = @_;
237 # get our base set of attrs from _relationship_attrs, if present
238 my $attrs = $self->_relationship_attrs('belongs_to') || {};
240 # If the referring column is nullable, make 'belongs_to' an
241 # outer join, unless explicitly set by relationship_attrs
242 my $nullable = grep { $self->schema->source($local_moniker)->column_info($_)->{is_nullable} } @$local_cols;
243 $attrs->{join_type} = 'LEFT' if $nullable && !defined $attrs->{join_type};
249 my ($self, $name) = @_;
252 # scalar ref for weird table name (like one containing a '.')
253 ($name = $$name) =~ s/\W+/_/g;
256 # remove 'schema.' prefix if any
257 $name =~ s/^[^.]+\.//;
263 sub _normalize_name {
264 my ($self, $name) = @_;
266 $name = $self->_sanitize_name($name);
268 my @words = split_name $name;
270 return join '_', map lc, @words;
273 sub _remote_relname {
274 my ($self, $remote_table, $cond) = @_;
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};
281 $col = $self->_normalize_name($col);
283 $remote_relname = $self->_inflect_singular($col);
286 $remote_relname = $self->_inflect_singular($self->_normalize_name($remote_table));
289 return $remote_relname;
292 sub _resolve_relname_collision {
293 my ($self, $moniker, $cols, $relname) = @_;
295 return $relname if $relname eq 'id'; # this shouldn't happen, but just in case
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;
306 my $new_relname = $relname;
307 while ($self->base->_is_result_class_method($new_relname)) {
308 $new_relname .= '_rel'
312 Relationship '$relname' in source '$moniker' for columns '@{[ join ',', @$cols ]}' collides with an inherited method.
313 Renaming to '$new_relname'.
314 See "RELATIONSHIP NAME COLLISIONS" in perldoc DBIx::Class::Schema::Loader::Base .
324 my ($self, $local_moniker, $rels, $uniqs) = @_;
328 my $local_class = $self->schema->class($local_moniker);
331 foreach my $rel (@$rels) {
332 next if !$rel->{remote_source};
333 $counters{$rel->{remote_source}}++;
336 foreach my $rel (@$rels) {
337 my $remote_moniker = $rel->{remote_source}
340 my $remote_class = $self->schema->class($remote_moniker);
341 my $remote_obj = $self->schema->source($remote_moniker);
342 my $remote_cols = $rel->{remote_columns} || [ $remote_obj->primary_columns ];
344 my $local_cols = $rel->{local_columns};
346 if($#$local_cols != $#$remote_cols) {
347 croak "Column count mismatch: $local_moniker (@$local_cols) "
348 . "$remote_moniker (@$remote_cols)";
352 foreach my $i (0 .. $#$local_cols) {
353 $cond{$remote_cols->[$i]} = $local_cols->[$i];
356 my ( $local_relname, $remote_relname, $remote_method ) =
357 $self->_relnames_and_method( $local_moniker, $rel, \%cond, $uniqs, \%counters );
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);
362 push(@{$all_code->{$local_class}},
363 { method => 'belongs_to',
364 args => [ $remote_relname,
367 $self->_remote_attrs($local_moniker, $local_cols),
372 my %rev_cond = reverse %cond;
373 for (keys %rev_cond) {
374 $rev_cond{"foreign.$_"} = "self.".$rev_cond{$_};
375 delete $rev_cond{$_};
378 push(@{$all_code->{$remote_class}},
379 { method => $remote_method,
380 args => [ $local_relname,
383 $self->_relationship_attrs($remote_method),
392 sub _relnames_and_method {
393 my ( $self, $local_moniker, $rel, $cond, $uniqs, $counters ) = @_;
395 my $remote_moniker = $rel->{remote_source};
396 my $remote_obj = $self->schema->source( $remote_moniker );
397 my $remote_class = $self->schema->class( $remote_moniker );
398 my $remote_relname = $self->_remote_relname( $remote_obj->from, $cond);
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);
405 my $local_relname_uninflected = $self->_normalize_name($local_table);
406 my $local_relname = $self->_inflect_plural($self->_normalize_name($local_table));
408 my $remote_method = 'has_many';
410 # If the local columns have a UNIQUE constraint, this is a one-to-one rel
411 if ($self->_array_eq([ $local_source->primary_columns ], $local_cols) ||
412 grep { $self->_array_eq($_->[1], $local_cols) } @$uniqs) {
413 $remote_method = 'might_have';
414 $local_relname = $self->_inflect_singular($local_relname_uninflected);
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;
422 if (-f (my $existing_remote_file = $self->base->get_dump_filename($remote_class))) {
423 my $class = "${remote_class}Temporary";
425 if (not Class::Inspector->loaded($class)) {
426 my $code = slurp $existing_remote_file;
428 $code =~ s/(?<=package $remote_class)/Temporary/g;
430 $code =~ s/__PACKAGE__->meta->make_immutable[^;]*;//g;
435 push @{ $self->_temp_classes }, $class;
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} }) ];
442 $relationship_exists = 1 if $self->_array_eq([ sort @$local_cols ], $rel_cols);
446 if (not $relationship_exists) {
447 my $colnames = q{_} . $self->_normalize_name(join '_', @$local_cols);
448 $remote_relname .= $colnames if keys %$cond > 1;
450 $local_relname = $self->_normalize_name($local_table . $colnames);
451 $local_relname =~ s/_id$//;
453 $local_relname_uninflected = $local_relname;
454 $local_relname = $self->_inflect_plural($local_relname);
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);
463 return ( $local_relname, $remote_relname, $remote_method );
469 for my $class (@{ $self->_temp_classes }) {
470 Class::Unload->unload($class);
473 $self->_temp_classes([]);
478 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
482 This library is free software; you can redistribute it and/or modify it under
483 the same terms as Perl itself.
488 # vim:et sts=4 sw=4 tw=0: