0.05999_01 shipped
[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 ($@) {
701da8c4 18 $class->throw_exception($@) unless $@ =~ /Can't locate/;
55de06f1 19 }
20
99be059e 21 unless (ref $cond) {
103647d5 22 my ($pri, $too_many) = $class->primary_columns;
701da8c4 23 $class->throw_exception( "might_have/has_one can only infer join for a single primary key; ${class} has more" )
07037f89 24 if $too_many;
103647d5 25 my $f_class_loaded = eval { $f_class->columns };
8e04bf91 26 my ($f_key,$guess);
dcf8330b 27 if (defined $cond && length $cond) {
99be059e 28 $f_key = $cond;
dcf8330b 29 $guess = "caller specified foreign key '$f_key'";
103647d5 30 } elsif ($f_class_loaded && $f_class->has_column($rel)) {
07037f89 31 $f_key = $rel;
dcf8330b 32 $guess = "using given relationship '$rel' for foreign key";
07037f89 33 } else {
103647d5 34 ($f_key, $too_many) = $f_class->primary_columns;
701da8c4 35 $class->throw_exception( "might_have/has_one can only infer join for a single primary key; ${f_class} has more" )
07037f89 36 if $too_many;
dcf8330b 37 $guess = "using primary key of foreign class for foreign key";
22b15c96 38 }
701da8c4 39 $class->throw_exception("No such column ${f_key} on foreign class ${f_class} ($guess)")
103647d5 40 if $f_class_loaded && !$f_class->has_column($f_key);
503536d5 41 $cond = { "foreign.${f_key}" => "self.${pri}" };
07037f89 42 }
07037f89 43 $class->add_relationship($rel, $f_class,
44 $cond,
503536d5 45 { accessor => 'single',
07037f89 46 cascade_update => 1, cascade_delete => 1,
47 ($join_type ? ('join_type' => $join_type) : ()),
503536d5 48 %{$attrs || {}} });
07037f89 49 1;
22b15c96 50}
51
521;