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