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