07f89c2953fa9490b227951d754162f1549db68f
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / ManyToMany.pm
1 package # hide from PAUSE
2     DBIx::Class::Relationship::ManyToMany;
3
4 use strict;
5 use warnings;
6
7 use DBIx::Class::Carp;
8 use Sub::Name 'subname';
9 use Scalar::Util 'blessed';
10 use DBIx::Class::_Util 'fail_on_internal_wantarray';
11 use namespace::clean;
12
13 our %_pod_inherit_config =
14   (
15    class_map => { 'DBIx::Class::Relationship::ManyToMany' => 'DBIx::Class::Relationship' }
16   );
17
18 sub many_to_many {
19   my ($class, $meth, $rel, $f_rel, $rel_attrs) = @_;
20
21   $class->throw_exception(
22     "missing relation in many-to-many"
23   ) unless $rel;
24
25   $class->throw_exception(
26     "missing foreign relation in many-to-many"
27   ) unless $f_rel;
28
29   {
30     no strict 'refs';
31     no warnings 'redefine';
32
33     my $add_meth = "add_to_${meth}";
34     my $remove_meth = "remove_from_${meth}";
35     my $set_meth = "set_${meth}";
36     my $rs_meth = "${meth}_rs";
37
38     for ($add_meth, $remove_meth, $set_meth, $rs_meth) {
39       if ( $class->can ($_) ) {
40         carp (<<"EOW") unless $ENV{DBIC_OVERWRITE_HELPER_METHODS_OK};
41
42 ***************************************************************************
43 The many-to-many relationship '$meth' is trying to create a utility method
44 called $_.
45 This will completely overwrite one such already existing method on class
46 $class.
47
48 You almost certainly want to rename your method or the many-to-many
49 relationship, as the functionality of the original method will not be
50 accessible anymore.
51
52 To disable this warning set to a true value the environment variable
53 DBIC_OVERWRITE_HELPER_METHODS_OK
54
55 ***************************************************************************
56 EOW
57       }
58     }
59
60     $rel_attrs->{alias} ||= $f_rel;
61
62     my $rs_meth_name = join '::', $class, $rs_meth;
63     *$rs_meth_name = subname $rs_meth_name, sub {
64       my $self = shift;
65       my $attrs = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
66       my @args = ($f_rel, @_ > 0 ? @_ : undef, { %{$rel_attrs||{}}, %$attrs });
67       my $rs = $self->search_related($rel)->search_related(
68         $f_rel, @_ > 0 ? @_ : undef, { %{$rel_attrs||{}}, %$attrs }
69       );
70       return $rs;
71     };
72
73     my $meth_name = join '::', $class, $meth;
74     *$meth_name = subname $meth_name, sub {
75       DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_WANTARRAY and wantarray and my $sog = fail_on_internal_wantarray($_[0]);
76       my $self = shift;
77       my $rs = $self->$rs_meth( @_ );
78       return (wantarray ? $rs->all : $rs);
79     };
80
81     my $add_meth_name = join '::', $class, $add_meth;
82     *$add_meth_name = subname $add_meth_name, sub {
83       my $self = shift;
84       @_ > 0 or $self->throw_exception(
85         "${add_meth} needs an object or hashref"
86       );
87       my $source = $self->result_source;
88       my $schema = $source->schema;
89       my $rel_source_name = $source->relationship_info($rel)->{source};
90       my $rel_source = $schema->resultset($rel_source_name)->result_source;
91       my $f_rel_source_name = $rel_source->relationship_info($f_rel)->{source};
92       my $f_rel_rs = $schema->resultset($f_rel_source_name)->search({}, $rel_attrs||{});
93
94       my $obj;
95       if (ref $_[0]) {
96         if (ref $_[0] eq 'HASH') {
97           $obj = $f_rel_rs->find_or_create($_[0]);
98         } else {
99           $obj = $_[0];
100         }
101       } else {
102         $obj = $f_rel_rs->find_or_create({@_});
103       }
104
105       my $link_vals = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
106       my $link = $self->search_related($rel)->new_result($link_vals);
107       $link->set_from_related($f_rel, $obj);
108       $link->insert();
109       return $obj;
110     };
111
112     my $set_meth_name = join '::', $class, $set_meth;
113     *$set_meth_name = subname $set_meth_name, sub {
114       my $self = shift;
115       @_ > 0 or $self->throw_exception(
116         "{$set_meth} needs a list of objects or hashrefs"
117       );
118       my @to_set = (ref($_[0]) eq 'ARRAY' ? @{ $_[0] } : @_);
119       # if there is a where clause in the attributes, ensure we only delete
120       # rows that are within the where restriction
121       if ($rel_attrs && $rel_attrs->{where}) {
122         $self->search_related( $rel, $rel_attrs->{where},{join => $f_rel})->delete;
123       } else {
124         $self->search_related( $rel, {} )->delete;
125       }
126       # add in the set rel objects
127       $self->$add_meth($_, ref($_[1]) ? $_[1] : {}) for (@to_set);
128     };
129
130     my $remove_meth_name = join '::', $class, $remove_meth;
131     *$remove_meth_name = subname $remove_meth_name, sub {
132       my ($self, $obj) = @_;
133       $self->throw_exception("${remove_meth} needs an object")
134         unless blessed ($obj);
135       my $rel_source = $self->search_related($rel)->result_source;
136       my $cond = $rel_source->relationship_info($f_rel)->{cond};
137       my ($link_cond, $crosstable) = $rel_source->_resolve_condition(
138         $cond, $obj, $f_rel, $f_rel
139       );
140
141       $self->throw_exception(
142         "Custom relationship '$rel' does not resolve to a join-free condition, "
143        ."unable to use with the ManyToMany helper '$f_rel'"
144       ) if $crosstable;
145
146       $self->search_related($rel, $link_cond)->delete;
147     };
148
149   }
150 }
151
152 1;