Added Pod::Inherit use to Makefile.PL at author-time, comments/suggestions as to...
[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 our %_pod_inherit_config = 
8   (
9    class_map => { 'DBIx::Class::Relationship::HasOne' => 'DBIx::Class::Relationship' }
10   );
11
12 sub might_have {
13   shift->_has_one('LEFT' => @_);
14 }
15
16 sub has_one {
17   shift->_has_one(undef() => @_);
18 }
19
20 sub _has_one {
21   my ($class, $join_type, $rel, $f_class, $cond, $attrs) = @_;
22   unless (ref $cond) {
23     $class->ensure_class_loaded($f_class);
24     my ($pri, $too_many) = $class->primary_columns;
25
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;
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
36     my $f_class_loaded = eval { $f_class->columns };
37     my ($f_key,$guess);
38     if (defined $cond && length $cond) {
39       $f_key = $cond;
40       $guess = "caller specified foreign key '$f_key'";
41     } elsif ($f_class_loaded && $f_class->has_column($rel)) {
42       $f_key = $rel;
43       $guess = "using given relationship '$rel' for foreign key";
44     } else {
45       ($f_key, $too_many) = $f_class->primary_columns;
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;
50       $guess = "using primary key of foreign class for foreign key";
51     }
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);
55     $cond = { "foreign.${f_key}" => "self.${pri}" };
56   }
57   $class->add_relationship($rel, $f_class,
58    $cond,
59    { accessor => 'single',
60      cascade_update => 1, cascade_delete => 1,
61      ($join_type ? ('join_type' => $join_type) : ()),
62      %{$attrs || {}} });
63   1;
64 }
65
66 1;