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 List::MoreUtils 'apply';
17 our $VERSION = '0.07002';
21 # remote_relname -- name of relationship from the local table referring to the remote table
22 # local_relname -- name of relationship from the remote table referring to the local table
23 # remote_method -- relationship type from remote table to local table, usually has_many
27 DBIx::Class::Schema::Loader::RelBuilder - Builds relationships for DBIx::Class::Schema::Loader
31 See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
35 This class builds relationships for L<DBIx::Class::Schema::Loader>. This
36 is module is not (yet) for external use.
42 Arguments: $base object
46 Arguments: local_moniker (scalar), fk_info (arrayref)
48 This generates the code for the relationships of a given table.
50 C<local_moniker> is the moniker name of the table which had the REFERENCES
51 statements. The fk_info arrayref's contents should take the form:
55 local_columns => [ 'col2', 'col3' ],
56 remote_columns => [ 'col5', 'col7' ],
57 remote_moniker => 'AnotherTableMoniker',
60 local_columns => [ 'col1', 'col4' ],
61 remote_columns => [ 'col1', 'col2' ],
62 remote_moniker => 'YetAnotherTableMoniker',
67 This method will return the generated relationships as a hashref keyed on the
68 class names. The values are arrayrefs of hashes containing method name and
72 'Some::Source::Class' => [
73 { method => 'belongs_to', arguments => [ 'col1', 'Another::Source::Class' ],
74 { method => 'has_many', arguments => [ 'anothers', 'Yet::Another::Source::Class', 'col15' ],
76 'Another::Source::Class' => [
84 __PACKAGE__->mk_group_accessors('simple', qw/
94 my ( $class, $base ) = @_;
96 # from old POD about this constructor:
97 # C<$schema_class> should be a schema class name, where the source
98 # classes have already been set up and registered. Column info,
99 # primary key, and unique constraints will be drawn from this
100 # schema for all of the existing source monikers.
102 # Options inflect_plural and inflect_singular are optional, and
103 # are better documented in L<DBIx::Class::Schema::Loader::Base>.
107 schema => $base->schema,
108 inflect_plural => $base->inflect_plural,
109 inflect_singular => $base->inflect_singular,
110 relationship_attrs => $base->relationship_attrs,
114 weaken $self->{base}; #< don't leak
116 bless $self => $class;
118 # validate the relationship_attrs arg
119 if( defined $self->relationship_attrs ) {
120 ref $self->relationship_attrs eq 'HASH'
121 or croak "relationship_attrs must be a hashref";
128 # pluralize a relationship name
129 sub _inflect_plural {
130 my ($self, $relname) = @_;
132 return '' if !defined $relname || $relname eq '';
134 if( ref $self->inflect_plural eq 'HASH' ) {
135 return $self->inflect_plural->{$relname}
136 if exists $self->inflect_plural->{$relname};
138 elsif( ref $self->inflect_plural eq 'CODE' ) {
139 my $inflected = $self->inflect_plural->($relname);
140 return $inflected if $inflected;
143 return $self->_to_PL($relname);
146 # Singularize a relationship name
147 sub _inflect_singular {
148 my ($self, $relname) = @_;
150 return '' if !defined $relname || $relname eq '';
152 if( ref $self->inflect_singular eq 'HASH' ) {
153 return $self->inflect_singular->{$relname}
154 if exists $self->inflect_singular->{$relname};
156 elsif( ref $self->inflect_singular eq 'CODE' ) {
157 my $inflected = $self->inflect_singular->($relname);
158 return $inflected if $inflected;
161 return $self->_to_S($relname);
165 my ($self, $name) = @_;
168 my $plural = Lingua::EN::Inflect::Phrase::to_PL($name);
175 my ($self, $name) = @_;
178 my $singular = Lingua::EN::Inflect::Phrase::to_S($name);
179 $singular =~ s/ /_/g;
184 sub _default_relationship_attrs { +{
194 on_delete => 'CASCADE',
195 on_update => 'CASCADE',
200 # accessor for options to be passed to each generated relationship
201 # type. take single argument, the relationship type name, and returns
202 # either a hashref (if some options are set), or nothing
203 sub _relationship_attrs {
204 my ( $self, $reltype ) = @_;
205 my $r = $self->relationship_attrs;
208 %{ $self->_default_relationship_attrs->{$reltype} || {} },
212 if( my $specific = $r->{$reltype} ) {
213 while( my ($k,$v) = each %$specific ) {
221 my ($self, $a, $b) = @_;
223 return unless @$a == @$b;
225 for (my $i = 0; $i < @$a; $i++) {
226 return unless $a->[$i] eq $b->[$i];
232 my ($self, $local_moniker, $local_cols) = @_;
234 # get our base set of attrs from _relationship_attrs, if present
235 my $attrs = $self->_relationship_attrs('belongs_to') || {};
237 # If the referring column is nullable, make 'belongs_to' an
238 # outer join, unless explicitly set by relationship_attrs
239 my $nullable = grep { $self->schema->source($local_moniker)->column_info($_)->{is_nullable} } @$local_cols;
240 $attrs->{join_type} = 'LEFT' if $nullable && !defined $attrs->{join_type};
246 my ($self, $name) = @_;
249 # scalar ref for weird table name (like one containing a '.')
250 ($name = $$name) =~ s/\W+/_/g;
253 # remove 'schema.' prefix if any
254 $name =~ s/^[^.]+\.//;
260 sub _normalize_name {
261 my ($self, $name) = @_;
263 $name = $self->_sanitize_name($name);
265 my @words = split_name $name;
267 return join '_', map lc, @words;
270 sub _remote_relname {
271 my ($self, $remote_table, $cond) = @_;
274 # for single-column case, set the remote relname to the column
275 # name, to make filter accessors work, but strip trailing _id
276 if(scalar keys %{$cond} == 1) {
277 my ($col) = values %{$cond};
278 $col = $self->_normalize_name($col);
280 $remote_relname = $self->_inflect_singular($col);
283 $remote_relname = $self->_inflect_singular($self->_normalize_name($remote_table));
286 return $remote_relname;
290 my ($self, $local_moniker, $rels, $uniqs) = @_;
294 my $local_class = $self->schema->class($local_moniker);
297 foreach my $rel (@$rels) {
298 next if !$rel->{remote_source};
299 $counters{$rel->{remote_source}}++;
302 foreach my $rel (@$rels) {
303 my $remote_moniker = $rel->{remote_source}
306 my $remote_class = $self->schema->class($remote_moniker);
307 my $remote_obj = $self->schema->source($remote_moniker);
308 my $remote_cols = $rel->{remote_columns} || [ $remote_obj->primary_columns ];
310 my $local_cols = $rel->{local_columns};
312 if($#$local_cols != $#$remote_cols) {
313 croak "Column count mismatch: $local_moniker (@$local_cols) "
314 . "$remote_moniker (@$remote_cols)";
318 foreach my $i (0 .. $#$local_cols) {
319 $cond{$remote_cols->[$i]} = $local_cols->[$i];
322 my ( $local_relname, $remote_relname, $remote_method ) =
323 $self->_relnames_and_method( $local_moniker, $rel, \%cond, $uniqs, \%counters );
325 push(@{$all_code->{$local_class}},
326 { method => 'belongs_to',
327 args => [ $remote_relname,
330 $self->_remote_attrs($local_moniker, $local_cols),
335 my %rev_cond = reverse %cond;
336 for (keys %rev_cond) {
337 $rev_cond{"foreign.$_"} = "self.".$rev_cond{$_};
338 delete $rev_cond{$_};
341 push(@{$all_code->{$remote_class}},
342 { method => $remote_method,
343 args => [ $local_relname,
346 $self->_relationship_attrs($remote_method),
355 sub _relnames_and_method {
356 my ( $self, $local_moniker, $rel, $cond, $uniqs, $counters ) = @_;
358 my $remote_moniker = $rel->{remote_source};
359 my $remote_obj = $self->schema->source( $remote_moniker );
360 my $remote_class = $self->schema->class( $remote_moniker );
361 my $remote_relname = $self->_remote_relname( $remote_obj->from, $cond);
363 my $local_cols = $rel->{local_columns};
364 my $local_table = $self->schema->source($local_moniker)->from;
365 my $local_class = $self->schema->class($local_moniker);
366 my $local_source = $self->schema->source($local_moniker);
368 my $local_relname_uninflected = $self->_normalize_name($local_table);
369 my $local_relname = $self->_inflect_plural($self->_normalize_name($local_table));
371 my $remote_method = 'has_many';
373 # If the local columns have a UNIQUE constraint, this is a one-to-one rel
374 if ($self->_array_eq([ $local_source->primary_columns ], $local_cols) ||
375 grep { $self->_array_eq($_->[1], $local_cols) } @$uniqs) {
376 $remote_method = 'might_have';
377 $local_relname = $self->_inflect_singular($local_relname_uninflected);
380 # If more than one rel between this pair of tables, use the local
381 # col names to distinguish, unless the rel was created previously.
382 if ($counters->{$remote_moniker} > 1) {
383 my $relationship_exists = 0;
385 if (-f (my $existing_remote_file = $self->base->get_dump_filename($remote_class))) {
386 my $class = "${remote_class}Temporary";
388 if (not do { no strict 'refs'; %{$class . '::'} }) {
389 my $code = slurp $existing_remote_file;
391 $code =~ s/(?<=package $remote_class)/Temporary/g;
393 $code =~ s/__PACKAGE__->meta->make_immutable[^;]*;//g;
398 push @{ $self->_temp_classes }, $class;
401 if ($class->has_relationship($local_relname)) {
402 my $rel_cols = [ sort { $a cmp $b } apply { s/^foreign\.//i }
403 (keys %{ $class->relationship_info($local_relname)->{cond} }) ];
405 $relationship_exists = 1 if $self->_array_eq([ sort @$local_cols ], $rel_cols);
409 if (not $relationship_exists) {
410 my $colnames = q{_} . $self->_normalize_name(join '_', @$local_cols);
411 $remote_relname .= $colnames if keys %$cond > 1;
413 $local_relname = $self->_normalize_name($local_table . $colnames);
414 $local_relname =~ s/_id$//;
416 $local_relname_uninflected = $local_relname;
417 $local_relname = $self->_inflect_plural($local_relname);
419 # if colnames were added and this is a might_have, re-inflect
420 if ($remote_method eq 'might_have') {
421 $local_relname = $self->_inflect_singular($local_relname_uninflected);
426 return ( $local_relname, $remote_relname, $remote_method );
432 for my $class (@{ $self->_temp_classes }) {
433 Class::Unload->unload($class);
436 $self->_temp_classes([]);
441 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
445 This library is free software; you can redistribute it and/or modify it under
446 the same terms as Perl itself.
451 # vim:et sts=4 sw=4 tw=0: