Merge 'trunk' into 'sybase'
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / HasOne.pm
CommitLineData
c0e7b4e5 1package # hide from PAUSE
2 DBIx::Class::Relationship::HasOne;
22b15c96 3
4use strict;
5use warnings;
6
044e70c7 7our %_pod_inherit_config =
8 (
9 class_map => { 'DBIx::Class::Relationship::HasOne' => 'DBIx::Class::Relationship' }
10 );
11
07037f89 12sub might_have {
13 shift->_has_one('LEFT' => @_);
14}
15
22b15c96 16sub has_one {
e5d98edd 17 shift->_has_one(undef() => @_);
07037f89 18}
19
20sub _has_one {
503536d5 21 my ($class, $join_type, $rel, $f_class, $cond, $attrs) = @_;
99be059e 22 unless (ref $cond) {
fd4df975 23 $class->ensure_class_loaded($f_class);
103647d5 24 my ($pri, $too_many) = $class->primary_columns;
e36de82e 25
fd4df975 26 $class->throw_exception(
27 "might_have/has_one can only infer join for a single primary key; ".
28 "${class} has more"
29 ) if $too_many;
e36de82e 30
31 $class->throw_exception(
32 "might_have/has_one needs a primary key to infer a join; ".
33 "${class} has none"
34 ) if !defined $pri && (!defined $cond || !length $cond);
35
103647d5 36 my $f_class_loaded = eval { $f_class->columns };
8e04bf91 37 my ($f_key,$guess);
dcf8330b 38 if (defined $cond && length $cond) {
99be059e 39 $f_key = $cond;
dcf8330b 40 $guess = "caller specified foreign key '$f_key'";
103647d5 41 } elsif ($f_class_loaded && $f_class->has_column($rel)) {
07037f89 42 $f_key = $rel;
dcf8330b 43 $guess = "using given relationship '$rel' for foreign key";
07037f89 44 } else {
103647d5 45 ($f_key, $too_many) = $f_class->primary_columns;
fd4df975 46 $class->throw_exception(
47 "might_have/has_one can only infer join for a single primary key; ".
48 "${f_class} has more"
49 ) if $too_many;
dcf8330b 50 $guess = "using primary key of foreign class for foreign key";
22b15c96 51 }
fd4df975 52 $class->throw_exception(
53 "No such column ${f_key} on foreign class ${f_class} ($guess)"
54 ) if $f_class_loaded && !$f_class->has_column($f_key);
503536d5 55 $cond = { "foreign.${f_key}" => "self.${pri}" };
07037f89 56 }
07037f89 57 $class->add_relationship($rel, $f_class,
58 $cond,
503536d5 59 { accessor => 'single',
07037f89 60 cascade_update => 1, cascade_delete => 1,
61 ($join_type ? ('join_type' => $join_type) : ()),
503536d5 62 %{$attrs || {}} });
07037f89 63 1;
22b15c96 64}
65
661;