changed relationship helpers to only call ensure_class_loaded when the join cond...
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / HasOne.pm
1 package # hide from PAUSE
2     DBIx::Class::Relationship::HasOne;
3
4 use strict;
5 use warnings;
6
7 sub might_have {
8   shift->_has_one('LEFT' => @_);
9 }
10
11 sub has_one {
12   shift->_has_one(undef() => @_);
13 }
14
15 sub _has_one {
16   my ($class, $join_type, $rel, $f_class, $cond, $attrs) = @_;
17   unless (ref $cond) {
18     $class->ensure_class_loaded($f_class);
19     my ($pri, $too_many) = $class->primary_columns;
20     $class->throw_exception(
21       "might_have/has_one can only infer join for a single primary key; ".
22       "${class} has more"
23     ) if $too_many;
24     my $f_class_loaded = eval { $f_class->columns };
25     my ($f_key,$guess);
26     if (defined $cond && length $cond) {
27       $f_key = $cond;
28       $guess = "caller specified foreign key '$f_key'";
29     } elsif ($f_class_loaded && $f_class->has_column($rel)) {
30       $f_key = $rel;
31       $guess = "using given relationship '$rel' for foreign key";
32     } else {
33       ($f_key, $too_many) = $f_class->primary_columns;
34       $class->throw_exception(
35         "might_have/has_one can only infer join for a single primary key; ".
36         "${f_class} has more"
37       ) if $too_many;
38       $guess = "using primary key of foreign class for foreign key";
39     }
40     $class->throw_exception(
41       "No such column ${f_key} on foreign class ${f_class} ($guess)"
42     ) if $f_class_loaded && !$f_class->has_column($f_key);
43     $cond = { "foreign.${f_key}" => "self.${pri}" };
44   }
45   $class->add_relationship($rel, $f_class,
46    $cond,
47    { accessor => 'single',
48      cascade_update => 1, cascade_delete => 1,
49      ($join_type ? ('join_type' => $join_type) : ()),
50      %{$attrs || {}} });
51   1;
52 }
53
54 1;