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