use namespace::clean w/ Try::Tiny
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / Base.pm
1 package DBIx::Class::Relationship::Base;
2
3 use strict;
4 use warnings;
5
6 use Scalar::Util ();
7 use base qw/DBIx::Class/;
8 use Try::Tiny;
9 use namespace::clean;
10
11 =head1 NAME
12
13 DBIx::Class::Relationship::Base - Inter-table relationships
14
15 =head1 SYNOPSIS
16
17 =head1 DESCRIPTION
18
19 This class provides methods to describe the relationships between the
20 tables in your database model. These are the "bare bones" relationships
21 methods, for predefined ones, look in L<DBIx::Class::Relationship>.
22
23 =head1 METHODS
24
25 =head2 add_relationship
26
27 =over 4
28
29 =item Arguments: 'relname', 'Foreign::Class', $cond, $attrs
30
31 =back
32
33   __PACKAGE__->add_relationship('relname', 'Foreign::Class', $cond, $attrs);
34
35 =head3 condition
36
37 The condition needs to be an L<SQL::Abstract>-style representation of the
38 join between the tables. When resolving the condition for use in a C<JOIN>,
39 keys using the pseudo-table C<foreign> are resolved to mean "the Table on the
40 other side of the relationship", and values using the pseudo-table C<self>
41 are resolved to mean "the Table this class is representing". Other
42 restrictions, such as by value, sub-select and other tables, may also be
43 used. Please check your database for C<JOIN> parameter support.
44
45 For example, if you're creating a relationship from C<Author> to C<Book>, where
46 the C<Book> table has a column C<author_id> containing the ID of the C<Author>
47 row:
48
49   { 'foreign.author_id' => 'self.id' }
50
51 will result in the C<JOIN> clause
52
53   author me JOIN book book ON book.author_id = me.id
54
55 For multi-column foreign keys, you will need to specify a C<foreign>-to-C<self>
56 mapping for each column in the key. For example, if you're creating a
57 relationship from C<Book> to C<Edition>, where the C<Edition> table refers to a
58 publisher and a type (e.g. "paperback"):
59
60   {
61     'foreign.publisher_id' => 'self.publisher_id',
62     'foreign.type_id'      => 'self.type_id',
63   }
64
65 This will result in the C<JOIN> clause:
66
67   book me JOIN edition edition ON edition.publisher_id = me.publisher_id
68     AND edition.type_id = me.type_id
69
70 Each key-value pair provided in a hashref will be used as C<AND>ed conditions.
71 To add an C<OR>ed condition, use an arrayref of hashrefs. See the
72 L<SQL::Abstract> documentation for more details.
73
74 =head3 attributes
75
76 The L<standard ResultSet attributes|DBIx::Class::ResultSet/ATTRIBUTES> may
77 be used as relationship attributes. In particular, the 'where' attribute is
78 useful for filtering relationships:
79
80      __PACKAGE__->has_many( 'valid_users', 'MyApp::Schema::User',
81         { 'foreign.user_id' => 'self.user_id' },
82         { where => { valid => 1 } }
83     );
84
85 The following attributes are also valid:
86
87 =over 4
88
89 =item join_type
90
91 Explicitly specifies the type of join to use in the relationship. Any SQL
92 join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in the SQL
93 command immediately before C<JOIN>.
94
95 =item proxy
96
97 An arrayref containing a list of accessors in the foreign class to create in
98 the main class. If, for example, you do the following:
99
100   MyDB::Schema::CD->might_have(liner_notes => 'MyDB::Schema::LinerNotes',
101     undef, {
102       proxy => [ qw/notes/ ],
103     });
104
105 Then, assuming MyDB::Schema::LinerNotes has an accessor named notes, you can do:
106
107   my $cd = MyDB::Schema::CD->find(1);
108   $cd->notes('Notes go here'); # set notes -- LinerNotes object is
109                                # created if it doesn't exist
110
111 =item accessor
112
113 Specifies the type of accessor that should be created for the relationship.
114 Valid values are C<single> (for when there is only a single related object),
115 C<multi> (when there can be many), and C<filter> (for when there is a single
116 related object, but you also want the relationship accessor to double as
117 a column accessor). For C<multi> accessors, an add_to_* method is also
118 created, which calls C<create_related> for the relationship.
119
120 =item is_foreign_key_constraint
121
122 If you are using L<SQL::Translator> to create SQL for you and you find that it
123 is creating constraints where it shouldn't, or not creating them where it
124 should, set this attribute to a true or false value to override the detection
125 of when to create constraints.
126
127 =item cascade_copy
128
129 If C<cascade_copy> is true on a C<has_many> relationship for an
130 object, then when you copy the object all the related objects will
131 be copied too. To turn this behaviour off, pass C<< cascade_copy => 0 >>
132 in the C<$attr> hashref.
133
134 The behaviour defaults to C<< cascade_copy => 1 >> for C<has_many>
135 relationships.
136
137 =item cascade_delete
138
139 By default, DBIx::Class cascades deletes across C<has_many>,
140 C<has_one> and C<might_have> relationships. You can disable this
141 behaviour on a per-relationship basis by supplying
142 C<< cascade_delete => 0 >> in the relationship attributes.
143
144 The cascaded operations are performed after the requested delete,
145 so if your database has a constraint on the relationship, it will
146 have deleted/updated the related records or raised an exception
147 before DBIx::Class gets to perform the cascaded operation.
148
149 =item cascade_update
150
151 By default, DBIx::Class cascades updates across C<has_one> and
152 C<might_have> relationships. You can disable this behaviour on a
153 per-relationship basis by supplying C<< cascade_update => 0 >> in
154 the relationship attributes.
155
156 This is not a RDMS style cascade update - it purely means that when
157 an object has update called on it, all the related objects also
158 have update called. It will not change foreign keys automatically -
159 you must arrange to do this yourself.
160
161 =item on_delete / on_update
162
163 If you are using L<SQL::Translator> to create SQL for you, you can use these
164 attributes to explicitly set the desired C<ON DELETE> or C<ON UPDATE> constraint
165 type. If not supplied the SQLT parser will attempt to infer the constraint type by
166 interrogating the attributes of the B<opposite> relationship. For any 'multi'
167 relationship with C<< cascade_delete => 1 >>, the corresponding belongs_to
168 relationship will be created with an C<ON DELETE CASCADE> constraint. For any
169 relationship bearing C<< cascade_copy => 1 >> the resulting belongs_to constraint
170 will be C<ON UPDATE CASCADE>. If you wish to disable this autodetection, and just
171 use the RDBMS' default constraint type, pass C<< on_delete => undef >> or
172 C<< on_delete => '' >>, and the same for C<on_update> respectively.
173
174 =item is_deferrable
175
176 Tells L<SQL::Translator> that the foreign key constraint it creates should be
177 deferrable. In other words, the user may request that the constraint be ignored
178 until the end of the transaction. Currently, only the PostgreSQL producer
179 actually supports this.
180
181 =item add_fk_index
182
183 Tells L<SQL::Translator> to add an index for this constraint. Can also be
184 specified globally in the args to L<DBIx::Class::Schema/deploy> or
185 L<DBIx::Class::Schema/create_ddl_dir>. Default is on, set to 0 to disable.
186
187 =back
188
189 =head2 register_relationship
190
191 =over 4
192
193 =item Arguments: $relname, $rel_info
194
195 =back
196
197 Registers a relationship on the class. This is called internally by
198 DBIx::Class::ResultSourceProxy to set up Accessors and Proxies.
199
200 =cut
201
202 sub register_relationship { }
203
204 =head2 related_resultset
205
206 =over 4
207
208 =item Arguments: $relationship_name
209
210 =item Return Value: $related_resultset
211
212 =back
213
214   $rs = $cd->related_resultset('artist');
215
216 Returns a L<DBIx::Class::ResultSet> for the relationship named
217 $relationship_name.
218
219 =cut
220
221 sub related_resultset {
222   my $self = shift;
223   $self->throw_exception("Can't call *_related as class methods")
224     unless ref $self;
225   my $rel = shift;
226   my $rel_info = $self->relationship_info($rel);
227   $self->throw_exception( "No such relationship ${rel}" )
228     unless $rel_info;
229
230   return $self->{related_resultsets}{$rel} ||= do {
231     my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
232     $attrs = { %{$rel_info->{attrs} || {}}, %$attrs };
233
234     $self->throw_exception( "Invalid query: @_" )
235       if (@_ > 1 && (@_ % 2 == 1));
236     my $query = ((@_ > 1) ? {@_} : shift);
237
238     my $source = $self->result_source;
239
240     # condition resolution may fail if an incomplete master-object prefetch
241     # is encountered - that is ok during prefetch construction (not yet in_storage)
242     my $cond = try {
243       $source->_resolve_condition( $rel_info->{cond}, $rel, $self )
244     }
245     catch {
246       if ($self->in_storage) {
247         $self->throw_exception ($_);
248       }
249
250       $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION;  # RV
251     };
252
253     if ($cond eq $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION) {
254       my $reverse = $source->reverse_relationship_info($rel);
255       foreach my $rev_rel (keys %$reverse) {
256         if ($reverse->{$rev_rel}{attrs}{accessor} && $reverse->{$rev_rel}{attrs}{accessor} eq 'multi') {
257           $attrs->{related_objects}{$rev_rel} = [ $self ];
258           Scalar::Util::weaken($attrs->{related_object}{$rev_rel}[0]);
259         } else {
260           $attrs->{related_objects}{$rev_rel} = $self;
261           Scalar::Util::weaken($attrs->{related_object}{$rev_rel});
262         }
263       }
264     }
265     if (ref $cond eq 'ARRAY') {
266       $cond = [ map {
267         if (ref $_ eq 'HASH') {
268           my $hash;
269           foreach my $key (keys %$_) {
270             my $newkey = $key !~ /\./ ? "me.$key" : $key;
271             $hash->{$newkey} = $_->{$key};
272           }
273           $hash;
274         } else {
275           $_;
276         }
277       } @$cond ];
278     } elsif (ref $cond eq 'HASH') {
279       foreach my $key (grep { ! /\./ } keys %$cond) {
280         $cond->{"me.$key"} = delete $cond->{$key};
281       }
282     }
283     $query = ($query ? { '-and' => [ $cond, $query ] } : $cond);
284     $self->result_source->related_source($rel)->resultset->search(
285       $query, $attrs
286     );
287   };
288 }
289
290 =head2 search_related
291
292   @objects = $rs->search_related('relname', $cond, $attrs);
293   $objects_rs = $rs->search_related('relname', $cond, $attrs);
294
295 Run a search on a related resultset. The search will be restricted to the
296 item or items represented by the L<DBIx::Class::ResultSet> it was called
297 upon. This method can be called on a ResultSet, a Row or a ResultSource class.
298
299 =cut
300
301 sub search_related {
302   return shift->related_resultset(shift)->search(@_);
303 }
304
305 =head2 search_related_rs
306
307   ( $objects_rs ) = $rs->search_related_rs('relname', $cond, $attrs);
308
309 This method works exactly the same as search_related, except that
310 it guarantees a resultset, even in list context.
311
312 =cut
313
314 sub search_related_rs {
315   return shift->related_resultset(shift)->search_rs(@_);
316 }
317
318 =head2 count_related
319
320   $obj->count_related('relname', $cond, $attrs);
321
322 Returns the count of all the items in the related resultset, restricted by the
323 current item or where conditions. Can be called on a
324 L<DBIx::Class::Manual::Glossary/"ResultSet"> or a
325 L<DBIx::Class::Manual::Glossary/"Row"> object.
326
327 =cut
328
329 sub count_related {
330   my $self = shift;
331   return $self->search_related(@_)->count;
332 }
333
334 =head2 new_related
335
336   my $new_obj = $obj->new_related('relname', \%col_data);
337
338 Create a new item of the related foreign class. If called on a
339 L<Row|DBIx::Class::Manual::Glossary/"Row"> object, it will magically
340 set any foreign key columns of the new object to the related primary
341 key columns of the source object for you.  The newly created item will
342 not be saved into your storage until you call L<DBIx::Class::Row/insert>
343 on it.
344
345 =cut
346
347 sub new_related {
348   my ($self, $rel, $values, $attrs) = @_;
349   return $self->search_related($rel)->new($values, $attrs);
350 }
351
352 =head2 create_related
353
354   my $new_obj = $obj->create_related('relname', \%col_data);
355
356 Creates a new item, similarly to new_related, and also inserts the item's data
357 into your storage medium. See the distinction between C<create> and C<new>
358 in L<DBIx::Class::ResultSet> for details.
359
360 =cut
361
362 sub create_related {
363   my $self = shift;
364   my $rel = shift;
365   my $obj = $self->search_related($rel)->create(@_);
366   delete $self->{related_resultsets}->{$rel};
367   return $obj;
368 }
369
370 =head2 find_related
371
372   my $found_item = $obj->find_related('relname', @pri_vals | \%pri_vals);
373
374 Attempt to find a related object using its primary key or unique constraints.
375 See L<DBIx::Class::ResultSet/find> for details.
376
377 =cut
378
379 sub find_related {
380   my $self = shift;
381   my $rel = shift;
382   return $self->search_related($rel)->find(@_);
383 }
384
385 =head2 find_or_new_related
386
387   my $new_obj = $obj->find_or_new_related('relname', \%col_data);
388
389 Find an item of a related class. If none exists, instantiate a new item of the
390 related class. The object will not be saved into your storage until you call
391 L<DBIx::Class::Row/insert> on it.
392
393 =cut
394
395 sub find_or_new_related {
396   my $self = shift;
397   my $obj = $self->find_related(@_);
398   return defined $obj ? $obj : $self->new_related(@_);
399 }
400
401 =head2 find_or_create_related
402
403   my $new_obj = $obj->find_or_create_related('relname', \%col_data);
404
405 Find or create an item of a related class. See
406 L<DBIx::Class::ResultSet/find_or_create> for details.
407
408 =cut
409
410 sub find_or_create_related {
411   my $self = shift;
412   my $obj = $self->find_related(@_);
413   return (defined($obj) ? $obj : $self->create_related(@_));
414 }
415
416 =head2 update_or_create_related
417
418   my $updated_item = $obj->update_or_create_related('relname', \%col_data, \%attrs?);
419
420 Update or create an item of a related class. See
421 L<DBIx::Class::ResultSet/update_or_create> for details.
422
423 =cut
424
425 sub update_or_create_related {
426   my $self = shift;
427   my $rel = shift;
428   return $self->related_resultset($rel)->update_or_create(@_);
429 }
430
431 =head2 set_from_related
432
433   $book->set_from_related('author', $author_obj);
434   $book->author($author_obj);                      ## same thing
435
436 Set column values on the current object, using related values from the given
437 related object. This is used to associate previously separate objects, for
438 example, to set the correct author for a book, find the Author object, then
439 call set_from_related on the book.
440
441 This is called internally when you pass existing objects as values to
442 L<DBIx::Class::ResultSet/create>, or pass an object to a belongs_to accessor.
443
444 The columns are only set in the local copy of the object, call L</update> to
445 set them in the storage.
446
447 =cut
448
449 sub set_from_related {
450   my ($self, $rel, $f_obj) = @_;
451   my $rel_info = $self->relationship_info($rel);
452   $self->throw_exception( "No such relationship ${rel}" ) unless $rel_info;
453   my $cond = $rel_info->{cond};
454   $self->throw_exception(
455     "set_from_related can only handle a hash condition; the ".
456     "condition for $rel is of type ".
457     (ref $cond ? ref $cond : 'plain scalar')
458   ) unless ref $cond eq 'HASH';
459   if (defined $f_obj) {
460     my $f_class = $rel_info->{class};
461     $self->throw_exception( "Object $f_obj isn't a ".$f_class )
462       unless Scalar::Util::blessed($f_obj) and $f_obj->isa($f_class);
463   }
464   $self->set_columns(
465     $self->result_source->_resolve_condition(
466        $rel_info->{cond}, $f_obj, $rel));
467   return 1;
468 }
469
470 =head2 update_from_related
471
472   $book->update_from_related('author', $author_obj);
473
474 The same as L</"set_from_related">, but the changes are immediately updated
475 in storage.
476
477 =cut
478
479 sub update_from_related {
480   my $self = shift;
481   $self->set_from_related(@_);
482   $self->update;
483 }
484
485 =head2 delete_related
486
487   $obj->delete_related('relname', $cond, $attrs);
488
489 Delete any related item subject to the given conditions.
490
491 =cut
492
493 sub delete_related {
494   my $self = shift;
495   my $obj = $self->search_related(@_)->delete;
496   delete $self->{related_resultsets}->{$_[0]};
497   return $obj;
498 }
499
500 =head2 add_to_$rel
501
502 B<Currently only available for C<has_many>, C<many-to-many> and 'multi' type
503 relationships.>
504
505 =over 4
506
507 =item Arguments: ($foreign_vals | $obj), $link_vals?
508
509 =back
510
511   my $role = $schema->resultset('Role')->find(1);
512   $actor->add_to_roles($role);
513       # creates a My::DBIC::Schema::ActorRoles linking table row object
514
515   $actor->add_to_roles({ name => 'lead' }, { salary => 15_000_000 });
516       # creates a new My::DBIC::Schema::Role row object and the linking table
517       # object with an extra column in the link
518
519 Adds a linking table object for C<$obj> or C<$foreign_vals>. If the first
520 argument is a hash reference, the related object is created first with the
521 column values in the hash. If an object reference is given, just the linking
522 table object is created. In either case, any additional column values for the
523 linking table object can be specified in C<$link_vals>.
524
525 =head2 set_$rel
526
527 B<Currently only available for C<many-to-many> relationships.>
528
529 =over 4
530
531 =item Arguments: (\@hashrefs | \@objs), $link_vals?
532
533 =back
534
535   my $actor = $schema->resultset('Actor')->find(1);
536   my @roles = $schema->resultset('Role')->search({ role =>
537      { '-in' => ['Fred', 'Barney'] } } );
538
539   $actor->set_roles(\@roles);
540      # Replaces all of $actor's previous roles with the two named
541
542   $actor->set_roles(\@roles, { salary => 15_000_000 });
543      # Sets a column in the link table for all roles
544
545
546 Replace all the related objects with the given reference to a list of
547 objects. This does a C<delete> B<on the link table resultset> to remove the
548 association between the current object and all related objects, then calls
549 C<add_to_$rel> repeatedly to link all the new objects.
550
551 Note that this means that this method will B<not> delete any objects in the
552 table on the right side of the relation, merely that it will delete the link
553 between them.
554
555 Due to a mistake in the original implementation of this method, it will also
556 accept a list of objects or hash references. This is B<deprecated> and will be
557 removed in a future version.
558
559 =head2 remove_from_$rel
560
561 B<Currently only available for C<many-to-many> relationships.>
562
563 =over 4
564
565 =item Arguments: $obj
566
567 =back
568
569   my $role = $schema->resultset('Role')->find(1);
570   $actor->remove_from_roles($role);
571       # removes $role's My::DBIC::Schema::ActorRoles linking table row object
572
573 Removes the link between the current object and the related object. Note that
574 the related object itself won't be deleted unless you call ->delete() on
575 it. This method just removes the link between the two objects.
576
577 =head1 AUTHORS
578
579 Matt S. Trout <mst@shadowcatsystems.co.uk>
580
581 =head1 LICENSE
582
583 You may distribute this code under the same terms as Perl itself.
584
585 =cut
586
587 1;