Re-fixed HasOne (how tf did we lose that ...)
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / HasOne.pm
CommitLineData
22b15c96 1package DBIx::Class::Relationship::HasOne;
2
3use strict;
4use warnings;
5
07037f89 6sub might_have {
7 shift->_has_one('LEFT' => @_);
8}
9
22b15c96 10sub has_one {
e5d98edd 11 shift->_has_one(undef() => @_);
07037f89 12}
13
14sub _has_one {
503536d5 15 my ($class, $join_type, $rel, $f_class, $cond, $attrs) = @_;
36e58b24 16 eval "require $f_class";
55de06f1 17 if ($@) {
18 $class->throw($@) unless $@ =~ /Can't locate/;
19 }
20
99be059e 21 unless (ref $cond) {
103647d5 22 my ($pri, $too_many) = $class->primary_columns;
07037f89 23 $class->throw( "might_have/has_one can only infer join for a single primary key; ${class} has more" )
24 if $too_many;
25 my $f_key;
103647d5 26 my $f_class_loaded = eval { $f_class->columns };
dcf8330b 27 my $guess;
28 if (defined $cond && length $cond) {
99be059e 29 $f_key = $cond;
dcf8330b 30 $guess = "caller specified foreign key '$f_key'";
103647d5 31 } elsif ($f_class_loaded && $f_class->has_column($rel)) {
07037f89 32 $f_key = $rel;
dcf8330b 33 $guess = "using given relationship '$rel' for foreign key";
07037f89 34 } else {
103647d5 35 ($f_key, $too_many) = $f_class->primary_columns;
07037f89 36 $class->throw( "might_have/has_one can only infer join for a single primary key; ${f_class} has more" )
37 if $too_many;
dcf8330b 38 $guess = "using primary key of foreign class for foreign key";
22b15c96 39 }
dcf8330b 40 $class->throw("No such column ${f_key} on foreign class ${f_class} ($guess)")
103647d5 41 if $f_class_loaded && !$f_class->has_column($f_key);
503536d5 42 $cond = { "foreign.${f_key}" => "self.${pri}" };
07037f89 43 }
07037f89 44 $class->add_relationship($rel, $f_class,
45 $cond,
503536d5 46 { accessor => 'single',
07037f89 47 cascade_update => 1, cascade_delete => 1,
48 ($join_type ? ('join_type' => $join_type) : ()),
503536d5 49 %{$attrs || {}} });
07037f89 50 1;
22b15c96 51}
52
531;