Consolidate single-pk checks from relationship inferrence codepaths
[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 use DBIx::Class::Carp;
7 use Try::Tiny;
8 use namespace::clean;
9
10 our %_pod_inherit_config =
11   (
12    class_map => { 'DBIx::Class::Relationship::HasOne' => 'DBIx::Class::Relationship' }
13   );
14
15 sub might_have {
16   shift->_has_one('LEFT' => @_);
17 }
18
19 sub has_one {
20   shift->_has_one(undef() => @_);
21 }
22
23 sub _has_one {
24   my ($class, $join_type, $rel, $f_class, $cond, $attrs) = @_;
25   unless (ref $cond) {
26     $class->ensure_class_loaded($f_class);
27
28     my $pri = $class->result_source_instance->_single_pri_col_or_die;
29
30     my $f_class_loaded = try { $f_class->columns };
31     my ($f_key,$guess);
32     if (defined $cond && length $cond) {
33       $f_key = $cond;
34       $guess = "caller specified foreign key '$f_key'";
35     } elsif ($f_class_loaded && $f_class->has_column($rel)) {
36       $f_key = $rel;
37       $guess = "using given relationship name '$rel' as foreign key column name";
38     } elsif ($f_class_loaded and my $f_pri = try {
39       $f_class->result_source_instance->_single_pri_col_or_die
40     }) {
41       $f_key = $f_pri;
42       $guess = "using primary key of foreign class for foreign key";
43     }
44
45     $class->throw_exception(
46       "No such column '$f_key' on foreign class ${f_class} ($guess)"
47     ) if $f_class_loaded && !$f_class->has_column($f_key);
48
49     $cond = { "foreign.${f_key}" => "self.${pri}" };
50   }
51   $class->_validate_has_one_condition($cond);
52
53   my $default_cascade = ref $cond eq 'CODE' ? 0 : 1;
54
55   $class->add_relationship($rel, $f_class,
56    $cond,
57    { accessor => 'single',
58      cascade_update => $default_cascade,
59      cascade_delete => $default_cascade,
60      ($join_type ? ('join_type' => $join_type) : ()),
61      %{$attrs || {}} });
62   1;
63 }
64
65 sub _validate_has_one_condition {
66   my ($class, $cond )  = @_;
67
68   return if $ENV{DBIC_DONT_VALIDATE_RELS};
69   return unless 'HASH' eq ref $cond;
70   foreach my $foreign_id ( keys %$cond ) {
71     my $self_id = $cond->{$foreign_id};
72
73     # we can ignore a bad $self_id because add_relationship handles this
74     # warning
75     return unless $self_id =~ /^self\.(.*)$/;
76     my $key = $1;
77     $class->throw_exception("Defining rel on ${class} that includes '$key' but no such column defined here yet")
78         unless $class->has_column($key);
79     my $column_info = $class->column_info($key);
80     if ( $column_info->{is_nullable} ) {
81       carp(qq'"might_have/has_one" must not be on columns with is_nullable set to true ($class/$key). This might indicate an incorrect use of those relationship helpers instead of belongs_to.');
82     }
83   }
84 }
85
86 1;