added ensure_class_loaded method to Componentized, which should fix problems with...
[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   $class->ensure_class_loaded($f_class);
18   unless (ref $cond) {
19     my ($pri, $too_many) = $class->primary_columns;
20     $class->throw_exception( "might_have/has_one can only infer join for a single primary key; ${class} has more" )
21       if $too_many;
22     my $f_class_loaded = eval { $f_class->columns };
23     my ($f_key,$guess);
24     if (defined $cond && length $cond) {
25       $f_key = $cond;
26       $guess = "caller specified foreign key '$f_key'";
27     } elsif ($f_class_loaded && $f_class->has_column($rel)) {
28       $f_key = $rel;
29       $guess = "using given relationship '$rel' for foreign key";
30     } else {
31       ($f_key, $too_many) = $f_class->primary_columns;
32       $class->throw_exception( "might_have/has_one can only infer join for a single primary key; ${f_class} has more" )
33         if $too_many;
34       $guess = "using primary key of foreign class for foreign key";
35     }
36     $class->throw_exception("No such column ${f_key} on foreign class ${f_class} ($guess)")
37       if $f_class_loaded && !$f_class->has_column($f_key);
38     $cond = { "foreign.${f_key}" => "self.${pri}" };
39   }
40   $class->add_relationship($rel, $f_class,
41    $cond,
42    { accessor => 'single',
43      cascade_update => 1, cascade_delete => 1,
44      ($join_type ? ('join_type' => $join_type) : ()),
45      %{$attrs || {}} });
46   1;
47 }
48
49 1;