All expected evals converted to try, except where no test is done,
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / HasMany.pm
1 package # hide from PAUSE
2     DBIx::Class::Relationship::HasMany;
3
4 use strict;
5 use warnings;
6 use Try::Tiny;
7
8 our %_pod_inherit_config = 
9   (
10    class_map => { 'DBIx::Class::Relationship::HasMany' => 'DBIx::Class::Relationship' }
11   );
12
13 sub has_many {
14   my ($class, $rel, $f_class, $cond, $attrs) = @_;
15
16   unless (ref $cond) {
17     $class->ensure_class_loaded($f_class);
18     my ($pri, $too_many) = try { $class->_pri_cols } 
19       catch {
20         $class->throw_exception("Can't infer join condition for ${rel} on ${class}: $_");
21       };
22
23     $class->throw_exception(
24       "has_many can only infer join for a single primary key; ".
25       "${class} has more"
26     ) if $too_many;
27
28     $class->throw_exception(
29       "has_many needs a primary key to infer a join; ".
30       "${class} has none"
31     ) if !defined $pri && (!defined $cond || !length $cond);
32
33     my ($f_key,$guess);
34     if (defined $cond && length $cond) {
35       $f_key = $cond;
36       $guess = "caller specified foreign key '$f_key'";
37     } else {
38       $class =~ /([^\:]+)$/;
39       $f_key = lc $1; # go ahead and guess; best we can do
40       $guess = "using our class name '$class' as foreign key";
41     }
42
43     my $f_class_loaded = eval { $f_class->columns };
44     $class->throw_exception(
45       "No such column ${f_key} on foreign class ${f_class} ($guess)"
46     ) if $f_class_loaded && !$f_class->has_column($f_key);
47
48     $cond = { "foreign.${f_key}" => "self.${pri}" };
49   }
50
51   $class->add_relationship($rel, $f_class, $cond, {
52     accessor => 'multi',
53     join_type => 'LEFT',
54     cascade_delete => 1,
55     cascade_copy => 1,
56     %{$attrs||{}}
57   });
58 }
59
60 1;