Switch infer_values_based_on to require_join_free_values in cond resolver
[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 base qw/DBIx::Class/;
7
8 use Scalar::Util qw/weaken blessed/;
9 use DBIx::Class::_Util qw(
10   UNRESOLVABLE_CONDITION DUMMY_ALIASPAIR
11   dbic_internal_try fail_on_internal_call
12 );
13 use DBIx::Class::SQLMaker::Util 'extract_equality_conditions';
14 use DBIx::Class::Carp;
15 use namespace::clean;
16
17 =head1 NAME
18
19 DBIx::Class::Relationship::Base - Inter-table relationships
20
21 =head1 SYNOPSIS
22
23   __PACKAGE__->add_relationship(
24     spiders => 'My::DB::Result::Creatures',
25     sub {
26       my $args = shift;
27       return {
28         "$args->{foreign_alias}.id"   => { -ident => "$args->{self_alias}.id" },
29         "$args->{foreign_alias}.type" => 'arachnid'
30       };
31     },
32   );
33
34 =head1 DESCRIPTION
35
36 This class provides methods to describe the relationships between the
37 tables in your database model. These are the "bare bones" relationships
38 methods, for predefined ones, look in L<DBIx::Class::Relationship>.
39
40 =head1 METHODS
41
42 =head2 add_relationship
43
44 =over 4
45
46 =item Arguments: $rel_name, $foreign_class, $condition, $attrs
47
48 =back
49
50   __PACKAGE__->add_relationship('rel_name',
51                                 'Foreign::Class',
52                                 $condition, $attrs);
53
54 Create a custom relationship between one result source and another
55 source, indicated by its class name.
56
57 =head3 condition
58
59 The condition argument describes the C<ON> clause of the C<JOIN>
60 expression used to connect the two sources when creating SQL queries.
61
62 =head4 Simple equality
63
64 To create simple equality joins, supply a hashref containing the remote
65 table column name as the key(s) prefixed by C<'foreign.'>, and the
66 corresponding local table column name as the value(s) prefixed by C<'self.'>.
67 Both C<foreign> and C<self> are pseudo aliases and must be entered
68 literally. They will be replaced with the actual correct table alias
69 when the SQL is produced.
70
71 For example given:
72
73   My::Schema::Author->has_many(
74     books => 'My::Schema::Book',
75     { 'foreign.author_id' => 'self.id' }
76   );
77
78 A query like:
79
80   $author_rs->search_related('books')->next
81
82 will result in the following C<JOIN> clause:
83
84   ... FROM author me LEFT JOIN book books ON books.author_id = me.id ...
85
86 This describes a relationship between the C<Author> table and the
87 C<Book> table where the C<Book> table has a column C<author_id>
88 containing the ID value of the C<Author>.
89
90 Similarly:
91
92   My::Schema::Book->has_many(
93     editions => 'My::Schema::Edition',
94     {
95       'foreign.publisher_id' => 'self.publisher_id',
96       'foreign.type_id'      => 'self.type_id',
97     }
98   );
99
100   ...
101
102   $book_rs->search_related('editions')->next
103
104 will result in the C<JOIN> clause:
105
106   ... FROM book me
107       LEFT JOIN edition editions ON
108            editions.publisher_id = me.publisher_id
109        AND editions.type_id = me.type_id ...
110
111 This describes the relationship from C<Book> to C<Edition>, where the
112 C<Edition> table refers to a publisher and a type (e.g. "paperback"):
113
114 =head4 Multiple groups of simple equality conditions
115
116 As is the default in L<SQL::Abstract>, the key-value pairs will be
117 C<AND>ed in the resulting C<JOIN> clause. An C<OR> can be achieved with
118 an arrayref. For example a condition like:
119
120   My::Schema::Item->has_many(
121     related_item_links => My::Schema::Item::Links,
122     [
123       { 'foreign.left_itemid'  => 'self.id' },
124       { 'foreign.right_itemid' => 'self.id' },
125     ],
126   );
127
128 will translate to the following C<JOIN> clause:
129
130  ... FROM item me JOIN item_relations related_item_links ON
131          related_item_links.left_itemid = me.id
132       OR related_item_links.right_itemid = me.id ...
133
134 This describes the relationship from C<Item> to C<Item::Links>, where
135 C<Item::Links> is a many-to-many linking table, linking items back to
136 themselves in a peer fashion (without a "parent-child" designation)
137
138 =head4 Custom join conditions
139
140   NOTE: The custom join condition specification mechanism is capable of
141   generating JOIN clauses of virtually unlimited complexity. This may limit
142   your ability to traverse some of the more involved relationship chains the
143   way you expect, *and* may bring your RDBMS to its knees. Exercise care
144   when declaring relationships as described here.
145
146 To specify joins which describe more than a simple equality of column
147 values, the custom join condition coderef syntax can be used. For
148 example:
149
150   My::Schema::Artist->has_many(
151     cds_80s => 'My::Schema::CD',
152     sub {
153       my $args = shift;
154
155       return {
156         "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
157         "$args->{foreign_alias}.year"   => { '>', "1979", '<', "1990" },
158       };
159     }
160   );
161
162   ...
163
164   $artist_rs->search_related('cds_80s')->next;
165
166 will result in the C<JOIN> clause:
167
168   ... FROM artist me LEFT JOIN cd cds_80s ON
169         cds_80s.artist = me.artistid
170     AND cds_80s.year < ?
171     AND cds_80s.year > ?
172
173 with the bind values:
174
175    '1990', '1979'
176
177 C<< $args->{foreign_alias} >> and C<< $args->{self_alias} >> are supplied the
178 same values that would be otherwise substituted for C<foreign> and C<self>
179 in the simple hashref syntax case.
180
181 The coderef is expected to return a valid L<SQL::Abstract> query-structure, just
182 like what one would supply as the first argument to
183 L<DBIx::Class::ResultSet/search>. The return value will be passed directly to
184 L<SQL::Abstract> and the resulting SQL will be used verbatim as the C<ON>
185 clause of the C<JOIN> statement associated with this relationship.
186
187 While every coderef-based condition must return a valid C<ON> clause, it may
188 elect to additionally return a simplified B<optional> join-free condition
189 consisting of a hashref with B<all keys being fully qualified names of columns
190 declared on the corresponding result source>. This boils down to two scenarios:
191
192 =over
193
194 =item *
195
196 When relationship resolution is invoked after C<< $result->$rel_name >>, as
197 opposed to C<< $rs->related_resultset($rel_name) >>, the C<$result> object
198 is passed to the coderef as C<< $args->{self_result_object} >>.
199
200 =item *
201
202 Alternatively when the user-space invokes resolution via
203 C<< $result->set_from_related( $rel_name => $foreign_values_or_object ) >>, the
204 corresponding data is passed to the coderef as C<< $args->{foreign_values} >>,
205 B<always> in the form of a hashref. If a foreign result object is supplied
206 (which is valid usage of L</set_from_related>), its values will be extracted
207 into hashref form by calling L<get_columns|DBIx::Class::Row/get_columns>.
208
209 =back
210
211 Note that the above scenarios are mutually exclusive, that is you will be supplied
212 none or only one of C<self_result_object> and C<foreign_values>. In other words if
213 you define your condition coderef as:
214
215   sub {
216     my $args = shift;
217
218     return (
219       {
220         "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
221         "$args->{foreign_alias}.year"   => { '>', "1979", '<', "1990" },
222       },
223       ! $args->{self_result_object} ? () : {
224         "$args->{foreign_alias}.artist" => $args->{self_result_object}->artistid,
225         "$args->{foreign_alias}.year"   => { '>', "1979", '<', "1990" },
226       },
227       ! $args->{foreign_values} ? () : {
228         "$args->{self_alias}.artistid" => $args->{foreign_values}{artist},
229       }
230     );
231   }
232
233 Then this code:
234
235     my $artist = $schema->resultset("Artist")->find({ id => 4 });
236     $artist->cds_80s->all;
237
238 Can skip a C<JOIN> altogether and instead produce:
239
240     SELECT cds_80s.cdid, cds_80s.artist, cds_80s.title, cds_80s.year, cds_80s.genreid, cds_80s.single_track
241       FROM cd cds_80s
242       WHERE cds_80s.artist = ?
243         AND cds_80s.year < ?
244         AND cds_80s.year > ?
245
246 With the bind values:
247
248     '4', '1990', '1979'
249
250 While this code:
251
252     my $cd = $schema->resultset("CD")->search({ artist => 1 }, { rows => 1 })->single;
253     my $artist = $schema->resultset("Artist")->new({});
254     $artist->set_from_related('cds_80s');
255
256 Will properly set the C<< $artist->artistid >> field of this new object to C<1>
257
258 Note that in order to be able to use L</set_from_related> (and by extension
259 L<< $result->create_related|DBIx::Class::Relationship::Base/create_related >>),
260 the returned join free condition B<must> contain only plain values/deflatable
261 objects. For instance the C<year> constraint in the above example prevents
262 the relationship from being used to create related objects using
263 C<< $artst->create_related( cds_80s => { title => 'blah' } ) >> (an
264 exception will be thrown).
265
266 In order to allow the user to go truly crazy when generating a custom C<ON>
267 clause, the C<$args> hashref passed to the subroutine contains some extra
268 metadata. Currently the supplied coderef is executed as:
269
270   $relationship_info->{cond}->({
271     self_resultsource   => The resultsource instance on which rel_name is registered
272     rel_name            => The relationship name (does *NOT* always match foreign_alias)
273
274     self_alias          => The alias of the invoking resultset
275     foreign_alias       => The alias of the to-be-joined resultset (does *NOT* always match rel_name)
276
277     # only one of these (or none at all) will ever be supplied to aid in the
278     # construction of a join-free condition
279
280     self_result_object  => The invocant *object* itself in case of a call like
281                            $result_object->$rel_name( ... )
282
283     foreign_values      => A *hashref* of related data: may be passed in directly or
284                            derived via ->get_columns() from a related object in case of
285                            $result_object->set_from_related( $rel_name, $foreign_result_object )
286
287     # deprecated inconsistent names, will be forever available for legacy code
288     self_rowobj         => Old deprecated slot for self_result_object
289     foreign_relname     => Old deprecated slot for rel_name
290   });
291
292 =head3 attributes
293
294 The L<standard ResultSet attributes|DBIx::Class::ResultSet/ATTRIBUTES> may
295 be used as relationship attributes. In particular, the 'where' attribute is
296 useful for filtering relationships:
297
298      __PACKAGE__->has_many( 'valid_users', 'MyApp::Schema::User',
299         { 'foreign.user_id' => 'self.user_id' },
300         { where => { valid => 1 } }
301     );
302
303 The following attributes are also valid:
304
305 =over 4
306
307 =item join_type
308
309 Explicitly specifies the type of join to use in the relationship. Any SQL
310 join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in the SQL
311 command immediately before C<JOIN>.
312
313 =item proxy =E<gt> $column | \@columns | \%column
314
315 The 'proxy' attribute can be used to retrieve values, and to perform
316 updates if the relationship has 'cascade_update' set. The 'might_have'
317 and 'has_one' relationships have this set by default; if you want a proxy
318 to update across a 'belongs_to' relationship, you must set the attribute
319 yourself.
320
321 =over 4
322
323 =item \@columns
324
325 An arrayref containing a list of accessors in the foreign class to create in
326 the main class. If, for example, you do the following:
327
328   MyApp::Schema::CD->might_have(liner_notes => 'MyApp::Schema::LinerNotes',
329     undef, {
330       proxy => [ qw/notes/ ],
331     });
332
333 Then, assuming MyApp::Schema::LinerNotes has an accessor named notes, you can do:
334
335   my $cd = MyApp::Schema::CD->find(1);
336   $cd->notes('Notes go here'); # set notes -- LinerNotes object is
337                                # created if it doesn't exist
338
339 For a 'belongs_to relationship, note the 'cascade_update':
340
341   MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd,
342       { proxy => ['title'], cascade_update => 1 }
343   );
344   $track->title('New Title');
345   $track->update; # updates title in CD
346
347 =item \%column
348
349 A hashref where each key is the accessor you want installed in the main class,
350 and its value is the name of the original in the foreign class.
351
352   MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
353       proxy => { cd_title => 'title' },
354   });
355
356 This will create an accessor named C<cd_title> on the C<$track> result object.
357
358 =back
359
360 NOTE: you can pass a nested struct too, for example:
361
362   MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
363     proxy => [ 'year', { cd_title => 'title' } ],
364   });
365
366 =item accessor
367
368 Specifies the type of accessor that should be created for the relationship.
369 Valid values are C<single> (for when there is only a single related object),
370 C<multi> (when there can be many), and C<filter> (for when there is a single
371 related object, but you also want the relationship accessor to double as
372 a column accessor). For C<multi> accessors, an add_to_* method is also
373 created, which calls C<create_related> for the relationship.
374
375 =item is_foreign_key_constraint
376
377 If you are using L<SQL::Translator> to create SQL for you and you find that it
378 is creating constraints where it shouldn't, or not creating them where it
379 should, set this attribute to a true or false value to override the detection
380 of when to create constraints.
381
382 =item cascade_copy
383
384 If C<cascade_copy> is true on a C<has_many> relationship for an
385 object, then when you copy the object all the related objects will
386 be copied too. To turn this behaviour off, pass C<< cascade_copy => 0 >>
387 in the C<$attr> hashref.
388
389 The behaviour defaults to C<< cascade_copy => 1 >> for C<has_many>
390 relationships.
391
392 =item cascade_delete
393
394 By default, DBIx::Class cascades deletes across C<has_many>,
395 C<has_one> and C<might_have> relationships. You can disable this
396 behaviour on a per-relationship basis by supplying
397 C<< cascade_delete => 0 >> in the relationship attributes.
398
399 The cascaded operations are performed after the requested delete,
400 so if your database has a constraint on the relationship, it will
401 have deleted/updated the related records or raised an exception
402 before DBIx::Class gets to perform the cascaded operation.
403
404 =item cascade_update
405
406 By default, DBIx::Class cascades updates across C<has_one> and
407 C<might_have> relationships. You can disable this behaviour on a
408 per-relationship basis by supplying C<< cascade_update => 0 >> in
409 the relationship attributes.
410
411 The C<belongs_to> relationship does not update across relationships
412 by default, so if you have a 'proxy' attribute on a belongs_to and want to
413 use 'update' on it, you must set C<< cascade_update => 1 >>.
414
415 This is not a RDMS style cascade update - it purely means that when
416 an object has update called on it, all the related objects also
417 have update called. It will not change foreign keys automatically -
418 you must arrange to do this yourself.
419
420 =item on_delete / on_update
421
422 If you are using L<SQL::Translator> to create SQL for you, you can use these
423 attributes to explicitly set the desired C<ON DELETE> or C<ON UPDATE> constraint
424 type. If not supplied the SQLT parser will attempt to infer the constraint type by
425 interrogating the attributes of the B<opposite> relationship. For any 'multi'
426 relationship with C<< cascade_delete => 1 >>, the corresponding belongs_to
427 relationship will be created with an C<ON DELETE CASCADE> constraint. For any
428 relationship bearing C<< cascade_copy => 1 >> the resulting belongs_to constraint
429 will be C<ON UPDATE CASCADE>. If you wish to disable this autodetection, and just
430 use the RDBMS' default constraint type, pass C<< on_delete => undef >> or
431 C<< on_delete => '' >>, and the same for C<on_update> respectively.
432
433 =item is_deferrable
434
435 Tells L<SQL::Translator> that the foreign key constraint it creates should be
436 deferrable. In other words, the user may request that the constraint be ignored
437 until the end of the transaction. Currently, only the PostgreSQL producer
438 actually supports this.
439
440 =item add_fk_index
441
442 Tells L<SQL::Translator> to add an index for this constraint. Can also be
443 specified globally in the args to L<DBIx::Class::Schema/deploy> or
444 L<DBIx::Class::Schema/create_ddl_dir>. Default is on, set to 0 to disable.
445
446 =back
447
448 =head2 register_relationship
449
450 =over 4
451
452 =item Arguments: $rel_name, $rel_info
453
454 =back
455
456 Registers a relationship on the class. This is called internally by
457 DBIx::Class::ResultSourceProxy to set up Accessors and Proxies.
458
459 =cut
460
461 sub register_relationship { }
462
463 =head2 related_resultset
464
465 =over 4
466
467 =item Arguments: $rel_name
468
469 =item Return Value: L<$related_resultset|DBIx::Class::ResultSet>
470
471 =back
472
473   $rs = $cd->related_resultset('artist');
474
475 Returns a L<DBIx::Class::ResultSet> for the relationship named
476 $rel_name.
477
478 =head2 $relationship_accessor
479
480 =over 4
481
482 =item Arguments: none
483
484 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | L<$related_resultset|DBIx::Class::ResultSet> | undef
485
486 =back
487
488   # These pairs do the same thing
489   $result = $cd->related_resultset('artist')->single;  # has_one relationship
490   $result = $cd->artist;
491   $rs = $cd->related_resultset('tracks');           # has_many relationship
492   $rs = $cd->tracks;
493
494 This is the recommended way to traverse through relationships, based
495 on the L</accessor> name given in the relationship definition.
496
497 This will return either a L<Result|DBIx::Class::Manual::ResultClass> or a
498 L<ResultSet|DBIx::Class::ResultSet>, depending on if the relationship is
499 C<single> (returns only one row) or C<multi> (returns many rows).  The
500 method may also return C<undef> if the relationship doesn't exist for
501 this instance (like in the case of C<might_have> relationships).
502
503 =cut
504
505 sub related_resultset {
506   $_[0]->throw_exception(
507     '$result->related_resultset() no longer accepts extra search arguments, '
508   . 'you need to switch to ...->related_resultset($relname)->search_rs(...) '
509   . 'instead (it was never documented and more importantly could never work '
510   . 'reliably due to the heavy caching involved)'
511   ) if @_ > 2;
512
513   $_[0]->throw_exception("Can't call *_related as class methods")
514     unless ref $_[0];
515
516   return $_[0]->{related_resultsets}{$_[1]}
517     if defined $_[0]->{related_resultsets}{$_[1]};
518
519   my ($self, $rel) = @_;
520
521   my $rsrc = $self->result_source;
522
523   my $rel_info = $rsrc->relationship_info($rel)
524     or $self->throw_exception( "No such relationship '$rel'" );
525
526   my $relcond_is_freeform = ref $rel_info->{cond} eq 'CODE';
527
528   my $jfc = $rsrc->_resolve_relationship_condition(
529
530     rel_name => $rel,
531     self_result_object => $self,
532
533     # an extra sanity check guard
534     require_join_free_condition => !!(
535       ! $relcond_is_freeform
536         and
537       $self->in_storage
538     ),
539
540     # an API where these are optional would be too cumbersome,
541     # instead always pass in some dummy values
542     DUMMY_ALIASPAIR,
543
544     # this may look weird, but remember that we are making a resultset
545     # out of an existing object, with the new source being at the head
546     # of the FROM chain. Having a 'me' alias is nothing but expected there
547     foreign_alias => 'me',
548
549   )->{join_free_condition};
550
551   my $rel_rset;
552
553   if( defined $jfc ) {
554
555     $rel_rset = $rsrc->related_source($rel)->resultset->search(
556       $jfc,
557       $rel_info->{attrs},
558     );
559   }
560   elsif( $relcond_is_freeform ) {
561
562     # A WHOREIFFIC hack to reinvoke the entire condition resolution
563     # with the correct alias. Another way of doing this involves a
564     # lot of state passing around, and the @_ positions are already
565     # mapped out, making this crap a less icky option.
566     #
567     # The point of this exercise is to retain the spirit of the original
568     # $obj->search_related($rel) where the resulting rset will have the
569     # root alias as 'me', instead of $rel (as opposed to invoking
570     # $rs->search_related)
571
572     # make the fake 'me' rel
573     local $rsrc->{_relationships}{me} = {
574       %{ $rsrc->{_relationships}{$rel} },
575       _original_name => $rel,
576     };
577
578     my $obj_table_alias = lc($rsrc->source_name) . '__row';
579     $obj_table_alias =~ s/\W+/_/g;
580
581     $rel_rset = $rsrc->resultset->search(
582       $self->ident_condition($obj_table_alias),
583       { alias => $obj_table_alias },
584     )->related_resultset('me')->search(undef, $rel_info->{attrs})
585   }
586   else {
587
588     my $attrs = { %{$rel_info->{attrs}} };
589     my $reverse = $rsrc->reverse_relationship_info($rel);
590
591     # FIXME - this loop doesn't seem correct - got to figure out
592     # at some point what exactly it does.
593     # See also the FIXME at the end of new_related()
594     ( ( $reverse->{$_}{attrs}{accessor}||'') eq 'multi' )
595       ? weaken( $attrs->{related_objects}{$_}[0] = $self )
596       : weaken( $attrs->{related_objects}{$_}    = $self )
597     for keys %$reverse;
598
599     $rel_rset = $rsrc->related_source($rel)->resultset->search(
600       UNRESOLVABLE_CONDITION, # guards potential use of the $rs in the future
601       $attrs,
602     );
603   }
604
605   $self->{related_resultsets}{$rel} = $rel_rset;
606 }
607
608 =head2 search_related
609
610 =over 4
611
612 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
613
614 =item Return Value: L<$resultset|DBIx::Class::ResultSet> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
615
616 =back
617
618 Run a search on a related resultset. The search will be restricted to the
619 results represented by the L<DBIx::Class::ResultSet> it was called
620 upon.
621
622 See L<DBIx::Class::ResultSet/search_related> for more information.
623
624 =cut
625
626 sub search_related :DBIC_method_is_indirect_sugar {
627   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
628   shift->related_resultset(shift)->search(@_);
629 }
630
631 =head2 search_related_rs
632
633 This method works exactly the same as search_related, except that
634 it guarantees a resultset, even in list context.
635
636 =cut
637
638 sub search_related_rs :DBIC_method_is_indirect_sugar {
639   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
640   shift->related_resultset(shift)->search_rs(@_)
641 }
642
643 =head2 count_related
644
645 =over 4
646
647 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
648
649 =item Return Value: $count
650
651 =back
652
653 Returns the count of all the rows in the related resultset, restricted by the
654 current result or where conditions.
655
656 =cut
657
658 sub count_related :DBIC_method_is_indirect_sugar {
659   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
660   shift->related_resultset(shift)->search_rs(@_)->count;
661 }
662
663 =head2 new_related
664
665 =over 4
666
667 =item Arguments: $rel_name, \%col_data
668
669 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
670
671 =back
672
673 Create a new result object of the related foreign class.  It will magically set
674 any foreign key columns of the new object to the related primary key columns
675 of the source object for you.  The newly created result will not be saved into
676 your storage until you call L<DBIx::Class::Row/insert> on it.
677
678 =cut
679
680 sub new_related {
681   my ($self, $rel, $data) = @_;
682
683   $self->throw_exception(
684     "Result object instantiation requires a hashref as argument"
685   ) unless ref $data eq 'HASH';
686
687   my $rsrc = $self->result_source;
688   my $rel_rsrc = $rsrc->related_source($rel);
689
690 ###
691 ### This section deliberately does not rely on require_join_free_values,
692 ### as quite often the resulting related object is useless without the
693 ### contents of $data mixed in. Originally this code was part of
694 ### resolve_relationship_condition() but given it has a single, very
695 ### context-specific call-site it made no sense to expose it to end users.
696 ###
697
698   my $rel_resolution = $rsrc->_resolve_relationship_condition (
699     rel_name => $rel,
700     self_result_object => $self,
701
702     # In case we are *not* in_storage it is ok to treat failed resolution as an empty hash
703     # This happens e.g. as a result of various in-memory related graph of objects
704     require_join_free_condition => !! $self->in_storage,
705
706     # dummy aliases with deliberately known lengths, so that we can
707     # quickly strip them below if needed
708     foreign_alias => 'F',
709     self_alias    => 'S',
710   );
711
712   my $rel_values =
713     $rel_resolution->{join_free_values}
714       ||
715     { map { substr( $_, 2 ) => $rel_resolution->{join_free_condition}{$_} } keys %{ $rel_resolution->{join_free_condition} } }
716   ;
717
718   # mix everything together
719   my $amalgamated_values = {
720     %{
721       # in case we got back join_free_values - they already have passed the extractor
722       $rel_resolution->{join_free_values}
723         ? $rel_values
724         : extract_equality_conditions(
725           $rel_values,
726           'consider_nulls'
727         )
728     },
729     %$data,
730   };
731
732   # cleanup possible rogue { somecolumn => [ -and => 1,2 ] }
733   ($amalgamated_values->{$_}||'') eq UNRESOLVABLE_CONDITION
734     and
735   delete $amalgamated_values->{$_}
736     for keys %$amalgamated_values;
737
738   if( my @nonvalues = grep { ! exists $amalgamated_values->{$_} } keys %$rel_values ) {
739
740     $self->throw_exception(
741       "Unable to complete value inferrence - relationship '$rel' "
742     . "on source '@{[ $rsrc->source_name ]}' results "
743     . 'in expression(s) instead of definitive values: '
744     . do {
745         # FIXME - used for diag only, but still icky
746         my $sqlm =
747           dbic_internal_try { $rsrc->schema->storage->sql_maker }
748             ||
749           (
750             require DBIx::Class::SQLMaker
751               and
752             DBIx::Class::SQLMaker->new
753           )
754         ;
755         local $sqlm->{quote_char};
756         local $sqlm->{_dequalify_idents} = 1;
757         ($sqlm->_recurse_where({ map { $_ => $rel_values->{$_} } @nonvalues }))[0]
758       }
759     );
760   }
761
762   # And more complications - in case the relationship did not resolve
763   # we *have* to loop things through search_related ( essentially re-resolving
764   # everything we did so far, but with different type of handholding )
765   # FIXME - this is still a mess, just a *little* better than it was
766   # See also the FIXME at the end of related_resultset()
767   exists $rel_resolution->{join_free_values}
768     ? $rel_rsrc->result_class->new({ -result_source => $rel_rsrc, %$amalgamated_values })
769     : $self->related_resultset($rel)->new_result( $amalgamated_values )
770   ;
771 }
772
773 =head2 create_related
774
775 =over 4
776
777 =item Arguments: $rel_name, \%col_data
778
779 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
780
781 =back
782
783   my $result = $obj->create_related($rel_name, \%col_data);
784
785 Creates a new result object, similarly to new_related, and also inserts the
786 result's data into your storage medium. See the distinction between C<create>
787 and C<new> in L<DBIx::Class::ResultSet> for details.
788
789 =cut
790
791 sub create_related {
792   my $self = shift;
793   my $rel = shift;
794   my $obj = $self->new_related($rel, @_)->insert;
795   delete $self->{related_resultsets}->{$rel};
796   return $obj;
797 }
798
799 =head2 find_related
800
801 =over 4
802
803 =item Arguments: $rel_name, \%col_data | @pk_values, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
804
805 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
806
807 =back
808
809   my $result = $obj->find_related($rel_name, \%col_data);
810
811 Attempt to find a related object using its primary key or unique constraints.
812 See L<DBIx::Class::ResultSet/find> for details.
813
814 =cut
815
816 sub find_related :DBIC_method_is_indirect_sugar {
817   #my ($self, $rel, @args) = @_;
818   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
819   return shift->related_resultset(shift)->find(@_);
820 }
821
822 =head2 find_or_new_related
823
824 =over 4
825
826 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
827
828 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
829
830 =back
831
832 Find a result object of a related class.  See L<DBIx::Class::ResultSet/find_or_new>
833 for details.
834
835 =cut
836
837 sub find_or_new_related {
838   my $self = shift;
839   my $rel = shift;
840   my $obj = $self->related_resultset($rel)->find(@_);
841   return defined $obj ? $obj : $self->related_resultset($rel)->new_result(@_);
842 }
843
844 =head2 find_or_create_related
845
846 =over 4
847
848 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
849
850 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
851
852 =back
853
854 Find or create a result object of a related class. See
855 L<DBIx::Class::ResultSet/find_or_create> for details.
856
857 =cut
858
859 sub find_or_create_related {
860   my $self = shift;
861   my $rel = shift;
862   my $obj = $self->related_resultset($rel)->find(@_);
863   return (defined($obj) ? $obj : $self->create_related( $rel => @_ ));
864 }
865
866 =head2 update_or_create_related
867
868 =over 4
869
870 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
871
872 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
873
874 =back
875
876 Update or create a result object of a related class. See
877 L<DBIx::Class::ResultSet/update_or_create> for details.
878
879 =cut
880
881 sub update_or_create_related :DBIC_method_is_indirect_sugar {
882   #my ($self, $rel, @args) = @_;
883   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
884   shift->related_resultset(shift)->update_or_create(@_);
885 }
886
887 =head2 set_from_related
888
889 =over 4
890
891 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
892
893 =item Return Value: not defined
894
895 =back
896
897   $book->set_from_related('author', $author_obj);
898   $book->author($author_obj);                      ## same thing
899
900 Set column values on the current object, using related values from the given
901 related object. This is used to associate previously separate objects, for
902 example, to set the correct author for a book, find the Author object, then
903 call set_from_related on the book.
904
905 This is called internally when you pass existing objects as values to
906 L<DBIx::Class::ResultSet/create>, or pass an object to a belongs_to accessor.
907
908 The columns are only set in the local copy of the object, call
909 L<update|DBIx::Class::Row/update> to update them in the storage.
910
911 =cut
912
913 sub set_from_related {
914   my ($self, $rel, $f_obj) = @_;
915
916   $self->set_columns( $self->result_source->_resolve_relationship_condition (
917     require_join_free_values => 1,
918     rel_name => $rel,
919     foreign_values => (
920       # maintain crazy set_from_related interface
921       #
922       ( ! defined $f_obj )          ? +{}
923     : ( ! defined blessed $f_obj )  ? $f_obj
924                                     : do {
925
926         my $f_result_class = $self->result_source->related_source($rel)->result_class;
927
928         unless( $f_obj->isa($f_result_class) ) {
929
930           $self->throw_exception(
931             'Object supplied to set_from_related() must inherit from '
932           . "'$DBIx::Class::ResultSource::__expected_result_class_isa'"
933           ) unless $f_obj->isa(
934             $DBIx::Class::ResultSource::__expected_result_class_isa
935           );
936
937           carp_unique(
938             'Object supplied to set_from_related() usually should inherit from '
939           . "the related ResultClass ('$f_result_class'), perhaps you've made "
940           . 'a mistake?'
941           );
942         }
943
944         +{ $f_obj->get_columns };
945       }
946     ),
947
948     # an API where these are optional would be too cumbersome,
949     # instead always pass in some dummy values
950     DUMMY_ALIASPAIR,
951
952   )->{join_free_values} );
953
954   return 1;
955 }
956
957 =head2 update_from_related
958
959 =over 4
960
961 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
962
963 =item Return Value: not defined
964
965 =back
966
967   $book->update_from_related('author', $author_obj);
968
969 The same as L</"set_from_related">, but the changes are immediately updated
970 in storage.
971
972 =cut
973
974 sub update_from_related {
975   my $self = shift;
976   $self->set_from_related(@_);
977   $self->update;
978 }
979
980 =head2 delete_related
981
982 =over 4
983
984 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
985
986 =item Return Value: $underlying_storage_rv
987
988 =back
989
990 Delete any related row, subject to the given conditions.  Internally, this
991 calls:
992
993   $self->search_related(@_)->delete
994
995 And returns the result of that.
996
997 =cut
998
999 sub delete_related {
1000   my $self = shift;
1001   my $rel = shift;
1002   my $obj = $self->related_resultset($rel)->search_rs(@_)->delete;
1003   delete $self->{related_resultsets}->{$rel};
1004   return $obj;
1005 }
1006
1007 =head2 add_to_$rel
1008
1009 B<Currently only available for C<has_many>, C<many_to_many> and 'multi' type
1010 relationships.>
1011
1012 =head3 has_many / multi
1013
1014 =over 4
1015
1016 =item Arguments: \%col_data
1017
1018 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
1019
1020 =back
1021
1022 Creates/inserts a new result object.  Internally, this calls:
1023
1024   $self->create_related($rel, @_)
1025
1026 And returns the result of that.
1027
1028 =head3 many_to_many
1029
1030 =over 4
1031
1032 =item Arguments: (\%col_data | L<$result|DBIx::Class::Manual::ResultClass>), \%link_col_data?
1033
1034 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
1035
1036 =back
1037
1038   my $role = $schema->resultset('Role')->find(1);
1039   $actor->add_to_roles($role);
1040       # creates a My::DBIC::Schema::ActorRoles linking table result object
1041
1042   $actor->add_to_roles({ name => 'lead' }, { salary => 15_000_000 });
1043       # creates a new My::DBIC::Schema::Role result object and the linking table
1044       # object with an extra column in the link
1045
1046 Adds a linking table object. If the first argument is a hash reference, the
1047 related object is created first with the column values in the hash. If an object
1048 reference is given, just the linking table object is created. In either case,
1049 any additional column values for the linking table object can be specified in
1050 C<\%link_col_data>.
1051
1052 See L<DBIx::Class::Relationship/many_to_many> for additional details.
1053
1054 =head2 set_$rel
1055
1056 B<Currently only available for C<many_to_many> relationships.>
1057
1058 =over 4
1059
1060 =item Arguments: (\@hashrefs_of_col_data | L<\@result_objs|DBIx::Class::Manual::ResultClass>), $link_vals?
1061
1062 =item Return Value: not defined
1063
1064 =back
1065
1066   my $actor = $schema->resultset('Actor')->find(1);
1067   my @roles = $schema->resultset('Role')->search({ role =>
1068      { '-in' => ['Fred', 'Barney'] } } );
1069
1070   $actor->set_roles(\@roles);
1071      # Replaces all of $actor's previous roles with the two named
1072
1073   $actor->set_roles(\@roles, { salary => 15_000_000 });
1074      # Sets a column in the link table for all roles
1075
1076
1077 Replace all the related objects with the given reference to a list of
1078 objects. This does a C<delete> B<on the link table resultset> to remove the
1079 association between the current object and all related objects, then calls
1080 C<add_to_$rel> repeatedly to link all the new objects.
1081
1082 Note that this means that this method will B<not> delete any objects in the
1083 table on the right side of the relation, merely that it will delete the link
1084 between them.
1085
1086 Due to a mistake in the original implementation of this method, it will also
1087 accept a list of objects or hash references. This is B<deprecated> and will be
1088 removed in a future version.
1089
1090 =head2 remove_from_$rel
1091
1092 B<Currently only available for C<many_to_many> relationships.>
1093
1094 =over 4
1095
1096 =item Arguments: L<$result|DBIx::Class::Manual::ResultClass>
1097
1098 =item Return Value: not defined
1099
1100 =back
1101
1102   my $role = $schema->resultset('Role')->find(1);
1103   $actor->remove_from_roles($role);
1104       # removes $role's My::DBIC::Schema::ActorRoles linking table result object
1105
1106 Removes the link between the current object and the related object. Note that
1107 the related object itself won't be deleted unless you call ->delete() on
1108 it. This method just removes the link between the two objects.
1109
1110 =head1 FURTHER QUESTIONS?
1111
1112 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
1113
1114 =head1 COPYRIGHT AND LICENSE
1115
1116 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
1117 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
1118 redistribute it and/or modify it under the same terms as the
1119 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.
1120
1121 =cut
1122
1123 1;