a274ee7906958b05d7fab8d41ca1dd0152964bcf
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultSet.pm
1 package DBIx::Class::ResultSet;
2
3 use strict;
4 use warnings;
5
6 use base 'DBIx::Class';
7
8 use DBIx::Class::Carp;
9 use DBIx::Class::ResultSetColumn;
10 use DBIx::Class::ResultClass::HashRefInflator;
11 use Scalar::Util qw( blessed reftype );
12 use SQL::Abstract 'is_literal_value';
13 use DBIx::Class::_Util qw(
14   dbic_internal_try dbic_internal_catch dump_value emit_loud_diag
15   fail_on_internal_wantarray fail_on_internal_call
16   UNRESOLVABLE_CONDITION DUMMY_ALIASPAIR
17 );
18 use DBIx::Class::SQLMaker::Util qw( normalize_sqla_condition extract_equality_conditions );
19 use DBIx::Class::ResultSource::FromSpec::Util 'find_join_path_to_alias';
20
21 BEGIN {
22   # De-duplication in _merge_attr() is disabled, but left in for reference
23   # (the merger is used for other things that ought not to be de-duped)
24   *__HM_DEDUP = sub () { 0 };
25 }
26
27 use namespace::clean;
28
29 use overload
30         '0+'     => "count",
31         'bool'   => "_bool",
32         fallback => 1;
33
34 # this is real - CDBICompat overrides it with insanity
35 # yes, prototype won't matter, but that's for now ;)
36 sub _bool () { 1 }
37
38 __PACKAGE__->mk_group_accessors('simple' => qw/_result_class result_source/);
39
40 =head1 NAME
41
42 DBIx::Class::ResultSet - Represents a query used for fetching a set of results.
43
44 =head1 SYNOPSIS
45
46   my $users_rs = $schema->resultset('User');
47   while( $user = $users_rs->next) {
48     print $user->username;
49   }
50
51   my $registered_users_rs = $schema->resultset('User')->search({ registered => 1 });
52   my @cds_in_2005 = $schema->resultset('CD')->search({ year => 2005 })->all();
53
54 =head1 DESCRIPTION
55
56 A ResultSet is an object which stores a set of conditions representing
57 a query. It is the backbone of DBIx::Class (i.e. the really
58 important/useful bit).
59
60 No SQL is executed on the database when a ResultSet is created, it
61 just stores all the conditions needed to create the query.
62
63 A basic ResultSet representing the data of an entire table is returned
64 by calling C<resultset> on a L<DBIx::Class::Schema> and passing in a
65 L<Source|DBIx::Class::Manual::Glossary/ResultSource> name.
66
67   my $users_rs = $schema->resultset('User');
68
69 A new ResultSet is returned from calling L</search> on an existing
70 ResultSet. The new one will contain all the conditions of the
71 original, plus any new conditions added in the C<search> call.
72
73 A ResultSet also incorporates an implicit iterator. L</next> and L</reset>
74 can be used to walk through all the L<DBIx::Class::Row>s the ResultSet
75 represents.
76
77 The query that the ResultSet represents is B<only> executed against
78 the database when these methods are called:
79 L</find>, L</next>, L</all>, L</first>, L</single>, L</count>.
80
81 If a resultset is used in a numeric context it returns the L</count>.
82 However, if it is used in a boolean context it is B<always> true.  So if
83 you want to check if a resultset has any results, you must use C<if $rs
84 != 0>.
85
86 =head1 EXAMPLES
87
88 =head2 Chaining resultsets
89
90 Let's say you've got a query that needs to be run to return some data
91 to the user. But, you have an authorization system in place that
92 prevents certain users from seeing certain information. So, you want
93 to construct the basic query in one method, but add constraints to it in
94 another.
95
96   sub get_data {
97     my $self = shift;
98     my $request = $self->get_request; # Get a request object somehow.
99     my $schema = $self->result_source->schema;
100
101     my $cd_rs = $schema->resultset('CD')->search({
102       title => $request->param('title'),
103       year => $request->param('year'),
104     });
105
106     $cd_rs = $self->apply_security_policy( $cd_rs );
107
108     return $cd_rs->all();
109   }
110
111   sub apply_security_policy {
112     my $self = shift;
113     my ($rs) = @_;
114
115     return $rs->search({
116       subversive => 0,
117     });
118   }
119
120 =head3 Resolving conditions and attributes
121
122 When a resultset is chained from another resultset (e.g.:
123 C<< my $new_rs = $old_rs->search(\%extra_cond, \%attrs) >>), conditions
124 and attributes with the same keys need resolving.
125
126 If any of L</columns>, L</select>, L</as> are present, they reset the
127 original selection, and start the selection "clean".
128
129 The L</join>, L</prefetch>, L</+columns>, L</+select>, L</+as> attributes
130 are merged into the existing ones from the original resultset.
131
132 The L</where> and L</having> attributes, and any search conditions, are
133 merged with an SQL C<AND> to the existing condition from the original
134 resultset.
135
136 All other attributes are overridden by any new ones supplied in the
137 search attributes.
138
139 =head2 Multiple queries
140
141 Since a resultset just defines a query, you can do all sorts of
142 things with it with the same object.
143
144   # Don't hit the DB yet.
145   my $cd_rs = $schema->resultset('CD')->search({
146     title => 'something',
147     year => 2009,
148   });
149
150   # Each of these hits the DB individually.
151   my $count = $cd_rs->count;
152   my $most_recent = $cd_rs->get_column('date_released')->max();
153   my @records = $cd_rs->all;
154
155 And it's not just limited to SELECT statements.
156
157   $cd_rs->delete();
158
159 This is even cooler:
160
161   $cd_rs->create({ artist => 'Fred' });
162
163 Which is the same as:
164
165   $schema->resultset('CD')->create({
166     title => 'something',
167     year => 2009,
168     artist => 'Fred'
169   });
170
171 See: L</search>, L</count>, L</get_column>, L</all>, L</create>.
172
173 =head2 Custom ResultSet classes
174
175 To add methods to your resultsets, you can subclass L<DBIx::Class::ResultSet>, similar to:
176
177   package MyApp::Schema::ResultSet::User;
178
179   use strict;
180   use warnings;
181
182   use base 'DBIx::Class::ResultSet';
183
184   sub active {
185     my $self = shift;
186     $self->search({ $self->current_source_alias . '.active' => 1 });
187   }
188
189   sub unverified {
190     my $self = shift;
191     $self->search({ $self->current_source_alias . '.verified' => 0 });
192   }
193
194   sub created_n_days_ago {
195     my ($self, $days_ago) = @_;
196     $self->search({
197       $self->current_source_alias . '.create_date' => {
198         '<=',
199       $self->result_source->schema->storage->datetime_parser->format_datetime(
200         DateTime->now( time_zone => 'UTC' )->subtract( days => $days_ago )
201       )}
202     });
203   }
204
205   sub users_to_warn { shift->active->unverified->created_n_days_ago(7) }
206
207   1;
208
209 See L<DBIx::Class::Schema/load_namespaces> on how DBIC can discover and
210 automatically attach L<Result|DBIx::Class::Manual::ResultClass>-specific
211 L<ResulSet|DBIx::Class::ResultSet> classes.
212
213 =head3 ResultSet subclassing with Moose and similar constructor-providers
214
215 Using L<Moose> or L<Moo> in your ResultSet classes is usually overkill, but
216 you may find it useful if your ResultSets contain a lot of business logic
217 (e.g. C<has xml_parser>, C<has json>, etc) or if you just prefer to organize
218 your code via roles.
219
220 In order to write custom ResultSet classes with L<Moo> you need to use the
221 following template. The L<BUILDARGS|Moo/BUILDARGS> is necessary due to the
222 unusual signature of the L<constructor provided by DBIC
223 |DBIx::Class::ResultSet/new> C<< ->new($source, \%args) >>.
224
225   use Moo;
226   extends 'DBIx::Class::ResultSet';
227   sub BUILDARGS { $_[2] } # ::RS::new() expects my ($class, $rsrc, $args) = @_
228
229   ...your code...
230
231   1;
232
233 If you want to build your custom ResultSet classes with L<Moose>, you need
234 a similar, though a little more elaborate template in order to interface the
235 inlining of the L<Moose>-provided
236 L<object constructor|Moose::Manual::Construction/WHERE'S THE CONSTRUCTOR?>,
237 with the DBIC one.
238
239   package MyApp::Schema::ResultSet::User;
240
241   use Moose;
242   use MooseX::NonMoose;
243   extends 'DBIx::Class::ResultSet';
244
245   sub BUILDARGS { $_[2] } # ::RS::new() expects my ($class, $rsrc, $args) = @_
246
247   ...your code...
248
249   __PACKAGE__->meta->make_immutable;
250
251   1;
252
253 The L<MooseX::NonMoose> is necessary so that the L<Moose> constructor does not
254 entirely overwrite the DBIC one (in contrast L<Moo> does this automatically).
255 Alternatively, you can skip L<MooseX::NonMoose> and get by with just L<Moose>
256 instead by doing:
257
258   __PACKAGE__->meta->make_immutable(inline_constructor => 0);
259
260 =head1 METHODS
261
262 =head2 new
263
264 =over 4
265
266 =item Arguments: L<$source|DBIx::Class::ResultSource>, L<\%attrs?|/ATTRIBUTES>
267
268 =item Return Value: L<$resultset|/search>
269
270 =back
271
272 The resultset constructor. Takes a source object (usually a
273 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
274 L</ATTRIBUTES> below).  Does not perform any queries -- these are
275 executed as needed by the other methods.
276
277 Generally you never construct a resultset manually. Instead you get one
278 from e.g. a
279 C<< $schema->L<resultset|DBIx::Class::Schema/resultset>('$source_name') >>
280 or C<< $another_resultset->L<search|/search>(...) >> (the later called in
281 scalar context):
282
283   my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
284
285 =over
286
287 =item WARNING
288
289 If called on an object, proxies to L</new_result> instead, so
290
291   my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
292
293 will return a CD object, not a ResultSet, and is equivalent to:
294
295   my $cd = $schema->resultset('CD')->new_result({ title => 'Spoon' });
296
297 Please also keep in mind that many internals call L</new_result> directly,
298 so overloading this method with the idea of intercepting new result object
299 creation B<will not work>. See also warning pertaining to L</create>.
300
301 =back
302
303 =cut
304
305 sub new {
306   my $class = shift;
307
308   if (ref $class) {
309     DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
310     return $class->new_result(@_);
311   }
312
313   my ($source, $attrs) = @_;
314   $source = $source->resolve
315     if $source->isa('DBIx::Class::ResultSourceHandle');
316
317   $attrs = { %{$attrs||{}} };
318   delete @{$attrs}{qw(_last_sqlmaker_alias_map _simple_passthrough_construction)};
319
320   if ($attrs->{page}) {
321     $attrs->{rows} ||= 10;
322   }
323
324   $attrs->{alias} ||= 'me';
325
326   my $self = bless {
327     result_source => $source,
328     cond => $attrs->{where},
329     pager => undef,
330     attrs => $attrs,
331   }, $class;
332
333   # if there is a dark selector, this means we are already in a
334   # chain and the cleanup/sanification was taken care of by
335   # _search_rs already
336   $self->_normalize_selection($attrs)
337     unless $attrs->{_dark_selector};
338
339   $self->result_class(
340     $attrs->{result_class} || $source->result_class
341   );
342
343   $self;
344 }
345
346 =head2 search
347
348 =over 4
349
350 =item Arguments: L<$cond|DBIx::Class::SQLMaker> | undef, L<\%attrs?|/ATTRIBUTES>
351
352 =item Return Value: $resultset (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
353
354 =back
355
356   my @cds    = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
357   my $new_rs = $cd_rs->search({ year => 2005 });
358
359   my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
360                  # year = 2005 OR year = 2004
361
362 In list context, C<< ->all() >> is called implicitly on the resultset, thus
363 returning a list of L<result|DBIx::Class::Manual::ResultClass> objects instead.
364 To avoid that, use L</search_rs>.
365
366 If you need to pass in additional attributes but no additional condition,
367 call it as C<search(undef, \%attrs)>.
368
369   # "SELECT name, artistid FROM $artist_table"
370   my @all_artists = $schema->resultset('Artist')->search(undef, {
371     columns => [qw/name artistid/],
372   });
373
374 For a list of attributes that can be passed to C<search>, see
375 L</ATTRIBUTES>. For more examples of using this function, see
376 L<Searching|DBIx::Class::Manual::Cookbook/SEARCHING>. For a complete
377 documentation for the first argument, see L<SQL::Abstract/"WHERE CLAUSES">
378 and its extension L<DBIx::Class::SQLMaker>.
379
380 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
381
382 =head3 CAVEAT
383
384 Note that L</search> does not process/deflate any of the values passed in the
385 L<SQL::Abstract>-compatible search condition structure. This is unlike other
386 condition-bound methods L</new_result>, L</create> and L</find>. The user must ensure
387 manually that any value passed to this method will stringify to something the
388 RDBMS knows how to deal with. A notable example is the handling of L<DateTime>
389 objects, for more info see:
390 L<DBIx::Class::Manual::Cookbook/Formatting DateTime objects in queries>.
391
392 =cut
393
394 sub search {
395   my $self = shift;
396   my $rs = $self->search_rs( @_ );
397
398   if (wantarray) {
399     DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_WANTARRAY and my $sog = fail_on_internal_wantarray;
400     return $rs->all;
401   }
402   elsif (defined wantarray) {
403     return $rs;
404   }
405   else {
406     # we can be called by a relationship helper, which in
407     # turn may be called in void context due to some braindead
408     # overload or whatever else the user decided to be clever
409     # at this particular day. Thus limit the exception to
410     # external code calls only
411     $self->throw_exception ('->search is *not* a mutator, calling it in void context makes no sense')
412       if (caller)[0] !~ /^\QDBIx::Class::/;
413
414     return ();
415   }
416 }
417
418 =head2 search_rs
419
420 =over 4
421
422 =item Arguments: L<$cond|DBIx::Class::SQLMaker>, L<\%attrs?|/ATTRIBUTES>
423
424 =item Return Value: L<$resultset|/search>
425
426 =back
427
428 This method does the same exact thing as search() except it will
429 always return a resultset, even in list context.
430
431 =cut
432
433 sub search_rs {
434   my $self = shift;
435
436   my $rsrc = $self->result_source;
437   my ($call_cond, $call_attrs);
438
439   # Special-case handling for (undef, undef) or (undef)
440   # Note that (foo => undef) is valid deprecated syntax
441   @_ = () if not scalar grep { defined $_ } @_;
442
443   # just a cond
444   if (@_ == 1) {
445     $call_cond = shift;
446   }
447   # fish out attrs in the ($condref, $attr) case
448   elsif (@_ == 2 and ( ! defined $_[0] or length ref $_[0] ) ) {
449     ($call_cond, $call_attrs) = @_;
450   }
451   elsif (@_ % 2) {
452     $self->throw_exception('Odd number of arguments to search')
453   }
454   # legacy search
455   elsif (@_) {
456     carp_unique 'search( %condition ) is deprecated, use search( \%condition ) instead'
457       unless $rsrc->result_class->isa('DBIx::Class::CDBICompat');
458
459     for my $i (0 .. $#_) {
460       next if $i % 2;
461       $self->throw_exception ('All keys in condition key/value pairs must be plain scalars')
462         if (! defined $_[$i] or length ref $_[$i] );
463     }
464
465     $call_cond = { @_ };
466   }
467
468   # see if we can keep the cache (no $rs changes)
469   my $cache;
470   my %safe = (alias => 1, cache => 1);
471   if ( ! grep { !$safe{$_} } keys %$call_attrs and (
472     ! defined $call_cond
473       or
474     ref $call_cond eq 'HASH' && ! keys %$call_cond
475       or
476     ref $call_cond eq 'ARRAY' && ! @$call_cond
477   )) {
478     $cache = $self->get_cache;
479   }
480
481   my $old_attrs = { %{$self->{attrs}} };
482   my ($old_having, $old_where) = delete @{$old_attrs}{qw(having where)};
483
484   my $new_attrs = { %$old_attrs };
485
486   # take care of call attrs (only if anything is changing)
487   if ($call_attrs and keys %$call_attrs) {
488
489     # copy for _normalize_selection
490     $call_attrs = { %$call_attrs };
491
492     my @selector_attrs = qw/select as columns cols +select +as +columns include_columns/;
493
494     # reset the current selector list if new selectors are supplied
495     delete @{$old_attrs}{(@selector_attrs, '_dark_selector')}
496       if grep { exists $call_attrs->{$_} } qw(columns cols select as);
497
498     # Normalize the new selector list (operates on the passed-in attr structure)
499     # Need to do it on every chain instead of only once on _resolved_attrs, in
500     # order to allow detection of empty vs partial 'as'
501     $call_attrs->{_dark_selector} = $old_attrs->{_dark_selector}
502       if $old_attrs->{_dark_selector};
503     $self->_normalize_selection ($call_attrs);
504
505     # start with blind overwriting merge, exclude selector attrs
506     $new_attrs = { %{$old_attrs}, %{$call_attrs} };
507     delete @{$new_attrs}{@selector_attrs};
508
509     for (@selector_attrs) {
510       $new_attrs->{$_} = $self->_merge_attr($old_attrs->{$_}, $call_attrs->{$_})
511         if ( exists $old_attrs->{$_} or exists $call_attrs->{$_} );
512     }
513
514     # older deprecated name, use only if {columns} is not there
515     if (my $c = delete $new_attrs->{cols}) {
516       carp_unique( "Resultset attribute 'cols' is deprecated, use 'columns' instead" );
517       if ($new_attrs->{columns}) {
518         carp "Resultset specifies both the 'columns' and the legacy 'cols' attributes - ignoring 'cols'";
519       }
520       else {
521         $new_attrs->{columns} = $c;
522       }
523     }
524
525
526     # join/prefetch use their own crazy merging heuristics
527     foreach my $key (qw/join prefetch/) {
528       $new_attrs->{$key} = $self->_merge_joinpref_attr($old_attrs->{$key}, $call_attrs->{$key})
529         if exists $call_attrs->{$key};
530     }
531
532     # stack binds together
533     $new_attrs->{bind} = [ @{ $old_attrs->{bind} || [] }, @{ $call_attrs->{bind} || [] } ];
534   }
535
536
537   for ($old_where, $call_cond) {
538     if (defined $_) {
539       $new_attrs->{where} = $self->_stack_cond (
540         $_, $new_attrs->{where}
541       );
542     }
543   }
544
545   if (defined $old_having) {
546     $new_attrs->{having} = $self->_stack_cond (
547       $old_having, $new_attrs->{having}
548     )
549   }
550
551   my $rs = (ref $self)->new($rsrc, $new_attrs);
552
553   $rs->set_cache($cache) if ($cache);
554
555   return $rs;
556 }
557
558 sub _normalize_selection {
559   my ($self, $attrs) = @_;
560
561   # legacy syntax
562   if ( exists $attrs->{include_columns} ) {
563     carp_unique( "Resultset attribute 'include_columns' is deprecated, use '+columns' instead" );
564     $attrs->{'+columns'} = $self->_merge_attr(
565       $attrs->{'+columns'}, delete $attrs->{include_columns}
566     );
567   }
568
569   # columns are always placed first, however
570
571   # Keep the X vs +X separation until _resolved_attrs time - this allows to
572   # delay the decision on whether to use a default select list ($rsrc->columns)
573   # allowing stuff like the remove_columns helper to work
574   #
575   # select/as +select/+as pairs need special handling - the amount of select/as
576   # elements in each pair does *not* have to be equal (think multicolumn
577   # selectors like distinct(foo, bar) ). If the selector is bare (no 'as'
578   # supplied at all) - try to infer the alias, either from the -as parameter
579   # of the selector spec, or use the parameter whole if it looks like a column
580   # name (ugly legacy heuristic). If all fails - leave the selector bare (which
581   # is ok as well), but make sure no more additions to the 'as' chain take place
582   for my $pref ('', '+') {
583
584     my ($sel, $as) = map {
585       my $key = "${pref}${_}";
586
587       my $val = [ ref $attrs->{$key} eq 'ARRAY'
588         ? @{$attrs->{$key}}
589         : $attrs->{$key} || ()
590       ];
591       delete $attrs->{$key};
592       $val;
593     } qw/select as/;
594
595     if (! @$as and ! @$sel ) {
596       next;
597     }
598     elsif (@$as and ! @$sel) {
599       $self->throw_exception(
600         "Unable to handle ${pref}as specification (@$as) without a corresponding ${pref}select"
601       );
602     }
603     elsif( ! @$as ) {
604       # no as part supplied at all - try to deduce (unless explicit end of named selection is declared)
605       # if any @$as has been supplied we assume the user knows what (s)he is doing
606       # and blindly keep stacking up pieces
607       unless ($attrs->{_dark_selector}) {
608         SELECTOR:
609         for (@$sel) {
610           if ( ref $_ eq 'HASH' and exists $_->{-as} ) {
611             push @$as, $_->{-as};
612           }
613           # assume any plain no-space, no-parenthesis string to be a column spec
614           # FIXME - this is retarded but is necessary to support shit like 'count(foo)'
615           elsif ( ! ref $_ and $_ =~ /^ [^\s\(\)]+ $/x) {
616             push @$as, $_;
617           }
618           # if all else fails - raise a flag that no more aliasing will be allowed
619           else {
620             $attrs->{_dark_selector} = {
621               plus_stage => $pref,
622               string => do {
623                 local $Data::Dumper::Indent = 0;
624                 dump_value $_;
625               },
626             };
627             last SELECTOR;
628           }
629         }
630       }
631     }
632     elsif (@$as < @$sel) {
633       $self->throw_exception(
634         "Unable to handle an ${pref}as specification (@$as) with less elements than the corresponding ${pref}select"
635       );
636     }
637     elsif ($pref and $attrs->{_dark_selector}) {
638       $self->throw_exception(
639         "Unable to process named '+select', resultset contains an unnamed selector $attrs->{_dark_selector}{string}"
640       );
641     }
642
643
644     # merge result
645     $attrs->{"${pref}select"} = $self->_merge_attr($attrs->{"${pref}select"}, $sel);
646     $attrs->{"${pref}as"} = $self->_merge_attr($attrs->{"${pref}as"}, $as);
647   }
648 }
649
650 sub _stack_cond {
651   my ($self, $left, $right) = @_;
652
653   (
654     (ref $_ eq 'ARRAY' and !@$_)
655       or
656     (ref $_ eq 'HASH' and ! keys %$_)
657   ) and $_ = undef for ($left, $right);
658
659   return(
660     # either one of the two undef
661     ( (defined $left) xor (defined $right) )  ? ( defined $left ? $left : $right )
662
663     # both undef
664   : ( ! defined $left )                       ? undef
665
666                                               : { -and => [$left, $right] }
667   );
668 }
669
670 =head2 search_literal
671
672 B<CAVEAT>: C<search_literal> is provided for Class::DBI compatibility and
673 should only be used in that context. C<search_literal> is a convenience
674 method. It is equivalent to calling C<< $schema->search(\[]) >>, but if you
675 want to ensure columns are bound correctly, use L</search>.
676
677 See L<DBIx::Class::Manual::Cookbook/SEARCHING> and
678 L<DBIx::Class::Manual::FAQ/Searching> for searching techniques that do not
679 require C<search_literal>.
680
681 =over 4
682
683 =item Arguments: $sql_fragment, @standalone_bind_values
684
685 =item Return Value: L<$resultset|/search> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
686
687 =back
688
689   my @cds   = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
690   my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
691
692 Pass a literal chunk of SQL to be added to the conditional part of the
693 resultset query.
694
695 Example of how to use C<search> instead of C<search_literal>
696
697   my @cds = $cd_rs->search_literal('cdid = ? AND (artist = ? OR artist = ?)', (2, 1, 2));
698   my @cds = $cd_rs->search(\[ 'cdid = ? AND (artist = ? OR artist = ?)', [ 'cdid', 2 ], [ 'artist', 1 ], [ 'artist', 2 ] ]);
699
700 =cut
701
702 sub search_literal {
703   my ($self, $sql, @bind) = @_;
704   my $attr;
705   if ( @bind && ref($bind[-1]) eq 'HASH' ) {
706     $attr = pop @bind;
707   }
708   return $self->search(\[ $sql, map [ {} => $_ ], @bind ], ($attr || () ));
709 }
710
711 =head2 find
712
713 =over 4
714
715 =item Arguments: \%columns_values | @pk_values, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
716
717 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
718
719 =back
720
721 Finds and returns a single row based on supplied criteria. Takes either a
722 hashref with the same format as L</create> (including inference of foreign
723 keys from related objects), or a list of primary key values in the same
724 order as the L<primary columns|DBIx::Class::ResultSource/primary_columns>
725 declaration on the L</result_source>.
726
727 In either case an attempt is made to combine conditions already existing on
728 the resultset with the condition passed to this method.
729
730 To aid with preparing the correct query for the storage you may supply the
731 C<key> attribute, which is the name of a
732 L<unique constraint|DBIx::Class::ResultSource/add_unique_constraint> (the
733 unique constraint corresponding to the
734 L<primary columns|DBIx::Class::ResultSource/primary_columns> is always named
735 C<primary>). If the C<key> attribute has been supplied, and DBIC is unable
736 to construct a query that satisfies the named unique constraint fully (
737 non-NULL values for each column member of the constraint) an exception is
738 thrown.
739
740 If no C<key> is specified, the search is carried over all unique constraints
741 which are fully defined by the available condition.
742
743 If no such constraint is found, C<find> currently defaults to a simple
744 C<< search->(\%column_values) >> which may or may not do what you expect.
745 Note that this fallback behavior may be deprecated in further versions. If
746 you need to search with arbitrary conditions - use L</search>. If the query
747 resulting from this fallback produces more than one row, a warning to the
748 effect is issued, though only the first row is constructed and returned as
749 C<$result_object>.
750
751 In addition to C<key>, L</find> recognizes and applies standard
752 L<resultset attributes|/ATTRIBUTES> in the same way as L</search> does.
753
754 Note that if you have extra concerns about the correctness of the resulting
755 query you need to specify the C<key> attribute and supply the entire condition
756 as an argument to find (since it is not always possible to perform the
757 combination of the resultset condition with the supplied one, especially if
758 the resultset condition contains literal sql).
759
760 For example, to find a row by its primary key:
761
762   my $cd = $schema->resultset('CD')->find(5);
763
764 You can also find a row by a specific unique constraint:
765
766   my $cd = $schema->resultset('CD')->find(
767     {
768       artist => 'Massive Attack',
769       title  => 'Mezzanine',
770     },
771     { key => 'cd_artist_title' }
772   );
773
774 See also L</find_or_create> and L</update_or_create>.
775
776 =cut
777
778 sub find {
779   my $self = shift;
780   my $attrs = (@_ > 1 && ref $_[-1] eq 'HASH' ? pop(@_) : {});
781
782
783   my $constraint_name;
784   if (exists $attrs->{key}) {
785     $constraint_name = defined $attrs->{key}
786       ? $attrs->{key}
787       : $self->throw_exception("An undefined 'key' resultset attribute makes no sense")
788     ;
789   }
790
791   # Parse out the condition from input
792   my $call_cond;
793
794   my $rsrc = $self->result_source;
795
796   if (ref $_[0] eq 'HASH') {
797     $call_cond = { %{$_[0]} };
798   }
799   else {
800     # if only values are supplied we need to default to 'primary'
801     $constraint_name = 'primary' unless defined $constraint_name;
802
803     my @c_cols = $rsrc->unique_constraint_columns($constraint_name);
804
805     $self->throw_exception(
806       "No constraint columns, maybe a malformed '$constraint_name' constraint?"
807     ) unless @c_cols;
808
809     $self->throw_exception (
810       'find() expects either a column/value hashref, or a list of values '
811     . "corresponding to the columns of the specified unique constraint '$constraint_name'"
812     ) unless @c_cols == @_;
813
814     @{$call_cond}{@c_cols} = @_;
815   }
816
817   # process relationship data if any
818   my $rel_list;
819
820   for my $key (keys %$call_cond) {
821     if (
822       # either a structure or a result-ish object
823       length ref($call_cond->{$key})
824         and
825       ( $rel_list ||= { map { $_ => 1 } $rsrc->relationships } )
826         ->{$key}
827         and
828       ! is_literal_value( $call_cond->{$key} )
829         and
830       # implicitly skip has_many's (likely MC), via the delete()
831       ( ref( my $foreign_val = delete $call_cond->{$key} ) ne 'ARRAY' )
832     ) {
833
834       # FIXME: it seems wrong that relationship conditions take precedence...?
835       $call_cond = {
836         %$call_cond,
837
838         %{ $rsrc->resolve_relationship_condition(
839           require_join_free_values => 1,
840           rel_name => $key,
841           foreign_values => (
842             (! defined blessed $foreign_val) ? $foreign_val : do {
843
844               my $f_result_class = $rsrc->related_source($key)->result_class;
845
846               unless( $foreign_val->isa($f_result_class) ) {
847
848                 $self->throw_exception(
849                   'Objects supplied to find() must inherit from '
850                 . "'$DBIx::Class::ResultSource::__expected_result_class_isa'"
851                 ) unless $foreign_val->isa(
852                   $DBIx::Class::ResultSource::__expected_result_class_isa
853                 );
854
855                 carp_unique(
856                   "Objects supplied to find() via '$key' usually should inherit from "
857                 . "the related ResultClass ('$f_result_class'), perhaps you've made "
858                 . 'a mistake?'
859                 );
860               }
861
862               +{ $foreign_val->get_columns };
863             }
864           ),
865
866           # an API where these are optional would be too cumbersome,
867           # instead always pass in some dummy values
868           DUMMY_ALIASPAIR,
869         )->{join_free_values} },
870       };
871     }
872   }
873
874   my $alias = exists $attrs->{alias} ? $attrs->{alias} : $self->{attrs}{alias};
875   my $final_cond;
876   if (defined $constraint_name) {
877     $final_cond = $self->_qualify_cond_columns (
878
879       $rsrc->_minimal_valueset_satisfying_constraint(
880         constraint_name => $constraint_name,
881         values => ($self->_merge_with_rscond($call_cond))[0],
882         carp_on_nulls => 1,
883       ),
884
885       $alias,
886     );
887   }
888   elsif ($self->{attrs}{accessor} and $self->{attrs}{accessor} eq 'single') {
889     # This means that we got here after a merger of relationship conditions
890     # in ::Relationship::Base::search_related (the row method), and furthermore
891     # the relationship is of the 'single' type. This means that the condition
892     # provided by the relationship (already attached to $self) is sufficient,
893     # as there can be only one row in the database that would satisfy the
894     # relationship
895   }
896   else {
897     my (@unique_queries, %seen_column_combinations, $ci, @fc_exceptions);
898
899     # no key was specified - fall down to heuristics mode:
900     # run through all unique queries registered on the resultset, and
901     # 'OR' all qualifying queries together
902     #
903     # always start from 'primary' if it exists at all
904     for my $c_name ( sort {
905         $a eq 'primary' ? -1
906       : $b eq 'primary' ? 1
907       : $a cmp $b
908     } $rsrc->unique_constraint_names) {
909
910       next if $seen_column_combinations{
911         join "\x00", sort $rsrc->unique_constraint_columns($c_name)
912       }++;
913
914       dbic_internal_try {
915         push @unique_queries, $self->_qualify_cond_columns(
916           $rsrc->_minimal_valueset_satisfying_constraint(
917             constraint_name => $c_name,
918             values => ($self->_merge_with_rscond($call_cond))[0],
919             columns_info => ($ci ||= $rsrc->columns_info),
920           ),
921           $alias
922         );
923       }
924       dbic_internal_catch {
925         push @fc_exceptions, $_ if $_ =~ /\bFilterColumn\b/;
926       };
927     }
928
929     $final_cond =
930         @unique_queries   ? \@unique_queries
931       : @fc_exceptions    ? $self->throw_exception(join "; ", map { $_ =~ /(.*) at .+ line \d+$/s } @fc_exceptions )
932       :                     $self->_non_unique_find_fallback ($call_cond, $attrs)
933     ;
934   }
935
936   # Run the query, passing the result_class since it should propagate for find
937   my $rs = $self->search ($final_cond, {result_class => $self->result_class, %$attrs});
938   if ($rs->_resolved_attrs->{collapse}) {
939     my $row = $rs->next;
940     carp "Query returned more than one row" if $rs->next;
941     return $row;
942   }
943   else {
944     return $rs->single;
945   }
946 }
947
948 # This is a stop-gap method as agreed during the discussion on find() cleanup:
949 # http://lists.scsys.co.uk/pipermail/dbix-class/2010-October/009535.html
950 #
951 # It is invoked when find() is called in legacy-mode with insufficiently-unique
952 # condition. It is provided for overrides until a saner way forward is devised
953 #
954 # *NOTE* This is not a public method, and it's *GUARANTEED* to disappear down
955 # the road. Please adjust your tests accordingly to catch this situation early
956 # DBIx::Class::ResultSet->can('_non_unique_find_fallback') is reasonable
957 #
958 # The method will not be removed without an adequately complete replacement
959 # for strict-mode enforcement
960 sub _non_unique_find_fallback {
961   my ($self, $cond, $attrs) = @_;
962
963   return $self->_qualify_cond_columns(
964     $cond,
965     exists $attrs->{alias}
966       ? $attrs->{alias}
967       : $self->{attrs}{alias}
968   );
969 }
970
971
972 sub _qualify_cond_columns {
973   my ($self, $cond, $alias) = @_;
974
975   my %aliased = %$cond;
976   for (keys %aliased) {
977     $aliased{"$alias.$_"} = delete $aliased{$_}
978       if $_ !~ /\./;
979   }
980
981   return \%aliased;
982 }
983
984 sub _build_unique_cond {
985   carp_unique sprintf
986     '_build_unique_cond is a private method, and moreover is about to go '
987   . 'away. Please contact the development team at %s if you believe you '
988   . 'have a genuine use for this method, in order to discuss alternatives.',
989     DBIx::Class::_ENV_::HELP_URL,
990   ;
991
992   my ($self, $constraint_name, $cond, $croak_on_null) = @_;
993
994   $self->result_source->_minimal_valueset_satisfying_constraint(
995     constraint_name => $constraint_name,
996     values => $cond,
997     carp_on_nulls => !$croak_on_null
998   );
999 }
1000
1001 =head2 search_related
1002
1003 =over 4
1004
1005 =item Arguments: $rel_name, $cond?, L<\%attrs?|/ATTRIBUTES>
1006
1007 =item Return Value: L<$resultset|/search> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
1008
1009 =back
1010
1011   $new_rs = $cd_rs->search_related('artist', {
1012     name => 'Emo-R-Us',
1013   });
1014
1015 Searches the specified relationship, optionally specifying a condition and
1016 attributes for matching records. See L</ATTRIBUTES> for more information.
1017
1018 In list context, C<< ->all() >> is called implicitly on the resultset, thus
1019 returning a list of result objects instead. To avoid that, use L</search_related_rs>.
1020
1021 See also L</search_related_rs>.
1022
1023 =cut
1024
1025 sub search_related :DBIC_method_is_indirect_sugar {
1026   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
1027   return shift->related_resultset(shift)->search(@_);
1028 }
1029
1030 =head2 search_related_rs
1031
1032 This method works exactly the same as search_related, except that
1033 it guarantees a resultset, even in list context.
1034
1035 =cut
1036
1037 sub search_related_rs :DBIC_method_is_indirect_sugar {
1038   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
1039   return shift->related_resultset(shift)->search_rs(@_);
1040 }
1041
1042 =head2 cursor
1043
1044 =over 4
1045
1046 =item Arguments: none
1047
1048 =item Return Value: L<$cursor|DBIx::Class::Cursor>
1049
1050 =back
1051
1052 Returns a storage-driven cursor to the given resultset. See
1053 L<DBIx::Class::Cursor> for more information.
1054
1055 =cut
1056
1057 sub cursor {
1058   my $self = shift;
1059
1060   return $self->{cursor} ||= do {
1061     my $attrs = $self->_resolved_attrs;
1062     $self->result_source->schema->storage->select(
1063       $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
1064     );
1065   };
1066 }
1067
1068 =head2 single
1069
1070 =over 4
1071
1072 =item Arguments: L<$cond?|DBIx::Class::SQLMaker>
1073
1074 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
1075
1076 =back
1077
1078   my $cd = $schema->resultset('CD')->single({ year => 2001 });
1079
1080 Inflates the first result without creating a cursor if the resultset has
1081 any records in it; if not returns C<undef>. Used by L</find> as a lean version
1082 of L</search>.
1083
1084 While this method can take an optional search condition (just like L</search>)
1085 being a fast-code-path it does not recognize search attributes. If you need to
1086 add extra joins or similar, call L</search> and then chain-call L</single> on the
1087 L<DBIx::Class::ResultSet> returned.
1088
1089 =over
1090
1091 =item B<Note>
1092
1093 As of 0.08100, this method enforces the assumption that the preceding
1094 query returns only one row. If more than one row is returned, you will receive
1095 a warning:
1096
1097   Query returned more than one row
1098
1099 In this case, you should be using L</next> or L</find> instead, or if you really
1100 know what you are doing, use the L</rows> attribute to explicitly limit the size
1101 of the resultset.
1102
1103 This method will also throw an exception if it is called on a resultset prefetching
1104 has_many, as such a prefetch implies fetching multiple rows from the database in
1105 order to assemble the resulting object.
1106
1107 =back
1108
1109 =cut
1110
1111 sub single {
1112   my ($self, $where) = @_;
1113   if(@_ > 2) {
1114       $self->throw_exception('single() only takes search conditions, no attributes. You want ->search( $cond, $attrs )->single()');
1115   }
1116
1117   my $attrs = { %{$self->_resolved_attrs} };
1118
1119   $self->throw_exception(
1120     'single() can not be used on resultsets collapsing a has_many. Use find( \%cond ) or next() instead'
1121   ) if $attrs->{collapse};
1122
1123   if ($where) {
1124     if (defined $attrs->{where}) {
1125       $attrs->{where} = {
1126         '-and' =>
1127             [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
1128                $where, delete $attrs->{where} ]
1129       };
1130     } else {
1131       $attrs->{where} = $where;
1132     }
1133   }
1134
1135   my $data = [ $self->result_source->schema->storage->select_single(
1136     $attrs->{from}, $attrs->{select},
1137     $attrs->{where}, $attrs
1138   )];
1139
1140   return undef unless @$data;
1141   $self->{_stashed_rows} = [ $data ];
1142   $self->_construct_results->[0];
1143 }
1144
1145 =head2 get_column
1146
1147 =over 4
1148
1149 =item Arguments: L<$cond?|DBIx::Class::SQLMaker>
1150
1151 =item Return Value: L<$resultsetcolumn|DBIx::Class::ResultSetColumn>
1152
1153 =back
1154
1155   my $max_length = $rs->get_column('length')->max;
1156
1157 Returns a L<DBIx::Class::ResultSetColumn> instance for a column of the ResultSet.
1158
1159 =cut
1160
1161 sub get_column {
1162   DBIx::Class::ResultSetColumn->new(@_);
1163 }
1164
1165 =head2 search_like
1166
1167 =over 4
1168
1169 =item Arguments: L<$cond|DBIx::Class::SQLMaker>, L<\%attrs?|/ATTRIBUTES>
1170
1171 =item Return Value: L<$resultset|/search> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
1172
1173 =back
1174
1175   # WHERE title LIKE '%blue%'
1176   $cd_rs = $rs->search_like({ title => '%blue%'});
1177
1178 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
1179 that this is simply a convenience method retained for ex Class::DBI users.
1180 You most likely want to use L</search> with specific operators.
1181
1182 For more information, see L<DBIx::Class::Manual::Cookbook>.
1183
1184 This method is deprecated and will be removed in 0.09. Use L<search()|/search>
1185 instead. An example conversion is:
1186
1187   ->search_like({ foo => 'bar' });
1188
1189   # Becomes
1190
1191   ->search({ foo => { like => 'bar' } });
1192
1193 =cut
1194
1195 sub search_like {
1196   my $class = shift;
1197   carp_unique (
1198     'search_like() is deprecated and will be removed in DBIC version 0.09.'
1199    .' Instead use ->search({ x => { -like => "y%" } })'
1200    .' (note the outer pair of {}s - they are important!)'
1201   );
1202   my $attrs = (@_ > 1 && ref $_[-1] eq 'HASH' ? pop(@_) : {});
1203   my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
1204   $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
1205   return $class->search($query, { %$attrs });
1206 }
1207
1208 =head2 slice
1209
1210 =over 4
1211
1212 =item Arguments: $first, $last
1213
1214 =item Return Value: L<$resultset|/search> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
1215
1216 =back
1217
1218 Returns a resultset or object list representing a subset of elements from the
1219 resultset slice is called on. Indexes are from 0, i.e., to get the first
1220 three records, call:
1221
1222   my ($one, $two, $three) = $rs->slice(0, 2);
1223
1224 =cut
1225
1226 sub slice {
1227   my ($self, $min, $max) = @_;
1228   my $attrs = {}; # = { %{ $self->{attrs} || {} } };
1229   $attrs->{offset} = $self->{attrs}{offset} || 0;
1230   $attrs->{offset} += $min;
1231   $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
1232   return $self->search(undef, $attrs);
1233 }
1234
1235 =head2 next
1236
1237 =over 4
1238
1239 =item Arguments: none
1240
1241 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
1242
1243 =back
1244
1245 Returns the next element in the resultset (C<undef> is there is none).
1246
1247 Can be used to efficiently iterate over records in the resultset:
1248
1249   my $rs = $schema->resultset('CD')->search;
1250   while (my $cd = $rs->next) {
1251     print $cd->title;
1252   }
1253
1254 Note that you need to store the resultset object, and call C<next> on it.
1255 Calling C<< resultset('Table')->next >> repeatedly will always return the
1256 first record from the resultset.
1257
1258 =cut
1259
1260 sub next {
1261   my ($self) = @_;
1262
1263   if (my $cache = $self->get_cache) {
1264     $self->{all_cache_position} ||= 0;
1265     return $cache->[$self->{all_cache_position}++];
1266   }
1267
1268   if ($self->{attrs}{cache}) {
1269     delete $self->{pager};
1270     $self->{all_cache_position} = 1;
1271     return ($self->all)[0];
1272   }
1273
1274   return shift(@{$self->{_stashed_results}}) if @{ $self->{_stashed_results}||[] };
1275
1276   $self->{_stashed_results} = $self->_construct_results
1277     or return undef;
1278
1279   return shift @{$self->{_stashed_results}};
1280 }
1281
1282 # Constructs as many results as it can in one pass while respecting
1283 # cursor laziness. Several modes of operation:
1284 #
1285 # * Always builds everything present in @{$self->{_stashed_rows}}
1286 # * If called with $fetch_all true - pulls everything off the cursor and
1287 #   builds all result structures (or objects) in one pass
1288 # * If $self->_resolved_attrs->{collapse} is true, checks the order_by
1289 #   and if the resultset is ordered properly by the left side:
1290 #   * Fetches stuff off the cursor until the "master object" changes,
1291 #     and saves the last extra row (if any) in @{$self->{_stashed_rows}}
1292 #   OR
1293 #   * Just fetches, and collapses/constructs everything as if $fetch_all
1294 #     was requested (there is no other way to collapse except for an
1295 #     eager cursor)
1296 # * If no collapse is requested - just get the next row, construct and
1297 #   return
1298 sub _construct_results {
1299   my ($self, $fetch_all) = @_;
1300
1301   my $rsrc = $self->result_source;
1302   my $attrs = $self->_resolved_attrs;
1303
1304   if (
1305     ! $fetch_all
1306       and
1307     ! $attrs->{order_by}
1308       and
1309     $attrs->{collapse}
1310       and
1311     my @pcols = $rsrc->primary_columns
1312   ) {
1313     # default order for collapsing unless the user asked for something
1314     $attrs->{order_by} = [ map { join '.', $attrs->{alias}, $_} @pcols ];
1315     $attrs->{_ordered_for_collapse} = 1;
1316     $attrs->{_order_is_artificial} = 1;
1317   }
1318
1319   # this will be used as both initial raw-row collector AND as a RV of
1320   # _construct_results. Not regrowing the array twice matters a lot...
1321   # a surprising amount actually
1322   my $rows = delete $self->{_stashed_rows};
1323
1324   my $cursor; # we may not need one at all
1325
1326   my $did_fetch_all = $fetch_all;
1327
1328   if ($fetch_all) {
1329     # FIXME SUBOPTIMAL - we can do better, cursor->next/all (well diff. methods) should return a ref
1330     $rows = [ ($rows ? @$rows : ()), $self->cursor->all ];
1331   }
1332   elsif( $attrs->{collapse} ) {
1333
1334     # a cursor will need to be closed over in case of collapse
1335     $cursor = $self->cursor;
1336
1337     $attrs->{_ordered_for_collapse} = (
1338       (
1339         $attrs->{order_by}
1340           and
1341         $rsrc->schema
1342               ->storage
1343                ->_extract_colinfo_of_stable_main_source_order_by_portion($attrs)
1344       ) ? 1 : 0
1345     ) unless defined $attrs->{_ordered_for_collapse};
1346
1347     if (! $attrs->{_ordered_for_collapse}) {
1348       $did_fetch_all = 1;
1349
1350       # instead of looping over ->next, use ->all in stealth mode
1351       # *without* calling a ->reset afterwards
1352       # FIXME ENCAPSULATION - encapsulation breach, cursor method additions pending
1353       if (! $cursor->{_done}) {
1354         $rows = [ ($rows ? @$rows : ()), $cursor->all ];
1355         $cursor->{_done} = 1;
1356       }
1357     }
1358   }
1359
1360   if (! $did_fetch_all and ! @{$rows||[]} ) {
1361     # FIXME SUBOPTIMAL - we can do better, cursor->next/all (well diff. methods) should return a ref
1362     $cursor ||= $self->cursor;
1363     if (scalar (my @r = $cursor->next) ) {
1364       $rows = [ \@r ];
1365     }
1366   }
1367
1368   return undef unless @{$rows||[]};
1369
1370   # sanity check - people are too clever for their own good
1371   if ($attrs->{collapse} and my $aliastypes = $attrs->{_last_sqlmaker_alias_map} ) {
1372
1373     my $multiplied_selectors;
1374     for my $sel_alias ( grep { $_ ne $attrs->{alias} } keys %{ $aliastypes->{selecting} } ) {
1375       if (
1376         $aliastypes->{multiplying}{$sel_alias}
1377           or
1378         $aliastypes->{premultiplied}{$sel_alias}
1379       ) {
1380         $multiplied_selectors->{$_} = 1 for values %{$aliastypes->{selecting}{$sel_alias}{-seen_columns}}
1381       }
1382     }
1383
1384     for my $i (0 .. $#{$attrs->{as}} ) {
1385       my $sel = $attrs->{select}[$i];
1386
1387       if (ref $sel eq 'SCALAR') {
1388         $sel = $$sel;
1389       }
1390       elsif( ref $sel eq 'REF' and ref $$sel eq 'ARRAY' ) {
1391         $sel = $$sel->[0];
1392       }
1393
1394       $self->throw_exception(
1395         'Result collapse not possible - selection from a has_many source redirected to the main object'
1396       ) if ($multiplied_selectors->{$sel} and $attrs->{as}[$i] !~ /\./);
1397     }
1398   }
1399
1400   # hotspot - skip the setter
1401   my $res_class = $self->_result_class;
1402
1403   my $inflator_cref = $self->{_result_inflator}{cref} ||= do {
1404     $res_class->can ('inflate_result')
1405       or $self->throw_exception("Inflator $res_class does not provide an inflate_result() method");
1406   };
1407
1408   my $infmap = $attrs->{as};
1409
1410   $self->{_result_inflator}{is_core_row} = ( (
1411     $inflator_cref
1412       ==
1413     ( \&DBIx::Class::Row::inflate_result || die "No ::Row::inflate_result() - can't happen" )
1414   ) ? 1 : 0 ) unless defined $self->{_result_inflator}{is_core_row};
1415
1416   $self->{_result_inflator}{is_hri} = ( (
1417     ! $self->{_result_inflator}{is_core_row}
1418       and
1419     $inflator_cref == \&DBIx::Class::ResultClass::HashRefInflator::inflate_result
1420   ) ? 1 : 0 ) unless defined $self->{_result_inflator}{is_hri};
1421
1422
1423   if ($attrs->{_simple_passthrough_construction}) {
1424     # construct a much simpler array->hash folder for the one-table HRI cases right here
1425     if ($self->{_result_inflator}{is_hri}) {
1426       for my $r (@$rows) {
1427         $r = { map { $infmap->[$_] => $r->[$_] } 0..$#$infmap };
1428       }
1429     }
1430     # FIXME SUBOPTIMAL this is a very very very hot spot
1431     # while rather optimal we can *still* do much better, by
1432     # building a smarter Row::inflate_result(), and
1433     # switch to feeding it data via a much leaner interface
1434     #
1435     # crude unscientific benchmarking indicated the shortcut eval is not worth it for
1436     # this particular resultset size
1437     elsif ( $self->{_result_inflator}{is_core_row} and @$rows < 60 ) {
1438       for my $r (@$rows) {
1439         $r = $inflator_cref->($res_class, $rsrc, { map { $infmap->[$_] => $r->[$_] } (0..$#$infmap) } );
1440       }
1441     }
1442     else {
1443       eval sprintf (
1444         ( $self->{_result_inflator}{is_core_row}
1445           ? '$_ = $inflator_cref->($res_class, $rsrc, { %s }) for @$rows'
1446           # a custom inflator may be a multiplier/reductor - put it in direct list ctx
1447           : '@$rows = map { $inflator_cref->($res_class, $rsrc, { %s } ) } @$rows'
1448         ),
1449         ( join (', ', map { "\$infmap->[$_] => \$_->[$_]" } 0..$#$infmap ) )
1450       ) . '; 1' or die;
1451     }
1452   }
1453   else {
1454     my $parser_type =
1455         $self->{_result_inflator}{is_hri}       ? 'hri'
1456       : $self->{_result_inflator}{is_core_row}  ? 'classic_pruning'
1457       :                                           'classic_nonpruning'
1458     ;
1459
1460     unless( $self->{_row_parser}{$parser_type}{cref} ) {
1461
1462       # $args and $attrs to _mk_row_parser are separated to delineate what is
1463       # core collapser stuff and what is dbic $rs specific
1464       $self->{_row_parser}{$parser_type}{src} = $rsrc->_mk_row_parser({
1465         inflate_map => $infmap,
1466         collapse => $attrs->{collapse},
1467         premultiplied => $attrs->{_main_source_premultiplied},
1468         hri_style => $self->{_result_inflator}{is_hri},
1469         prune_null_branches => $self->{_result_inflator}{is_hri} || $self->{_result_inflator}{is_core_row},
1470       }, $attrs);
1471
1472       $self->{_row_parser}{$parser_type}{cref} = do {
1473         package # hide form PAUSE
1474           DBIx::Class::__GENERATED_ROW_PARSER__;
1475
1476         eval $self->{_row_parser}{$parser_type}{src};
1477       } || die $@;
1478     }
1479
1480     # this needs to close over the *current* cursor, hence why it is not cached above
1481     my $next_cref = ($did_fetch_all or ! $attrs->{collapse})
1482       ? undef
1483       : sub {
1484         # FIXME SUBOPTIMAL - we can do better, cursor->next/all (well diff. methods) should return a ref
1485         my @r = $cursor->next or return;
1486         \@r
1487       }
1488     ;
1489
1490     $self->{_row_parser}{$parser_type}{cref}->(
1491       $rows,
1492       $next_cref,
1493       ( $self->{_stashed_rows} = [] ),
1494       ( my $null_violations = {} ),
1495     );
1496
1497     $self->throw_exception(
1498       'Collapse aborted - the following columns are declared (or defaulted to) '
1499     . 'non-nullable within DBIC but NULLs were retrieved from storage: '
1500     . join( ', ', map { "'$infmap->[$_]'" } sort { $a <=> $b } keys %$null_violations )
1501     . ' within data row ' . dump_value({
1502       map {
1503         $infmap->[$_] =>
1504           ( ! defined $self->{_stashed_rows}[0][$_] or length $self->{_stashed_rows}[0][$_] < 50 )
1505             ? $self->{_stashed_rows}[0][$_]
1506             : substr( $self->{_stashed_rows}[0][$_], 0, 50 ) . '...'
1507       } 0 .. $#{$self->{_stashed_rows}[0]}
1508     })
1509     ) if keys %$null_violations;
1510
1511     # simple in-place substitution, does not regrow $rows
1512     if ($self->{_result_inflator}{is_core_row}) {
1513       $_ = $inflator_cref->($res_class, $rsrc, @$_) for @$rows
1514     }
1515     # Special-case multi-object HRI - there is no $inflator_cref pass at all
1516     elsif ( ! $self->{_result_inflator}{is_hri} ) {
1517       # the inflator may be a multiplier/reductor - put it in list ctx
1518       @$rows = map { $inflator_cref->($res_class, $rsrc, @$_) } @$rows;
1519     }
1520   }
1521
1522   # The @$rows check seems odd at first - why wouldn't we want to warn
1523   # regardless? The issue is things like find() etc, where the user
1524   # *knows* only one result will come back. In these cases the ->all
1525   # is not a pessimization, but rather something we actually want
1526   carp_unique(
1527     'Unable to properly collapse has_many results in iterator mode due '
1528   . 'to order criteria - performed an eager cursor slurp underneath. '
1529   . 'Consider using ->all() instead'
1530   ) if ( ! $fetch_all and @$rows > 1 );
1531
1532   return $rows;
1533 }
1534
1535 =head2 result_source
1536
1537 =over 4
1538
1539 =item Arguments: L<$result_source?|DBIx::Class::ResultSource>
1540
1541 =item Return Value: L<$result_source|DBIx::Class::ResultSource>
1542
1543 =back
1544
1545 An accessor for the primary ResultSource object from which this ResultSet
1546 is derived.
1547
1548 =head2 result_class
1549
1550 =over 4
1551
1552 =item Arguments: $result_class?
1553
1554 =item Return Value: $result_class
1555
1556 =back
1557
1558 An accessor for the class to use when creating result objects. Defaults to
1559 C<< result_source->result_class >> - which in most cases is the name of the
1560 L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class.
1561
1562 Note that changing the result_class will also remove any components
1563 that were originally loaded in the source class via
1564 L<load_components|Class::C3::Componentised/load_components( @comps )>.
1565 Any overloaded methods in the original source class will not run.
1566
1567 =cut
1568
1569 sub result_class {
1570   my ($self, $result_class) = @_;
1571   if ($result_class) {
1572
1573     # don't fire this for an object
1574     $self->ensure_class_loaded($result_class)
1575       unless ref($result_class);
1576
1577     if ($self->get_cache) {
1578       carp_unique('Changing the result_class of a ResultSet instance with cached results is a noop - the cache contents will not be altered');
1579     }
1580     # FIXME ENCAPSULATION - encapsulation breach, cursor method additions pending
1581     elsif ($self->{cursor} && $self->{cursor}{_pos}) {
1582       $self->throw_exception('Changing the result_class of a ResultSet instance with an active cursor is not supported');
1583     }
1584
1585     $self->_result_class($result_class);
1586
1587     delete $self->{_result_inflator};
1588   }
1589   $self->_result_class;
1590 }
1591
1592 =head2 count
1593
1594 =over 4
1595
1596 =item Arguments: L<$cond|DBIx::Class::SQLMaker>, L<\%attrs?|/ATTRIBUTES>
1597
1598 =item Return Value: $count
1599
1600 =back
1601
1602 Performs an SQL C<COUNT> with the same query as the resultset was built
1603 with to find the number of elements. Passing arguments is equivalent to
1604 C<< $rs->search ($cond, \%attrs)->count >>
1605
1606 =cut
1607
1608 sub count {
1609   my $self = shift;
1610   return $self->search(@_)->count if @_ and defined $_[0];
1611   return scalar @{ $self->get_cache } if $self->get_cache;
1612
1613   my $attrs = { %{ $self->_resolved_attrs } };
1614
1615   # this is a little optimization - it is faster to do the limit
1616   # adjustments in software, instead of a subquery
1617   my ($rows, $offset) = delete @{$attrs}{qw/rows offset/};
1618
1619   my $crs;
1620   if ($self->_has_resolved_attr (qw/collapse group_by/)) {
1621     $crs = $self->_count_subq_rs ($attrs);
1622   }
1623   else {
1624     $crs = $self->_count_rs ($attrs);
1625   }
1626   my $count = $crs->next;
1627
1628   $count -= $offset if $offset;
1629   $count = $rows if $rows and $rows < $count;
1630   $count = 0 if ($count < 0);
1631
1632   return $count;
1633 }
1634
1635 =head2 count_rs
1636
1637 =over 4
1638
1639 =item Arguments: L<$cond|DBIx::Class::SQLMaker>, L<\%attrs?|/ATTRIBUTES>
1640
1641 =item Return Value: L<$count_rs|DBIx::Class::ResultSetColumn>
1642
1643 =back
1644
1645 Same as L</count> but returns a L<DBIx::Class::ResultSetColumn> object.
1646 This can be very handy for subqueries:
1647
1648   ->search( { amount => $some_rs->count_rs->as_query } )
1649
1650 As with regular resultsets the SQL query will be executed only after
1651 the resultset is accessed via L</next> or L</all>. That would return
1652 the same single value obtainable via L</count>.
1653
1654 =cut
1655
1656 sub count_rs {
1657   my $self = shift;
1658   return $self->search(@_)->count_rs if @_;
1659
1660   # this may look like a lack of abstraction (count() does about the same)
1661   # but in fact an _rs *must* use a subquery for the limits, as the
1662   # software based limiting can not be ported if this $rs is to be used
1663   # in a subquery itself (i.e. ->as_query)
1664   if ($self->_has_resolved_attr (qw/collapse group_by offset rows/)) {
1665     return $self->_count_subq_rs($self->{_attrs});
1666   }
1667   else {
1668     return $self->_count_rs($self->{_attrs});
1669   }
1670 }
1671
1672 #
1673 # returns a ResultSetColumn object tied to the count query
1674 #
1675 sub _count_rs {
1676   my ($self, $attrs) = @_;
1677
1678   my $rsrc = $self->result_source;
1679
1680   my $tmp_attrs = { %$attrs };
1681   # take off any limits, record_filter is cdbi, and no point of ordering nor locking a count
1682   delete @{$tmp_attrs}{qw/rows offset order_by record_filter for/};
1683
1684   # overwrite the selector (supplied by the storage)
1685   $rsrc->resultset_class->new($rsrc, {
1686     %$tmp_attrs,
1687     select => $rsrc->schema->storage->_count_select ($rsrc, $attrs),
1688     as => 'count',
1689   })->get_column ('count');
1690 }
1691
1692 #
1693 # same as above but uses a subquery
1694 #
1695 sub _count_subq_rs {
1696   my ($self, $attrs) = @_;
1697
1698   my $rsrc = $self->result_source;
1699
1700   my $sub_attrs = { %$attrs };
1701   # extra selectors do not go in the subquery and there is no point of ordering it, nor locking it
1702   delete @{$sub_attrs}{qw/collapse columns as select order_by for/};
1703
1704   # if we multi-prefetch we group_by something unique, as this is what we would
1705   # get out of the rs via ->next/->all. We *DO WANT* to clobber old group_by regardless
1706   if ( $attrs->{collapse}  ) {
1707     $sub_attrs->{group_by} = [ map { "$attrs->{alias}.$_" } @{
1708       $rsrc->_identifying_column_set || $self->throw_exception(
1709         'Unable to construct a unique group_by criteria properly collapsing the '
1710       . 'has_many prefetch before count()'
1711       );
1712     } ]
1713   }
1714
1715   # Calculate subquery selector
1716   if (my $g = $sub_attrs->{group_by}) {
1717
1718     my $sql_maker = $rsrc->schema->storage->sql_maker;
1719
1720     # necessary as the group_by may refer to aliased functions
1721     my $sel_index;
1722     for my $sel (@{$attrs->{select}}) {
1723       $sel_index->{$sel->{-as}} = $sel
1724         if (ref $sel eq 'HASH' and $sel->{-as});
1725     }
1726
1727     # anything from the original select mentioned on the group-by needs to make it to the inner selector
1728     # also look for named aggregates referred in the having clause
1729     # having often contains scalarrefs - thus parse it out entirely
1730     my @parts = @$g;
1731     if ($attrs->{having}) {
1732       local $sql_maker->{having_bind};
1733       local $sql_maker->{quote_char} = $sql_maker->{quote_char};
1734       local $sql_maker->{name_sep} = $sql_maker->{name_sep};
1735       unless (defined $sql_maker->{quote_char} and length $sql_maker->{quote_char}) {
1736         $sql_maker->{quote_char} = [ "\x00", "\xFF" ];
1737         # if we don't unset it we screw up retarded but unfortunately working
1738         # 'MAX(foo.bar)' => { '>', 3 }
1739         $sql_maker->{name_sep} = '';
1740       }
1741
1742       my ($lquote, $rquote, $sep) = map { quotemeta $_ } ($sql_maker->_quote_chars, $sql_maker->name_sep);
1743
1744       my $having_sql = $sql_maker->_parse_rs_attrs ({ having => $attrs->{having} });
1745       my %seen_having;
1746
1747       # search for both a proper quoted qualified string, for a naive unquoted scalarref
1748       # and if all fails for an utterly naive quoted scalar-with-function
1749       while ($having_sql =~ /
1750         $rquote $sep $lquote (.+?) $rquote
1751           |
1752         [\s,] \w+ \. (\w+) [\s,]
1753           |
1754         [\s,] $lquote (.+?) $rquote [\s,]
1755       /gx) {
1756         my $part = $1 || $2 || $3;  # one of them matched if we got here
1757         unless ($seen_having{$part}++) {
1758           push @parts, $part;
1759         }
1760       }
1761     }
1762
1763     for (@parts) {
1764       my $colpiece = $sel_index->{$_} || $_;
1765
1766       # unqualify join-based group_by's. Arcane but possible query
1767       # also horrible horrible hack to alias a column (not a func.)
1768       # (probably need to introduce SQLA syntax)
1769       if ($colpiece =~ /\./ && $colpiece !~ /^$attrs->{alias}\./) {
1770         my $as = $colpiece;
1771         $as =~ s/\./__/;
1772         $colpiece = \ sprintf ('%s AS %s', map { $sql_maker->_quote ($_) } ($colpiece, $as) );
1773       }
1774       push @{$sub_attrs->{select}}, $colpiece;
1775     }
1776   }
1777   else {
1778     my @pcols = map { "$attrs->{alias}.$_" } ($rsrc->primary_columns);
1779     $sub_attrs->{select} = @pcols ? \@pcols : [ 1 ];
1780   }
1781
1782   return $rsrc->resultset_class
1783                ->new ($rsrc, $sub_attrs)
1784                 ->as_subselect_rs
1785                  ->search ({}, { columns => { count => $rsrc->schema->storage->_count_select ($rsrc, $attrs) } })
1786                   ->get_column ('count');
1787 }
1788
1789
1790 =head2 count_literal
1791
1792 B<CAVEAT>: C<count_literal> is provided for Class::DBI compatibility and
1793 should only be used in that context. See L</search_literal> for further info.
1794
1795 =over 4
1796
1797 =item Arguments: $sql_fragment, @standalone_bind_values
1798
1799 =item Return Value: $count
1800
1801 =back
1802
1803 Counts the results in a literal query. Equivalent to calling L</search_literal>
1804 with the passed arguments, then L</count>.
1805
1806 =cut
1807
1808 sub count_literal :DBIC_method_is_indirect_sugar {
1809   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
1810   shift->search_literal(@_)->count
1811 }
1812
1813 =head2 all
1814
1815 =over 4
1816
1817 =item Arguments: none
1818
1819 =item Return Value: L<@result_objs|DBIx::Class::Manual::ResultClass>
1820
1821 =back
1822
1823 Returns all elements in the resultset.
1824
1825 =cut
1826
1827 sub all {
1828   my $self = shift;
1829   if(@_) {
1830     $self->throw_exception("all() doesn't take any arguments, you probably wanted ->search(...)->all()");
1831   }
1832
1833   delete @{$self}{qw/_stashed_rows _stashed_results/};
1834
1835   if (my $c = $self->get_cache) {
1836     return @$c;
1837   }
1838
1839   $self->cursor->reset;
1840
1841   my $objs = $self->_construct_results('fetch_all') || [];
1842
1843   $self->set_cache($objs) if $self->{attrs}{cache};
1844
1845   return @$objs;
1846 }
1847
1848 =head2 reset
1849
1850 =over 4
1851
1852 =item Arguments: none
1853
1854 =item Return Value: $self
1855
1856 =back
1857
1858 Resets the resultset's cursor, so you can iterate through the elements again.
1859 Implicitly resets the storage cursor, so a subsequent L</next> will trigger
1860 another query.
1861
1862 =cut
1863
1864 sub reset {
1865   my ($self) = @_;
1866
1867   delete @{$self}{qw/_stashed_rows _stashed_results/};
1868   $self->{all_cache_position} = 0;
1869   $self->cursor->reset;
1870   return $self;
1871 }
1872
1873 =head2 first
1874
1875 =over 4
1876
1877 =item Arguments: none
1878
1879 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
1880
1881 =back
1882
1883 L<Resets|/reset> the resultset (causing a fresh query to storage) and returns
1884 an object for the first result (or C<undef> if the resultset is empty).
1885
1886 =cut
1887
1888 sub first :DBIC_method_is_indirect_sugar {
1889   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
1890   return $_[0]->reset->next;
1891 }
1892
1893
1894 # _rs_update_delete
1895 #
1896 # Determines whether and what type of subquery is required for the $rs operation.
1897 # If grouping is necessary either supplies its own, or verifies the current one
1898 # After all is done delegates to the proper storage method.
1899
1900 sub _rs_update_delete {
1901   my ($self, $op, $values) = @_;
1902
1903   my $rsrc = $self->result_source;
1904   my $storage = $rsrc->schema->storage;
1905
1906   my $attrs = { %{$self->_resolved_attrs} };
1907
1908   my $join_classifications;
1909   my ($existing_group_by) = delete @{$attrs}{qw(group_by _grouped_by_distinct)};
1910
1911   # do we need a subquery for any reason?
1912   my $needs_subq = (
1913     defined $existing_group_by
1914       or
1915     # if {from} is unparseable wrap a subq
1916     ref($attrs->{from}) ne 'ARRAY'
1917       or
1918     # limits call for a subq
1919     $self->_has_resolved_attr(qw/rows offset/)
1920   );
1921
1922   # simplify the joinmap, so we can further decide if a subq is necessary
1923   if (!$needs_subq and @{$attrs->{from}} > 1) {
1924
1925     ($attrs->{from}, $join_classifications) =
1926       $storage->_prune_unused_joins ($attrs);
1927
1928     # any non-pruneable non-local restricting joins imply subq
1929     $needs_subq = grep { $_ ne $attrs->{alias} } keys %{ $join_classifications->{restricting} || {} };
1930   }
1931
1932   # check if the head is composite (by now all joins are thrown out unless $needs_subq)
1933   $needs_subq ||= (
1934     (ref $attrs->{from}[0]) ne 'HASH'
1935       or
1936     ref $attrs->{from}[0]{ $attrs->{from}[0]{-alias} }
1937   );
1938
1939   my ($cond, $guard);
1940   # do we need anything like a subquery?
1941   if (! $needs_subq) {
1942     # Most databases do not allow aliasing of tables in UPDATE/DELETE. Thus
1943     # a condition containing 'me' or other table prefixes will not work
1944     # at all. Tell SQLMaker to dequalify idents via a gross hack.
1945     $cond = do {
1946       my $sqla = $rsrc->schema->storage->sql_maker;
1947       local $sqla->{_dequalify_idents} = 1;
1948       \[ $sqla->_recurse_where($self->{cond}) ];
1949     };
1950   }
1951   else {
1952     # we got this far - means it is time to wrap a subquery
1953     my $idcols = $rsrc->_identifying_column_set || $self->throw_exception(
1954       sprintf(
1955         "Unable to perform complex resultset %s() without an identifying set of columns on source '%s'",
1956         $op,
1957         $rsrc->source_name,
1958       )
1959     );
1960
1961     # make a new $rs selecting only the PKs (that's all we really need for the subq)
1962     delete $attrs->{$_} for qw/select as collapse/;
1963     $attrs->{columns} = [ map { "$attrs->{alias}.$_" } @$idcols ];
1964
1965     # this will be consumed by the pruner waaaaay down the stack
1966     $attrs->{_force_prune_multiplying_joins} = 1;
1967
1968     my $subrs = (ref $self)->new($rsrc, $attrs);
1969
1970     if (@$idcols == 1) {
1971       $cond = { $idcols->[0] => { -in => $subrs->as_query } };
1972     }
1973     elsif ($storage->_use_multicolumn_in) {
1974       # no syntax for calling this properly yet
1975       # !!! EXPERIMENTAL API !!! WILL CHANGE !!!
1976       $cond = $storage->sql_maker->_where_op_multicolumn_in (
1977         $idcols, # how do I convey a list of idents...? can binds reside on lhs?
1978         $subrs->as_query
1979       ),
1980     }
1981     else {
1982       # if all else fails - get all primary keys and operate over a ORed set
1983       # wrap in a transaction for consistency
1984       # this is where the group_by/multiplication starts to matter
1985       if (
1986         $existing_group_by
1987           or
1988         # we do not need to check pre-multipliers, since if the premulti is there, its
1989         # parent (who is multi) will be there too
1990         keys %{ $join_classifications->{multiplying} || {} }
1991       ) {
1992         # make sure if there is a supplied group_by it matches the columns compiled above
1993         # perfectly. Anything else can not be sanely executed on most databases so croak
1994         # right then and there
1995         if ($existing_group_by) {
1996           my @current_group_by = map
1997             { $_ =~ /\./ ? $_ : "$attrs->{alias}.$_" }
1998             @$existing_group_by
1999           ;
2000
2001           if (
2002             join ("\x00", sort @current_group_by)
2003               ne
2004             join ("\x00", sort @{$attrs->{columns}} )
2005           ) {
2006             $self->throw_exception (
2007               "You have just attempted a $op operation on a resultset which does group_by"
2008               . ' on columns other than the primary keys, while DBIC internally needs to retrieve'
2009               . ' the primary keys in a subselect. All sane RDBMS engines do not support this'
2010               . ' kind of queries. Please retry the operation with a modified group_by or'
2011               . ' without using one at all.'
2012             );
2013           }
2014         }
2015
2016         $subrs = $subrs->search({}, { group_by => $attrs->{columns} });
2017       }
2018
2019       $guard = $storage->txn_scope_guard;
2020
2021       for my $row ($subrs->cursor->all) {
2022         push @$cond, { map
2023           { $idcols->[$_] => $row->[$_] }
2024           (0 .. $#$idcols)
2025         };
2026       }
2027     }
2028   }
2029
2030   my $res = $cond ? $storage->$op (
2031     $rsrc,
2032     $op eq 'update' ? $values : (),
2033     $cond,
2034   ) : '0E0';
2035
2036   $guard->commit if $guard;
2037
2038   return $res;
2039 }
2040
2041 =head2 update
2042
2043 =over 4
2044
2045 =item Arguments: \%values
2046
2047 =item Return Value: $underlying_storage_rv
2048
2049 =back
2050
2051 Sets the specified columns in the resultset to the supplied values in a
2052 single query. Note that this will not run any accessor/set_column/update
2053 triggers, nor will it update any result object instances derived from this
2054 resultset (this includes the contents of the L<resultset cache|/set_cache>
2055 if any). See L</update_all> if you need to execute any on-update
2056 triggers or cascades defined either by you or a
2057 L<result component|DBIx::Class::Manual::Component/WHAT IS A COMPONENT>.
2058
2059 The return value is a pass through of what the underlying
2060 storage backend returned, and may vary. See L<DBI/execute> for the most
2061 common case.
2062
2063 =head3 CAVEAT
2064
2065 Note that L</update> does not process/deflate any of the values passed in.
2066 This is unlike the corresponding L<DBIx::Class::Row/update>. The user must
2067 ensure manually that any value passed to this method will stringify to
2068 something the RDBMS knows how to deal with. A notable example is the
2069 handling of L<DateTime> objects, for more info see:
2070 L<DBIx::Class::Manual::Cookbook/Formatting DateTime objects in queries>.
2071
2072 =cut
2073
2074 sub update {
2075   my ($self, $values) = @_;
2076   $self->throw_exception('Values for update must be a hash')
2077     unless ref $values eq 'HASH';
2078
2079   return $self->_rs_update_delete ('update', $values);
2080 }
2081
2082 =head2 update_all
2083
2084 =over 4
2085
2086 =item Arguments: \%values
2087
2088 =item Return Value: 1
2089
2090 =back
2091
2092 Fetches all objects and updates them one at a time via
2093 L<DBIx::Class::Row/update>. Note that C<update_all> will run DBIC defined
2094 triggers, while L</update> will not.
2095
2096 =cut
2097
2098 sub update_all {
2099   my ($self, $values) = @_;
2100   $self->throw_exception('Values for update_all must be a hash')
2101     unless ref $values eq 'HASH';
2102
2103   my $guard = $self->result_source->schema->txn_scope_guard;
2104   $_->update({%$values}) for $self->all;  # shallow copy - update will mangle it
2105   $guard->commit;
2106   return 1;
2107 }
2108
2109 =head2 delete
2110
2111 =over 4
2112
2113 =item Arguments: none
2114
2115 =item Return Value: $underlying_storage_rv
2116
2117 =back
2118
2119 Deletes the rows matching this resultset in a single query. Note that this
2120 will not run any delete triggers, nor will it alter the
2121 L<in_storage|DBIx::Class::Row/in_storage> status of any result object instances
2122 derived from this resultset (this includes the contents of the
2123 L<resultset cache|/set_cache> if any). See L</delete_all> if you need to
2124 execute any on-delete triggers or cascades defined either by you or a
2125 L<result component|DBIx::Class::Manual::Component/WHAT IS A COMPONENT>.
2126
2127 The return value is a pass through of what the underlying storage backend
2128 returned, and may vary. See L<DBI/execute> for the most common case.
2129
2130 =cut
2131
2132 sub delete {
2133   my $self = shift;
2134   $self->throw_exception('delete does not accept any arguments')
2135     if @_;
2136
2137   return $self->_rs_update_delete ('delete');
2138 }
2139
2140 =head2 delete_all
2141
2142 =over 4
2143
2144 =item Arguments: none
2145
2146 =item Return Value: 1
2147
2148 =back
2149
2150 Fetches all objects and deletes them one at a time via
2151 L<DBIx::Class::Row/delete>. Note that C<delete_all> will run DBIC defined
2152 triggers, while L</delete> will not.
2153
2154 =cut
2155
2156 sub delete_all {
2157   my $self = shift;
2158   $self->throw_exception('delete_all does not accept any arguments')
2159     if @_;
2160
2161   my $guard = $self->result_source->schema->txn_scope_guard;
2162   $_->delete for $self->all;
2163   $guard->commit;
2164   return 1;
2165 }
2166
2167 =head2 populate
2168
2169 =over 4
2170
2171 =item Arguments: [ \@column_list, \@row_values+ ] | [ \%col_data+ ]
2172
2173 =item Return Value: L<\@result_objects|DBIx::Class::Manual::ResultClass> (scalar context) | L<@result_objects|DBIx::Class::Manual::ResultClass> (list context)
2174
2175 =back
2176
2177 Accepts either an arrayref of hashrefs or alternatively an arrayref of
2178 arrayrefs.
2179
2180 =over
2181
2182 =item NOTE
2183
2184 The context of this method call has an important effect on what is
2185 submitted to storage. In void context data is fed directly to fastpath
2186 insertion routines provided by the underlying storage (most often
2187 L<DBI/execute_for_fetch>), bypassing the L<new|DBIx::Class::Row/new> and
2188 L<insert|DBIx::Class::Row/insert> calls on the
2189 L<Result|DBIx::Class::Manual::ResultClass> class, including any
2190 augmentation of these methods provided by components. For example if you
2191 are using something like L<DBIx::Class::UUIDColumns> to create primary
2192 keys for you, you will find that your PKs are empty.  In this case you
2193 will have to explicitly force scalar or list context in order to create
2194 those values.
2195
2196 =back
2197
2198 In non-void (scalar or list) context, this method is simply a wrapper
2199 for L</create>. Depending on list or scalar context either a list of
2200 L<Result|DBIx::Class::Manual::ResultClass> objects or an arrayref
2201 containing these objects is returned.
2202
2203 When supplying data in "arrayref of arrayrefs" invocation style, the
2204 first element should be a list of column names and each subsequent
2205 element should be a data value in the earlier specified column order.
2206 For example:
2207
2208   $schema->resultset("Artist")->populate([
2209     [ qw( artistid name ) ],
2210     [ 100, 'A Formally Unknown Singer' ],
2211     [ 101, 'A singer that jumped the shark two albums ago' ],
2212     [ 102, 'An actually cool singer' ],
2213   ]);
2214
2215 For the arrayref of hashrefs style each hashref should be a structure
2216 suitable for passing to L</create>. Multi-create is also permitted with
2217 this syntax.
2218
2219   $schema->resultset("Artist")->populate([
2220      { artistid => 4, name => 'Manufactured Crap', cds => [
2221         { title => 'My First CD', year => 2006 },
2222         { title => 'Yet More Tweeny-Pop crap', year => 2007 },
2223       ],
2224      },
2225      { artistid => 5, name => 'Angsty-Whiny Girl', cds => [
2226         { title => 'My parents sold me to a record company', year => 2005 },
2227         { title => 'Why Am I So Ugly?', year => 2006 },
2228         { title => 'I Got Surgery and am now Popular', year => 2007 }
2229       ],
2230      },
2231   ]);
2232
2233 If you attempt a void-context multi-create as in the example above (each
2234 Artist also has the related list of CDs), and B<do not> supply the
2235 necessary autoinc foreign key information, this method will proxy to the
2236 less efficient L</create>, and then throw the Result objects away. In this
2237 case there are obviously no benefits to using this method over L</create>.
2238
2239 =cut
2240
2241 sub populate {
2242   my $self = shift;
2243
2244   # this is naive and just a quick check
2245   # the types will need to be checked more thoroughly when the
2246   # multi-source populate gets added
2247   my $data = (
2248     ref $_[0] eq 'ARRAY'
2249       and
2250     ( @{$_[0]} or return )
2251       and
2252     ( ref $_[0][0] eq 'HASH' or ref $_[0][0] eq 'ARRAY' )
2253       and
2254     $_[0]
2255   ) or $self->throw_exception('Populate expects an arrayref of hashrefs or arrayref of arrayrefs');
2256
2257   # FIXME - no cref handling
2258   # At this point assume either hashes or arrays
2259
2260   my $rsrc = $self->result_source;
2261   my $storage = $rsrc->schema->storage;
2262
2263   if(defined wantarray) {
2264     my (@results, $guard);
2265
2266     if (ref $data->[0] eq 'ARRAY') {
2267       # column names only, nothing to do
2268       return if @$data == 1;
2269
2270       $guard = $storage->txn_scope_guard
2271         if @$data > 2;
2272
2273       @results = map
2274         { my $vals = $_; $self->new_result({ map { $data->[0][$_] => $vals->[$_] } 0..$#{$data->[0]} })->insert }
2275         @{$data}[1 .. $#$data]
2276       ;
2277     }
2278     else {
2279
2280       $guard = $storage->txn_scope_guard
2281         if @$data > 1;
2282
2283       @results = map { $self->new_result($_)->insert } @$data;
2284     }
2285
2286     $guard->commit if $guard;
2287     return wantarray ? @results : \@results;
2288   }
2289
2290   # we have to deal with *possibly incomplete* related data
2291   # this means we have to walk the data structure twice
2292   # whether we want this or not
2293   # jnap, I hate you ;)
2294   my $rel_info = { map { $_ => $rsrc->relationship_info($_) } $rsrc->relationships };
2295
2296   my ($colinfo, $colnames, $slices_with_rels);
2297   my $data_start = 0;
2298
2299   DATA_SLICE:
2300   for my $i (0 .. $#$data) {
2301
2302     my $current_slice_seen_rel_infos;
2303
2304 ### Determine/Supplement collists
2305 ### BEWARE - This is a hot piece of code, a lot of weird idioms were used
2306     if( ref $data->[$i] eq 'ARRAY' ) {
2307
2308       # positional(!) explicit column list
2309       if ($i == 0) {
2310         # column names only, nothing to do
2311         return if @$data == 1;
2312
2313         $colinfo->{$data->[0][$_]} = { pos => $_, name => $data->[0][$_] } and push @$colnames, $data->[0][$_]
2314           for 0 .. $#{$data->[0]};
2315
2316         $data_start = 1;
2317
2318         next DATA_SLICE;
2319       }
2320       else {
2321         for (values %$colinfo) {
2322           if ($_->{is_rel} ||= (
2323             $rel_info->{$_->{name}}
2324               and
2325             (
2326               ref $data->[$i][$_->{pos}] eq 'ARRAY'
2327                 or
2328               ref $data->[$i][$_->{pos}] eq 'HASH'
2329                 or
2330               (
2331                 defined blessed $data->[$i][$_->{pos}]
2332                   and
2333                 $data->[$i][$_->{pos}]->isa(
2334                   $DBIx::Class::ResultSource::__expected_result_class_isa
2335                     ||
2336                   emit_loud_diag(
2337                     confess => 1,
2338                     msg => 'Global $DBIx::Class::ResultSource::__expected_result_class_isa unexpectedly unset...'
2339                   )
2340                 )
2341               )
2342             )
2343               and
2344             1
2345           )) {
2346
2347             # moar sanity check... sigh
2348             for ( ref $data->[$i][$_->{pos}] eq 'ARRAY' ? @{$data->[$i][$_->{pos}]} : $data->[$i][$_->{pos}] ) {
2349               if (
2350                 defined blessed $_
2351                   and
2352                 $_->isa(
2353                   $DBIx::Class::ResultSource::__expected_result_class_isa
2354                     ||
2355                   emit_loud_diag(
2356                     confess => 1,
2357                     msg => 'Global $DBIx::Class::ResultSource::__expected_result_class_isa unexpectedly unset...'
2358                   )
2359                 )
2360               ) {
2361                 carp_unique("Fast-path populate() with supplied related objects is not possible - falling back to regular create()");
2362                 return my $throwaway = $self->populate(@_);
2363               }
2364             }
2365
2366             push @$current_slice_seen_rel_infos, $rel_info->{$_->{name}};
2367           }
2368         }
2369       }
2370
2371      if ($current_slice_seen_rel_infos) {
2372         push @$slices_with_rels, { map { $colnames->[$_] => $data->[$i][$_] } 0 .. $#$colnames };
2373
2374         # this is needed further down to decide whether or not to fallback to create()
2375         $colinfo->{$colnames->[$_]}{seen_null} ||= ! defined $data->[$i][$_]
2376           for 0 .. $#$colnames;
2377       }
2378     }
2379     elsif( ref $data->[$i] eq 'HASH' ) {
2380
2381       for ( sort keys %{$data->[$i]} ) {
2382
2383         $colinfo->{$_} ||= do {
2384
2385           $self->throw_exception("Column '$_' must be present in supplied explicit column list")
2386             if $data_start; # it will be 0 on AoH, 1 on AoA
2387
2388           push @$colnames, $_;
2389
2390           # RV
2391           { pos => $#$colnames, name => $_ }
2392         };
2393
2394         if ($colinfo->{$_}{is_rel} ||= (
2395           $rel_info->{$_}
2396             and
2397           (
2398             ref $data->[$i]{$_} eq 'ARRAY'
2399               or
2400             ref $data->[$i]{$_} eq 'HASH'
2401               or
2402             (
2403               defined blessed $data->[$i]{$_}
2404                 and
2405               $data->[$i]{$_}->isa(
2406                 $DBIx::Class::ResultSource::__expected_result_class_isa
2407                   ||
2408                 emit_loud_diag(
2409                   confess => 1,
2410                   msg => 'Global $DBIx::Class::ResultSource::__expected_result_class_isa unexpectedly unset...'
2411                 )
2412               )
2413             )
2414           )
2415             and
2416           1
2417         )) {
2418
2419           # moar sanity check... sigh
2420           for ( ref $data->[$i]{$_} eq 'ARRAY' ? @{$data->[$i]{$_}} : $data->[$i]{$_} ) {
2421             if (
2422               defined blessed $_
2423                 and
2424               $_->isa(
2425                 $DBIx::Class::ResultSource::__expected_result_class_isa
2426                   ||
2427                 emit_loud_diag(
2428                   confess => 1,
2429                   msg => 'Global $DBIx::Class::ResultSource::__expected_result_class_isa unexpectedly unset...'
2430                 )
2431               )
2432             ) {
2433               carp_unique("Fast-path populate() with supplied related objects is not possible - falling back to regular create()");
2434               return my $throwaway = $self->populate(@_);
2435             }
2436           }
2437
2438           push @$current_slice_seen_rel_infos, $rel_info->{$_};
2439         }
2440       }
2441
2442       if ($current_slice_seen_rel_infos) {
2443         push @$slices_with_rels, $data->[$i];
2444
2445         # this is needed further down to decide whether or not to fallback to create()
2446         $colinfo->{$_}{seen_null} ||= ! defined $data->[$i]{$_}
2447           for keys %{$data->[$i]};
2448       }
2449     }
2450     else {
2451       $self->throw_exception('Unexpected populate() data structure member type: ' . ref $data->[$i] );
2452     }
2453
2454     if ( grep
2455       { $_->{attrs}{is_depends_on} }
2456       @{ $current_slice_seen_rel_infos || [] }
2457     ) {
2458       carp_unique("Fast-path populate() of belongs_to relationship data is not possible - falling back to regular create()");
2459       return my $throwaway = $self->populate(@_);
2460     }
2461   }
2462
2463   if( $slices_with_rels ) {
2464
2465     # need to exclude the rel "columns"
2466     $colnames = [ grep { ! $colinfo->{$_}{is_rel} } @$colnames ];
2467
2468     # extra sanity check - ensure the main source is in fact identifiable
2469     # the localizing of nullability is insane, but oh well... the use-case is legit
2470     my $ci = $rsrc->columns_info($colnames);
2471
2472     $ci->{$_} = { %{$ci->{$_}}, is_nullable => 0 }
2473       for grep { ! $colinfo->{$_}{seen_null} } keys %$ci;
2474
2475     unless( $rsrc->_identifying_column_set($ci) ) {
2476       carp_unique("Fast-path populate() of non-uniquely identifiable rows with related data is not possible - falling back to regular create()");
2477       return my $throwaway = $self->populate(@_);
2478     }
2479   }
2480
2481 ### inherit the data locked in the conditions of the resultset
2482   my ($rs_data) = $self->_merge_with_rscond({});
2483   delete @{$rs_data}{@$colnames};  # passed-in stuff takes precedence
2484
2485   # if anything left - decompose rs_data
2486   my $rs_data_vals;
2487   if (keys %$rs_data) {
2488      push @$rs_data_vals, $rs_data->{$_}
2489       for sort keys %$rs_data;
2490   }
2491
2492 ### start work
2493   my $guard;
2494   $guard = $storage->txn_scope_guard
2495     if $slices_with_rels;
2496
2497 ### main source data
2498   # FIXME - need to switch entirely to a coderef-based thing,
2499   # so that large sets aren't copied several times... I think
2500   $storage->_insert_bulk(
2501     $rsrc,
2502     [ @$colnames, sort keys %$rs_data ],
2503     [ map {
2504       ref $data->[$_] eq 'ARRAY'
2505       ? (
2506           $slices_with_rels ? [ @{$data->[$_]}[0..$#$colnames], @{$rs_data_vals||[]} ]  # the collist changed
2507         : $rs_data_vals     ? [ @{$data->[$_]}, @$rs_data_vals ]
2508         :                     $data->[$_]
2509       )
2510       : [ @{$data->[$_]}{@$colnames}, @{$rs_data_vals||[]} ]
2511     } $data_start .. $#$data ],
2512   );
2513
2514 ### do the children relationships
2515   if ( $slices_with_rels ) {
2516     my @rels = grep { $colinfo->{$_}{is_rel} } keys %$colinfo
2517       or die 'wtf... please report a bug with DBIC_TRACE=1 output (stacktrace)';
2518
2519     for my $sl (@$slices_with_rels) {
2520
2521       my ($main_proto, $main_proto_rs);
2522       for my $rel (@rels) {
2523         next unless defined $sl->{$rel};
2524
2525         $main_proto ||= {
2526           %$rs_data,
2527           (map { $_ => $sl->{$_} } @$colnames),
2528         };
2529
2530         unless (defined $colinfo->{$rel}{rs}) {
2531
2532           $colinfo->{$rel}{rs} = $rsrc->related_source($rel)->resultset;
2533
2534           $colinfo->{$rel}{fk_map} = { reverse %{ $rsrc->resolve_relationship_condition(
2535             rel_name => $rel,
2536
2537             # an API where these are optional would be too cumbersome,
2538             # instead always pass in some dummy values
2539             DUMMY_ALIASPAIR,
2540           )->{identity_map} || {} } };
2541
2542         }
2543
2544         $colinfo->{$rel}{rs}->search({ map # only so that we inherit them values properly, no actual search
2545           {
2546             $_ => { '=' =>
2547               ( $main_proto_rs ||= $rsrc->resultset->search($main_proto) )
2548                 ->get_column( $colinfo->{$rel}{fk_map}{$_} )
2549                  ->as_query
2550             }
2551           }
2552           keys %{$colinfo->{$rel}{fk_map}}
2553         })->populate( ref $sl->{$rel} eq 'ARRAY' ? $sl->{$rel} : [ $sl->{$rel} ] );
2554
2555         1;
2556       }
2557     }
2558   }
2559
2560   $guard->commit if $guard;
2561 }
2562
2563 =head2 pager
2564
2565 =over 4
2566
2567 =item Arguments: none
2568
2569 =item Return Value: L<$pager|Data::Page>
2570
2571 =back
2572
2573 Returns a L<Data::Page> object for the current resultset. Only makes
2574 sense for queries with a C<page> attribute.
2575
2576 To get the full count of entries for a paged resultset, call
2577 C<total_entries> on the L<Data::Page> object.
2578
2579 =cut
2580
2581 sub pager {
2582   my ($self) = @_;
2583
2584   return $self->{pager} if $self->{pager};
2585
2586   my $attrs = $self->{attrs};
2587   if (!defined $attrs->{page}) {
2588     $self->throw_exception("Can't create pager for non-paged rs");
2589   }
2590   elsif ($attrs->{page} <= 0) {
2591     $self->throw_exception('Invalid page number (page-numbers are 1-based)');
2592   }
2593   $attrs->{rows} ||= 10;
2594
2595   # throw away the paging flags and re-run the count (possibly
2596   # with a subselect) to get the real total count
2597   my $count_attrs = { %$attrs };
2598   delete @{$count_attrs}{qw/rows offset page pager/};
2599
2600   my $total_rs = (ref $self)->new($self->result_source, $count_attrs);
2601
2602   require DBIx::Class::ResultSet::Pager;
2603   return $self->{pager} = DBIx::Class::ResultSet::Pager->new(
2604     sub { $total_rs->count },  #lazy-get the total
2605     $attrs->{rows},
2606     $self->{attrs}{page},
2607   );
2608 }
2609
2610 =head2 page
2611
2612 =over 4
2613
2614 =item Arguments: $page_number
2615
2616 =item Return Value: L<$resultset|/search>
2617
2618 =back
2619
2620 Returns a resultset for the $page_number page of the resultset on which page
2621 is called, where each page contains a number of rows equal to the 'rows'
2622 attribute set on the resultset (10 by default).
2623
2624 =cut
2625
2626 sub page {
2627   my ($self, $page) = @_;
2628   return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
2629 }
2630
2631 =head2 new_result
2632
2633 =over 4
2634
2635 =item Arguments: \%col_data
2636
2637 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2638
2639 =back
2640
2641 Creates a new result object in the resultset's result class and returns
2642 it. The row is not inserted into the database at this point, call
2643 L<DBIx::Class::Row/insert> to do that. Calling L<DBIx::Class::Row/in_storage>
2644 will tell you whether the result object has been inserted or not.
2645
2646 Passes the hashref of input on to L<DBIx::Class::Row/new>.
2647
2648 =cut
2649
2650 sub new_result {
2651   my ($self, $values) = @_;
2652
2653   $self->throw_exception( "Result object instantiation requires a single hashref argument" )
2654     if @_ > 2 or ref $values ne 'HASH';
2655
2656   my ($merged_cond, $cols_from_relations) = $self->_merge_with_rscond($values);
2657
2658   my $new = $self->result_class->new({
2659     %$merged_cond,
2660     ( @$cols_from_relations
2661       ? (-cols_from_relations => $cols_from_relations)
2662       : ()
2663     ),
2664     -result_source => $self->result_source, # DO NOT REMOVE THIS, REQUIRED
2665   });
2666
2667   if (
2668     reftype($new) eq 'HASH'
2669       and
2670     ! keys %$new
2671       and
2672     blessed($new)
2673   ) {
2674     carp_unique (sprintf (
2675       "%s->new returned a blessed empty hashref - a strong indicator something is wrong with its inheritance chain",
2676       $self->result_class,
2677     ));
2678   }
2679
2680   $new;
2681 }
2682
2683 # _merge_with_rscond
2684 #
2685 # Takes a simple hash of K/V data and returns its copy merged with the
2686 # condition already present on the resultset. Additionally returns an
2687 # arrayref of value/condition names, which were inferred from related
2688 # objects (this is needed for in-memory related objects)
2689 sub _merge_with_rscond {
2690   my ($self, $data) = @_;
2691
2692   my ($implied_data, @cols_from_relations);
2693
2694   my $alias = $self->{attrs}{alias};
2695
2696   if (! defined $self->{cond}) {
2697     # just massage $data below
2698   }
2699   elsif ($self->{cond} eq UNRESOLVABLE_CONDITION) {
2700     $implied_data = $self->{attrs}{related_objects};  # nothing might have been inserted yet
2701     @cols_from_relations = keys %{ $implied_data || {} };
2702   }
2703   else {
2704     my $eqs = extract_equality_conditions( $self->{cond}, 'consider_nulls' );
2705     $implied_data = { map {
2706       ( ($eqs->{$_}||'') eq UNRESOLVABLE_CONDITION ) ? () : ( $_ => $eqs->{$_} )
2707     } keys %$eqs };
2708   }
2709
2710   return (
2711     { map
2712       { %{ $self->_remove_alias($_, $alias) } }
2713       # precedence must be given to passed values over values inherited from
2714       # the cond, so the order here is important.
2715       ( $implied_data||(), $data)
2716     },
2717     \@cols_from_relations
2718   );
2719 }
2720
2721 # _has_resolved_attr
2722 #
2723 # determines if the resultset defines at least one
2724 # of the attributes supplied
2725 #
2726 # used to determine if a subquery is necessary
2727 #
2728 # supports some virtual attributes:
2729 #   -join
2730 #     This will scan for any joins being present on the resultset.
2731 #     It is not a mere key-search but a deep inspection of {from}
2732 #
2733
2734 sub _has_resolved_attr {
2735   my ($self, @attr_names) = @_;
2736
2737   my $attrs = $self->_resolved_attrs;
2738
2739   my %extra_checks;
2740
2741   for my $n (@attr_names) {
2742     if (grep { $n eq $_ } (qw/-join/) ) {
2743       $extra_checks{$n}++;
2744       next;
2745     }
2746
2747     my $attr =  $attrs->{$n};
2748
2749     next if not defined $attr;
2750
2751     if (ref $attr eq 'HASH') {
2752       return 1 if keys %$attr;
2753     }
2754     elsif (ref $attr eq 'ARRAY') {
2755       return 1 if @$attr;
2756     }
2757     else {
2758       return 1 if $attr;
2759     }
2760   }
2761
2762   # a resolved join is expressed as a multi-level from
2763   return 1 if (
2764     $extra_checks{-join}
2765       and
2766     ref $attrs->{from} eq 'ARRAY'
2767       and
2768     @{$attrs->{from}} > 1
2769   );
2770
2771   return 0;
2772 }
2773
2774 # _remove_alias
2775 #
2776 # Remove the specified alias from the specified query hash. A copy is made so
2777 # the original query is not modified.
2778
2779 sub _remove_alias {
2780   my ($self, $query, $alias) = @_;
2781
2782   my %orig = %{ $query || {} };
2783   my %unaliased;
2784
2785   foreach my $key (keys %orig) {
2786     if ($key !~ /\./) {
2787       $unaliased{$key} = $orig{$key};
2788       next;
2789     }
2790     $unaliased{$1} = $orig{$key}
2791       if $key =~ m/^(?:\Q$alias\E\.)?([^.]+)$/;
2792   }
2793
2794   return \%unaliased;
2795 }
2796
2797 =head2 as_query
2798
2799 =over 4
2800
2801 =item Arguments: none
2802
2803 =item Return Value: \[ $sql, L<@bind_values|/DBIC BIND VALUES> ]
2804
2805 =back
2806
2807 Returns the SQL query and bind vars associated with the invocant.
2808
2809 This is generally used as the RHS for a subquery.
2810
2811 =cut
2812
2813 sub as_query {
2814   my $self = shift;
2815
2816   my $attrs = { %{ $self->_resolved_attrs } };
2817
2818   my $aq = $self->result_source->schema->storage->_select_args_to_query (
2819     $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
2820   );
2821
2822   $aq;
2823 }
2824
2825 =head2 find_or_new
2826
2827 =over 4
2828
2829 =item Arguments: \%col_data, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
2830
2831 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2832
2833 =back
2834
2835   my $artist = $schema->resultset('Artist')->find_or_new(
2836     { artist => 'fred' }, { key => 'artists' });
2837
2838   $cd->cd_to_producer->find_or_new({ producer => $producer },
2839                                    { key => 'primary' });
2840
2841 Find an existing record from this resultset using L</find>. if none exists,
2842 instantiate a new result object and return it. The object will not be saved
2843 into your storage until you call L<DBIx::Class::Row/insert> on it.
2844
2845 You most likely want this method when looking for existing rows using a unique
2846 constraint that is not the primary key, or looking for related rows.
2847
2848 If you want objects to be saved immediately, use L</find_or_create> instead.
2849
2850 B<Note>: Make sure to read the documentation of L</find> and understand the
2851 significance of the C<key> attribute, as its lack may skew your search, and
2852 subsequently result in spurious new objects.
2853
2854 B<Note>: Take care when using C<find_or_new> with a table having
2855 columns with default values that you intend to be automatically
2856 supplied by the database (e.g. an auto_increment primary key column).
2857 In normal usage, the value of such columns should NOT be included at
2858 all in the call to C<find_or_new>, even when set to C<undef>.
2859
2860 =cut
2861
2862 sub find_or_new {
2863   my $self     = shift;
2864   my $attrs    = (@_ > 1 && ref $_[-1] eq 'HASH' ? pop(@_) : {});
2865   my $hash     = ref $_[0] eq 'HASH' ? shift : {@_};
2866   if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2867     return $row;
2868   }
2869   return $self->new_result($hash);
2870 }
2871
2872 =head2 create
2873
2874 =over 4
2875
2876 =item Arguments: \%col_data
2877
2878 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2879
2880 =back
2881
2882 Attempt to create a single new row or a row with multiple related rows
2883 in the table represented by the resultset (and related tables). This
2884 will not check for duplicate rows before inserting, use
2885 L</find_or_create> to do that.
2886
2887 To create one row for this resultset, pass a hashref of key/value
2888 pairs representing the columns of the table and the values you wish to
2889 store. If the appropriate relationships are set up, foreign key fields
2890 can also be passed an object representing the foreign row, and the
2891 value will be set to its primary key.
2892
2893 To create related objects, pass a hashref of related-object column values
2894 B<keyed on the relationship name>. If the relationship is of type C<multi>
2895 (L<DBIx::Class::Relationship/has_many>) - pass an arrayref of hashrefs.
2896 The process will correctly identify columns holding foreign keys, and will
2897 transparently populate them from the keys of the corresponding relation.
2898 This can be applied recursively, and will work correctly for a structure
2899 with an arbitrary depth and width, as long as the relationships actually
2900 exists and the correct column data has been supplied.
2901
2902 Instead of hashrefs of plain related data (key/value pairs), you may
2903 also pass new or inserted objects. New objects (not inserted yet, see
2904 L</new_result>), will be inserted into their appropriate tables.
2905
2906 Effectively a shortcut for C<< ->new_result(\%col_data)->insert >>.
2907
2908 Example of creating a new row.
2909
2910   $person_rs->create({
2911     name=>"Some Person",
2912     email=>"somebody@someplace.com"
2913   });
2914
2915 Example of creating a new row and also creating rows in a related C<has_many>
2916 or C<has_one> resultset.  Note Arrayref.
2917
2918   $artist_rs->create(
2919      { artistid => 4, name => 'Manufactured Crap', cds => [
2920         { title => 'My First CD', year => 2006 },
2921         { title => 'Yet More Tweeny-Pop crap', year => 2007 },
2922       ],
2923      },
2924   );
2925
2926 Example of creating a new row and also creating a row in a related
2927 C<belongs_to> resultset. Note Hashref.
2928
2929   $cd_rs->create({
2930     title=>"Music for Silly Walks",
2931     year=>2000,
2932     artist => {
2933       name=>"Silly Musician",
2934     }
2935   });
2936
2937 =over
2938
2939 =item WARNING
2940
2941 When subclassing ResultSet never attempt to override this method. Since
2942 it is a simple shortcut for C<< $self->new_result($attrs)->insert >>, a
2943 lot of the internals simply never call it, so your override will be
2944 bypassed more often than not. Override either L<DBIx::Class::Row/new>
2945 or L<DBIx::Class::Row/insert> depending on how early in the
2946 L</create> process you need to intervene. See also warning pertaining to
2947 L</new>.
2948
2949 =back
2950
2951 =cut
2952
2953 sub create :DBIC_method_is_indirect_sugar {
2954   #my ($self, $col_data) = @_;
2955   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
2956   return shift->new_result(shift)->insert;
2957 }
2958
2959 =head2 find_or_create
2960
2961 =over 4
2962
2963 =item Arguments: \%col_data, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
2964
2965 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2966
2967 =back
2968
2969   $cd->cd_to_producer->find_or_create({ producer => $producer },
2970                                       { key => 'primary' });
2971
2972 Tries to find a record based on its primary key or unique constraints; if none
2973 is found, creates one and returns that instead.
2974
2975   my $cd = $schema->resultset('CD')->find_or_create({
2976     cdid   => 5,
2977     artist => 'Massive Attack',
2978     title  => 'Mezzanine',
2979     year   => 2005,
2980   });
2981
2982 Also takes an optional C<key> attribute, to search by a specific key or unique
2983 constraint. For example:
2984
2985   my $cd = $schema->resultset('CD')->find_or_create(
2986     {
2987       artist => 'Massive Attack',
2988       title  => 'Mezzanine',
2989     },
2990     { key => 'cd_artist_title' }
2991   );
2992
2993 B<Note>: Make sure to read the documentation of L</find> and understand the
2994 significance of the C<key> attribute, as its lack may skew your search, and
2995 subsequently result in spurious row creation.
2996
2997 B<Note>: Because find_or_create() reads from the database and then
2998 possibly inserts based on the result, this method is subject to a race
2999 condition. Another process could create a record in the table after
3000 the find has completed and before the create has started. To avoid
3001 this problem, use find_or_create() inside a transaction.
3002
3003 B<Note>: Take care when using C<find_or_create> with a table having
3004 columns with default values that you intend to be automatically
3005 supplied by the database (e.g. an auto_increment primary key column).
3006 In normal usage, the value of such columns should NOT be included at
3007 all in the call to C<find_or_create>, even when set to C<undef>.
3008
3009 See also L</find> and L</update_or_create>. For information on how to declare
3010 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
3011
3012 If you need to know if an existing row was found or a new one created use
3013 L</find_or_new> and L<DBIx::Class::Row/in_storage> instead. Don't forget
3014 to call L<DBIx::Class::Row/insert> to save the newly created row to the
3015 database!
3016
3017   my $cd = $schema->resultset('CD')->find_or_new({
3018     cdid   => 5,
3019     artist => 'Massive Attack',
3020     title  => 'Mezzanine',
3021     year   => 2005,
3022   });
3023
3024   if( !$cd->in_storage ) {
3025       # do some stuff
3026       $cd->insert;
3027   }
3028
3029 =cut
3030
3031 sub find_or_create {
3032   my $self     = shift;
3033   my $attrs    = (@_ > 1 && ref $_[-1] eq 'HASH' ? pop(@_) : {});
3034   my $hash     = ref $_[0] eq 'HASH' ? shift : {@_};
3035   if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
3036     return $row;
3037   }
3038   return $self->new_result($hash)->insert;
3039 }
3040
3041 =head2 update_or_create
3042
3043 =over 4
3044
3045 =item Arguments: \%col_data, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
3046
3047 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
3048
3049 =back
3050
3051   $resultset->update_or_create({ col => $val, ... });
3052
3053 Like L</find_or_create>, but if a row is found it is immediately updated via
3054 C<< $found_row->update (\%col_data) >>.
3055
3056
3057 Takes an optional C<key> attribute to search on a specific unique constraint.
3058 For example:
3059
3060   # In your application
3061   my $cd = $schema->resultset('CD')->update_or_create(
3062     {
3063       artist => 'Massive Attack',
3064       title  => 'Mezzanine',
3065       year   => 1998,
3066     },
3067     { key => 'cd_artist_title' }
3068   );
3069
3070   $cd->cd_to_producer->update_or_create({
3071     producer => $producer,
3072     name => 'harry',
3073   }, {
3074     key => 'primary',
3075   });
3076
3077 B<Note>: Make sure to read the documentation of L</find> and understand the
3078 significance of the C<key> attribute, as its lack may skew your search, and
3079 subsequently result in spurious row creation.
3080
3081 B<Note>: Take care when using C<update_or_create> with a table having
3082 columns with default values that you intend to be automatically
3083 supplied by the database (e.g. an auto_increment primary key column).
3084 In normal usage, the value of such columns should NOT be included at
3085 all in the call to C<update_or_create>, even when set to C<undef>.
3086
3087 See also L</find> and L</find_or_create>. For information on how to declare
3088 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
3089
3090 If you need to know if an existing row was updated or a new one created use
3091 L</update_or_new> and L<DBIx::Class::Row/in_storage> instead. Don't forget
3092 to call L<DBIx::Class::Row/insert> to save the newly created row to the
3093 database!
3094
3095 =cut
3096
3097 sub update_or_create {
3098   my $self = shift;
3099   my $attrs = (@_ > 1 && ref $_[-1] eq 'HASH' ? pop(@_) : {});
3100   my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
3101
3102   my $row = $self->find($cond, $attrs);
3103   if (defined $row) {
3104     $row->update($cond);
3105     return $row;
3106   }
3107
3108   return $self->new_result($cond)->insert;
3109 }
3110
3111 =head2 update_or_new
3112
3113 =over 4
3114
3115 =item Arguments: \%col_data, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
3116
3117 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
3118
3119 =back
3120
3121   $resultset->update_or_new({ col => $val, ... });
3122
3123 Like L</find_or_new> but if a row is found it is immediately updated via
3124 C<< $found_row->update (\%col_data) >>.
3125
3126 For example:
3127
3128   # In your application
3129   my $cd = $schema->resultset('CD')->update_or_new(
3130     {
3131       artist => 'Massive Attack',
3132       title  => 'Mezzanine',
3133       year   => 1998,
3134     },
3135     { key => 'cd_artist_title' }
3136   );
3137
3138   if ($cd->in_storage) {
3139       # the cd was updated
3140   }
3141   else {
3142       # the cd is not yet in the database, let's insert it
3143       $cd->insert;
3144   }
3145
3146 B<Note>: Make sure to read the documentation of L</find> and understand the
3147 significance of the C<key> attribute, as its lack may skew your search, and
3148 subsequently result in spurious new objects.
3149
3150 B<Note>: Take care when using C<update_or_new> with a table having
3151 columns with default values that you intend to be automatically
3152 supplied by the database (e.g. an auto_increment primary key column).
3153 In normal usage, the value of such columns should NOT be included at
3154 all in the call to C<update_or_new>, even when set to C<undef>.
3155
3156 See also L</find>, L</find_or_create> and L</find_or_new>.
3157
3158 =cut
3159
3160 sub update_or_new {
3161     my $self  = shift;
3162     my $attrs = ( @_ > 1 && ref $_[-1] eq 'HASH' ? pop(@_) : {} );
3163     my $cond  = ref $_[0] eq 'HASH' ? shift : {@_};
3164
3165     my $row = $self->find( $cond, $attrs );
3166     if ( defined $row ) {
3167         $row->update($cond);
3168         return $row;
3169     }
3170
3171     return $self->new_result($cond);
3172 }
3173
3174 =head2 get_cache
3175
3176 =over 4
3177
3178 =item Arguments: none
3179
3180 =item Return Value: L<\@result_objs|DBIx::Class::Manual::ResultClass> | undef
3181
3182 =back
3183
3184 Gets the contents of the cache for the resultset, if the cache is set.
3185
3186 The cache is populated either by using the L</prefetch> attribute to
3187 L</search> or by calling L</set_cache>.
3188
3189 =cut
3190
3191 sub get_cache {
3192   shift->{all_cache};
3193 }
3194
3195 =head2 set_cache
3196
3197 =over 4
3198
3199 =item Arguments: L<\@result_objs|DBIx::Class::Manual::ResultClass>
3200
3201 =item Return Value: L<\@result_objs|DBIx::Class::Manual::ResultClass>
3202
3203 =back
3204
3205 Sets the contents of the cache for the resultset. Expects an arrayref
3206 of objects of the same class as those produced by the resultset. Note that
3207 if the cache is set, the resultset will return the cached objects rather
3208 than re-querying the database even if the cache attr is not set.
3209
3210 The contents of the cache can also be populated by using the
3211 L</prefetch> attribute to L</search>.
3212
3213 =cut
3214
3215 sub set_cache {
3216   my ( $self, $data ) = @_;
3217   $self->throw_exception("set_cache requires an arrayref")
3218       if defined($data) && (ref $data ne 'ARRAY');
3219   $self->{all_cache} = $data;
3220 }
3221
3222 =head2 clear_cache
3223
3224 =over 4
3225
3226 =item Arguments: none
3227
3228 =item Return Value: undef
3229
3230 =back
3231
3232 Clears the cache for the resultset.
3233
3234 =cut
3235
3236 sub clear_cache {
3237   shift->set_cache(undef);
3238 }
3239
3240 =head2 is_paged
3241
3242 =over 4
3243
3244 =item Arguments: none
3245
3246 =item Return Value: true, if the resultset has been paginated
3247
3248 =back
3249
3250 =cut
3251
3252 sub is_paged {
3253   my ($self) = @_;
3254   return !!$self->{attrs}{page};
3255 }
3256
3257 =head2 is_ordered
3258
3259 =over 4
3260
3261 =item Arguments: none
3262
3263 =item Return Value: true, if the resultset has been ordered with C<order_by>.
3264
3265 =back
3266
3267 =cut
3268
3269 sub is_ordered {
3270   my ($self) = @_;
3271   return scalar $self->result_source->schema->storage->_extract_order_criteria($self->{attrs}{order_by});
3272 }
3273
3274 =head2 related_resultset
3275
3276 =over 4
3277
3278 =item Arguments: $rel_name
3279
3280 =item Return Value: L<$resultset|/search>
3281
3282 =back
3283
3284 Returns a related resultset for the supplied relationship name.
3285
3286   $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
3287
3288 =cut
3289
3290 sub related_resultset {
3291   $_[0]->throw_exception(
3292     'Extra arguments to $rs->related_resultset() were always quietly '
3293   . 'discarded without consideration, you need to switch to '
3294   . '...->related_resultset( $relname )->search_rs( $search, $args ) instead.'
3295   ) if @_ > 2;
3296
3297   return $_[0]->{related_resultsets}{$_[1]}
3298     if defined $_[0]->{related_resultsets}{$_[1]};
3299
3300   my ($self, $rel) = @_;
3301
3302   return $self->{related_resultsets}{$rel} = do {
3303     my $rsrc = $self->result_source;
3304     my $rel_info = $rsrc->relationship_info($rel);
3305
3306     $self->throw_exception(
3307       "search_related: result source '" . $rsrc->source_name .
3308         "' has no such relationship $rel")
3309       unless $rel_info;
3310
3311     my $attrs = $self->_chain_relationship($rel);
3312
3313     # Previously this atribute was deleted (instead of being set as it is now)
3314     # Doing so seems to be harmless in all available test permutations
3315     # See also 01d59a6a6 and mst's comment below
3316     #
3317     $attrs->{alias} = $rsrc->schema->storage->relname_to_table_alias(
3318       $rel,
3319       $attrs->{seen_join}{$rel}
3320     );
3321
3322     # since this is search_related, and we already slid the select window inwards
3323     # (the select/as attrs were deleted in the beginning), we need to flip all
3324     # left joins to inner, so we get the expected results
3325     #
3326     # The DBIC relationship chaining implementation is pretty simple - every
3327     # new related_relationship is pushed onto the {from} stack, and the {select}
3328     # window simply slides further in. This means that when we count somewhere
3329     # in the middle, we got to make sure that everything in the join chain is an
3330     # actual inner join, otherwise the count will come back with unpredictable
3331     # results (a resultset may be generated with _some_ rows regardless of if
3332     # the relation which the $rs currently selects has rows or not). E.g.
3333     # $artist_rs->cds->count - normally generates:
3334     # SELECT COUNT( * ) FROM artist me LEFT JOIN cd cds ON cds.artist = me.artistid
3335     # which actually returns the number of artists * (number of cds || 1)
3336     #
3337     # So what we do here is crawl {from}, determine if the current alias is at
3338     # the top of the stack, and if not - make sure the chain is inner-joined down
3339     # to the root.
3340     #
3341     my $switch_branch = find_join_path_to_alias(
3342       $attrs->{from},
3343       $attrs->{alias},
3344     );
3345
3346     if ( @{ $switch_branch || [] } ) {
3347
3348       # So it looks like we will have to switch some stuff around.
3349       # local() is useless here as we will be leaving the scope
3350       # anyway, and deep cloning is just too fucking expensive
3351       # So replace the first hashref in the node arrayref manually
3352       my @new_from = $attrs->{from}[0];
3353       my $sw_idx = { map { (values %$_), 1 } @$switch_branch }; #there's one k/v per join-path
3354
3355       for my $j ( @{$attrs->{from}}[ 1 .. $#{$attrs->{from}} ] ) {
3356         my $jalias = $j->[0]{-alias};
3357
3358         if ($sw_idx->{$jalias}) {
3359           my %attrs = %{$j->[0]};
3360           delete $attrs{-join_type};
3361           push @new_from, [
3362             \%attrs,
3363             @{$j}[ 1 .. $#$j ],
3364           ];
3365         }
3366         else {
3367           push @new_from, $j;
3368         }
3369       }
3370
3371       $attrs->{from} = \@new_from;
3372     }
3373
3374
3375     #XXX - temp fix for result_class bug. There likely is a more elegant fix -groditi
3376     delete $attrs->{result_class};
3377
3378     my $new = do {
3379
3380       # The reason we do this now instead of passing the alias to the
3381       # search_rs below is that if you wrap/overload resultset on the
3382       # source you need to know what alias it's -going- to have for things
3383       # to work sanely (e.g. RestrictWithObject wants to be able to add
3384       # extra query restrictions, and these may need to be $alias.)
3385       #                                       -- mst ~ 2007 (01d59a6a6)
3386       #
3387       # FIXME - this seems to be no longer neccessary (perhaps due to the
3388       # advances in relcond resolution. Testing DBIC::S::RWO and its only
3389       # dependent (as of Jun 2015 ) does not yield any difference with or
3390       # without this line. Nevertheless keep it as is for now, to minimize
3391       # churn, there is enough potential for breakage in 0.0829xx as it is
3392       #                                       -- ribasushi Jun 2015
3393       #
3394       my $rel_source = $rsrc->related_source($rel);
3395       local $rel_source->resultset_attributes->{alias} = $attrs->{alias};
3396
3397       $rel_source->resultset->search_rs( undef, $attrs );
3398     };
3399
3400     if (my $cache = $self->get_cache) {
3401       my @related_cache = map
3402         { $_->related_resultset($rel)->get_cache || () }
3403         @$cache
3404       ;
3405
3406       $new->set_cache([ map @$_, @related_cache ]) if @related_cache == @$cache;
3407     }
3408
3409     $new;
3410   };
3411 }
3412
3413 =head2 current_source_alias
3414
3415 =over 4
3416
3417 =item Arguments: none
3418
3419 =item Return Value: $source_alias
3420
3421 =back
3422
3423 Returns the current table alias for the result source this resultset is built
3424 on, that will be used in the SQL query. Usually it is C<me>.
3425
3426 Currently the source alias that refers to the result set returned by a
3427 L</search>/L</find> family method depends on how you got to the resultset: it's
3428 C<me> by default, but eg. L</search_related> aliases it to the related result
3429 source name (and keeps C<me> referring to the original result set). The long
3430 term goal is to make L<DBIx::Class> always alias the current resultset as C<me>
3431 (and make this method unnecessary).
3432
3433 Thus it's currently necessary to use this method in predefined queries (see
3434 L<DBIx::Class::Manual::Cookbook/Predefined searches>) when referring to the
3435 source alias of the current result set:
3436
3437   # in a result set class
3438   sub modified_by {
3439     my ($self, $user) = @_;
3440
3441     my $me = $self->current_source_alias;
3442
3443     return $self->search({
3444       "$me.modified" => $user->id,
3445     });
3446   }
3447
3448 The alias of L<newly created resultsets|/search> can be altered by the
3449 L<alias attribute|/alias>.
3450
3451 =cut
3452
3453 sub current_source_alias {
3454   return (shift->{attrs} || {})->{alias} || 'me';
3455 }
3456
3457 =head2 as_subselect_rs
3458
3459 =over 4
3460
3461 =item Arguments: none
3462
3463 =item Return Value: L<$resultset|/search>
3464
3465 =back
3466
3467 Act as a barrier to SQL symbols.  The resultset provided will be made into a
3468 "virtual view" by including it as a subquery within the from clause.  From this
3469 point on, any joined tables are inaccessible to ->search on the resultset (as if
3470 it were simply where-filtered without joins).  For example:
3471
3472  my $rs = $schema->resultset('Bar')->search({'x.name' => 'abc'},{ join => 'x' });
3473
3474  # 'x' now pollutes the query namespace
3475
3476  # So the following works as expected
3477  my $ok_rs = $rs->search({'x.other' => 1});
3478
3479  # But this doesn't: instead of finding a 'Bar' related to two x rows (abc and
3480  # def) we look for one row with contradictory terms and join in another table
3481  # (aliased 'x_2') which we never use
3482  my $broken_rs = $rs->search({'x.name' => 'def'});
3483
3484  my $rs2 = $rs->as_subselect_rs;
3485
3486  # doesn't work - 'x' is no longer accessible in $rs2, having been sealed away
3487  my $not_joined_rs = $rs2->search({'x.other' => 1});
3488
3489  # works as expected: finds a 'table' row related to two x rows (abc and def)
3490  my $correctly_joined_rs = $rs2->search({'x.name' => 'def'});
3491
3492 Another example of when one might use this would be to select a subset of
3493 columns in a group by clause:
3494
3495  my $rs = $schema->resultset('Bar')->search(undef, {
3496    group_by => [qw{ id foo_id baz_id }],
3497  })->as_subselect_rs->search(undef, {
3498    columns => [qw{ id foo_id }]
3499  });
3500
3501 In the above example normally columns would have to be equal to the group by,
3502 but because we isolated the group by into a subselect the above works.
3503
3504 =cut
3505
3506 sub as_subselect_rs {
3507
3508   # FIXME - remove at some point in the future (2018-ish)
3509   wantarray
3510     and
3511   carp_unique(
3512     'Starting with DBIC@0.082900 as_subselect_rs() always returns a ResultSet '
3513   . 'instance regardless of calling context. Please force scalar() context to '
3514   . 'silence this warning'
3515   )
3516     and
3517   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_WANTARRAY
3518     and
3519   my $sog = fail_on_internal_wantarray
3520   ;
3521
3522   my $self = shift;
3523
3524   my $alias = $self->current_source_alias;
3525
3526   my $fresh_rs = (ref $self)->new (
3527     $self->result_source
3528   );
3529
3530   # these pieces will be locked in the subquery
3531   delete $fresh_rs->{cond};
3532   delete @{$fresh_rs->{attrs}}{qw/where bind/};
3533
3534   $fresh_rs->search_rs( {}, {
3535     from => [{
3536       $alias => $self->as_query,
3537       -alias  => $alias,
3538       -rsrc   => $self->result_source,
3539     }],
3540     alias => $alias,
3541   });
3542 }
3543
3544 # This code is called by search_related, and makes sure there
3545 # is clear separation between the joins before, during, and
3546 # after the relationship. This information is needed later
3547 # in order to properly resolve prefetch aliases (any alias
3548 # with a relation_chain_depth less than the depth of the
3549 # current prefetch is not considered)
3550 #
3551 # The increments happen twice per join. An even number means a
3552 # relationship specified via a search_related, whereas an odd
3553 # number indicates a join/prefetch added via attributes
3554 #
3555 # Also this code will wrap the current resultset (the one we
3556 # chain to) in a subselect IFF it contains limiting attributes
3557 sub _chain_relationship {
3558   my ($self, $rel) = @_;
3559   my $source = $self->result_source;
3560   my $attrs = { %{$self->{attrs}||{}} };
3561
3562   # we need to take the prefetch the attrs into account before we
3563   # ->_resolve_join as otherwise they get lost - captainL
3564   my $join = $self->_merge_joinpref_attr( $attrs->{join}, $attrs->{prefetch} );
3565
3566   delete @{$attrs}{qw/join prefetch collapse group_by distinct _grouped_by_distinct select as columns +select +as +columns/};
3567
3568   my $seen = { %{ (delete $attrs->{seen_join}) || {} } };
3569
3570   my $from;
3571   my @force_subq_attrs = qw/offset rows group_by having/;
3572
3573   if (
3574     ($attrs->{from} && ref $attrs->{from} ne 'ARRAY')
3575       ||
3576     $self->_has_resolved_attr (@force_subq_attrs)
3577   ) {
3578     # Nuke the prefetch (if any) before the new $rs attrs
3579     # are resolved (prefetch is useless - we are wrapping
3580     # a subquery anyway).
3581     my $rs_copy = $self->search;
3582     $rs_copy->{attrs}{join} = $self->_merge_joinpref_attr (
3583       $rs_copy->{attrs}{join},
3584       delete $rs_copy->{attrs}{prefetch},
3585     );
3586
3587     $from = [{
3588       -rsrc   => $source,
3589       -alias  => $attrs->{alias},
3590       $attrs->{alias} => $rs_copy->as_query,
3591     }];
3592     delete @{$attrs}{@force_subq_attrs, qw/where bind/};
3593     $seen->{-relation_chain_depth} = 0;
3594   }
3595   elsif ($attrs->{from}) {  #shallow copy suffices
3596     $from = [ @{$attrs->{from}} ];
3597   }
3598   else {
3599     $from = [{
3600       -rsrc  => $source,
3601       -alias => $attrs->{alias},
3602       $attrs->{alias} => $source->from,
3603     }];
3604   }
3605
3606   my $jpath = ($seen->{-relation_chain_depth})
3607     ? $from->[-1][0]{-join_path}
3608     : [];
3609
3610   my @requested_joins = $source->_resolve_join(
3611     $join,
3612     $attrs->{alias},
3613     $seen,
3614     $jpath,
3615   );
3616
3617   push @$from, @requested_joins;
3618
3619   $seen->{-relation_chain_depth}++;
3620
3621   # if $self already had a join/prefetch specified on it, the requested
3622   # $rel might very well be already included. What we do in this case
3623   # is effectively a no-op (except that we bump up the chain_depth on
3624   # the join in question so we could tell it *is* the search_related)
3625   my $already_joined;
3626
3627   # we consider the last one thus reverse
3628   for my $j (reverse @requested_joins) {
3629     my ($last_j) = keys %{$j->[0]{-join_path}[-1]};
3630     if ($rel eq $last_j) {
3631       $j->[0]{-relation_chain_depth}++;
3632       $already_joined++;
3633       last;
3634     }
3635   }
3636
3637   unless ($already_joined) {
3638     push @$from, $source->_resolve_join(
3639       $rel,
3640       $attrs->{alias},
3641       $seen,
3642       $jpath,
3643     );
3644   }
3645
3646   $seen->{-relation_chain_depth}++;
3647
3648   return {%$attrs, from => $from, seen_join => $seen};
3649 }
3650
3651 sub _resolved_attrs {
3652   my $self = shift;
3653   return $self->{_attrs} if $self->{_attrs};
3654
3655   my $attrs  = { %{ $self->{attrs} || {} } };
3656   my $source = $attrs->{result_source} = $self->result_source;
3657   my $alias  = $attrs->{alias};
3658
3659   $self->throw_exception("Specifying distinct => 1 in conjunction with collapse => 1 is unsupported")
3660     if $attrs->{collapse} and $attrs->{distinct};
3661
3662
3663   # Sanity check the paging attributes
3664   # SQLMaker does it too, but in case of a software_limit we'll never get there
3665   if (defined $attrs->{offset}) {
3666     $self->throw_exception('A supplied offset attribute must be a non-negative integer')
3667       if ( $attrs->{offset} =~ /[^0-9]/ or $attrs->{offset} < 0 );
3668   }
3669   if (defined $attrs->{rows}) {
3670     $self->throw_exception("The rows attribute must be a positive integer if present")
3671       if ( $attrs->{rows} =~ /[^0-9]/ or $attrs->{rows} <= 0 );
3672   }
3673
3674   # normalize where condition
3675   $attrs->{where} = normalize_sqla_condition( $attrs->{where} )
3676     if $attrs->{where};
3677
3678   # default selection list
3679   $attrs->{columns} = [ $source->columns ]
3680     unless grep { exists $attrs->{$_} } qw/columns cols select as/;
3681
3682   # merge selectors together
3683   for (qw/columns select as/) {
3684     $attrs->{$_} = $self->_merge_attr($attrs->{$_}, delete $attrs->{"+$_"})
3685       if $attrs->{$_} or $attrs->{"+$_"};
3686   }
3687
3688   # disassemble columns
3689   my (@sel, @as);
3690   if (my $cols = delete $attrs->{columns}) {
3691     for my $c (ref $cols eq 'ARRAY' ? @$cols : $cols) {
3692       if (ref $c eq 'HASH') {
3693         for my $as (sort keys %$c) {
3694           push @sel, $c->{$as};
3695           push @as, $as;
3696         }
3697       }
3698       else {
3699         push @sel, $c;
3700         push @as, $c;
3701       }
3702     }
3703   }
3704
3705   # when trying to weed off duplicates later do not go past this point -
3706   # everything added from here on is unbalanced "anyone's guess" stuff
3707   my $dedup_stop_idx = $#as;
3708
3709   push @as, @{ ref $attrs->{as} eq 'ARRAY' ? $attrs->{as} : [ $attrs->{as} ] }
3710     if $attrs->{as};
3711   push @sel, @{ ref $attrs->{select} eq 'ARRAY' ? $attrs->{select} : [ $attrs->{select} ] }
3712     if $attrs->{select};
3713
3714   # assume all unqualified selectors to apply to the current alias (legacy stuff)
3715   $_ = (ref $_ or $_ =~ /\./) ? $_ : "$alias.$_" for @sel;
3716
3717   # disqualify all $alias.col as-bits (inflate-map mandated)
3718   $_ = ($_ =~ /^\Q$alias.\E(.+)$/) ? $1 : $_ for @as;
3719
3720   # de-duplicate the result (remove *identical* select/as pairs)
3721   # and also die on duplicate {as} pointing to different {select}s
3722   # not using a c-style for as the condition is prone to shrinkage
3723   my $seen;
3724   my $i = 0;
3725   while ($i <= $dedup_stop_idx) {
3726     if ($seen->{"$sel[$i] \x00\x00 $as[$i]"}++) {
3727       splice @sel, $i, 1;
3728       splice @as, $i, 1;
3729       $dedup_stop_idx--;
3730     }
3731     elsif ($seen->{$as[$i]}++) {
3732       $self->throw_exception(
3733         "inflate_result() alias '$as[$i]' specified twice with different SQL-side {select}-ors"
3734       );
3735     }
3736     else {
3737       $i++;
3738     }
3739   }
3740
3741   $attrs->{select} = \@sel;
3742   $attrs->{as} = \@as;
3743
3744   $attrs->{from} ||= [{
3745     -rsrc   => $source,
3746     -alias  => $self->{attrs}{alias},
3747     $self->{attrs}{alias} => $source->from,
3748   }];
3749
3750   if ( $attrs->{join} || $attrs->{prefetch} ) {
3751
3752     $self->throw_exception ('join/prefetch can not be used with a custom {from}')
3753       if ref $attrs->{from} ne 'ARRAY';
3754
3755     my $join = (delete $attrs->{join}) || {};
3756
3757     if ( defined $attrs->{prefetch} ) {
3758       $join = $self->_merge_joinpref_attr( $join, $attrs->{prefetch} );
3759     }
3760
3761     $attrs->{from} =    # have to copy here to avoid corrupting the original
3762       [
3763         @{ $attrs->{from} },
3764         $source->_resolve_join(
3765           $join,
3766           $alias,
3767           { %{ $attrs->{seen_join} || {} } },
3768           ( $attrs->{seen_join} && keys %{$attrs->{seen_join}})
3769             ? $attrs->{from}[-1][0]{-join_path}
3770             : []
3771           ,
3772         )
3773       ];
3774   }
3775
3776
3777   for my $attr (qw(order_by group_by)) {
3778
3779     if ( defined $attrs->{$attr} ) {
3780       $attrs->{$attr} = (
3781         ref( $attrs->{$attr} ) eq 'ARRAY'
3782         ? [ @{ $attrs->{$attr} } ]
3783         : [ $attrs->{$attr} || () ]
3784       );
3785
3786       delete $attrs->{$attr} unless @{$attrs->{$attr}};
3787     }
3788   }
3789
3790
3791   # set collapse default based on presence of prefetch
3792   my $prefetch;
3793   if (
3794     defined $attrs->{prefetch}
3795       and
3796     $prefetch = $self->_merge_joinpref_attr( {}, delete $attrs->{prefetch} )
3797   ) {
3798     $self->throw_exception("Specifying prefetch in conjunction with an explicit collapse => 0 is unsupported")
3799       if defined $attrs->{collapse} and ! $attrs->{collapse};
3800
3801     $attrs->{collapse} = 1;
3802   }
3803
3804
3805   # run through the resulting joinstructure (starting from our current slot)
3806   # and unset collapse if proven unnecessary
3807   #
3808   # also while we are at it find out if the current root source has
3809   # been premultiplied by previous related_source chaining
3810   #
3811   # this allows to predict whether a root object with all other relation
3812   # data set to NULL is in fact unique
3813   if ($attrs->{collapse}) {
3814
3815     if (ref $attrs->{from} eq 'ARRAY') {
3816
3817       if (@{$attrs->{from}} == 1) {
3818         # no joins - no collapse
3819         $attrs->{collapse} = 0;
3820       }
3821       else {
3822         # find where our table-spec starts
3823         my @fromlist = @{$attrs->{from}};
3824         while (@fromlist) {
3825           my $t = shift @fromlist;
3826
3827           my $is_multi;
3828           # me vs join from-spec distinction - a ref means non-root
3829           if (ref $t eq 'ARRAY') {
3830             $t = $t->[0];
3831             $is_multi ||= ! $t->{-is_single};
3832           }
3833           last if ($t->{-alias} && $t->{-alias} eq $alias);
3834           $attrs->{_main_source_premultiplied} ||= $is_multi;
3835         }
3836
3837         # no non-singles remaining, nor any premultiplication - nothing to collapse
3838         if (
3839           ! $attrs->{_main_source_premultiplied}
3840             and
3841           ! grep { ! $_->[0]{-is_single} } @fromlist
3842         ) {
3843           $attrs->{collapse} = 0;
3844         }
3845       }
3846     }
3847
3848     else {
3849       # if we can not analyze the from - err on the side of safety
3850       $attrs->{_main_source_premultiplied} = 1;
3851     }
3852   }
3853
3854
3855   # generate the distinct induced group_by before injecting the prefetched select/as parts
3856   if (delete $attrs->{distinct}) {
3857     if ($attrs->{group_by}) {
3858       carp_unique ("Useless use of distinct on a grouped resultset ('distinct' is ignored when a 'group_by' is present)");
3859     }
3860     else {
3861       $attrs->{_grouped_by_distinct} = 1;
3862       # distinct affects only the main selection part, not what prefetch may add below
3863       ($attrs->{group_by}, my $new_order) = $source->schema->storage->_group_over_selection($attrs);
3864
3865       # FIXME possibly ignore a rewritten order_by (may turn out to be an issue)
3866       # The thinking is: if we are collapsing the subquerying prefetch engine will
3867       # rip stuff apart for us anyway, and we do not want to have a potentially
3868       # function-converted external order_by
3869       # ( there is an explicit if ( collapse && _grouped_by_distinct ) check in DBIHacks )
3870       $attrs->{order_by} = $new_order unless $attrs->{collapse};
3871     }
3872   }
3873
3874
3875   # generate selections based on the prefetch helper
3876   if ($prefetch) {
3877
3878     $self->throw_exception("Unable to prefetch, resultset contains an unnamed selector $attrs->{_dark_selector}{string}")
3879       if $attrs->{_dark_selector};
3880
3881     # this is a separate structure (we don't look in {from} directly)
3882     # as the resolver needs to shift things off the lists to work
3883     # properly (identical-prefetches on different branches)
3884     my $joined_node_aliases_map = {};
3885     if (ref $attrs->{from} eq 'ARRAY') {
3886
3887       my $start_depth = $attrs->{seen_join}{-relation_chain_depth} || 0;
3888
3889       for my $j ( @{$attrs->{from}}[1 .. $#{$attrs->{from}} ] ) {
3890         next unless $j->[0]{-alias};
3891         next unless $j->[0]{-join_path};
3892         next if ($j->[0]{-relation_chain_depth} || 0) < $start_depth;
3893
3894         my @jpath = map { keys %$_ } @{$j->[0]{-join_path}};
3895
3896         my $p = $joined_node_aliases_map;
3897         $p = $p->{$_} ||= {} for @jpath[ ($start_depth/2) .. $#jpath]; #only even depths are actual jpath boundaries
3898         push @{$p->{-join_aliases} }, $j->[0]{-alias};
3899       }
3900     }
3901
3902     ( push @{$attrs->{select}}, $_->[0] ) and ( push @{$attrs->{as}}, $_->[1] )
3903       for $source->_resolve_selection_from_prefetch( $prefetch, $joined_node_aliases_map );
3904   }
3905
3906
3907   $attrs->{_simple_passthrough_construction} = !(
3908     $attrs->{collapse}
3909       or
3910     grep { $_ =~ /\./ } @{$attrs->{as}}
3911   );
3912
3913
3914   # if both page and offset are specified, produce a combined offset
3915   # even though it doesn't make much sense, this is what pre 081xx has
3916   # been doing
3917   if (my $page = delete $attrs->{page}) {
3918     $attrs->{offset} =
3919       ($attrs->{rows} * ($page - 1))
3920             +
3921       ($attrs->{offset} || 0)
3922     ;
3923   }
3924
3925   return $self->{_attrs} = $attrs;
3926 }
3927
3928 sub _rollout_attr {
3929   my ($self, $attr) = @_;
3930
3931   if (ref $attr eq 'HASH') {
3932     return $self->_rollout_hash($attr);
3933   } elsif (ref $attr eq 'ARRAY') {
3934     return $self->_rollout_array($attr);
3935   } else {
3936     return [$attr];
3937   }
3938 }
3939
3940 sub _rollout_array {
3941   my ($self, $attr) = @_;
3942
3943   my @rolled_array;
3944   foreach my $element (@{$attr}) {
3945     if (ref $element eq 'HASH') {
3946       push( @rolled_array, @{ $self->_rollout_hash( $element ) } );
3947     } elsif (ref $element eq 'ARRAY') {
3948       #  XXX - should probably recurse here
3949       push( @rolled_array, @{$self->_rollout_array($element)} );
3950     } else {
3951       push( @rolled_array, $element );
3952     }
3953   }
3954   return \@rolled_array;
3955 }
3956
3957 sub _rollout_hash {
3958   my ($self, $attr) = @_;
3959
3960   my @rolled_array;
3961   foreach my $key (keys %{$attr}) {
3962     push( @rolled_array, { $key => $attr->{$key} } );
3963   }
3964   return \@rolled_array;
3965 }
3966
3967 sub _calculate_score {
3968   my ($self, $a, $b) = @_;
3969
3970   if (defined $a xor defined $b) {
3971     return 0;
3972   }
3973   elsif (not defined $a) {
3974     return 1;
3975   }
3976
3977   if (ref $b eq 'HASH') {
3978     my ($b_key) = keys %{$b};
3979     $b_key = '' if ! defined $b_key;
3980     if (ref $a eq 'HASH') {
3981       my ($a_key) = keys %{$a};
3982       $a_key = '' if ! defined $a_key;
3983       if ($a_key eq $b_key) {
3984         return (1 + $self->_calculate_score( $a->{$a_key}, $b->{$b_key} ));
3985       } else {
3986         return 0;
3987       }
3988     } else {
3989       return ($a eq $b_key) ? 1 : 0;
3990     }
3991   } else {
3992     if (ref $a eq 'HASH') {
3993       my ($a_key) = keys %{$a};
3994       return ($b eq $a_key) ? 1 : 0;
3995     } else {
3996       return ($b eq $a) ? 1 : 0;
3997     }
3998   }
3999 }
4000
4001 sub _merge_joinpref_attr {
4002   my ($self, $orig, $import) = @_;
4003
4004   return $import unless defined($orig);
4005   return $orig unless defined($import);
4006
4007   $orig = $self->_rollout_attr($orig);
4008   $import = $self->_rollout_attr($import);
4009
4010   my $seen_keys;
4011   foreach my $import_element ( @{$import} ) {
4012     # find best candidate from $orig to merge $b_element into
4013     my $best_candidate = { position => undef, score => 0 }; my $position = 0;
4014     foreach my $orig_element ( @{$orig} ) {
4015       my $score = $self->_calculate_score( $orig_element, $import_element );
4016       if ($score > $best_candidate->{score}) {
4017         $best_candidate->{position} = $position;
4018         $best_candidate->{score} = $score;
4019       }
4020       $position++;
4021     }
4022     my ($import_key) = ( ref $import_element eq 'HASH' ) ? keys %{$import_element} : ($import_element);
4023     $import_key = '' if not defined $import_key;
4024
4025     if ($best_candidate->{score} == 0 || exists $seen_keys->{$import_key}) {
4026       push( @{$orig}, $import_element );
4027     } else {
4028       my $orig_best = $orig->[$best_candidate->{position}];
4029       # merge orig_best and b_element together and replace original with merged
4030       if (ref $orig_best ne 'HASH') {
4031         $orig->[$best_candidate->{position}] = $import_element;
4032       } elsif (ref $import_element eq 'HASH') {
4033         my ($key) = keys %{$orig_best};
4034         $orig->[$best_candidate->{position}] = { $key => $self->_merge_joinpref_attr($orig_best->{$key}, $import_element->{$key}) };
4035       }
4036     }
4037     $seen_keys->{$import_key} = 1; # don't merge the same key twice
4038   }
4039
4040   return @$orig ? $orig : ();
4041 }
4042
4043 {
4044   my $hm;
4045
4046   sub _merge_attr {
4047     $hm ||= do {
4048       require Hash::Merge;
4049       my $hm = Hash::Merge->new;
4050
4051       $hm->specify_behavior({
4052         SCALAR => {
4053           SCALAR => sub {
4054             my ($defl, $defr) = map { defined $_ } (@_[0,1]);
4055
4056             if ($defl xor $defr) {
4057               return [ $defl ? $_[0] : $_[1] ];
4058             }
4059             elsif (! $defl) {
4060               return [];
4061             }
4062             elsif (__HM_DEDUP and $_[0] eq $_[1]) {
4063               return [ $_[0] ];
4064             }
4065             else {
4066               return [$_[0], $_[1]];
4067             }
4068           },
4069           ARRAY => sub {
4070             return $_[1] if !defined $_[0];
4071             return $_[1] if __HM_DEDUP and grep { $_ eq $_[0] } @{$_[1]};
4072             return [$_[0], @{$_[1]}]
4073           },
4074           HASH  => sub {
4075             return [] if !defined $_[0] and !keys %{$_[1]};
4076             return [ $_[1] ] if !defined $_[0];
4077             return [ $_[0] ] if !keys %{$_[1]};
4078             return [$_[0], $_[1]]
4079           },
4080         },
4081         ARRAY => {
4082           SCALAR => sub {
4083             return $_[0] if !defined $_[1];
4084             return $_[0] if __HM_DEDUP and grep { $_ eq $_[1] } @{$_[0]};
4085             return [@{$_[0]}, $_[1]]
4086           },
4087           ARRAY => sub {
4088             my @ret = @{$_[0]} or return $_[1];
4089             return [ @ret, @{$_[1]} ] unless __HM_DEDUP;
4090             my %idx = map { $_ => 1 } @ret;
4091             push @ret, grep { ! defined $idx{$_} } (@{$_[1]});
4092             \@ret;
4093           },
4094           HASH => sub {
4095             return [ $_[1] ] if ! @{$_[0]};
4096             return $_[0] if !keys %{$_[1]};
4097             return $_[0] if __HM_DEDUP and grep { $_ eq $_[1] } @{$_[0]};
4098             return [ @{$_[0]}, $_[1] ];
4099           },
4100         },
4101         HASH => {
4102           SCALAR => sub {
4103             return [] if !keys %{$_[0]} and !defined $_[1];
4104             return [ $_[0] ] if !defined $_[1];
4105             return [ $_[1] ] if !keys %{$_[0]};
4106             return [$_[0], $_[1]]
4107           },
4108           ARRAY => sub {
4109             return [] if !keys %{$_[0]} and !@{$_[1]};
4110             return [ $_[0] ] if !@{$_[1]};
4111             return $_[1] if !keys %{$_[0]};
4112             return $_[1] if __HM_DEDUP and grep { $_ eq $_[0] } @{$_[1]};
4113             return [ $_[0], @{$_[1]} ];
4114           },
4115           HASH => sub {
4116             return [] if !keys %{$_[0]} and !keys %{$_[1]};
4117             return [ $_[0] ] if !keys %{$_[1]};
4118             return [ $_[1] ] if !keys %{$_[0]};
4119             return [ $_[0] ] if $_[0] eq $_[1];
4120             return [ $_[0], $_[1] ];
4121           },
4122         }
4123       } => 'DBIC_RS_ATTR_MERGER');
4124       $hm;
4125     };
4126
4127     return $hm->merge ($_[1], $_[2]);
4128   }
4129 }
4130
4131 sub STORABLE_freeze {
4132   my ($self, $cloning) = @_;
4133   my $to_serialize = { %$self };
4134
4135   # A cursor in progress can't be serialized (and would make little sense anyway)
4136   # the parser can be regenerated (and can't be serialized)
4137   delete @{$to_serialize}{qw/cursor _row_parser _result_inflator/};
4138
4139   # nor is it sensical to store a not-yet-fired-count pager
4140   if ($to_serialize->{pager} and ref $to_serialize->{pager}{total_entries} eq 'CODE') {
4141     delete $to_serialize->{pager};
4142   }
4143
4144   Storable::nfreeze($to_serialize);
4145 }
4146
4147 # need this hook for symmetry
4148 sub STORABLE_thaw {
4149   my ($self, $cloning, $serialized) = @_;
4150
4151   %$self = %{ Storable::thaw($serialized) };
4152
4153   $self;
4154 }
4155
4156
4157 =head2 throw_exception
4158
4159 See L<DBIx::Class::Schema/throw_exception> for details.
4160
4161 =cut
4162
4163 sub throw_exception {
4164   my $self=shift;
4165
4166   if (ref $self and my $rsrc = $self->result_source) {
4167     $rsrc->throw_exception(@_)
4168   }
4169   else {
4170     DBIx::Class::Exception->throw(@_);
4171   }
4172 }
4173
4174 1;
4175
4176 __END__
4177
4178 # XXX: FIXME: Attributes docs need clearing up
4179
4180 =head1 ATTRIBUTES
4181
4182 Attributes are used to refine a ResultSet in various ways when
4183 searching for data. They can be passed to any method which takes an
4184 C<\%attrs> argument. See L</search>, L</search_rs>, L</find>,
4185 L</count>.
4186
4187 Default attributes can be set on the result class using
4188 L<DBIx::Class::ResultSource/resultset_attributes>.  (Please read
4189 the CAVEATS on that feature before using it!)
4190
4191 These are in no particular order:
4192
4193 =head2 order_by
4194
4195 =over 4
4196
4197 =item Value: ( $order_by | \@order_by | \%order_by )
4198
4199 =back
4200
4201 Which column(s) to order the results by.
4202
4203 [The full list of suitable values is documented in
4204 L<SQL::Abstract/"ORDER BY CLAUSES">; the following is a summary of
4205 common options.]
4206
4207 If a single column name, or an arrayref of names is supplied, the
4208 argument is passed through directly to SQL. The hashref syntax allows
4209 for connection-agnostic specification of ordering direction:
4210
4211  For descending order:
4212
4213   order_by => { -desc => [qw/col1 col2 col3/] }
4214
4215  For explicit ascending order:
4216
4217   order_by => { -asc => 'col' }
4218
4219 The old scalarref syntax (i.e. order_by => \'year DESC') is still
4220 supported, although you are strongly encouraged to use the hashref
4221 syntax as outlined above.
4222
4223 =head2 columns
4224
4225 =over 4
4226
4227 =item Value: \@columns | \%columns | $column
4228
4229 =back
4230
4231 Shortcut to request a particular set of columns to be retrieved. Each
4232 column spec may be a string (a table column name), or a hash (in which
4233 case the key is the C<as> value, and the value is used as the C<select>
4234 expression). Adds the L</current_source_alias> onto the start of any column without a C<.> in
4235 it and sets C<select> from that, then auto-populates C<as> from
4236 C<select> as normal. (You may also use the C<cols> attribute, as in
4237 earlier versions of DBIC, but this is deprecated)
4238
4239 Essentially C<columns> does the same as L</select> and L</as>.
4240
4241     columns => [ 'some_column', { dbic_slot => 'another_column' } ]
4242
4243 is the same as
4244
4245     select => [qw(some_column another_column)],
4246     as     => [qw(some_column dbic_slot)]
4247
4248 If you want to individually retrieve related columns (in essence perform
4249 manual L</prefetch>) you have to make sure to specify the correct inflation slot
4250 chain such that it matches existing relationships:
4251
4252     my $rs = $schema->resultset('Artist')->search({}, {
4253         # required to tell DBIC to collapse has_many relationships
4254         collapse => 1,
4255         join     => { cds => 'tracks' },
4256         '+columns'  => {
4257           'cds.cdid'         => 'cds.cdid',
4258           'cds.tracks.title' => 'tracks.title',
4259         },
4260     });
4261
4262 Like elsewhere, literal SQL or literal values can be included by using a
4263 scalar reference or a literal bind value, and these values will be available
4264 in the result with C<get_column> (see also
4265 L<SQL::Abstract/Literal SQL and value type operators>):
4266
4267     # equivalent SQL: SELECT 1, 'a string', IF(my_column,?,?) ...
4268     # bind values: $true_value, $false_value
4269     columns => [
4270         {
4271             foo => \1,
4272             bar => \q{'a string'},
4273             baz => \[ 'IF(my_column,?,?)', $true_value, $false_value ],
4274         }
4275     ]
4276
4277 =head2 +columns
4278
4279 B<NOTE:> You B<MUST> explicitly quote C<'+columns'> when using this attribute.
4280 Not doing so causes Perl to incorrectly interpret C<+columns> as a bareword
4281 with a unary plus operator before it, which is the same as simply C<columns>.
4282
4283 =over 4
4284
4285 =item Value: \@extra_columns
4286
4287 =back
4288
4289 Indicates additional columns to be selected from storage. Works the same as
4290 L</columns> but adds columns to the current selection. (You may also use the
4291 C<include_columns> attribute, as in earlier versions of DBIC, but this is
4292 deprecated)
4293
4294   $schema->resultset('CD')->search(undef, {
4295     '+columns' => ['artist.name'],
4296     join => ['artist']
4297   });
4298
4299 would return all CDs and include a 'name' column to the information
4300 passed to object inflation. Note that the 'artist' is the name of the
4301 column (or relationship) accessor, and 'name' is the name of the column
4302 accessor in the related table.
4303
4304 =head2 select
4305
4306 =over 4
4307
4308 =item Value: \@select_columns
4309
4310 =back
4311
4312 Indicates which columns should be selected from the storage. You can use
4313 column names, or in the case of RDBMS back ends, function or stored procedure
4314 names:
4315
4316   $rs = $schema->resultset('Employee')->search(undef, {
4317     select => [
4318       'name',
4319       { count => 'employeeid' },
4320       { max => { length => 'name' }, -as => 'longest_name' }
4321     ]
4322   });
4323
4324   # Equivalent SQL
4325   SELECT name, COUNT( employeeid ), MAX( LENGTH( name ) ) AS longest_name FROM employee
4326
4327 B<NOTE:> You will almost always need a corresponding L</as> attribute when you
4328 use L</select>, to instruct DBIx::Class how to store the result of the column.
4329
4330 Also note that the L</as> attribute has B<nothing to do> with the SQL-side
4331 C<AS> identifier aliasing. You B<can> alias a function (so you can use it e.g.
4332 in an C<ORDER BY> clause), however this is done via the C<-as> B<select
4333 function attribute> supplied as shown in the example above.
4334
4335 =head2 +select
4336
4337 B<NOTE:> You B<MUST> explicitly quote C<'+select'> when using this attribute.
4338 Not doing so causes Perl to incorrectly interpret C<+select> as a bareword
4339 with a unary plus operator before it, which is the same as simply C<select>.
4340
4341 =over 4
4342
4343 =item Value: \@extra_select_columns
4344
4345 =back
4346
4347 Indicates additional columns to be selected from storage.  Works the same as
4348 L</select> but adds columns to the current selection, instead of specifying
4349 a new explicit list.
4350
4351 =head2 as
4352
4353 =over 4
4354
4355 =item Value: \@inflation_names
4356
4357 =back
4358
4359 Indicates DBIC-side names for object inflation. That is L</as> indicates the
4360 slot name in which the column value will be stored within the
4361 L<Row|DBIx::Class::Row> object. The value will then be accessible via this
4362 identifier by the C<get_column> method (or via the object accessor B<if one
4363 with the same name already exists>) as shown below.
4364
4365 The L</as> attribute has B<nothing to do> with the SQL-side identifier
4366 aliasing C<AS>. See L</select> for details.
4367
4368   $rs = $schema->resultset('Employee')->search(undef, {
4369     select => [
4370       'name',
4371       { count => 'employeeid' },
4372       { max => { length => 'name' }, -as => 'longest_name' }
4373     ],
4374     as => [qw/
4375       name
4376       employee_count
4377       max_name_length
4378     /],
4379   });
4380
4381 If the object against which the search is performed already has an accessor
4382 matching a column name specified in C<as>, the value can be retrieved using
4383 the accessor as normal:
4384
4385   my $name = $employee->name();
4386
4387 If on the other hand an accessor does not exist in the object, you need to
4388 use C<get_column> instead:
4389
4390   my $employee_count = $employee->get_column('employee_count');
4391
4392 You can create your own accessors if required - see
4393 L<DBIx::Class::Manual::Cookbook> for details.
4394
4395 =head2 +as
4396
4397 B<NOTE:> You B<MUST> explicitly quote C<'+as'> when using this attribute.
4398 Not doing so causes Perl to incorrectly interpret C<+as> as a bareword
4399 with a unary plus operator before it, which is the same as simply C<as>.
4400
4401 =over 4
4402
4403 =item Value: \@extra_inflation_names
4404
4405 =back
4406
4407 Indicates additional inflation names for selectors added via L</+select>. See L</as>.
4408
4409 =head2 join
4410
4411 =over 4
4412
4413 =item Value: ($rel_name | \@rel_names | \%rel_names)
4414
4415 =back
4416
4417 Contains a list of relationships that should be joined for this query.  For
4418 example:
4419
4420   # Get CDs by Nine Inch Nails
4421   my $rs = $schema->resultset('CD')->search(
4422     { 'artist.name' => 'Nine Inch Nails' },
4423     { join => 'artist' }
4424   );
4425
4426 Can also contain a hash reference to refer to the other relation's relations.
4427 For example:
4428
4429   package MyApp::Schema::Track;
4430   use base qw/DBIx::Class/;
4431   __PACKAGE__->table('track');
4432   __PACKAGE__->add_columns(qw/trackid cd position title/);
4433   __PACKAGE__->set_primary_key('trackid');
4434   __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
4435   1;
4436
4437   # In your application
4438   my $rs = $schema->resultset('Artist')->search(
4439     { 'track.title' => 'Teardrop' },
4440     {
4441       join     => { cd => 'track' },
4442       order_by => 'artist.name',
4443     }
4444   );
4445
4446 You need to use the relationship (not the table) name in  conditions,
4447 because they are aliased as such. The current table is aliased as "me", so
4448 you need to use me.column_name in order to avoid ambiguity. For example:
4449
4450   # Get CDs from 1984 with a 'Foo' track
4451   my $rs = $schema->resultset('CD')->search(
4452     {
4453       'me.year' => 1984,
4454       'tracks.name' => 'Foo'
4455     },
4456     { join => 'tracks' }
4457   );
4458
4459 If the same join is supplied twice, it will be aliased to <rel>_2 (and
4460 similarly for a third time). For e.g.
4461
4462   my $rs = $schema->resultset('Artist')->search({
4463     'cds.title'   => 'Down to Earth',
4464     'cds_2.title' => 'Popular',
4465   }, {
4466     join => [ qw/cds cds/ ],
4467   });
4468
4469 will return a set of all artists that have both a cd with title 'Down
4470 to Earth' and a cd with title 'Popular'.
4471
4472 If you want to fetch related objects from other tables as well, see L</prefetch>
4473 below.
4474
4475  NOTE: An internal join-chain pruner will discard certain joins while
4476  constructing the actual SQL query, as long as the joins in question do not
4477  affect the retrieved result. This for example includes 1:1 left joins
4478  that are not part of the restriction specification (WHERE/HAVING) nor are
4479  a part of the query selection.
4480
4481 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
4482
4483 =head2 collapse
4484
4485 =over 4
4486
4487 =item Value: (0 | 1)
4488
4489 =back
4490
4491 When set to a true value, indicates that any rows fetched from joined has_many
4492 relationships are to be aggregated into the corresponding "parent" object. For
4493 example, the resultset:
4494
4495   my $rs = $schema->resultset('CD')->search({}, {
4496     '+columns' => [ qw/ tracks.title tracks.position / ],
4497     join => 'tracks',
4498     collapse => 1,
4499   });
4500
4501 While executing the following query:
4502
4503   SELECT me.*, tracks.title, tracks.position
4504     FROM cd me
4505     LEFT JOIN track tracks
4506       ON tracks.cdid = me.cdid
4507
4508 Will return only as many objects as there are rows in the CD source, even
4509 though the result of the query may span many rows. Each of these CD objects
4510 will in turn have multiple "Track" objects hidden behind the has_many
4511 generated accessor C<tracks>. Without C<< collapse => 1 >>, the return values
4512 of this resultset would be as many CD objects as there are tracks (a "Cartesian
4513 product"), with each CD object containing exactly one of all fetched Track data.
4514
4515 When a collapse is requested on a non-ordered resultset, an order by some
4516 unique part of the main source (the left-most table) is inserted automatically.
4517 This is done so that the resultset is allowed to be "lazy" - calling
4518 L<< $rs->next|/next >> will fetch only as many rows as it needs to build the next
4519 object with all of its related data.
4520
4521 If an L</order_by> is already declared, and orders the resultset in a way that
4522 makes collapsing as described above impossible (e.g. C<< ORDER BY
4523 has_many_rel.column >> or C<ORDER BY RANDOM()>), DBIC will automatically
4524 switch to "eager" mode and slurp the entire resultset before constructing the
4525 first object returned by L</next>.
4526
4527 Setting this attribute on a resultset that does not join any has_many
4528 relations is a no-op.
4529
4530 For a more in-depth discussion, see L</PREFETCHING>.
4531
4532 =head2 prefetch
4533
4534 =over 4
4535
4536 =item Value: ($rel_name | \@rel_names | \%rel_names)
4537
4538 =back
4539
4540 This attribute is a shorthand for specifying a L</join> spec, adding all
4541 columns from the joined related sources as L</+columns> and setting
4542 L</collapse> to a true value. It can be thought of as a rough B<superset>
4543 of the L</join> attribute.
4544
4545 For example, the following two queries are equivalent:
4546
4547   my $rs = $schema->resultset('Artist')->search({}, {
4548     prefetch => { cds => ['genre', 'tracks' ] },
4549   });
4550
4551 and
4552
4553   my $rs = $schema->resultset('Artist')->search({}, {
4554     join => { cds => ['genre', 'tracks' ] },
4555     collapse => 1,
4556     '+columns' => [
4557       (map
4558         { +{ "cds.$_" => "cds.$_" } }
4559         $schema->source('Artist')->related_source('cds')->columns
4560       ),
4561       (map
4562         { +{ "cds.genre.$_" => "genre.$_" } }
4563         $schema->source('Artist')->related_source('cds')->related_source('genre')->columns
4564       ),
4565       (map
4566         { +{ "cds.tracks.$_" => "tracks.$_" } }
4567         $schema->source('Artist')->related_source('cds')->related_source('tracks')->columns
4568       ),
4569     ],
4570   });
4571
4572 Both producing the following SQL:
4573
4574   SELECT  me.artistid, me.name, me.rank, me.charfield,
4575           cds.cdid, cds.artist, cds.title, cds.year, cds.genreid, cds.single_track,
4576           genre.genreid, genre.name,
4577           tracks.trackid, tracks.cd, tracks.position, tracks.title, tracks.last_updated_on, tracks.last_updated_at
4578     FROM artist me
4579     LEFT JOIN cd cds
4580       ON cds.artist = me.artistid
4581     LEFT JOIN genre genre
4582       ON genre.genreid = cds.genreid
4583     LEFT JOIN track tracks
4584       ON tracks.cd = cds.cdid
4585   ORDER BY me.artistid
4586
4587 While L</prefetch> implies a L</join>, it is ok to mix the two together, as
4588 the arguments are properly merged and generally do the right thing. For
4589 example, you may want to do the following:
4590
4591   my $artists_and_cds_without_genre = $schema->resultset('Artist')->search(
4592     { 'genre.genreid' => undef },
4593     {
4594       join => { cds => 'genre' },
4595       prefetch => 'cds',
4596     }
4597   );
4598
4599 Which generates the following SQL:
4600
4601   SELECT  me.artistid, me.name, me.rank, me.charfield,
4602           cds.cdid, cds.artist, cds.title, cds.year, cds.genreid, cds.single_track
4603     FROM artist me
4604     LEFT JOIN cd cds
4605       ON cds.artist = me.artistid
4606     LEFT JOIN genre genre
4607       ON genre.genreid = cds.genreid
4608   WHERE genre.genreid IS NULL
4609   ORDER BY me.artistid
4610
4611 For a more in-depth discussion, see L</PREFETCHING>.
4612
4613 =head2 alias
4614
4615 =over 4
4616
4617 =item Value: $source_alias
4618
4619 =back
4620
4621 Sets the source alias for the query.  Normally, this defaults to C<me>, but
4622 nested search queries (sub-SELECTs) might need specific aliases set to
4623 reference inner queries.  For example:
4624
4625    my $q = $rs
4626       ->related_resultset('CDs')
4627       ->related_resultset('Tracks')
4628       ->search({
4629          'track.id' => { -ident => 'none_search.id' },
4630       })
4631       ->as_query;
4632
4633    my $ids = $self->search({
4634       -not_exists => $q,
4635    }, {
4636       alias    => 'none_search',
4637       group_by => 'none_search.id',
4638    })->get_column('id')->as_query;
4639
4640    $self->search({ id => { -in => $ids } })
4641
4642 This attribute is directly tied to L</current_source_alias>.
4643
4644 =head2 page
4645
4646 =over 4
4647
4648 =item Value: $page
4649
4650 =back
4651
4652 Makes the resultset paged and specifies the page to retrieve. Effectively
4653 identical to creating a non-pages resultset and then calling ->page($page)
4654 on it.
4655
4656 If L</rows> attribute is not specified it defaults to 10 rows per page.
4657
4658 When you have a paged resultset, L</count> will only return the number
4659 of rows in the page. To get the total, use the L</pager> and call
4660 C<total_entries> on it.
4661
4662 =head2 rows
4663
4664 =over 4
4665
4666 =item Value: $rows
4667
4668 =back
4669
4670 Specifies the maximum number of rows for direct retrieval or the number of
4671 rows per page if the page attribute or method is used.
4672
4673 =head2 offset
4674
4675 =over 4
4676
4677 =item Value: $offset
4678
4679 =back
4680
4681 Specifies the (zero-based) row number for the  first row to be returned, or the
4682 of the first row of the first page if paging is used.
4683
4684 =head2 software_limit
4685
4686 =over 4
4687
4688 =item Value: (0 | 1)
4689
4690 =back
4691
4692 When combined with L</rows> and/or L</offset> the generated SQL will not
4693 include any limit dialect stanzas. Instead the entire result will be selected
4694 as if no limits were specified, and DBIC will perform the limit locally, by
4695 artificially advancing and finishing the resulting L</cursor>.
4696
4697 This is the recommended way of performing resultset limiting when no sane RDBMS
4698 implementation is available (e.g.
4699 L<Sybase ASE|DBIx::Class::Storage::DBI::Sybase::ASE> using the
4700 L<Generic Sub Query|DBIx::Class::SQLMaker::LimitDialects/GenericSubQ> hack)
4701
4702 =head2 group_by
4703
4704 =over 4
4705
4706 =item Value: \@columns
4707
4708 =back
4709
4710 A arrayref of columns to group by. Can include columns of joined tables.
4711
4712   group_by => [qw/ column1 column2 ... /]
4713
4714 =head2 having
4715
4716 =over 4
4717
4718 =item Value: $condition
4719
4720 =back
4721
4722 The HAVING operator specifies a B<secondary> condition applied to the set
4723 after the grouping calculations have been done. In other words it is a
4724 constraint just like L</where> (and accepting the same
4725 L<SQL::Abstract syntax|SQL::Abstract/WHERE CLAUSES>) applied to the data
4726 as it exists after GROUP BY has taken place. Specifying L</having> without
4727 L</group_by> is a logical mistake, and a fatal error on most RDBMS engines.
4728
4729 E.g.
4730
4731   having => { 'count_employee' => { '>=', 100 } }
4732
4733 or with an in-place function in which case literal SQL is required:
4734
4735   having => \[ 'count(employee) >= ?', 100 ]
4736
4737 =head2 distinct
4738
4739 =over 4
4740
4741 =item Value: (0 | 1)
4742
4743 =back
4744
4745 Set to 1 to automatically generate a L</group_by> clause based on the selection
4746 (including intelligent handling of L</order_by> contents). Note that the group
4747 criteria calculation takes place over the B<final> selection. This includes
4748 any L</+columns>, L</+select> or L</order_by> additions in subsequent
4749 L</search> calls, and standalone columns selected via
4750 L<DBIx::Class::ResultSetColumn> (L</get_column>). A notable exception are the
4751 extra selections specified via L</prefetch> - such selections are explicitly
4752 excluded from group criteria calculations.
4753
4754 If the final ResultSet also explicitly defines a L</group_by> attribute, this
4755 setting is ignored and an appropriate warning is issued.
4756
4757 =head2 where
4758
4759 Adds extra conditions to the resultset, combined with the preexisting C<WHERE>
4760 conditions, same as the B<first> argument to the L<search operator|/search>
4761
4762   # only return rows WHERE deleted IS NULL for all searches
4763   __PACKAGE__->resultset_attributes({ where => { deleted => undef } });
4764
4765 Note that the above example is
4766 L<strongly discouraged|DBIx::Class::ResultSource/resultset_attributes>.
4767
4768 =head2 cache
4769
4770 Set to 1 to cache search results. This prevents extra SQL queries if you
4771 revisit rows in your ResultSet:
4772
4773   my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
4774
4775   while( my $artist = $resultset->next ) {
4776     ... do stuff ...
4777   }
4778
4779   $resultset->first; # without cache, this would issue a query
4780
4781 By default, searches are not cached.
4782
4783 For more examples of using these attributes, see
4784 L<DBIx::Class::Manual::Cookbook>.
4785
4786 =head2 for
4787
4788 =over 4
4789
4790 =item Value: ( 'update' | 'shared' | \$scalar )
4791
4792 =back
4793
4794 Set to 'update' for a SELECT ... FOR UPDATE or 'shared' for a SELECT
4795 ... FOR SHARED. If \$scalar is passed, this is taken directly and embedded in the
4796 query.
4797
4798 =head1 PREFETCHING
4799
4800 DBIx::Class supports arbitrary related data prefetching from multiple related
4801 sources. Any combination of relationship types and column sets are supported.
4802 If L<collapsing|/collapse> is requested, there is an additional requirement of
4803 selecting enough data to make every individual object uniquely identifiable.
4804
4805 Here are some more involved examples, based on the following relationship map:
4806
4807   # Assuming:
4808   My::Schema::CD->belongs_to( artist      => 'My::Schema::Artist'     );
4809   My::Schema::CD->might_have( liner_note  => 'My::Schema::LinerNotes' );
4810   My::Schema::CD->has_many(   tracks      => 'My::Schema::Track'      );
4811
4812   My::Schema::Artist->belongs_to( record_label => 'My::Schema::RecordLabel' );
4813
4814   My::Schema::Track->has_many( guests => 'My::Schema::Guest' );
4815
4816
4817
4818   my $rs = $schema->resultset('Tag')->search(
4819     undef,
4820     {
4821       prefetch => {
4822         cd => 'artist'
4823       }
4824     }
4825   );
4826
4827 The initial search results in SQL like the following:
4828
4829   SELECT tag.*, cd.*, artist.* FROM tag
4830   JOIN cd ON tag.cd = cd.cdid
4831   JOIN artist ON cd.artist = artist.artistid
4832
4833 L<DBIx::Class> has no need to go back to the database when we access the
4834 C<cd> or C<artist> relationships, which saves us two SQL statements in this
4835 case.
4836
4837 Simple prefetches will be joined automatically, so there is no need
4838 for a C<join> attribute in the above search.
4839
4840 The L</prefetch> attribute can be used with any of the relationship types
4841 and multiple prefetches can be specified together. Below is a more complex
4842 example that prefetches a CD's artist, its liner notes (if present),
4843 the cover image, the tracks on that CD, and the guests on those
4844 tracks.
4845
4846   my $rs = $schema->resultset('CD')->search(
4847     undef,
4848     {
4849       prefetch => [
4850         { artist => 'record_label'},  # belongs_to => belongs_to
4851         'liner_note',                 # might_have
4852         'cover_image',                # has_one
4853         { tracks => 'guests' },       # has_many => has_many
4854       ]
4855     }
4856   );
4857
4858 This will produce SQL like the following:
4859
4860   SELECT cd.*, artist.*, record_label.*, liner_note.*, cover_image.*,
4861          tracks.*, guests.*
4862     FROM cd me
4863     JOIN artist artist
4864       ON artist.artistid = me.artistid
4865     JOIN record_label record_label
4866       ON record_label.labelid = artist.labelid
4867     LEFT JOIN track tracks
4868       ON tracks.cdid = me.cdid
4869     LEFT JOIN guest guests
4870       ON guests.trackid = track.trackid
4871     LEFT JOIN liner_notes liner_note
4872       ON liner_note.cdid = me.cdid
4873     JOIN cd_artwork cover_image
4874       ON cover_image.cdid = me.cdid
4875   ORDER BY tracks.cd
4876
4877 Now the C<artist>, C<record_label>, C<liner_note>, C<cover_image>,
4878 C<tracks>, and C<guests> of the CD will all be available through the
4879 relationship accessors without the need for additional queries to the
4880 database.
4881
4882 =head3 CAVEATS
4883
4884 Prefetch does a lot of deep magic. As such, it may not behave exactly
4885 as you might expect.
4886
4887 =over 4
4888
4889 =item *
4890
4891 Prefetch uses the L</cache> to populate the prefetched relationships. This
4892 may or may not be what you want.
4893
4894 =item *
4895
4896 If you specify a condition on a prefetched relationship, ONLY those
4897 rows that match the prefetched condition will be fetched into that relationship.
4898 This means that adding prefetch to a search() B<may alter> what is returned by
4899 traversing a relationship. So, if you have C<< Artist->has_many(CDs) >> and you do
4900
4901   my $artist_rs = $schema->resultset('Artist')->search({
4902       'cds.year' => 2008,
4903   }, {
4904       join => 'cds',
4905   });
4906
4907   my $count = $artist_rs->first->cds->count;
4908
4909   my $artist_rs_prefetch = $artist_rs->search( {}, { prefetch => 'cds' } );
4910
4911   my $prefetch_count = $artist_rs_prefetch->first->cds->count;
4912
4913   cmp_ok( $count, '==', $prefetch_count, "Counts should be the same" );
4914
4915 That cmp_ok() may or may not pass depending on the datasets involved. In other
4916 words the C<WHERE> condition would apply to the entire dataset, just like
4917 it would in regular SQL. If you want to add a condition only to the "right side"
4918 of a C<LEFT JOIN> - consider declaring and using a L<relationship with a custom
4919 condition|DBIx::Class::Relationship::Base/condition>
4920
4921 =back
4922
4923 =head1 DBIC BIND VALUES
4924
4925 Because DBIC may need more information to bind values than just the column name
4926 and value itself, it uses a special format for both passing and receiving bind
4927 values.  Each bind value should be composed of an arrayref of
4928 C<< [ \%args => $val ] >>.  The format of C<< \%args >> is currently:
4929
4930 =over 4
4931
4932 =item dbd_attrs
4933
4934 If present (in any form), this is what is being passed directly to bind_param.
4935 Note that different DBD's expect different bind args.  (e.g. DBD::SQLite takes
4936 a single numerical type, while DBD::Pg takes a hashref if bind options.)
4937
4938 If this is specified, all other bind options described below are ignored.
4939
4940 =item sqlt_datatype
4941
4942 If present, this is used to infer the actual bind attribute by passing to
4943 C<< $resolved_storage->bind_attribute_by_data_type() >>.  Defaults to the
4944 "data_type" from the L<add_columns column info|DBIx::Class::ResultSource/add_columns>.
4945
4946 Note that the data type is somewhat freeform (hence the sqlt_ prefix);
4947 currently drivers are expected to "Do the Right Thing" when given a common
4948 datatype name.  (Not ideal, but that's what we got at this point.)
4949
4950 =item sqlt_size
4951
4952 Currently used to correctly allocate buffers for bind_param_inout().
4953 Defaults to "size" from the L<add_columns column info|DBIx::Class::ResultSource/add_columns>,
4954 or to a sensible value based on the "data_type".
4955
4956 =item dbic_colname
4957
4958 Used to fill in missing sqlt_datatype and sqlt_size attributes (if they are
4959 explicitly specified they are never overridden).  Also used by some weird DBDs,
4960 where the column name should be available at bind_param time (e.g. Oracle).
4961
4962 =back
4963
4964 For backwards compatibility and convenience, the following shortcuts are
4965 supported:
4966
4967   [ $name => $val ] === [ { dbic_colname => $name }, $val ]
4968   [ \$dt  => $val ] === [ { sqlt_datatype => $dt }, $val ]
4969   [ undef,   $val ] === [ {}, $val ]
4970   $val              === [ {}, $val ]
4971
4972 =head1 FURTHER QUESTIONS?
4973
4974 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
4975
4976 =head1 COPYRIGHT AND LICENSE
4977
4978 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
4979 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
4980 redistribute it and/or modify it under the same terms as the
4981 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.
4982
4983 =cut