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