Bugfixes, optimisations
[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 {
07037f89 11 shift->_has_one(undef => @_);
12}
13
14sub _has_one {
503536d5 15 my ($class, $join_type, $rel, $f_class, $cond, $attrs) = @_;
36e58b24 16 eval "require $f_class";
99be059e 17 unless (ref $cond) {
07037f89 18 my ($pri, $too_many) = keys %{ $class->_primaries };
19 $class->throw( "might_have/has_one can only infer join for a single primary key; ${class} has more" )
20 if $too_many;
21 my $f_key;
dcf8330b 22 my $f_class_loaded = eval { $f_class->_columns };
23 my $guess;
24 if (defined $cond && length $cond) {
99be059e 25 $f_key = $cond;
dcf8330b 26 $guess = "caller specified foreign key '$f_key'";
27 } elsif ($f_class_loaded && $f_class->_columns->{$rel}) {
07037f89 28 $f_key = $rel;
dcf8330b 29 $guess = "using given relationship '$rel' for foreign key";
07037f89 30 } else {
31 ($f_key, $too_many) = keys %{ $f_class->_primaries };
32 $class->throw( "might_have/has_one can only infer join for a single primary key; ${f_class} has more" )
33 if $too_many;
dcf8330b 34 $guess = "using primary key of foreign class for foreign key";
22b15c96 35 }
dcf8330b 36 $class->throw("No such column ${f_key} on foreign class ${f_class} ($guess)")
37 if $f_class_loaded && !exists $f_class->_columns->{$f_key};
503536d5 38 $cond = { "foreign.${f_key}" => "self.${pri}" };
07037f89 39 }
07037f89 40 $class->add_relationship($rel, $f_class,
41 $cond,
503536d5 42 { accessor => 'single',
07037f89 43 cascade_update => 1, cascade_delete => 1,
44 ($join_type ? ('join_type' => $join_type) : ()),
503536d5 45 %{$attrs || {}} });
07037f89 46 1;
22b15c96 47}
48
491;