All expected evals converted to try, except where no test is done,
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / BelongsTo.pm
CommitLineData
9b83fccd 1package # hide from PAUSE
2 DBIx::Class::Relationship::BelongsTo;
3
4# Documentation for these methods can be found in
5# DBIx::Class::Relationship
07037f89 6
7use strict;
8use warnings;
ed7ab0f4 9use Try::Tiny;
07037f89 10
044e70c7 11our %_pod_inherit_config =
12 (
13 class_map => { 'DBIx::Class::Relationship::BelongsTo' => 'DBIx::Class::Relationship' }
14 );
15
07037f89 16sub belongs_to {
17 my ($class, $rel, $f_class, $cond, $attrs) = @_;
6bf6ba2f 18
19 # assume a foreign key contraint unless defined otherwise
20 $attrs->{is_foreign_key_constraint} = 1
21 if not exists $attrs->{is_foreign_key_constraint};
cef1bdda 22 $attrs->{undef_on_null_fk} = 1
23 if not exists $attrs->{undef_on_null_fk};
6bf6ba2f 24
aeb1bf75 25 # no join condition or just a column name
7b601771 26 if (!ref $cond) {
fd4df975 27 $class->ensure_class_loaded($f_class);
ed7ab0f4 28 my %f_primaries = map { $_ => 1 } try { $f_class->_pri_cols }
29 catch {
30 $class->throw_exception( "Can't infer join condition for ${rel} on ${class}: $_");
31 };
1e3bc087 32
33 my ($pri, $too_many) = keys %f_primaries;
fd4df975 34 $class->throw_exception(
35 "Can't infer join condition for ${rel} on ${class}; ".
fd4df975 36 "${f_class} has multiple primary keys"
37 ) if $too_many;
1e3bc087 38
39 my $fk = defined $cond ? $cond : $rel;
fd4df975 40 $class->throw_exception(
41 "Can't infer join condition for ${rel} on ${class}; ".
42 "$fk is not a column of $class"
43 ) unless $class->has_column($fk);
1e3bc087 44
45 my $acc_type = $class->has_column($rel) ? 'filter' : 'single';
07037f89 46 $class->add_relationship($rel, $f_class,
1e3bc087 47 { "foreign.${pri}" => "self.${fk}" },
5a3c5f64 48 { accessor => $acc_type, %{$attrs || {}} }
07037f89 49 );
50 }
aeb1bf75 51 # explicit join condition
4ff1b819 52 elsif (ref $cond) {
53 if (ref $cond eq 'HASH') { # ARRAY is also valid
54 my $cond_rel;
55 for (keys %$cond) {
56 if (m/\./) { # Explicit join condition
57 $cond_rel = $cond;
58 last;
59 }
60 $cond_rel->{"foreign.$_"} = "self.".$cond->{$_};
99be059e 61 }
4ff1b819 62 $cond = $cond_rel;
07037f89 63 }
4ff1b819 64 my $acc_type = ((ref $cond eq 'HASH')
65 && keys %$cond == 1
66 && $class->has_column($rel))
67 ? 'filter'
68 : 'single';
07037f89 69 $class->add_relationship($rel, $f_class,
4ff1b819 70 $cond,
0cc03829 71 { accessor => $acc_type, %{$attrs || {}} }
07037f89 72 );
73 }
7b601771 74 else {
fd4df975 75 $class->throw_exception(
76 'third argument for belongs_to must be undef, a column name, '.
77 'or a join condition'
78 );
7b601771 79 }
07037f89 80 return 1;
81}
82
e09b8a14 83# Attempt to remove the POD so it (maybe) falls off the indexer
503536d5 84
e09b8a14 85#=head1 AUTHORS
86#
87#Alexander Hartmaier <Alexander.Hartmaier@t-systems.at>
88#
89#Matt S. Trout <mst@shadowcatsystems.co.uk>
90#
91#=cut
503536d5 92
07037f89 931;