2d6ea30d58e62edf64c45d38fc9d847cfe2ef625
[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   my $self = shift;
3508
3509   my $alias = $self->current_source_alias;
3510
3511   my $fresh_rs = (ref $self)->new (
3512     $self->result_source
3513   );
3514
3515   # these pieces will be locked in the subquery
3516   delete $fresh_rs->{cond};
3517   delete @{$fresh_rs->{attrs}}{qw/where bind/};
3518
3519   return $fresh_rs->search( {}, {
3520     from => [{
3521       $alias => $self->as_query,
3522       -alias  => $alias,
3523       -rsrc   => $self->result_source,
3524     }],
3525     alias => $alias,
3526   });
3527 }
3528
3529 # This code is called by search_related, and makes sure there
3530 # is clear separation between the joins before, during, and
3531 # after the relationship. This information is needed later
3532 # in order to properly resolve prefetch aliases (any alias
3533 # with a relation_chain_depth less than the depth of the
3534 # current prefetch is not considered)
3535 #
3536 # The increments happen twice per join. An even number means a
3537 # relationship specified via a search_related, whereas an odd
3538 # number indicates a join/prefetch added via attributes
3539 #
3540 # Also this code will wrap the current resultset (the one we
3541 # chain to) in a subselect IFF it contains limiting attributes
3542 sub _chain_relationship {
3543   my ($self, $rel) = @_;
3544   my $source = $self->result_source;
3545   my $attrs = { %{$self->{attrs}||{}} };
3546
3547   # we need to take the prefetch the attrs into account before we
3548   # ->_resolve_join as otherwise they get lost - captainL
3549   my $join = $self->_merge_joinpref_attr( $attrs->{join}, $attrs->{prefetch} );
3550
3551   delete @{$attrs}{qw/join prefetch collapse group_by distinct _grouped_by_distinct select as columns +select +as +columns/};
3552
3553   my $seen = { %{ (delete $attrs->{seen_join}) || {} } };
3554
3555   my $from;
3556   my @force_subq_attrs = qw/offset rows group_by having/;
3557
3558   if (
3559     ($attrs->{from} && ref $attrs->{from} ne 'ARRAY')
3560       ||
3561     $self->_has_resolved_attr (@force_subq_attrs)
3562   ) {
3563     # Nuke the prefetch (if any) before the new $rs attrs
3564     # are resolved (prefetch is useless - we are wrapping
3565     # a subquery anyway).
3566     my $rs_copy = $self->search;
3567     $rs_copy->{attrs}{join} = $self->_merge_joinpref_attr (
3568       $rs_copy->{attrs}{join},
3569       delete $rs_copy->{attrs}{prefetch},
3570     );
3571
3572     $from = [{
3573       -rsrc   => $source,
3574       -alias  => $attrs->{alias},
3575       $attrs->{alias} => $rs_copy->as_query,
3576     }];
3577     delete @{$attrs}{@force_subq_attrs, qw/where bind/};
3578     $seen->{-relation_chain_depth} = 0;
3579   }
3580   elsif ($attrs->{from}) {  #shallow copy suffices
3581     $from = [ @{$attrs->{from}} ];
3582   }
3583   else {
3584     $from = [{
3585       -rsrc  => $source,
3586       -alias => $attrs->{alias},
3587       $attrs->{alias} => $source->from,
3588     }];
3589   }
3590
3591   my $jpath = ($seen->{-relation_chain_depth})
3592     ? $from->[-1][0]{-join_path}
3593     : [];
3594
3595   my @requested_joins = $source->_resolve_join(
3596     $join,
3597     $attrs->{alias},
3598     $seen,
3599     $jpath,
3600   );
3601
3602   push @$from, @requested_joins;
3603
3604   $seen->{-relation_chain_depth}++;
3605
3606   # if $self already had a join/prefetch specified on it, the requested
3607   # $rel might very well be already included. What we do in this case
3608   # is effectively a no-op (except that we bump up the chain_depth on
3609   # the join in question so we could tell it *is* the search_related)
3610   my $already_joined;
3611
3612   # we consider the last one thus reverse
3613   for my $j (reverse @requested_joins) {
3614     my ($last_j) = keys %{$j->[0]{-join_path}[-1]};
3615     if ($rel eq $last_j) {
3616       $j->[0]{-relation_chain_depth}++;
3617       $already_joined++;
3618       last;
3619     }
3620   }
3621
3622   unless ($already_joined) {
3623     push @$from, $source->_resolve_join(
3624       $rel,
3625       $attrs->{alias},
3626       $seen,
3627       $jpath,
3628     );
3629   }
3630
3631   $seen->{-relation_chain_depth}++;
3632
3633   return {%$attrs, from => $from, seen_join => $seen};
3634 }
3635
3636 sub _resolved_attrs {
3637   my $self = shift;
3638   return $self->{_attrs} if $self->{_attrs};
3639
3640   my $attrs  = { %{ $self->{attrs} || {} } };
3641   my $source = $attrs->{result_source} = $self->result_source;
3642   my $alias  = $attrs->{alias};
3643
3644   $self->throw_exception("Specifying distinct => 1 in conjunction with collapse => 1 is unsupported")
3645     if $attrs->{collapse} and $attrs->{distinct};
3646
3647
3648   # Sanity check the paging attributes
3649   # SQLMaker does it too, but in case of a software_limit we'll never get there
3650   if (defined $attrs->{offset}) {
3651     $self->throw_exception('A supplied offset attribute must be a non-negative integer')
3652       if ( $attrs->{offset} =~ /[^0-9]/ or $attrs->{offset} < 0 );
3653   }
3654   if (defined $attrs->{rows}) {
3655     $self->throw_exception("The rows attribute must be a positive integer if present")
3656       if ( $attrs->{rows} =~ /[^0-9]/ or $attrs->{rows} <= 0 );
3657   }
3658
3659   # normalize where condition
3660   $attrs->{where} = normalize_sqla_condition( $attrs->{where} )
3661     if $attrs->{where};
3662
3663   # default selection list
3664   $attrs->{columns} = [ $source->columns ]
3665     unless grep { exists $attrs->{$_} } qw/columns cols select as/;
3666
3667   # merge selectors together
3668   for (qw/columns select as/) {
3669     $attrs->{$_} = $self->_merge_attr($attrs->{$_}, delete $attrs->{"+$_"})
3670       if $attrs->{$_} or $attrs->{"+$_"};
3671   }
3672
3673   # disassemble columns
3674   my (@sel, @as);
3675   if (my $cols = delete $attrs->{columns}) {
3676     for my $c (ref $cols eq 'ARRAY' ? @$cols : $cols) {
3677       if (ref $c eq 'HASH') {
3678         for my $as (sort keys %$c) {
3679           push @sel, $c->{$as};
3680           push @as, $as;
3681         }
3682       }
3683       else {
3684         push @sel, $c;
3685         push @as, $c;
3686       }
3687     }
3688   }
3689
3690   # when trying to weed off duplicates later do not go past this point -
3691   # everything added from here on is unbalanced "anyone's guess" stuff
3692   my $dedup_stop_idx = $#as;
3693
3694   push @as, @{ ref $attrs->{as} eq 'ARRAY' ? $attrs->{as} : [ $attrs->{as} ] }
3695     if $attrs->{as};
3696   push @sel, @{ ref $attrs->{select} eq 'ARRAY' ? $attrs->{select} : [ $attrs->{select} ] }
3697     if $attrs->{select};
3698
3699   # assume all unqualified selectors to apply to the current alias (legacy stuff)
3700   $_ = (ref $_ or $_ =~ /\./) ? $_ : "$alias.$_" for @sel;
3701
3702   # disqualify all $alias.col as-bits (inflate-map mandated)
3703   $_ = ($_ =~ /^\Q$alias.\E(.+)$/) ? $1 : $_ for @as;
3704
3705   # de-duplicate the result (remove *identical* select/as pairs)
3706   # and also die on duplicate {as} pointing to different {select}s
3707   # not using a c-style for as the condition is prone to shrinkage
3708   my $seen;
3709   my $i = 0;
3710   while ($i <= $dedup_stop_idx) {
3711     if ($seen->{"$sel[$i] \x00\x00 $as[$i]"}++) {
3712       splice @sel, $i, 1;
3713       splice @as, $i, 1;
3714       $dedup_stop_idx--;
3715     }
3716     elsif ($seen->{$as[$i]}++) {
3717       $self->throw_exception(
3718         "inflate_result() alias '$as[$i]' specified twice with different SQL-side {select}-ors"
3719       );
3720     }
3721     else {
3722       $i++;
3723     }
3724   }
3725
3726   $attrs->{select} = \@sel;
3727   $attrs->{as} = \@as;
3728
3729   $attrs->{from} ||= [{
3730     -rsrc   => $source,
3731     -alias  => $self->{attrs}{alias},
3732     $self->{attrs}{alias} => $source->from,
3733   }];
3734
3735   if ( $attrs->{join} || $attrs->{prefetch} ) {
3736
3737     $self->throw_exception ('join/prefetch can not be used with a custom {from}')
3738       if ref $attrs->{from} ne 'ARRAY';
3739
3740     my $join = (delete $attrs->{join}) || {};
3741
3742     if ( defined $attrs->{prefetch} ) {
3743       $join = $self->_merge_joinpref_attr( $join, $attrs->{prefetch} );
3744     }
3745
3746     $attrs->{from} =    # have to copy here to avoid corrupting the original
3747       [
3748         @{ $attrs->{from} },
3749         $source->_resolve_join(
3750           $join,
3751           $alias,
3752           { %{ $attrs->{seen_join} || {} } },
3753           ( $attrs->{seen_join} && keys %{$attrs->{seen_join}})
3754             ? $attrs->{from}[-1][0]{-join_path}
3755             : []
3756           ,
3757         )
3758       ];
3759   }
3760
3761
3762   for my $attr (qw(order_by group_by)) {
3763
3764     if ( defined $attrs->{$attr} ) {
3765       $attrs->{$attr} = (
3766         ref( $attrs->{$attr} ) eq 'ARRAY'
3767         ? [ @{ $attrs->{$attr} } ]
3768         : [ $attrs->{$attr} || () ]
3769       );
3770
3771       delete $attrs->{$attr} unless @{$attrs->{$attr}};
3772     }
3773   }
3774
3775
3776   # set collapse default based on presence of prefetch
3777   my $prefetch;
3778   if (
3779     defined $attrs->{prefetch}
3780       and
3781     $prefetch = $self->_merge_joinpref_attr( {}, delete $attrs->{prefetch} )
3782   ) {
3783     $self->throw_exception("Specifying prefetch in conjunction with an explicit collapse => 0 is unsupported")
3784       if defined $attrs->{collapse} and ! $attrs->{collapse};
3785
3786     $attrs->{collapse} = 1;
3787   }
3788
3789
3790   # run through the resulting joinstructure (starting from our current slot)
3791   # and unset collapse if proven unnecessary
3792   #
3793   # also while we are at it find out if the current root source has
3794   # been premultiplied by previous related_source chaining
3795   #
3796   # this allows to predict whether a root object with all other relation
3797   # data set to NULL is in fact unique
3798   if ($attrs->{collapse}) {
3799
3800     if (ref $attrs->{from} eq 'ARRAY') {
3801
3802       if (@{$attrs->{from}} == 1) {
3803         # no joins - no collapse
3804         $attrs->{collapse} = 0;
3805       }
3806       else {
3807         # find where our table-spec starts
3808         my @fromlist = @{$attrs->{from}};
3809         while (@fromlist) {
3810           my $t = shift @fromlist;
3811
3812           my $is_multi;
3813           # me vs join from-spec distinction - a ref means non-root
3814           if (ref $t eq 'ARRAY') {
3815             $t = $t->[0];
3816             $is_multi ||= ! $t->{-is_single};
3817           }
3818           last if ($t->{-alias} && $t->{-alias} eq $alias);
3819           $attrs->{_main_source_premultiplied} ||= $is_multi;
3820         }
3821
3822         # no non-singles remaining, nor any premultiplication - nothing to collapse
3823         if (
3824           ! $attrs->{_main_source_premultiplied}
3825             and
3826           ! grep { ! $_->[0]{-is_single} } @fromlist
3827         ) {
3828           $attrs->{collapse} = 0;
3829         }
3830       }
3831     }
3832
3833     else {
3834       # if we can not analyze the from - err on the side of safety
3835       $attrs->{_main_source_premultiplied} = 1;
3836     }
3837   }
3838
3839
3840   # generate the distinct induced group_by before injecting the prefetched select/as parts
3841   if (delete $attrs->{distinct}) {
3842     if ($attrs->{group_by}) {
3843       carp_unique ("Useless use of distinct on a grouped resultset ('distinct' is ignored when a 'group_by' is present)");
3844     }
3845     else {
3846       $attrs->{_grouped_by_distinct} = 1;
3847       # distinct affects only the main selection part, not what prefetch may add below
3848       ($attrs->{group_by}, my $new_order) = $source->schema->storage->_group_over_selection($attrs);
3849
3850       # FIXME possibly ignore a rewritten order_by (may turn out to be an issue)
3851       # The thinking is: if we are collapsing the subquerying prefetch engine will
3852       # rip stuff apart for us anyway, and we do not want to have a potentially
3853       # function-converted external order_by
3854       # ( there is an explicit if ( collapse && _grouped_by_distinct ) check in DBIHacks )
3855       $attrs->{order_by} = $new_order unless $attrs->{collapse};
3856     }
3857   }
3858
3859
3860   # generate selections based on the prefetch helper
3861   if ($prefetch) {
3862
3863     $self->throw_exception("Unable to prefetch, resultset contains an unnamed selector $attrs->{_dark_selector}{string}")
3864       if $attrs->{_dark_selector};
3865
3866     # this is a separate structure (we don't look in {from} directly)
3867     # as the resolver needs to shift things off the lists to work
3868     # properly (identical-prefetches on different branches)
3869     my $joined_node_aliases_map = {};
3870     if (ref $attrs->{from} eq 'ARRAY') {
3871
3872       my $start_depth = $attrs->{seen_join}{-relation_chain_depth} || 0;
3873
3874       for my $j ( @{$attrs->{from}}[1 .. $#{$attrs->{from}} ] ) {
3875         next unless $j->[0]{-alias};
3876         next unless $j->[0]{-join_path};
3877         next if ($j->[0]{-relation_chain_depth} || 0) < $start_depth;
3878
3879         my @jpath = map { keys %$_ } @{$j->[0]{-join_path}};
3880
3881         my $p = $joined_node_aliases_map;
3882         $p = $p->{$_} ||= {} for @jpath[ ($start_depth/2) .. $#jpath]; #only even depths are actual jpath boundaries
3883         push @{$p->{-join_aliases} }, $j->[0]{-alias};
3884       }
3885     }
3886
3887     ( push @{$attrs->{select}}, $_->[0] ) and ( push @{$attrs->{as}}, $_->[1] )
3888       for $source->_resolve_selection_from_prefetch( $prefetch, $joined_node_aliases_map );
3889   }
3890
3891
3892   $attrs->{_simple_passthrough_construction} = !(
3893     $attrs->{collapse}
3894       or
3895     grep { $_ =~ /\./ } @{$attrs->{as}}
3896   );
3897
3898
3899   # if both page and offset are specified, produce a combined offset
3900   # even though it doesn't make much sense, this is what pre 081xx has
3901   # been doing
3902   if (my $page = delete $attrs->{page}) {
3903     $attrs->{offset} =
3904       ($attrs->{rows} * ($page - 1))
3905             +
3906       ($attrs->{offset} || 0)
3907     ;
3908   }
3909
3910   return $self->{_attrs} = $attrs;
3911 }
3912
3913 sub _rollout_attr {
3914   my ($self, $attr) = @_;
3915
3916   if (ref $attr eq 'HASH') {
3917     return $self->_rollout_hash($attr);
3918   } elsif (ref $attr eq 'ARRAY') {
3919     return $self->_rollout_array($attr);
3920   } else {
3921     return [$attr];
3922   }
3923 }
3924
3925 sub _rollout_array {
3926   my ($self, $attr) = @_;
3927
3928   my @rolled_array;
3929   foreach my $element (@{$attr}) {
3930     if (ref $element eq 'HASH') {
3931       push( @rolled_array, @{ $self->_rollout_hash( $element ) } );
3932     } elsif (ref $element eq 'ARRAY') {
3933       #  XXX - should probably recurse here
3934       push( @rolled_array, @{$self->_rollout_array($element)} );
3935     } else {
3936       push( @rolled_array, $element );
3937     }
3938   }
3939   return \@rolled_array;
3940 }
3941
3942 sub _rollout_hash {
3943   my ($self, $attr) = @_;
3944
3945   my @rolled_array;
3946   foreach my $key (keys %{$attr}) {
3947     push( @rolled_array, { $key => $attr->{$key} } );
3948   }
3949   return \@rolled_array;
3950 }
3951
3952 sub _calculate_score {
3953   my ($self, $a, $b) = @_;
3954
3955   if (defined $a xor defined $b) {
3956     return 0;
3957   }
3958   elsif (not defined $a) {
3959     return 1;
3960   }
3961
3962   if (ref $b eq 'HASH') {
3963     my ($b_key) = keys %{$b};
3964     $b_key = '' if ! defined $b_key;
3965     if (ref $a eq 'HASH') {
3966       my ($a_key) = keys %{$a};
3967       $a_key = '' if ! defined $a_key;
3968       if ($a_key eq $b_key) {
3969         return (1 + $self->_calculate_score( $a->{$a_key}, $b->{$b_key} ));
3970       } else {
3971         return 0;
3972       }
3973     } else {
3974       return ($a eq $b_key) ? 1 : 0;
3975     }
3976   } else {
3977     if (ref $a eq 'HASH') {
3978       my ($a_key) = keys %{$a};
3979       return ($b eq $a_key) ? 1 : 0;
3980     } else {
3981       return ($b eq $a) ? 1 : 0;
3982     }
3983   }
3984 }
3985
3986 sub _merge_joinpref_attr {
3987   my ($self, $orig, $import) = @_;
3988
3989   return $import unless defined($orig);
3990   return $orig unless defined($import);
3991
3992   $orig = $self->_rollout_attr($orig);
3993   $import = $self->_rollout_attr($import);
3994
3995   my $seen_keys;
3996   foreach my $import_element ( @{$import} ) {
3997     # find best candidate from $orig to merge $b_element into
3998     my $best_candidate = { position => undef, score => 0 }; my $position = 0;
3999     foreach my $orig_element ( @{$orig} ) {
4000       my $score = $self->_calculate_score( $orig_element, $import_element );
4001       if ($score > $best_candidate->{score}) {
4002         $best_candidate->{position} = $position;
4003         $best_candidate->{score} = $score;
4004       }
4005       $position++;
4006     }
4007     my ($import_key) = ( ref $import_element eq 'HASH' ) ? keys %{$import_element} : ($import_element);
4008     $import_key = '' if not defined $import_key;
4009
4010     if ($best_candidate->{score} == 0 || exists $seen_keys->{$import_key}) {
4011       push( @{$orig}, $import_element );
4012     } else {
4013       my $orig_best = $orig->[$best_candidate->{position}];
4014       # merge orig_best and b_element together and replace original with merged
4015       if (ref $orig_best ne 'HASH') {
4016         $orig->[$best_candidate->{position}] = $import_element;
4017       } elsif (ref $import_element eq 'HASH') {
4018         my ($key) = keys %{$orig_best};
4019         $orig->[$best_candidate->{position}] = { $key => $self->_merge_joinpref_attr($orig_best->{$key}, $import_element->{$key}) };
4020       }
4021     }
4022     $seen_keys->{$import_key} = 1; # don't merge the same key twice
4023   }
4024
4025   return @$orig ? $orig : ();
4026 }
4027
4028 {
4029   my $hm;
4030
4031   sub _merge_attr {
4032     $hm ||= do {
4033       require Hash::Merge;
4034       my $hm = Hash::Merge->new;
4035
4036       $hm->specify_behavior({
4037         SCALAR => {
4038           SCALAR => sub {
4039             my ($defl, $defr) = map { defined $_ } (@_[0,1]);
4040
4041             if ($defl xor $defr) {
4042               return [ $defl ? $_[0] : $_[1] ];
4043             }
4044             elsif (! $defl) {
4045               return [];
4046             }
4047             elsif (__HM_DEDUP and $_[0] eq $_[1]) {
4048               return [ $_[0] ];
4049             }
4050             else {
4051               return [$_[0], $_[1]];
4052             }
4053           },
4054           ARRAY => sub {
4055             return $_[1] if !defined $_[0];
4056             return $_[1] if __HM_DEDUP and grep { $_ eq $_[0] } @{$_[1]};
4057             return [$_[0], @{$_[1]}]
4058           },
4059           HASH  => sub {
4060             return [] if !defined $_[0] and !keys %{$_[1]};
4061             return [ $_[1] ] if !defined $_[0];
4062             return [ $_[0] ] if !keys %{$_[1]};
4063             return [$_[0], $_[1]]
4064           },
4065         },
4066         ARRAY => {
4067           SCALAR => sub {
4068             return $_[0] if !defined $_[1];
4069             return $_[0] if __HM_DEDUP and grep { $_ eq $_[1] } @{$_[0]};
4070             return [@{$_[0]}, $_[1]]
4071           },
4072           ARRAY => sub {
4073             my @ret = @{$_[0]} or return $_[1];
4074             return [ @ret, @{$_[1]} ] unless __HM_DEDUP;
4075             my %idx = map { $_ => 1 } @ret;
4076             push @ret, grep { ! defined $idx{$_} } (@{$_[1]});
4077             \@ret;
4078           },
4079           HASH => sub {
4080             return [ $_[1] ] if ! @{$_[0]};
4081             return $_[0] if !keys %{$_[1]};
4082             return $_[0] if __HM_DEDUP and grep { $_ eq $_[1] } @{$_[0]};
4083             return [ @{$_[0]}, $_[1] ];
4084           },
4085         },
4086         HASH => {
4087           SCALAR => sub {
4088             return [] if !keys %{$_[0]} and !defined $_[1];
4089             return [ $_[0] ] if !defined $_[1];
4090             return [ $_[1] ] if !keys %{$_[0]};
4091             return [$_[0], $_[1]]
4092           },
4093           ARRAY => sub {
4094             return [] if !keys %{$_[0]} and !@{$_[1]};
4095             return [ $_[0] ] if !@{$_[1]};
4096             return $_[1] if !keys %{$_[0]};
4097             return $_[1] if __HM_DEDUP and grep { $_ eq $_[0] } @{$_[1]};
4098             return [ $_[0], @{$_[1]} ];
4099           },
4100           HASH => sub {
4101             return [] if !keys %{$_[0]} and !keys %{$_[1]};
4102             return [ $_[0] ] if !keys %{$_[1]};
4103             return [ $_[1] ] if !keys %{$_[0]};
4104             return [ $_[0] ] if $_[0] eq $_[1];
4105             return [ $_[0], $_[1] ];
4106           },
4107         }
4108       } => 'DBIC_RS_ATTR_MERGER');
4109       $hm;
4110     };
4111
4112     return $hm->merge ($_[1], $_[2]);
4113   }
4114 }
4115
4116 sub STORABLE_freeze {
4117   my ($self, $cloning) = @_;
4118   my $to_serialize = { %$self };
4119
4120   # A cursor in progress can't be serialized (and would make little sense anyway)
4121   # the parser can be regenerated (and can't be serialized)
4122   delete @{$to_serialize}{qw/cursor _row_parser _result_inflator/};
4123
4124   # nor is it sensical to store a not-yet-fired-count pager
4125   if ($to_serialize->{pager} and ref $to_serialize->{pager}{total_entries} eq 'CODE') {
4126     delete $to_serialize->{pager};
4127   }
4128
4129   Storable::nfreeze($to_serialize);
4130 }
4131
4132 # need this hook for symmetry
4133 sub STORABLE_thaw {
4134   my ($self, $cloning, $serialized) = @_;
4135
4136   %$self = %{ Storable::thaw($serialized) };
4137
4138   $self;
4139 }
4140
4141
4142 =head2 throw_exception
4143
4144 See L<DBIx::Class::Schema/throw_exception> for details.
4145
4146 =cut
4147
4148 sub throw_exception {
4149   my $self=shift;
4150
4151   if (ref $self and my $rsrc = $self->result_source) {
4152     $rsrc->throw_exception(@_)
4153   }
4154   else {
4155     DBIx::Class::Exception->throw(@_);
4156   }
4157 }
4158
4159 1;
4160
4161 __END__
4162
4163 # XXX: FIXME: Attributes docs need clearing up
4164
4165 =head1 ATTRIBUTES
4166
4167 Attributes are used to refine a ResultSet in various ways when
4168 searching for data. They can be passed to any method which takes an
4169 C<\%attrs> argument. See L</search>, L</search_rs>, L</find>,
4170 L</count>.
4171
4172 Default attributes can be set on the result class using
4173 L<DBIx::Class::ResultSource/resultset_attributes>.  (Please read
4174 the CAVEATS on that feature before using it!)
4175
4176 These are in no particular order:
4177
4178 =head2 order_by
4179
4180 =over 4
4181
4182 =item Value: ( $order_by | \@order_by | \%order_by )
4183
4184 =back
4185
4186 Which column(s) to order the results by.
4187
4188 [The full list of suitable values is documented in
4189 L<SQL::Abstract/"ORDER BY CLAUSES">; the following is a summary of
4190 common options.]
4191
4192 If a single column name, or an arrayref of names is supplied, the
4193 argument is passed through directly to SQL. The hashref syntax allows
4194 for connection-agnostic specification of ordering direction:
4195
4196  For descending order:
4197
4198   order_by => { -desc => [qw/col1 col2 col3/] }
4199
4200  For explicit ascending order:
4201
4202   order_by => { -asc => 'col' }
4203
4204 The old scalarref syntax (i.e. order_by => \'year DESC') is still
4205 supported, although you are strongly encouraged to use the hashref
4206 syntax as outlined above.
4207
4208 =head2 columns
4209
4210 =over 4
4211
4212 =item Value: \@columns | \%columns | $column
4213
4214 =back
4215
4216 Shortcut to request a particular set of columns to be retrieved. Each
4217 column spec may be a string (a table column name), or a hash (in which
4218 case the key is the C<as> value, and the value is used as the C<select>
4219 expression). Adds the L</current_source_alias> onto the start of any column without a C<.> in
4220 it and sets C<select> from that, then auto-populates C<as> from
4221 C<select> as normal. (You may also use the C<cols> attribute, as in
4222 earlier versions of DBIC, but this is deprecated)
4223
4224 Essentially C<columns> does the same as L</select> and L</as>.
4225
4226     columns => [ 'some_column', { dbic_slot => 'another_column' } ]
4227
4228 is the same as
4229
4230     select => [qw(some_column another_column)],
4231     as     => [qw(some_column dbic_slot)]
4232
4233 If you want to individually retrieve related columns (in essence perform
4234 manual L</prefetch>) you have to make sure to specify the correct inflation slot
4235 chain such that it matches existing relationships:
4236
4237     my $rs = $schema->resultset('Artist')->search({}, {
4238         # required to tell DBIC to collapse has_many relationships
4239         collapse => 1,
4240         join     => { cds => 'tracks' },
4241         '+columns'  => {
4242           'cds.cdid'         => 'cds.cdid',
4243           'cds.tracks.title' => 'tracks.title',
4244         },
4245     });
4246
4247 Like elsewhere, literal SQL or literal values can be included by using a
4248 scalar reference or a literal bind value, and these values will be available
4249 in the result with C<get_column> (see also
4250 L<SQL::Abstract/Literal SQL and value type operators>):
4251
4252     # equivalent SQL: SELECT 1, 'a string', IF(my_column,?,?) ...
4253     # bind values: $true_value, $false_value
4254     columns => [
4255         {
4256             foo => \1,
4257             bar => \q{'a string'},
4258             baz => \[ 'IF(my_column,?,?)', $true_value, $false_value ],
4259         }
4260     ]
4261
4262 =head2 +columns
4263
4264 B<NOTE:> You B<MUST> explicitly quote C<'+columns'> when using this attribute.
4265 Not doing so causes Perl to incorrectly interpret C<+columns> as a bareword
4266 with a unary plus operator before it, which is the same as simply C<columns>.
4267
4268 =over 4
4269
4270 =item Value: \@extra_columns
4271
4272 =back
4273
4274 Indicates additional columns to be selected from storage. Works the same as
4275 L</columns> but adds columns to the current selection. (You may also use the
4276 C<include_columns> attribute, as in earlier versions of DBIC, but this is
4277 deprecated)
4278
4279   $schema->resultset('CD')->search(undef, {
4280     '+columns' => ['artist.name'],
4281     join => ['artist']
4282   });
4283
4284 would return all CDs and include a 'name' column to the information
4285 passed to object inflation. Note that the 'artist' is the name of the
4286 column (or relationship) accessor, and 'name' is the name of the column
4287 accessor in the related table.
4288
4289 =head2 select
4290
4291 =over 4
4292
4293 =item Value: \@select_columns
4294
4295 =back
4296
4297 Indicates which columns should be selected from the storage. You can use
4298 column names, or in the case of RDBMS back ends, function or stored procedure
4299 names:
4300
4301   $rs = $schema->resultset('Employee')->search(undef, {
4302     select => [
4303       'name',
4304       { count => 'employeeid' },
4305       { max => { length => 'name' }, -as => 'longest_name' }
4306     ]
4307   });
4308
4309   # Equivalent SQL
4310   SELECT name, COUNT( employeeid ), MAX( LENGTH( name ) ) AS longest_name FROM employee
4311
4312 B<NOTE:> You will almost always need a corresponding L</as> attribute when you
4313 use L</select>, to instruct DBIx::Class how to store the result of the column.
4314
4315 Also note that the L</as> attribute has B<nothing to do> with the SQL-side
4316 C<AS> identifier aliasing. You B<can> alias a function (so you can use it e.g.
4317 in an C<ORDER BY> clause), however this is done via the C<-as> B<select
4318 function attribute> supplied as shown in the example above.
4319
4320 =head2 +select
4321
4322 B<NOTE:> You B<MUST> explicitly quote C<'+select'> when using this attribute.
4323 Not doing so causes Perl to incorrectly interpret C<+select> as a bareword
4324 with a unary plus operator before it, which is the same as simply C<select>.
4325
4326 =over 4
4327
4328 =item Value: \@extra_select_columns
4329
4330 =back
4331
4332 Indicates additional columns to be selected from storage.  Works the same as
4333 L</select> but adds columns to the current selection, instead of specifying
4334 a new explicit list.
4335
4336 =head2 as
4337
4338 =over 4
4339
4340 =item Value: \@inflation_names
4341
4342 =back
4343
4344 Indicates DBIC-side names for object inflation. That is L</as> indicates the
4345 slot name in which the column value will be stored within the
4346 L<Row|DBIx::Class::Row> object. The value will then be accessible via this
4347 identifier by the C<get_column> method (or via the object accessor B<if one
4348 with the same name already exists>) as shown below.
4349
4350 The L</as> attribute has B<nothing to do> with the SQL-side identifier
4351 aliasing C<AS>. See L</select> for details.
4352
4353   $rs = $schema->resultset('Employee')->search(undef, {
4354     select => [
4355       'name',
4356       { count => 'employeeid' },
4357       { max => { length => 'name' }, -as => 'longest_name' }
4358     ],
4359     as => [qw/
4360       name
4361       employee_count
4362       max_name_length
4363     /],
4364   });
4365
4366 If the object against which the search is performed already has an accessor
4367 matching a column name specified in C<as>, the value can be retrieved using
4368 the accessor as normal:
4369
4370   my $name = $employee->name();
4371
4372 If on the other hand an accessor does not exist in the object, you need to
4373 use C<get_column> instead:
4374
4375   my $employee_count = $employee->get_column('employee_count');
4376
4377 You can create your own accessors if required - see
4378 L<DBIx::Class::Manual::Cookbook> for details.
4379
4380 =head2 +as
4381
4382 B<NOTE:> You B<MUST> explicitly quote C<'+as'> when using this attribute.
4383 Not doing so causes Perl to incorrectly interpret C<+as> as a bareword
4384 with a unary plus operator before it, which is the same as simply C<as>.
4385
4386 =over 4
4387
4388 =item Value: \@extra_inflation_names
4389
4390 =back
4391
4392 Indicates additional inflation names for selectors added via L</+select>. See L</as>.
4393
4394 =head2 join
4395
4396 =over 4
4397
4398 =item Value: ($rel_name | \@rel_names | \%rel_names)
4399
4400 =back
4401
4402 Contains a list of relationships that should be joined for this query.  For
4403 example:
4404
4405   # Get CDs by Nine Inch Nails
4406   my $rs = $schema->resultset('CD')->search(
4407     { 'artist.name' => 'Nine Inch Nails' },
4408     { join => 'artist' }
4409   );
4410
4411 Can also contain a hash reference to refer to the other relation's relations.
4412 For example:
4413
4414   package MyApp::Schema::Track;
4415   use base qw/DBIx::Class/;
4416   __PACKAGE__->table('track');
4417   __PACKAGE__->add_columns(qw/trackid cd position title/);
4418   __PACKAGE__->set_primary_key('trackid');
4419   __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
4420   1;
4421
4422   # In your application
4423   my $rs = $schema->resultset('Artist')->search(
4424     { 'track.title' => 'Teardrop' },
4425     {
4426       join     => { cd => 'track' },
4427       order_by => 'artist.name',
4428     }
4429   );
4430
4431 You need to use the relationship (not the table) name in  conditions,
4432 because they are aliased as such. The current table is aliased as "me", so
4433 you need to use me.column_name in order to avoid ambiguity. For example:
4434
4435   # Get CDs from 1984 with a 'Foo' track
4436   my $rs = $schema->resultset('CD')->search(
4437     {
4438       'me.year' => 1984,
4439       'tracks.name' => 'Foo'
4440     },
4441     { join => 'tracks' }
4442   );
4443
4444 If the same join is supplied twice, it will be aliased to <rel>_2 (and
4445 similarly for a third time). For e.g.
4446
4447   my $rs = $schema->resultset('Artist')->search({
4448     'cds.title'   => 'Down to Earth',
4449     'cds_2.title' => 'Popular',
4450   }, {
4451     join => [ qw/cds cds/ ],
4452   });
4453
4454 will return a set of all artists that have both a cd with title 'Down
4455 to Earth' and a cd with title 'Popular'.
4456
4457 If you want to fetch related objects from other tables as well, see L</prefetch>
4458 below.
4459
4460  NOTE: An internal join-chain pruner will discard certain joins while
4461  constructing the actual SQL query, as long as the joins in question do not
4462  affect the retrieved result. This for example includes 1:1 left joins
4463  that are not part of the restriction specification (WHERE/HAVING) nor are
4464  a part of the query selection.
4465
4466 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
4467
4468 =head2 collapse
4469
4470 =over 4
4471
4472 =item Value: (0 | 1)
4473
4474 =back
4475
4476 When set to a true value, indicates that any rows fetched from joined has_many
4477 relationships are to be aggregated into the corresponding "parent" object. For
4478 example, the resultset:
4479
4480   my $rs = $schema->resultset('CD')->search({}, {
4481     '+columns' => [ qw/ tracks.title tracks.position / ],
4482     join => 'tracks',
4483     collapse => 1,
4484   });
4485
4486 While executing the following query:
4487
4488   SELECT me.*, tracks.title, tracks.position
4489     FROM cd me
4490     LEFT JOIN track tracks
4491       ON tracks.cdid = me.cdid
4492
4493 Will return only as many objects as there are rows in the CD source, even
4494 though the result of the query may span many rows. Each of these CD objects
4495 will in turn have multiple "Track" objects hidden behind the has_many
4496 generated accessor C<tracks>. Without C<< collapse => 1 >>, the return values
4497 of this resultset would be as many CD objects as there are tracks (a "Cartesian
4498 product"), with each CD object containing exactly one of all fetched Track data.
4499
4500 When a collapse is requested on a non-ordered resultset, an order by some
4501 unique part of the main source (the left-most table) is inserted automatically.
4502 This is done so that the resultset is allowed to be "lazy" - calling
4503 L<< $rs->next|/next >> will fetch only as many rows as it needs to build the next
4504 object with all of its related data.
4505
4506 If an L</order_by> is already declared, and orders the resultset in a way that
4507 makes collapsing as described above impossible (e.g. C<< ORDER BY
4508 has_many_rel.column >> or C<ORDER BY RANDOM()>), DBIC will automatically
4509 switch to "eager" mode and slurp the entire resultset before constructing the
4510 first object returned by L</next>.
4511
4512 Setting this attribute on a resultset that does not join any has_many
4513 relations is a no-op.
4514
4515 For a more in-depth discussion, see L</PREFETCHING>.
4516
4517 =head2 prefetch
4518
4519 =over 4
4520
4521 =item Value: ($rel_name | \@rel_names | \%rel_names)
4522
4523 =back
4524
4525 This attribute is a shorthand for specifying a L</join> spec, adding all
4526 columns from the joined related sources as L</+columns> and setting
4527 L</collapse> to a true value. It can be thought of as a rough B<superset>
4528 of the L</join> attribute.
4529
4530 For example, the following two queries are equivalent:
4531
4532   my $rs = $schema->resultset('Artist')->search({}, {
4533     prefetch => { cds => ['genre', 'tracks' ] },
4534   });
4535
4536 and
4537
4538   my $rs = $schema->resultset('Artist')->search({}, {
4539     join => { cds => ['genre', 'tracks' ] },
4540     collapse => 1,
4541     '+columns' => [
4542       (map
4543         { +{ "cds.$_" => "cds.$_" } }
4544         $schema->source('Artist')->related_source('cds')->columns
4545       ),
4546       (map
4547         { +{ "cds.genre.$_" => "genre.$_" } }
4548         $schema->source('Artist')->related_source('cds')->related_source('genre')->columns
4549       ),
4550       (map
4551         { +{ "cds.tracks.$_" => "tracks.$_" } }
4552         $schema->source('Artist')->related_source('cds')->related_source('tracks')->columns
4553       ),
4554     ],
4555   });
4556
4557 Both producing the following SQL:
4558
4559   SELECT  me.artistid, me.name, me.rank, me.charfield,
4560           cds.cdid, cds.artist, cds.title, cds.year, cds.genreid, cds.single_track,
4561           genre.genreid, genre.name,
4562           tracks.trackid, tracks.cd, tracks.position, tracks.title, tracks.last_updated_on, tracks.last_updated_at
4563     FROM artist me
4564     LEFT JOIN cd cds
4565       ON cds.artist = me.artistid
4566     LEFT JOIN genre genre
4567       ON genre.genreid = cds.genreid
4568     LEFT JOIN track tracks
4569       ON tracks.cd = cds.cdid
4570   ORDER BY me.artistid
4571
4572 While L</prefetch> implies a L</join>, it is ok to mix the two together, as
4573 the arguments are properly merged and generally do the right thing. For
4574 example, you may want to do the following:
4575
4576   my $artists_and_cds_without_genre = $schema->resultset('Artist')->search(
4577     { 'genre.genreid' => undef },
4578     {
4579       join => { cds => 'genre' },
4580       prefetch => 'cds',
4581     }
4582   );
4583
4584 Which generates the following SQL:
4585
4586   SELECT  me.artistid, me.name, me.rank, me.charfield,
4587           cds.cdid, cds.artist, cds.title, cds.year, cds.genreid, cds.single_track
4588     FROM artist me
4589     LEFT JOIN cd cds
4590       ON cds.artist = me.artistid
4591     LEFT JOIN genre genre
4592       ON genre.genreid = cds.genreid
4593   WHERE genre.genreid IS NULL
4594   ORDER BY me.artistid
4595
4596 For a more in-depth discussion, see L</PREFETCHING>.
4597
4598 =head2 alias
4599
4600 =over 4
4601
4602 =item Value: $source_alias
4603
4604 =back
4605
4606 Sets the source alias for the query.  Normally, this defaults to C<me>, but
4607 nested search queries (sub-SELECTs) might need specific aliases set to
4608 reference inner queries.  For example:
4609
4610    my $q = $rs
4611       ->related_resultset('CDs')
4612       ->related_resultset('Tracks')
4613       ->search({
4614          'track.id' => { -ident => 'none_search.id' },
4615       })
4616       ->as_query;
4617
4618    my $ids = $self->search({
4619       -not_exists => $q,
4620    }, {
4621       alias    => 'none_search',
4622       group_by => 'none_search.id',
4623    })->get_column('id')->as_query;
4624
4625    $self->search({ id => { -in => $ids } })
4626
4627 This attribute is directly tied to L</current_source_alias>.
4628
4629 =head2 page
4630
4631 =over 4
4632
4633 =item Value: $page
4634
4635 =back
4636
4637 Makes the resultset paged and specifies the page to retrieve. Effectively
4638 identical to creating a non-pages resultset and then calling ->page($page)
4639 on it.
4640
4641 If L</rows> attribute is not specified it defaults to 10 rows per page.
4642
4643 When you have a paged resultset, L</count> will only return the number
4644 of rows in the page. To get the total, use the L</pager> and call
4645 C<total_entries> on it.
4646
4647 =head2 rows
4648
4649 =over 4
4650
4651 =item Value: $rows
4652
4653 =back
4654
4655 Specifies the maximum number of rows for direct retrieval or the number of
4656 rows per page if the page attribute or method is used.
4657
4658 =head2 offset
4659
4660 =over 4
4661
4662 =item Value: $offset
4663
4664 =back
4665
4666 Specifies the (zero-based) row number for the  first row to be returned, or the
4667 of the first row of the first page if paging is used.
4668
4669 =head2 software_limit
4670
4671 =over 4
4672
4673 =item Value: (0 | 1)
4674
4675 =back
4676
4677 When combined with L</rows> and/or L</offset> the generated SQL will not
4678 include any limit dialect stanzas. Instead the entire result will be selected
4679 as if no limits were specified, and DBIC will perform the limit locally, by
4680 artificially advancing and finishing the resulting L</cursor>.
4681
4682 This is the recommended way of performing resultset limiting when no sane RDBMS
4683 implementation is available (e.g.
4684 L<Sybase ASE|DBIx::Class::Storage::DBI::Sybase::ASE> using the
4685 L<Generic Sub Query|DBIx::Class::SQLMaker::LimitDialects/GenericSubQ> hack)
4686
4687 =head2 group_by
4688
4689 =over 4
4690
4691 =item Value: \@columns
4692
4693 =back
4694
4695 A arrayref of columns to group by. Can include columns of joined tables.
4696
4697   group_by => [qw/ column1 column2 ... /]
4698
4699 =head2 having
4700
4701 =over 4
4702
4703 =item Value: $condition
4704
4705 =back
4706
4707 The HAVING operator specifies a B<secondary> condition applied to the set
4708 after the grouping calculations have been done. In other words it is a
4709 constraint just like L</where> (and accepting the same
4710 L<SQL::Abstract syntax|SQL::Abstract/WHERE CLAUSES>) applied to the data
4711 as it exists after GROUP BY has taken place. Specifying L</having> without
4712 L</group_by> is a logical mistake, and a fatal error on most RDBMS engines.
4713
4714 E.g.
4715
4716   having => { 'count_employee' => { '>=', 100 } }
4717
4718 or with an in-place function in which case literal SQL is required:
4719
4720   having => \[ 'count(employee) >= ?', 100 ]
4721
4722 =head2 distinct
4723
4724 =over 4
4725
4726 =item Value: (0 | 1)
4727
4728 =back
4729
4730 Set to 1 to automatically generate a L</group_by> clause based on the selection
4731 (including intelligent handling of L</order_by> contents). Note that the group
4732 criteria calculation takes place over the B<final> selection. This includes
4733 any L</+columns>, L</+select> or L</order_by> additions in subsequent
4734 L</search> calls, and standalone columns selected via
4735 L<DBIx::Class::ResultSetColumn> (L</get_column>). A notable exception are the
4736 extra selections specified via L</prefetch> - such selections are explicitly
4737 excluded from group criteria calculations.
4738
4739 If the final ResultSet also explicitly defines a L</group_by> attribute, this
4740 setting is ignored and an appropriate warning is issued.
4741
4742 =head2 where
4743
4744 Adds extra conditions to the resultset, combined with the preexisting C<WHERE>
4745 conditions, same as the B<first> argument to the L<search operator|/search>
4746
4747   # only return rows WHERE deleted IS NULL for all searches
4748   __PACKAGE__->resultset_attributes({ where => { deleted => undef } });
4749
4750 Note that the above example is
4751 L<strongly discouraged|DBIx::Class::ResultSource/resultset_attributes>.
4752
4753 =head2 cache
4754
4755 Set to 1 to cache search results. This prevents extra SQL queries if you
4756 revisit rows in your ResultSet:
4757
4758   my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
4759
4760   while( my $artist = $resultset->next ) {
4761     ... do stuff ...
4762   }
4763
4764   $resultset->first; # without cache, this would issue a query
4765
4766 By default, searches are not cached.
4767
4768 For more examples of using these attributes, see
4769 L<DBIx::Class::Manual::Cookbook>.
4770
4771 =head2 for
4772
4773 =over 4
4774
4775 =item Value: ( 'update' | 'shared' | \$scalar )
4776
4777 =back
4778
4779 Set to 'update' for a SELECT ... FOR UPDATE or 'shared' for a SELECT
4780 ... FOR SHARED. If \$scalar is passed, this is taken directly and embedded in the
4781 query.
4782
4783 =head1 PREFETCHING
4784
4785 DBIx::Class supports arbitrary related data prefetching from multiple related
4786 sources. Any combination of relationship types and column sets are supported.
4787 If L<collapsing|/collapse> is requested, there is an additional requirement of
4788 selecting enough data to make every individual object uniquely identifiable.
4789
4790 Here are some more involved examples, based on the following relationship map:
4791
4792   # Assuming:
4793   My::Schema::CD->belongs_to( artist      => 'My::Schema::Artist'     );
4794   My::Schema::CD->might_have( liner_note  => 'My::Schema::LinerNotes' );
4795   My::Schema::CD->has_many(   tracks      => 'My::Schema::Track'      );
4796
4797   My::Schema::Artist->belongs_to( record_label => 'My::Schema::RecordLabel' );
4798
4799   My::Schema::Track->has_many( guests => 'My::Schema::Guest' );
4800
4801
4802
4803   my $rs = $schema->resultset('Tag')->search(
4804     undef,
4805     {
4806       prefetch => {
4807         cd => 'artist'
4808       }
4809     }
4810   );
4811
4812 The initial search results in SQL like the following:
4813
4814   SELECT tag.*, cd.*, artist.* FROM tag
4815   JOIN cd ON tag.cd = cd.cdid
4816   JOIN artist ON cd.artist = artist.artistid
4817
4818 L<DBIx::Class> has no need to go back to the database when we access the
4819 C<cd> or C<artist> relationships, which saves us two SQL statements in this
4820 case.
4821
4822 Simple prefetches will be joined automatically, so there is no need
4823 for a C<join> attribute in the above search.
4824
4825 The L</prefetch> attribute can be used with any of the relationship types
4826 and multiple prefetches can be specified together. Below is a more complex
4827 example that prefetches a CD's artist, its liner notes (if present),
4828 the cover image, the tracks on that CD, and the guests on those
4829 tracks.
4830
4831   my $rs = $schema->resultset('CD')->search(
4832     undef,
4833     {
4834       prefetch => [
4835         { artist => 'record_label'},  # belongs_to => belongs_to
4836         'liner_note',                 # might_have
4837         'cover_image',                # has_one
4838         { tracks => 'guests' },       # has_many => has_many
4839       ]
4840     }
4841   );
4842
4843 This will produce SQL like the following:
4844
4845   SELECT cd.*, artist.*, record_label.*, liner_note.*, cover_image.*,
4846          tracks.*, guests.*
4847     FROM cd me
4848     JOIN artist artist
4849       ON artist.artistid = me.artistid
4850     JOIN record_label record_label
4851       ON record_label.labelid = artist.labelid
4852     LEFT JOIN track tracks
4853       ON tracks.cdid = me.cdid
4854     LEFT JOIN guest guests
4855       ON guests.trackid = track.trackid
4856     LEFT JOIN liner_notes liner_note
4857       ON liner_note.cdid = me.cdid
4858     JOIN cd_artwork cover_image
4859       ON cover_image.cdid = me.cdid
4860   ORDER BY tracks.cd
4861
4862 Now the C<artist>, C<record_label>, C<liner_note>, C<cover_image>,
4863 C<tracks>, and C<guests> of the CD will all be available through the
4864 relationship accessors without the need for additional queries to the
4865 database.
4866
4867 =head3 CAVEATS
4868
4869 Prefetch does a lot of deep magic. As such, it may not behave exactly
4870 as you might expect.
4871
4872 =over 4
4873
4874 =item *
4875
4876 Prefetch uses the L</cache> to populate the prefetched relationships. This
4877 may or may not be what you want.
4878
4879 =item *
4880
4881 If you specify a condition on a prefetched relationship, ONLY those
4882 rows that match the prefetched condition will be fetched into that relationship.
4883 This means that adding prefetch to a search() B<may alter> what is returned by
4884 traversing a relationship. So, if you have C<< Artist->has_many(CDs) >> and you do
4885
4886   my $artist_rs = $schema->resultset('Artist')->search({
4887       'cds.year' => 2008,
4888   }, {
4889       join => 'cds',
4890   });
4891
4892   my $count = $artist_rs->first->cds->count;
4893
4894   my $artist_rs_prefetch = $artist_rs->search( {}, { prefetch => 'cds' } );
4895
4896   my $prefetch_count = $artist_rs_prefetch->first->cds->count;
4897
4898   cmp_ok( $count, '==', $prefetch_count, "Counts should be the same" );
4899
4900 That cmp_ok() may or may not pass depending on the datasets involved. In other
4901 words the C<WHERE> condition would apply to the entire dataset, just like
4902 it would in regular SQL. If you want to add a condition only to the "right side"
4903 of a C<LEFT JOIN> - consider declaring and using a L<relationship with a custom
4904 condition|DBIx::Class::Relationship::Base/condition>
4905
4906 =back
4907
4908 =head1 DBIC BIND VALUES
4909
4910 Because DBIC may need more information to bind values than just the column name
4911 and value itself, it uses a special format for both passing and receiving bind
4912 values.  Each bind value should be composed of an arrayref of
4913 C<< [ \%args => $val ] >>.  The format of C<< \%args >> is currently:
4914
4915 =over 4
4916
4917 =item dbd_attrs
4918
4919 If present (in any form), this is what is being passed directly to bind_param.
4920 Note that different DBD's expect different bind args.  (e.g. DBD::SQLite takes
4921 a single numerical type, while DBD::Pg takes a hashref if bind options.)
4922
4923 If this is specified, all other bind options described below are ignored.
4924
4925 =item sqlt_datatype
4926
4927 If present, this is used to infer the actual bind attribute by passing to
4928 C<< $resolved_storage->bind_attribute_by_data_type() >>.  Defaults to the
4929 "data_type" from the L<add_columns column info|DBIx::Class::ResultSource/add_columns>.
4930
4931 Note that the data type is somewhat freeform (hence the sqlt_ prefix);
4932 currently drivers are expected to "Do the Right Thing" when given a common
4933 datatype name.  (Not ideal, but that's what we got at this point.)
4934
4935 =item sqlt_size
4936
4937 Currently used to correctly allocate buffers for bind_param_inout().
4938 Defaults to "size" from the L<add_columns column info|DBIx::Class::ResultSource/add_columns>,
4939 or to a sensible value based on the "data_type".
4940
4941 =item dbic_colname
4942
4943 Used to fill in missing sqlt_datatype and sqlt_size attributes (if they are
4944 explicitly specified they are never overridden).  Also used by some weird DBDs,
4945 where the column name should be available at bind_param time (e.g. Oracle).
4946
4947 =back
4948
4949 For backwards compatibility and convenience, the following shortcuts are
4950 supported:
4951
4952   [ $name => $val ] === [ { dbic_colname => $name }, $val ]
4953   [ \$dt  => $val ] === [ { sqlt_datatype => $dt }, $val ]
4954   [ undef,   $val ] === [ {}, $val ]
4955   $val              === [ {}, $val ]
4956
4957 =head1 FURTHER QUESTIONS?
4958
4959 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
4960
4961 =head1 COPYRIGHT AND LICENSE
4962
4963 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
4964 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
4965 redistribute it and/or modify it under the same terms as the
4966 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.
4967
4968 =cut