Improve the populate docs in ::Schema and ::ResultSet
[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: [ \@column_list, \@row_values+ ] | [ \%col_data+ ]
2042
2043 =item Return Value: L<\@result_objects|DBIx::Class::Manual::ResultClass> (scalar context) | L<@result_objects|DBIx::Class::Manual::ResultClass> (list context)
2044
2045 =back
2046
2047 Accepts either an arrayref of hashrefs or alternatively an arrayref of
2048 arrayrefs.
2049
2050 =over
2051
2052 =item NOTE
2053
2054 The context of this method call has an important effect on what is
2055 submitted to storage. In void context data is fed directly to fastpath
2056 insertion routines provided by the underlying storage (most often
2057 L<DBI/execute_for_fetch>), bypassing the L<new|DBIx::Class::Row/new> and
2058 L<insert|DBIx::Class::Row/insert> calls on the
2059 L<Result|DBIx::Class::Manual::ResultClass> class, including any
2060 augmentation of these methods provided by components. For example if you
2061 are using something like L<DBIx::Class::UUIDColumns> to create primary
2062 keys for you, you will find that your PKs are empty.  In this case you
2063 will have to explicitly force scalar or list context in order to create
2064 those values.
2065
2066 =back
2067
2068 In non-void (scalar or list) context, this method is simply a wrapper
2069 for L</create>. Depending on list or scalar context either a list of
2070 L<Result|DBIx::Class::Manual::ResultClass> objects or an arrayref
2071 containing these objects is returned.
2072
2073 When supplying data in "arrayref of arrayrefs" invocation style, the
2074 first element should be a list of column names and each subsequent
2075 element should be a data value in the earlier specified column order.
2076 For example:
2077
2078   $Arstist_rs->populate([
2079     [ qw( artistid name ) ],
2080     [ 100, 'A Formally Unknown Singer' ],
2081     [ 101, 'A singer that jumped the shark two albums ago' ],
2082     [ 102, 'An actually cool singer' ],
2083   ]);
2084
2085 For the arrayref of hashrefs style each hashref should be a structure
2086 suitable for passing to L</create>. Multi-create is also permitted with
2087 this syntax.
2088
2089   $schema->resultset("Artist")->populate([
2090      { artistid => 4, name => 'Manufactured Crap', cds => [
2091         { title => 'My First CD', year => 2006 },
2092         { title => 'Yet More Tweeny-Pop crap', year => 2007 },
2093       ],
2094      },
2095      { artistid => 5, name => 'Angsty-Whiny Girl', cds => [
2096         { title => 'My parents sold me to a record company', year => 2005 },
2097         { title => 'Why Am I So Ugly?', year => 2006 },
2098         { title => 'I Got Surgery and am now Popular', year => 2007 }
2099       ],
2100      },
2101   ]);
2102
2103 If you attempt a void-context multi-create as in the example above (each
2104 Artist also has the related list of CDs), and B<do not> supply the
2105 necessary autoinc foreign key information, this method will proxy to the
2106 less efficient L</create>, and then throw the Result objects away. In this
2107 case there are obviously no benefits to using this method over L</create>.
2108
2109 =cut
2110
2111 sub populate {
2112   my $self = shift;
2113
2114   # cruft placed in standalone method
2115   my $data = $self->_normalize_populate_args(@_);
2116
2117   return unless @$data;
2118
2119   if(defined wantarray) {
2120     my @created;
2121     foreach my $item (@$data) {
2122       push(@created, $self->create($item));
2123     }
2124     return wantarray ? @created : \@created;
2125   }
2126   else {
2127     my $first = $data->[0];
2128
2129     # if a column is a registered relationship, and is a non-blessed hash/array, consider
2130     # it relationship data
2131     my (@rels, @columns);
2132     my $rsrc = $self->result_source;
2133     my $rels = { map { $_ => $rsrc->relationship_info($_) } $rsrc->relationships };
2134     for (keys %$first) {
2135       my $ref = ref $first->{$_};
2136       $rels->{$_} && ($ref eq 'ARRAY' or $ref eq 'HASH')
2137         ? push @rels, $_
2138         : push @columns, $_
2139       ;
2140     }
2141
2142     my @pks = $rsrc->primary_columns;
2143
2144     ## do the belongs_to relationships
2145     foreach my $index (0..$#$data) {
2146
2147       # delegate to create() for any dataset without primary keys with specified relationships
2148       if (grep { !defined $data->[$index]->{$_} } @pks ) {
2149         for my $r (@rels) {
2150           if (grep { ref $data->[$index]{$r} eq $_ } qw/HASH ARRAY/) {  # a related set must be a HASH or AoH
2151             my @ret = $self->populate($data);
2152             return;
2153           }
2154         }
2155       }
2156
2157       foreach my $rel (@rels) {
2158         next unless ref $data->[$index]->{$rel} eq "HASH";
2159         my $result = $self->related_resultset($rel)->create($data->[$index]->{$rel});
2160         my ($reverse_relname, $reverse_relinfo) = %{$rsrc->reverse_relationship_info($rel)};
2161         my $related = $result->result_source->_resolve_condition(
2162           $reverse_relinfo->{cond},
2163           $self,
2164           $result,
2165           $rel,
2166         );
2167
2168         delete $data->[$index]->{$rel};
2169         $data->[$index] = {%{$data->[$index]}, %$related};
2170
2171         push @columns, keys %$related if $index == 0;
2172       }
2173     }
2174
2175     ## inherit the data locked in the conditions of the resultset
2176     my ($rs_data) = $self->_merge_with_rscond({});
2177     delete @{$rs_data}{@columns};
2178     my @inherit_cols = keys %$rs_data;
2179     my @inherit_data = values %$rs_data;
2180
2181     ## do bulk insert on current row
2182     $rsrc->storage->insert_bulk(
2183       $rsrc,
2184       [@columns, @inherit_cols],
2185       [ map { [ @$_{@columns}, @inherit_data ] } @$data ],
2186     );
2187
2188     ## do the has_many relationships
2189     foreach my $item (@$data) {
2190
2191       my $main_row;
2192
2193       foreach my $rel (@rels) {
2194         next unless ref $item->{$rel} eq "ARRAY" && @{ $item->{$rel} };
2195
2196         $main_row ||= $self->new_result({map { $_ => $item->{$_} } @pks});
2197
2198         my $child = $main_row->$rel;
2199
2200         my $related = $child->result_source->_resolve_condition(
2201           $rels->{$rel}{cond},
2202           $child,
2203           $main_row,
2204           $rel,
2205         );
2206
2207         my @rows_to_add = ref $item->{$rel} eq 'ARRAY' ? @{$item->{$rel}} : ($item->{$rel});
2208         my @populate = map { {%$_, %$related} } @rows_to_add;
2209
2210         $child->populate( \@populate );
2211       }
2212     }
2213   }
2214 }
2215
2216
2217 # populate() argumnets went over several incarnations
2218 # What we ultimately support is AoH
2219 sub _normalize_populate_args {
2220   my ($self, $arg) = @_;
2221
2222   if (ref $arg eq 'ARRAY') {
2223     if (!@$arg) {
2224       return [];
2225     }
2226     elsif (ref $arg->[0] eq 'HASH') {
2227       return $arg;
2228     }
2229     elsif (ref $arg->[0] eq 'ARRAY') {
2230       my @ret;
2231       my @colnames = @{$arg->[0]};
2232       foreach my $values (@{$arg}[1 .. $#$arg]) {
2233         push @ret, { map { $colnames[$_] => $values->[$_] } (0 .. $#colnames) };
2234       }
2235       return \@ret;
2236     }
2237   }
2238
2239   $self->throw_exception('Populate expects an arrayref of hashrefs or arrayref of arrayrefs');
2240 }
2241
2242 =head2 pager
2243
2244 =over 4
2245
2246 =item Arguments: none
2247
2248 =item Return Value: L<$pager|Data::Page>
2249
2250 =back
2251
2252 Returns a L<Data::Page> object for the current resultset. Only makes
2253 sense for queries with a C<page> attribute.
2254
2255 To get the full count of entries for a paged resultset, call
2256 C<total_entries> on the L<Data::Page> object.
2257
2258 =cut
2259
2260 sub pager {
2261   my ($self) = @_;
2262
2263   return $self->{pager} if $self->{pager};
2264
2265   my $attrs = $self->{attrs};
2266   if (!defined $attrs->{page}) {
2267     $self->throw_exception("Can't create pager for non-paged rs");
2268   }
2269   elsif ($attrs->{page} <= 0) {
2270     $self->throw_exception('Invalid page number (page-numbers are 1-based)');
2271   }
2272   $attrs->{rows} ||= 10;
2273
2274   # throw away the paging flags and re-run the count (possibly
2275   # with a subselect) to get the real total count
2276   my $count_attrs = { %$attrs };
2277   delete $count_attrs->{$_} for qw/rows offset page pager/;
2278
2279   my $total_rs = (ref $self)->new($self->result_source, $count_attrs);
2280
2281   require DBIx::Class::ResultSet::Pager;
2282   return $self->{pager} = DBIx::Class::ResultSet::Pager->new(
2283     sub { $total_rs->count },  #lazy-get the total
2284     $attrs->{rows},
2285     $self->{attrs}{page},
2286   );
2287 }
2288
2289 =head2 page
2290
2291 =over 4
2292
2293 =item Arguments: $page_number
2294
2295 =item Return Value: L<$resultset|/search>
2296
2297 =back
2298
2299 Returns a resultset for the $page_number page of the resultset on which page
2300 is called, where each page contains a number of rows equal to the 'rows'
2301 attribute set on the resultset (10 by default).
2302
2303 =cut
2304
2305 sub page {
2306   my ($self, $page) = @_;
2307   return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
2308 }
2309
2310 =head2 new_result
2311
2312 =over 4
2313
2314 =item Arguments: \%col_data
2315
2316 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2317
2318 =back
2319
2320 Creates a new result object in the resultset's result class and returns
2321 it. The row is not inserted into the database at this point, call
2322 L<DBIx::Class::Row/insert> to do that. Calling L<DBIx::Class::Row/in_storage>
2323 will tell you whether the result object has been inserted or not.
2324
2325 Passes the hashref of input on to L<DBIx::Class::Row/new>.
2326
2327 =cut
2328
2329 sub new_result {
2330   my ($self, $values) = @_;
2331
2332   $self->throw_exception( "new_result takes only one argument - a hashref of values" )
2333     if @_ > 2;
2334
2335   $self->throw_exception( "new_result expects a hashref" )
2336     unless (ref $values eq 'HASH');
2337
2338   my ($merged_cond, $cols_from_relations) = $self->_merge_with_rscond($values);
2339
2340   my %new = (
2341     %$merged_cond,
2342     @$cols_from_relations
2343       ? (-cols_from_relations => $cols_from_relations)
2344       : (),
2345     -result_source => $self->result_source, # DO NOT REMOVE THIS, REQUIRED
2346   );
2347
2348   return $self->result_class->new(\%new);
2349 }
2350
2351 # _merge_with_rscond
2352 #
2353 # Takes a simple hash of K/V data and returns its copy merged with the
2354 # condition already present on the resultset. Additionally returns an
2355 # arrayref of value/condition names, which were inferred from related
2356 # objects (this is needed for in-memory related objects)
2357 sub _merge_with_rscond {
2358   my ($self, $data) = @_;
2359
2360   my (%new_data, @cols_from_relations);
2361
2362   my $alias = $self->{attrs}{alias};
2363
2364   if (! defined $self->{cond}) {
2365     # just massage $data below
2366   }
2367   elsif ($self->{cond} eq $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION) {
2368     %new_data = %{ $self->{attrs}{related_objects} || {} };  # nothing might have been inserted yet
2369     @cols_from_relations = keys %new_data;
2370   }
2371   elsif (ref $self->{cond} ne 'HASH') {
2372     $self->throw_exception(
2373       "Can't abstract implicit construct, resultset condition not a hash"
2374     );
2375   }
2376   else {
2377     # precendence must be given to passed values over values inherited from
2378     # the cond, so the order here is important.
2379     my $collapsed_cond = $self->_collapse_cond($self->{cond});
2380     my %implied = %{$self->_remove_alias($collapsed_cond, $alias)};
2381
2382     while ( my($col, $value) = each %implied ) {
2383       my $vref = ref $value;
2384       if (
2385         $vref eq 'HASH'
2386           and
2387         keys(%$value) == 1
2388           and
2389         (keys %$value)[0] eq '='
2390       ) {
2391         $new_data{$col} = $value->{'='};
2392       }
2393       elsif( !$vref or $vref eq 'SCALAR' or blessed($value) ) {
2394         $new_data{$col} = $value;
2395       }
2396     }
2397   }
2398
2399   %new_data = (
2400     %new_data,
2401     %{ $self->_remove_alias($data, $alias) },
2402   );
2403
2404   return (\%new_data, \@cols_from_relations);
2405 }
2406
2407 # _has_resolved_attr
2408 #
2409 # determines if the resultset defines at least one
2410 # of the attributes supplied
2411 #
2412 # used to determine if a subquery is neccessary
2413 #
2414 # supports some virtual attributes:
2415 #   -join
2416 #     This will scan for any joins being present on the resultset.
2417 #     It is not a mere key-search but a deep inspection of {from}
2418 #
2419
2420 sub _has_resolved_attr {
2421   my ($self, @attr_names) = @_;
2422
2423   my $attrs = $self->_resolved_attrs;
2424
2425   my %extra_checks;
2426
2427   for my $n (@attr_names) {
2428     if (grep { $n eq $_ } (qw/-join/) ) {
2429       $extra_checks{$n}++;
2430       next;
2431     }
2432
2433     my $attr =  $attrs->{$n};
2434
2435     next if not defined $attr;
2436
2437     if (ref $attr eq 'HASH') {
2438       return 1 if keys %$attr;
2439     }
2440     elsif (ref $attr eq 'ARRAY') {
2441       return 1 if @$attr;
2442     }
2443     else {
2444       return 1 if $attr;
2445     }
2446   }
2447
2448   # a resolved join is expressed as a multi-level from
2449   return 1 if (
2450     $extra_checks{-join}
2451       and
2452     ref $attrs->{from} eq 'ARRAY'
2453       and
2454     @{$attrs->{from}} > 1
2455   );
2456
2457   return 0;
2458 }
2459
2460 # _collapse_cond
2461 #
2462 # Recursively collapse the condition.
2463
2464 sub _collapse_cond {
2465   my ($self, $cond, $collapsed) = @_;
2466
2467   $collapsed ||= {};
2468
2469   if (ref $cond eq 'ARRAY') {
2470     foreach my $subcond (@$cond) {
2471       next unless ref $subcond;  # -or
2472       $collapsed = $self->_collapse_cond($subcond, $collapsed);
2473     }
2474   }
2475   elsif (ref $cond eq 'HASH') {
2476     if (keys %$cond and (keys %$cond)[0] eq '-and') {
2477       foreach my $subcond (@{$cond->{-and}}) {
2478         $collapsed = $self->_collapse_cond($subcond, $collapsed);
2479       }
2480     }
2481     else {
2482       foreach my $col (keys %$cond) {
2483         my $value = $cond->{$col};
2484         $collapsed->{$col} = $value;
2485       }
2486     }
2487   }
2488
2489   return $collapsed;
2490 }
2491
2492 # _remove_alias
2493 #
2494 # Remove the specified alias from the specified query hash. A copy is made so
2495 # the original query is not modified.
2496
2497 sub _remove_alias {
2498   my ($self, $query, $alias) = @_;
2499
2500   my %orig = %{ $query || {} };
2501   my %unaliased;
2502
2503   foreach my $key (keys %orig) {
2504     if ($key !~ /\./) {
2505       $unaliased{$key} = $orig{$key};
2506       next;
2507     }
2508     $unaliased{$1} = $orig{$key}
2509       if $key =~ m/^(?:\Q$alias\E\.)?([^.]+)$/;
2510   }
2511
2512   return \%unaliased;
2513 }
2514
2515 =head2 as_query
2516
2517 =over 4
2518
2519 =item Arguments: none
2520
2521 =item Return Value: \[ $sql, L<@bind_values|/DBIC BIND VALUES> ]
2522
2523 =back
2524
2525 Returns the SQL query and bind vars associated with the invocant.
2526
2527 This is generally used as the RHS for a subquery.
2528
2529 =cut
2530
2531 sub as_query {
2532   my $self = shift;
2533
2534   my $attrs = $self->_resolved_attrs_copy;
2535
2536   # For future use:
2537   #
2538   # in list ctx:
2539   # my ($sql, \@bind, \%dbi_bind_attrs) = _select_args_to_query (...)
2540   # $sql also has no wrapping parenthesis in list ctx
2541   #
2542   my $sqlbind = $self->result_source->storage
2543     ->_select_args_to_query ($attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs);
2544
2545   return $sqlbind;
2546 }
2547
2548 =head2 find_or_new
2549
2550 =over 4
2551
2552 =item Arguments: \%col_data, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
2553
2554 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2555
2556 =back
2557
2558   my $artist = $schema->resultset('Artist')->find_or_new(
2559     { artist => 'fred' }, { key => 'artists' });
2560
2561   $cd->cd_to_producer->find_or_new({ producer => $producer },
2562                                    { key => 'primary });
2563
2564 Find an existing record from this resultset using L</find>. if none exists,
2565 instantiate a new result object and return it. The object will not be saved
2566 into your storage until you call L<DBIx::Class::Row/insert> on it.
2567
2568 You most likely want this method when looking for existing rows using a unique
2569 constraint that is not the primary key, or looking for related rows.
2570
2571 If you want objects to be saved immediately, use L</find_or_create> instead.
2572
2573 B<Note>: Make sure to read the documentation of L</find> and understand the
2574 significance of the C<key> attribute, as its lack may skew your search, and
2575 subsequently result in spurious new objects.
2576
2577 B<Note>: Take care when using C<find_or_new> with a table having
2578 columns with default values that you intend to be automatically
2579 supplied by the database (e.g. an auto_increment primary key column).
2580 In normal usage, the value of such columns should NOT be included at
2581 all in the call to C<find_or_new>, even when set to C<undef>.
2582
2583 =cut
2584
2585 sub find_or_new {
2586   my $self     = shift;
2587   my $attrs    = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2588   my $hash     = ref $_[0] eq 'HASH' ? shift : {@_};
2589   if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2590     return $row;
2591   }
2592   return $self->new_result($hash);
2593 }
2594
2595 =head2 create
2596
2597 =over 4
2598
2599 =item Arguments: \%col_data
2600
2601 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2602
2603 =back
2604
2605 Attempt to create a single new row or a row with multiple related rows
2606 in the table represented by the resultset (and related tables). This
2607 will not check for duplicate rows before inserting, use
2608 L</find_or_create> to do that.
2609
2610 To create one row for this resultset, pass a hashref of key/value
2611 pairs representing the columns of the table and the values you wish to
2612 store. If the appropriate relationships are set up, foreign key fields
2613 can also be passed an object representing the foreign row, and the
2614 value will be set to its primary key.
2615
2616 To create related objects, pass a hashref of related-object column values
2617 B<keyed on the relationship name>. If the relationship is of type C<multi>
2618 (L<DBIx::Class::Relationship/has_many>) - pass an arrayref of hashrefs.
2619 The process will correctly identify columns holding foreign keys, and will
2620 transparently populate them from the keys of the corresponding relation.
2621 This can be applied recursively, and will work correctly for a structure
2622 with an arbitrary depth and width, as long as the relationships actually
2623 exists and the correct column data has been supplied.
2624
2625 Instead of hashrefs of plain related data (key/value pairs), you may
2626 also pass new or inserted objects. New objects (not inserted yet, see
2627 L</new_result>), will be inserted into their appropriate tables.
2628
2629 Effectively a shortcut for C<< ->new_result(\%col_data)->insert >>.
2630
2631 Example of creating a new row.
2632
2633   $person_rs->create({
2634     name=>"Some Person",
2635     email=>"somebody@someplace.com"
2636   });
2637
2638 Example of creating a new row and also creating rows in a related C<has_many>
2639 or C<has_one> resultset.  Note Arrayref.
2640
2641   $artist_rs->create(
2642      { artistid => 4, name => 'Manufactured Crap', cds => [
2643         { title => 'My First CD', year => 2006 },
2644         { title => 'Yet More Tweeny-Pop crap', year => 2007 },
2645       ],
2646      },
2647   );
2648
2649 Example of creating a new row and also creating a row in a related
2650 C<belongs_to> resultset. Note Hashref.
2651
2652   $cd_rs->create({
2653     title=>"Music for Silly Walks",
2654     year=>2000,
2655     artist => {
2656       name=>"Silly Musician",
2657     }
2658   });
2659
2660 =over
2661
2662 =item WARNING
2663
2664 When subclassing ResultSet never attempt to override this method. Since
2665 it is a simple shortcut for C<< $self->new_result($attrs)->insert >>, a
2666 lot of the internals simply never call it, so your override will be
2667 bypassed more often than not. Override either L<DBIx::Class::Row/new>
2668 or L<DBIx::Class::Row/insert> depending on how early in the
2669 L</create> process you need to intervene. See also warning pertaining to
2670 L</new>.
2671
2672 =back
2673
2674 =cut
2675
2676 sub create {
2677   my ($self, $attrs) = @_;
2678   $self->throw_exception( "create needs a hashref" )
2679     unless ref $attrs eq 'HASH';
2680   return $self->new_result($attrs)->insert;
2681 }
2682
2683 =head2 find_or_create
2684
2685 =over 4
2686
2687 =item Arguments: \%col_data, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
2688
2689 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2690
2691 =back
2692
2693   $cd->cd_to_producer->find_or_create({ producer => $producer },
2694                                       { key => 'primary' });
2695
2696 Tries to find a record based on its primary key or unique constraints; if none
2697 is found, creates one and returns that instead.
2698
2699   my $cd = $schema->resultset('CD')->find_or_create({
2700     cdid   => 5,
2701     artist => 'Massive Attack',
2702     title  => 'Mezzanine',
2703     year   => 2005,
2704   });
2705
2706 Also takes an optional C<key> attribute, to search by a specific key or unique
2707 constraint. For example:
2708
2709   my $cd = $schema->resultset('CD')->find_or_create(
2710     {
2711       artist => 'Massive Attack',
2712       title  => 'Mezzanine',
2713     },
2714     { key => 'cd_artist_title' }
2715   );
2716
2717 B<Note>: Make sure to read the documentation of L</find> and understand the
2718 significance of the C<key> attribute, as its lack may skew your search, and
2719 subsequently result in spurious row creation.
2720
2721 B<Note>: Because find_or_create() reads from the database and then
2722 possibly inserts based on the result, this method is subject to a race
2723 condition. Another process could create a record in the table after
2724 the find has completed and before the create has started. To avoid
2725 this problem, use find_or_create() inside a transaction.
2726
2727 B<Note>: Take care when using C<find_or_create> with a table having
2728 columns with default values that you intend to be automatically
2729 supplied by the database (e.g. an auto_increment primary key column).
2730 In normal usage, the value of such columns should NOT be included at
2731 all in the call to C<find_or_create>, even when set to C<undef>.
2732
2733 See also L</find> and L</update_or_create>. For information on how to declare
2734 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2735
2736 If you need to know if an existing row was found or a new one created use
2737 L</find_or_new> and L<DBIx::Class::Row/in_storage> instead. Don't forget
2738 to call L<DBIx::Class::Row/insert> to save the newly created row to the
2739 database!
2740
2741   my $cd = $schema->resultset('CD')->find_or_new({
2742     cdid   => 5,
2743     artist => 'Massive Attack',
2744     title  => 'Mezzanine',
2745     year   => 2005,
2746   });
2747
2748   if( !$cd->in_storage ) {
2749       # do some stuff
2750       $cd->insert;
2751   }
2752
2753 =cut
2754
2755 sub find_or_create {
2756   my $self     = shift;
2757   my $attrs    = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2758   my $hash     = ref $_[0] eq 'HASH' ? shift : {@_};
2759   if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2760     return $row;
2761   }
2762   return $self->create($hash);
2763 }
2764
2765 =head2 update_or_create
2766
2767 =over 4
2768
2769 =item Arguments: \%col_data, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
2770
2771 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2772
2773 =back
2774
2775   $resultset->update_or_create({ col => $val, ... });
2776
2777 Like L</find_or_create>, but if a row is found it is immediately updated via
2778 C<< $found_row->update (\%col_data) >>.
2779
2780
2781 Takes an optional C<key> attribute to search on a specific unique constraint.
2782 For example:
2783
2784   # In your application
2785   my $cd = $schema->resultset('CD')->update_or_create(
2786     {
2787       artist => 'Massive Attack',
2788       title  => 'Mezzanine',
2789       year   => 1998,
2790     },
2791     { key => 'cd_artist_title' }
2792   );
2793
2794   $cd->cd_to_producer->update_or_create({
2795     producer => $producer,
2796     name => 'harry',
2797   }, {
2798     key => 'primary',
2799   });
2800
2801 B<Note>: Make sure to read the documentation of L</find> and understand the
2802 significance of the C<key> attribute, as its lack may skew your search, and
2803 subsequently result in spurious row creation.
2804
2805 B<Note>: Take care when using C<update_or_create> with a table having
2806 columns with default values that you intend to be automatically
2807 supplied by the database (e.g. an auto_increment primary key column).
2808 In normal usage, the value of such columns should NOT be included at
2809 all in the call to C<update_or_create>, even when set to C<undef>.
2810
2811 See also L</find> and L</find_or_create>. For information on how to declare
2812 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2813
2814 If you need to know if an existing row was updated or a new one created use
2815 L</update_or_new> and L<DBIx::Class::Row/in_storage> instead. Don't forget
2816 to call L<DBIx::Class::Row/insert> to save the newly created row to the
2817 database!
2818
2819 =cut
2820
2821 sub update_or_create {
2822   my $self = shift;
2823   my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2824   my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
2825
2826   my $row = $self->find($cond, $attrs);
2827   if (defined $row) {
2828     $row->update($cond);
2829     return $row;
2830   }
2831
2832   return $self->create($cond);
2833 }
2834
2835 =head2 update_or_new
2836
2837 =over 4
2838
2839 =item Arguments: \%col_data, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
2840
2841 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2842
2843 =back
2844
2845   $resultset->update_or_new({ col => $val, ... });
2846
2847 Like L</find_or_new> but if a row is found it is immediately updated via
2848 C<< $found_row->update (\%col_data) >>.
2849
2850 For example:
2851
2852   # In your application
2853   my $cd = $schema->resultset('CD')->update_or_new(
2854     {
2855       artist => 'Massive Attack',
2856       title  => 'Mezzanine',
2857       year   => 1998,
2858     },
2859     { key => 'cd_artist_title' }
2860   );
2861
2862   if ($cd->in_storage) {
2863       # the cd was updated
2864   }
2865   else {
2866       # the cd is not yet in the database, let's insert it
2867       $cd->insert;
2868   }
2869
2870 B<Note>: Make sure to read the documentation of L</find> and understand the
2871 significance of the C<key> attribute, as its lack may skew your search, and
2872 subsequently result in spurious new objects.
2873
2874 B<Note>: Take care when using C<update_or_new> with a table having
2875 columns with default values that you intend to be automatically
2876 supplied by the database (e.g. an auto_increment primary key column).
2877 In normal usage, the value of such columns should NOT be included at
2878 all in the call to C<update_or_new>, even when set to C<undef>.
2879
2880 See also L</find>, L</find_or_create> and L</find_or_new>.
2881
2882 =cut
2883
2884 sub update_or_new {
2885     my $self  = shift;
2886     my $attrs = ( @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {} );
2887     my $cond  = ref $_[0] eq 'HASH' ? shift : {@_};
2888
2889     my $row = $self->find( $cond, $attrs );
2890     if ( defined $row ) {
2891         $row->update($cond);
2892         return $row;
2893     }
2894
2895     return $self->new_result($cond);
2896 }
2897
2898 =head2 get_cache
2899
2900 =over 4
2901
2902 =item Arguments: none
2903
2904 =item Return Value: L<\@result_objs|DBIx::Class::Manual::ResultClass> | undef
2905
2906 =back
2907
2908 Gets the contents of the cache for the resultset, if the cache is set.
2909
2910 The cache is populated either by using the L</prefetch> attribute to
2911 L</search> or by calling L</set_cache>.
2912
2913 =cut
2914
2915 sub get_cache {
2916   shift->{all_cache};
2917 }
2918
2919 =head2 set_cache
2920
2921 =over 4
2922
2923 =item Arguments: L<\@result_objs|DBIx::Class::Manual::ResultClass>
2924
2925 =item Return Value: L<\@result_objs|DBIx::Class::Manual::ResultClass>
2926
2927 =back
2928
2929 Sets the contents of the cache for the resultset. Expects an arrayref
2930 of objects of the same class as those produced by the resultset. Note that
2931 if the cache is set, the resultset will return the cached objects rather
2932 than re-querying the database even if the cache attr is not set.
2933
2934 The contents of the cache can also be populated by using the
2935 L</prefetch> attribute to L</search>.
2936
2937 =cut
2938
2939 sub set_cache {
2940   my ( $self, $data ) = @_;
2941   $self->throw_exception("set_cache requires an arrayref")
2942       if defined($data) && (ref $data ne 'ARRAY');
2943   $self->{all_cache} = $data;
2944 }
2945
2946 =head2 clear_cache
2947
2948 =over 4
2949
2950 =item Arguments: none
2951
2952 =item Return Value: undef
2953
2954 =back
2955
2956 Clears the cache for the resultset.
2957
2958 =cut
2959
2960 sub clear_cache {
2961   shift->set_cache(undef);
2962 }
2963
2964 =head2 is_paged
2965
2966 =over 4
2967
2968 =item Arguments: none
2969
2970 =item Return Value: true, if the resultset has been paginated
2971
2972 =back
2973
2974 =cut
2975
2976 sub is_paged {
2977   my ($self) = @_;
2978   return !!$self->{attrs}{page};
2979 }
2980
2981 =head2 is_ordered
2982
2983 =over 4
2984
2985 =item Arguments: none
2986
2987 =item Return Value: true, if the resultset has been ordered with C<order_by>.
2988
2989 =back
2990
2991 =cut
2992
2993 sub is_ordered {
2994   my ($self) = @_;
2995   return scalar $self->result_source->storage->_extract_order_criteria($self->{attrs}{order_by});
2996 }
2997
2998 =head2 related_resultset
2999
3000 =over 4
3001
3002 =item Arguments: $rel_name
3003
3004 =item Return Value: L<$resultset|/search>
3005
3006 =back
3007
3008 Returns a related resultset for the supplied relationship name.
3009
3010   $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
3011
3012 =cut
3013
3014 sub related_resultset {
3015   my ($self, $rel) = @_;
3016
3017   $self->{related_resultsets} ||= {};
3018   return $self->{related_resultsets}{$rel} ||= do {
3019     my $rsrc = $self->result_source;
3020     my $rel_info = $rsrc->relationship_info($rel);
3021
3022     $self->throw_exception(
3023       "search_related: result source '" . $rsrc->source_name .
3024         "' has no such relationship $rel")
3025       unless $rel_info;
3026
3027     my $attrs = $self->_chain_relationship($rel);
3028
3029     my $join_count = $attrs->{seen_join}{$rel};
3030
3031     my $alias = $self->result_source->storage
3032         ->relname_to_table_alias($rel, $join_count);
3033
3034     # since this is search_related, and we already slid the select window inwards
3035     # (the select/as attrs were deleted in the beginning), we need to flip all
3036     # left joins to inner, so we get the expected results
3037     # read the comment on top of the actual function to see what this does
3038     $attrs->{from} = $rsrc->schema->storage->_inner_join_to_node ($attrs->{from}, $alias);
3039
3040
3041     #XXX - temp fix for result_class bug. There likely is a more elegant fix -groditi
3042     delete @{$attrs}{qw(result_class alias)};
3043
3044     my $new_cache;
3045
3046     if (my $cache = $self->get_cache) {
3047       if ($cache->[0] && $cache->[0]->related_resultset($rel)->get_cache) {
3048         $new_cache = [ map { @{$_->related_resultset($rel)->get_cache} }
3049                         @$cache ];
3050       }
3051     }
3052
3053     my $rel_source = $rsrc->related_source($rel);
3054
3055     my $new = do {
3056
3057       # The reason we do this now instead of passing the alias to the
3058       # search_rs below is that if you wrap/overload resultset on the
3059       # source you need to know what alias it's -going- to have for things
3060       # to work sanely (e.g. RestrictWithObject wants to be able to add
3061       # extra query restrictions, and these may need to be $alias.)
3062
3063       my $rel_attrs = $rel_source->resultset_attributes;
3064       local $rel_attrs->{alias} = $alias;
3065
3066       $rel_source->resultset
3067                  ->search_rs(
3068                      undef, {
3069                        %$attrs,
3070                        where => $attrs->{where},
3071                    });
3072     };
3073     $new->set_cache($new_cache) if $new_cache;
3074     $new;
3075   };
3076 }
3077
3078 =head2 current_source_alias
3079
3080 =over 4
3081
3082 =item Arguments: none
3083
3084 =item Return Value: $source_alias
3085
3086 =back
3087
3088 Returns the current table alias for the result source this resultset is built
3089 on, that will be used in the SQL query. Usually it is C<me>.
3090
3091 Currently the source alias that refers to the result set returned by a
3092 L</search>/L</find> family method depends on how you got to the resultset: it's
3093 C<me> by default, but eg. L</search_related> aliases it to the related result
3094 source name (and keeps C<me> referring to the original result set). The long
3095 term goal is to make L<DBIx::Class> always alias the current resultset as C<me>
3096 (and make this method unnecessary).
3097
3098 Thus it's currently necessary to use this method in predefined queries (see
3099 L<DBIx::Class::Manual::Cookbook/Predefined searches>) when referring to the
3100 source alias of the current result set:
3101
3102   # in a result set class
3103   sub modified_by {
3104     my ($self, $user) = @_;
3105
3106     my $me = $self->current_source_alias;
3107
3108     return $self->search({
3109       "$me.modified" => $user->id,
3110     });
3111   }
3112
3113 =cut
3114
3115 sub current_source_alias {
3116   my ($self) = @_;
3117
3118   return ($self->{attrs} || {})->{alias} || 'me';
3119 }
3120
3121 =head2 as_subselect_rs
3122
3123 =over 4
3124
3125 =item Arguments: none
3126
3127 =item Return Value: L<$resultset|/search>
3128
3129 =back
3130
3131 Act as a barrier to SQL symbols.  The resultset provided will be made into a
3132 "virtual view" by including it as a subquery within the from clause.  From this
3133 point on, any joined tables are inaccessible to ->search on the resultset (as if
3134 it were simply where-filtered without joins).  For example:
3135
3136  my $rs = $schema->resultset('Bar')->search({'x.name' => 'abc'},{ join => 'x' });
3137
3138  # 'x' now pollutes the query namespace
3139
3140  # So the following works as expected
3141  my $ok_rs = $rs->search({'x.other' => 1});
3142
3143  # But this doesn't: instead of finding a 'Bar' related to two x rows (abc and
3144  # def) we look for one row with contradictory terms and join in another table
3145  # (aliased 'x_2') which we never use
3146  my $broken_rs = $rs->search({'x.name' => 'def'});
3147
3148  my $rs2 = $rs->as_subselect_rs;
3149
3150  # doesn't work - 'x' is no longer accessible in $rs2, having been sealed away
3151  my $not_joined_rs = $rs2->search({'x.other' => 1});
3152
3153  # works as expected: finds a 'table' row related to two x rows (abc and def)
3154  my $correctly_joined_rs = $rs2->search({'x.name' => 'def'});
3155
3156 Another example of when one might use this would be to select a subset of
3157 columns in a group by clause:
3158
3159  my $rs = $schema->resultset('Bar')->search(undef, {
3160    group_by => [qw{ id foo_id baz_id }],
3161  })->as_subselect_rs->search(undef, {
3162    columns => [qw{ id foo_id }]
3163  });
3164
3165 In the above example normally columns would have to be equal to the group by,
3166 but because we isolated the group by into a subselect the above works.
3167
3168 =cut
3169
3170 sub as_subselect_rs {
3171   my $self = shift;
3172
3173   my $attrs = $self->_resolved_attrs;
3174
3175   my $fresh_rs = (ref $self)->new (
3176     $self->result_source
3177   );
3178
3179   # these pieces will be locked in the subquery
3180   delete $fresh_rs->{cond};
3181   delete @{$fresh_rs->{attrs}}{qw/where bind/};
3182
3183   return $fresh_rs->search( {}, {
3184     from => [{
3185       $attrs->{alias} => $self->as_query,
3186       -alias  => $attrs->{alias},
3187       -rsrc   => $self->result_source,
3188     }],
3189     alias => $attrs->{alias},
3190   });
3191 }
3192
3193 # This code is called by search_related, and makes sure there
3194 # is clear separation between the joins before, during, and
3195 # after the relationship. This information is needed later
3196 # in order to properly resolve prefetch aliases (any alias
3197 # with a relation_chain_depth less than the depth of the
3198 # current prefetch is not considered)
3199 #
3200 # The increments happen twice per join. An even number means a
3201 # relationship specified via a search_related, whereas an odd
3202 # number indicates a join/prefetch added via attributes
3203 #
3204 # Also this code will wrap the current resultset (the one we
3205 # chain to) in a subselect IFF it contains limiting attributes
3206 sub _chain_relationship {
3207   my ($self, $rel) = @_;
3208   my $source = $self->result_source;
3209   my $attrs = { %{$self->{attrs}||{}} };
3210
3211   # we need to take the prefetch the attrs into account before we
3212   # ->_resolve_join as otherwise they get lost - captainL
3213   my $join = $self->_merge_joinpref_attr( $attrs->{join}, $attrs->{prefetch} );
3214
3215   delete @{$attrs}{qw/join prefetch collapse group_by distinct select as columns +select +as +columns/};
3216
3217   my $seen = { %{ (delete $attrs->{seen_join}) || {} } };
3218
3219   my $from;
3220   my @force_subq_attrs = qw/offset rows group_by having/;
3221
3222   if (
3223     ($attrs->{from} && ref $attrs->{from} ne 'ARRAY')
3224       ||
3225     $self->_has_resolved_attr (@force_subq_attrs)
3226   ) {
3227     # Nuke the prefetch (if any) before the new $rs attrs
3228     # are resolved (prefetch is useless - we are wrapping
3229     # a subquery anyway).
3230     my $rs_copy = $self->search;
3231     $rs_copy->{attrs}{join} = $self->_merge_joinpref_attr (
3232       $rs_copy->{attrs}{join},
3233       delete $rs_copy->{attrs}{prefetch},
3234     );
3235
3236     $from = [{
3237       -rsrc   => $source,
3238       -alias  => $attrs->{alias},
3239       $attrs->{alias} => $rs_copy->as_query,
3240     }];
3241     delete @{$attrs}{@force_subq_attrs, qw/where bind/};
3242     $seen->{-relation_chain_depth} = 0;
3243   }
3244   elsif ($attrs->{from}) {  #shallow copy suffices
3245     $from = [ @{$attrs->{from}} ];
3246   }
3247   else {
3248     $from = [{
3249       -rsrc  => $source,
3250       -alias => $attrs->{alias},
3251       $attrs->{alias} => $source->from,
3252     }];
3253   }
3254
3255   my $jpath = ($seen->{-relation_chain_depth})
3256     ? $from->[-1][0]{-join_path}
3257     : [];
3258
3259   my @requested_joins = $source->_resolve_join(
3260     $join,
3261     $attrs->{alias},
3262     $seen,
3263     $jpath,
3264   );
3265
3266   push @$from, @requested_joins;
3267
3268   $seen->{-relation_chain_depth}++;
3269
3270   # if $self already had a join/prefetch specified on it, the requested
3271   # $rel might very well be already included. What we do in this case
3272   # is effectively a no-op (except that we bump up the chain_depth on
3273   # the join in question so we could tell it *is* the search_related)
3274   my $already_joined;
3275
3276   # we consider the last one thus reverse
3277   for my $j (reverse @requested_joins) {
3278     my ($last_j) = keys %{$j->[0]{-join_path}[-1]};
3279     if ($rel eq $last_j) {
3280       $j->[0]{-relation_chain_depth}++;
3281       $already_joined++;
3282       last;
3283     }
3284   }
3285
3286   unless ($already_joined) {
3287     push @$from, $source->_resolve_join(
3288       $rel,
3289       $attrs->{alias},
3290       $seen,
3291       $jpath,
3292     );
3293   }
3294
3295   $seen->{-relation_chain_depth}++;
3296
3297   return {%$attrs, from => $from, seen_join => $seen};
3298 }
3299
3300 # too many times we have to do $attrs = { %{$self->_resolved_attrs} }
3301 sub _resolved_attrs_copy {
3302   my $self = shift;
3303   return { %{$self->_resolved_attrs (@_)} };
3304 }
3305
3306 sub _resolved_attrs {
3307   my $self = shift;
3308   return $self->{_attrs} if $self->{_attrs};
3309
3310   my $attrs  = { %{ $self->{attrs} || {} } };
3311   my $source = $self->result_source;
3312   my $alias  = $attrs->{alias};
3313
3314   # default selection list
3315   $attrs->{columns} = [ $source->columns ]
3316     unless List::Util::first { exists $attrs->{$_} } qw/columns cols select as/;
3317
3318   # merge selectors together
3319   for (qw/columns select as/) {
3320     $attrs->{$_} = $self->_merge_attr($attrs->{$_}, delete $attrs->{"+$_"})
3321       if $attrs->{$_} or $attrs->{"+$_"};
3322   }
3323
3324   # disassemble columns
3325   my (@sel, @as);
3326   if (my $cols = delete $attrs->{columns}) {
3327     for my $c (ref $cols eq 'ARRAY' ? @$cols : $cols) {
3328       if (ref $c eq 'HASH') {
3329         for my $as (sort keys %$c) {
3330           push @sel, $c->{$as};
3331           push @as, $as;
3332         }
3333       }
3334       else {
3335         push @sel, $c;
3336         push @as, $c;
3337       }
3338     }
3339   }
3340
3341   # when trying to weed off duplicates later do not go past this point -
3342   # everything added from here on is unbalanced "anyone's guess" stuff
3343   my $dedup_stop_idx = $#as;
3344
3345   push @as, @{ ref $attrs->{as} eq 'ARRAY' ? $attrs->{as} : [ $attrs->{as} ] }
3346     if $attrs->{as};
3347   push @sel, @{ ref $attrs->{select} eq 'ARRAY' ? $attrs->{select} : [ $attrs->{select} ] }
3348     if $attrs->{select};
3349
3350   # assume all unqualified selectors to apply to the current alias (legacy stuff)
3351   for (@sel) {
3352     $_ = (ref $_ or $_ =~ /\./) ? $_ : "$alias.$_";
3353   }
3354
3355   # disqualify all $alias.col as-bits (collapser mandated)
3356   for (@as) {
3357     $_ = ($_ =~ /^\Q$alias.\E(.+)$/) ? $1 : $_;
3358   }
3359
3360   # de-duplicate the result (remove *identical* select/as pairs)
3361   # and also die on duplicate {as} pointing to different {select}s
3362   # not using a c-style for as the condition is prone to shrinkage
3363   my $seen;
3364   my $i = 0;
3365   while ($i <= $dedup_stop_idx) {
3366     if ($seen->{"$sel[$i] \x00\x00 $as[$i]"}++) {
3367       splice @sel, $i, 1;
3368       splice @as, $i, 1;
3369       $dedup_stop_idx--;
3370     }
3371     elsif ($seen->{$as[$i]}++) {
3372       $self->throw_exception(
3373         "inflate_result() alias '$as[$i]' specified twice with different SQL-side {select}-ors"
3374       );
3375     }
3376     else {
3377       $i++;
3378     }
3379   }
3380
3381   $attrs->{select} = \@sel;
3382   $attrs->{as} = \@as;
3383
3384   $attrs->{from} ||= [{
3385     -rsrc   => $source,
3386     -alias  => $self->{attrs}{alias},
3387     $self->{attrs}{alias} => $source->from,
3388   }];
3389
3390   if ( $attrs->{join} || $attrs->{prefetch} ) {
3391
3392     $self->throw_exception ('join/prefetch can not be used with a custom {from}')
3393       if ref $attrs->{from} ne 'ARRAY';
3394
3395     my $join = (delete $attrs->{join}) || {};
3396
3397     if ( defined $attrs->{prefetch} ) {
3398       $join = $self->_merge_joinpref_attr( $join, $attrs->{prefetch} );
3399     }
3400
3401     $attrs->{from} =    # have to copy here to avoid corrupting the original
3402       [
3403         @{ $attrs->{from} },
3404         $source->_resolve_join(
3405           $join,
3406           $alias,
3407           { %{ $attrs->{seen_join} || {} } },
3408           ( $attrs->{seen_join} && keys %{$attrs->{seen_join}})
3409             ? $attrs->{from}[-1][0]{-join_path}
3410             : []
3411           ,
3412         )
3413       ];
3414   }
3415
3416   if ( defined $attrs->{order_by} ) {
3417     $attrs->{order_by} = (
3418       ref( $attrs->{order_by} ) eq 'ARRAY'
3419       ? [ @{ $attrs->{order_by} } ]
3420       : [ $attrs->{order_by} || () ]
3421     );
3422   }
3423
3424   if ($attrs->{group_by} and ref $attrs->{group_by} ne 'ARRAY') {
3425     $attrs->{group_by} = [ $attrs->{group_by} ];
3426   }
3427
3428   # generate the distinct induced group_by early, as prefetch will be carried via a
3429   # subquery (since a group_by is present)
3430   if (delete $attrs->{distinct}) {
3431     if ($attrs->{group_by}) {
3432       carp_unique ("Useless use of distinct on a grouped resultset ('distinct' is ignored when a 'group_by' is present)");
3433     }
3434     else {
3435       # distinct affects only the main selection part, not what prefetch may
3436       # add below.
3437       $attrs->{group_by} = $source->storage->_group_over_selection (
3438         $attrs->{from},
3439         $attrs->{select},
3440         $attrs->{order_by},
3441       );
3442     }
3443   }
3444
3445   $attrs->{collapse} ||= {};
3446   if ($attrs->{prefetch}) {
3447
3448     $self->throw_exception("Unable to prefetch, resultset contains an unnamed selector $attrs->{_dark_selector}{string}")
3449       if $attrs->{_dark_selector};
3450
3451     my $prefetch = $self->_merge_joinpref_attr( {}, delete $attrs->{prefetch} );
3452
3453     my $prefetch_ordering = [];
3454
3455     # this is a separate structure (we don't look in {from} directly)
3456     # as the resolver needs to shift things off the lists to work
3457     # properly (identical-prefetches on different branches)
3458     my $join_map = {};
3459     if (ref $attrs->{from} eq 'ARRAY') {
3460
3461       my $start_depth = $attrs->{seen_join}{-relation_chain_depth} || 0;
3462
3463       for my $j ( @{$attrs->{from}}[1 .. $#{$attrs->{from}} ] ) {
3464         next unless $j->[0]{-alias};
3465         next unless $j->[0]{-join_path};
3466         next if ($j->[0]{-relation_chain_depth} || 0) < $start_depth;
3467
3468         my @jpath = map { keys %$_ } @{$j->[0]{-join_path}};
3469
3470         my $p = $join_map;
3471         $p = $p->{$_} ||= {} for @jpath[ ($start_depth/2) .. $#jpath]; #only even depths are actual jpath boundaries
3472         push @{$p->{-join_aliases} }, $j->[0]{-alias};
3473       }
3474     }
3475
3476     my @prefetch =
3477       $source->_resolve_prefetch( $prefetch, $alias, $join_map, $prefetch_ordering, $attrs->{collapse} );
3478
3479     # we need to somehow mark which columns came from prefetch
3480     if (@prefetch) {
3481       my $sel_end = $#{$attrs->{select}};
3482       $attrs->{_prefetch_selector_range} = [ $sel_end + 1, $sel_end + @prefetch ];
3483     }
3484
3485     push @{ $attrs->{select} }, (map { $_->[0] } @prefetch);
3486     push @{ $attrs->{as} }, (map { $_->[1] } @prefetch);
3487
3488     push( @{$attrs->{order_by}}, @$prefetch_ordering );
3489     $attrs->{_collapse_order_by} = \@$prefetch_ordering;
3490   }
3491
3492   # if both page and offset are specified, produce a combined offset
3493   # even though it doesn't make much sense, this is what pre 081xx has
3494   # been doing
3495   if (my $page = delete $attrs->{page}) {
3496     $attrs->{offset} =
3497       ($attrs->{rows} * ($page - 1))
3498             +
3499       ($attrs->{offset} || 0)
3500     ;
3501   }
3502
3503   return $self->{_attrs} = $attrs;
3504 }
3505
3506 sub _rollout_attr {
3507   my ($self, $attr) = @_;
3508
3509   if (ref $attr eq 'HASH') {
3510     return $self->_rollout_hash($attr);
3511   } elsif (ref $attr eq 'ARRAY') {
3512     return $self->_rollout_array($attr);
3513   } else {
3514     return [$attr];
3515   }
3516 }
3517
3518 sub _rollout_array {
3519   my ($self, $attr) = @_;
3520
3521   my @rolled_array;
3522   foreach my $element (@{$attr}) {
3523     if (ref $element eq 'HASH') {
3524       push( @rolled_array, @{ $self->_rollout_hash( $element ) } );
3525     } elsif (ref $element eq 'ARRAY') {
3526       #  XXX - should probably recurse here
3527       push( @rolled_array, @{$self->_rollout_array($element)} );
3528     } else {
3529       push( @rolled_array, $element );
3530     }
3531   }
3532   return \@rolled_array;
3533 }
3534
3535 sub _rollout_hash {
3536   my ($self, $attr) = @_;
3537
3538   my @rolled_array;
3539   foreach my $key (keys %{$attr}) {
3540     push( @rolled_array, { $key => $attr->{$key} } );
3541   }
3542   return \@rolled_array;
3543 }
3544
3545 sub _calculate_score {
3546   my ($self, $a, $b) = @_;
3547
3548   if (defined $a xor defined $b) {
3549     return 0;
3550   }
3551   elsif (not defined $a) {
3552     return 1;
3553   }
3554
3555   if (ref $b eq 'HASH') {
3556     my ($b_key) = keys %{$b};
3557     if (ref $a eq 'HASH') {
3558       my ($a_key) = keys %{$a};
3559       if ($a_key eq $b_key) {
3560         return (1 + $self->_calculate_score( $a->{$a_key}, $b->{$b_key} ));
3561       } else {
3562         return 0;
3563       }
3564     } else {
3565       return ($a eq $b_key) ? 1 : 0;
3566     }
3567   } else {
3568     if (ref $a eq 'HASH') {
3569       my ($a_key) = keys %{$a};
3570       return ($b eq $a_key) ? 1 : 0;
3571     } else {
3572       return ($b eq $a) ? 1 : 0;
3573     }
3574   }
3575 }
3576
3577 sub _merge_joinpref_attr {
3578   my ($self, $orig, $import) = @_;
3579
3580   return $import unless defined($orig);
3581   return $orig unless defined($import);
3582
3583   $orig = $self->_rollout_attr($orig);
3584   $import = $self->_rollout_attr($import);
3585
3586   my $seen_keys;
3587   foreach my $import_element ( @{$import} ) {
3588     # find best candidate from $orig to merge $b_element into
3589     my $best_candidate = { position => undef, score => 0 }; my $position = 0;
3590     foreach my $orig_element ( @{$orig} ) {
3591       my $score = $self->_calculate_score( $orig_element, $import_element );
3592       if ($score > $best_candidate->{score}) {
3593         $best_candidate->{position} = $position;
3594         $best_candidate->{score} = $score;
3595       }
3596       $position++;
3597     }
3598     my ($import_key) = ( ref $import_element eq 'HASH' ) ? keys %{$import_element} : ($import_element);
3599     $import_key = '' if not defined $import_key;
3600
3601     if ($best_candidate->{score} == 0 || exists $seen_keys->{$import_key}) {
3602       push( @{$orig}, $import_element );
3603     } else {
3604       my $orig_best = $orig->[$best_candidate->{position}];
3605       # merge orig_best and b_element together and replace original with merged
3606       if (ref $orig_best ne 'HASH') {
3607         $orig->[$best_candidate->{position}] = $import_element;
3608       } elsif (ref $import_element eq 'HASH') {
3609         my ($key) = keys %{$orig_best};
3610         $orig->[$best_candidate->{position}] = { $key => $self->_merge_joinpref_attr($orig_best->{$key}, $import_element->{$key}) };
3611       }
3612     }
3613     $seen_keys->{$import_key} = 1; # don't merge the same key twice
3614   }
3615
3616   return $orig;
3617 }
3618
3619 {
3620   my $hm;
3621
3622   sub _merge_attr {
3623     $hm ||= do {
3624       require Hash::Merge;
3625       my $hm = Hash::Merge->new;
3626
3627       $hm->specify_behavior({
3628         SCALAR => {
3629           SCALAR => sub {
3630             my ($defl, $defr) = map { defined $_ } (@_[0,1]);
3631
3632             if ($defl xor $defr) {
3633               return [ $defl ? $_[0] : $_[1] ];
3634             }
3635             elsif (! $defl) {
3636               return [];
3637             }
3638             elsif (__HM_DEDUP and $_[0] eq $_[1]) {
3639               return [ $_[0] ];
3640             }
3641             else {
3642               return [$_[0], $_[1]];
3643             }
3644           },
3645           ARRAY => sub {
3646             return $_[1] if !defined $_[0];
3647             return $_[1] if __HM_DEDUP and List::Util::first { $_ eq $_[0] } @{$_[1]};
3648             return [$_[0], @{$_[1]}]
3649           },
3650           HASH  => sub {
3651             return [] if !defined $_[0] and !keys %{$_[1]};
3652             return [ $_[1] ] if !defined $_[0];
3653             return [ $_[0] ] if !keys %{$_[1]};
3654             return [$_[0], $_[1]]
3655           },
3656         },
3657         ARRAY => {
3658           SCALAR => sub {
3659             return $_[0] if !defined $_[1];
3660             return $_[0] if __HM_DEDUP and List::Util::first { $_ eq $_[1] } @{$_[0]};
3661             return [@{$_[0]}, $_[1]]
3662           },
3663           ARRAY => sub {
3664             my @ret = @{$_[0]} or return $_[1];
3665             return [ @ret, @{$_[1]} ] unless __HM_DEDUP;
3666             my %idx = map { $_ => 1 } @ret;
3667             push @ret, grep { ! defined $idx{$_} } (@{$_[1]});
3668             \@ret;
3669           },
3670           HASH => sub {
3671             return [ $_[1] ] if ! @{$_[0]};
3672             return $_[0] if !keys %{$_[1]};
3673             return $_[0] if __HM_DEDUP and List::Util::first { $_ eq $_[1] } @{$_[0]};
3674             return [ @{$_[0]}, $_[1] ];
3675           },
3676         },
3677         HASH => {
3678           SCALAR => sub {
3679             return [] if !keys %{$_[0]} and !defined $_[1];
3680             return [ $_[0] ] if !defined $_[1];
3681             return [ $_[1] ] if !keys %{$_[0]};
3682             return [$_[0], $_[1]]
3683           },
3684           ARRAY => sub {
3685             return [] if !keys %{$_[0]} and !@{$_[1]};
3686             return [ $_[0] ] if !@{$_[1]};
3687             return $_[1] if !keys %{$_[0]};
3688             return $_[1] if __HM_DEDUP and List::Util::first { $_ eq $_[0] } @{$_[1]};
3689             return [ $_[0], @{$_[1]} ];
3690           },
3691           HASH => sub {
3692             return [] if !keys %{$_[0]} and !keys %{$_[1]};
3693             return [ $_[0] ] if !keys %{$_[1]};
3694             return [ $_[1] ] if !keys %{$_[0]};
3695             return [ $_[0] ] if $_[0] eq $_[1];
3696             return [ $_[0], $_[1] ];
3697           },
3698         }
3699       } => 'DBIC_RS_ATTR_MERGER');
3700       $hm;
3701     };
3702
3703     return $hm->merge ($_[1], $_[2]);
3704   }
3705 }
3706
3707 sub STORABLE_freeze {
3708   my ($self, $cloning) = @_;
3709   my $to_serialize = { %$self };
3710
3711   # A cursor in progress can't be serialized (and would make little sense anyway)
3712   delete $to_serialize->{cursor};
3713
3714   # nor is it sensical to store a not-yet-fired-count pager
3715   if ($to_serialize->{pager} and ref $to_serialize->{pager}{total_entries} eq 'CODE') {
3716     delete $to_serialize->{pager};
3717   }
3718
3719   Storable::nfreeze($to_serialize);
3720 }
3721
3722 # need this hook for symmetry
3723 sub STORABLE_thaw {
3724   my ($self, $cloning, $serialized) = @_;
3725
3726   %$self = %{ Storable::thaw($serialized) };
3727
3728   $self;
3729 }
3730
3731
3732 =head2 throw_exception
3733
3734 See L<DBIx::Class::Schema/throw_exception> for details.
3735
3736 =cut
3737
3738 sub throw_exception {
3739   my $self=shift;
3740
3741   if (ref $self and my $rsrc = $self->result_source) {
3742     $rsrc->throw_exception(@_)
3743   }
3744   else {
3745     DBIx::Class::Exception->throw(@_);
3746   }
3747 }
3748
3749 # XXX: FIXME: Attributes docs need clearing up
3750
3751 =head1 ATTRIBUTES
3752
3753 Attributes are used to refine a ResultSet in various ways when
3754 searching for data. They can be passed to any method which takes an
3755 C<\%attrs> argument. See L</search>, L</search_rs>, L</find>,
3756 L</count>.
3757
3758 Default attributes can be set on the result class using
3759 L<DBIx::Class::ResultSource/resultset_attributes>.  (Please read
3760 the CAVEATS on that feature before using it!)
3761
3762 These are in no particular order:
3763
3764 =head2 order_by
3765
3766 =over 4
3767
3768 =item Value: ( $order_by | \@order_by | \%order_by )
3769
3770 =back
3771
3772 Which column(s) to order the results by.
3773
3774 [The full list of suitable values is documented in
3775 L<SQL::Abstract/"ORDER BY CLAUSES">; the following is a summary of
3776 common options.]
3777
3778 If a single column name, or an arrayref of names is supplied, the
3779 argument is passed through directly to SQL. The hashref syntax allows
3780 for connection-agnostic specification of ordering direction:
3781
3782  For descending order:
3783
3784   order_by => { -desc => [qw/col1 col2 col3/] }
3785
3786  For explicit ascending order:
3787
3788   order_by => { -asc => 'col' }
3789
3790 The old scalarref syntax (i.e. order_by => \'year DESC') is still
3791 supported, although you are strongly encouraged to use the hashref
3792 syntax as outlined above.
3793
3794 =head2 columns
3795
3796 =over 4
3797
3798 =item Value: \@columns
3799
3800 =back
3801
3802 Shortcut to request a particular set of columns to be retrieved. Each
3803 column spec may be a string (a table column name), or a hash (in which
3804 case the key is the C<as> value, and the value is used as the C<select>
3805 expression). Adds C<me.> onto the start of any column without a C<.> in
3806 it and sets C<select> from that, then auto-populates C<as> from
3807 C<select> as normal. (You may also use the C<cols> attribute, as in
3808 earlier versions of DBIC.)
3809
3810 Essentially C<columns> does the same as L</select> and L</as>.
3811
3812     columns => [ 'foo', { bar => 'baz' } ]
3813
3814 is the same as
3815
3816     select => [qw/foo baz/],
3817     as => [qw/foo bar/]
3818
3819 =head2 +columns
3820
3821 =over 4
3822
3823 =item Value: \@columns
3824
3825 =back
3826
3827 Indicates additional columns to be selected from storage. Works the same
3828 as L</columns> but adds columns to the selection. (You may also use the
3829 C<include_columns> attribute, as in earlier versions of DBIC). For
3830 example:-
3831
3832   $schema->resultset('CD')->search(undef, {
3833     '+columns' => ['artist.name'],
3834     join => ['artist']
3835   });
3836
3837 would return all CDs and include a 'name' column to the information
3838 passed to object inflation. Note that the 'artist' is the name of the
3839 column (or relationship) accessor, and 'name' is the name of the column
3840 accessor in the related table.
3841
3842 B<NOTE:> You need to explicitly quote '+columns' when defining the attribute.
3843 Not doing so causes Perl to incorrectly interpret +columns as a bareword with a
3844 unary plus operator before it.
3845
3846 =head2 include_columns
3847
3848 =over 4
3849
3850 =item Value: \@columns
3851
3852 =back
3853
3854 Deprecated.  Acts as a synonym for L</+columns> for backward compatibility.
3855
3856 =head2 select
3857
3858 =over 4
3859
3860 =item Value: \@select_columns
3861
3862 =back
3863
3864 Indicates which columns should be selected from the storage. You can use
3865 column names, or in the case of RDBMS back ends, function or stored procedure
3866 names:
3867
3868   $rs = $schema->resultset('Employee')->search(undef, {
3869     select => [
3870       'name',
3871       { count => 'employeeid' },
3872       { max => { length => 'name' }, -as => 'longest_name' }
3873     ]
3874   });
3875
3876   # Equivalent SQL
3877   SELECT name, COUNT( employeeid ), MAX( LENGTH( name ) ) AS longest_name FROM employee
3878
3879 B<NOTE:> You will almost always need a corresponding L</as> attribute when you
3880 use L</select>, to instruct DBIx::Class how to store the result of the column.
3881 Also note that the L</as> attribute has nothing to do with the SQL-side 'AS'
3882 identifier aliasing. You can however alias a function, so you can use it in
3883 e.g. an C<ORDER BY> clause. This is done via the C<-as> B<select function
3884 attribute> supplied as shown in the example above.
3885
3886 B<NOTE:> You need to explicitly quote '+select'/'+as' when defining the attributes.
3887 Not doing so causes Perl to incorrectly interpret them as a bareword with a
3888 unary plus operator before it.
3889
3890 =head2 +select
3891
3892 =over 4
3893
3894 Indicates additional columns to be selected from storage.  Works the same as
3895 L</select> but adds columns to the default selection, instead of specifying
3896 an explicit list.
3897
3898 =back
3899
3900 =head2 +as
3901
3902 =over 4
3903
3904 Indicates additional column names for those added via L</+select>. See L</as>.
3905
3906 =back
3907
3908 =head2 as
3909
3910 =over 4
3911
3912 =item Value: \@inflation_names
3913
3914 =back
3915
3916 Indicates column names for object inflation. That is L</as> indicates the
3917 slot name in which the column value will be stored within the
3918 L<Row|DBIx::Class::Row> object. The value will then be accessible via this
3919 identifier by the C<get_column> method (or via the object accessor B<if one
3920 with the same name already exists>) as shown below. The L</as> attribute has
3921 B<nothing to do> with the SQL-side C<AS>. See L</select> for details.
3922
3923   $rs = $schema->resultset('Employee')->search(undef, {
3924     select => [
3925       'name',
3926       { count => 'employeeid' },
3927       { max => { length => 'name' }, -as => 'longest_name' }
3928     ],
3929     as => [qw/
3930       name
3931       employee_count
3932       max_name_length
3933     /],
3934   });
3935
3936 If the object against which the search is performed already has an accessor
3937 matching a column name specified in C<as>, the value can be retrieved using
3938 the accessor as normal:
3939
3940   my $name = $employee->name();
3941
3942 If on the other hand an accessor does not exist in the object, you need to
3943 use C<get_column> instead:
3944
3945   my $employee_count = $employee->get_column('employee_count');
3946
3947 You can create your own accessors if required - see
3948 L<DBIx::Class::Manual::Cookbook> for details.
3949
3950 =head2 join
3951
3952 =over 4
3953
3954 =item Value: ($rel_name | \@rel_names | \%rel_names)
3955
3956 =back
3957
3958 Contains a list of relationships that should be joined for this query.  For
3959 example:
3960
3961   # Get CDs by Nine Inch Nails
3962   my $rs = $schema->resultset('CD')->search(
3963     { 'artist.name' => 'Nine Inch Nails' },
3964     { join => 'artist' }
3965   );
3966
3967 Can also contain a hash reference to refer to the other relation's relations.
3968 For example:
3969
3970   package MyApp::Schema::Track;
3971   use base qw/DBIx::Class/;
3972   __PACKAGE__->table('track');
3973   __PACKAGE__->add_columns(qw/trackid cd position title/);
3974   __PACKAGE__->set_primary_key('trackid');
3975   __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
3976   1;
3977
3978   # In your application
3979   my $rs = $schema->resultset('Artist')->search(
3980     { 'track.title' => 'Teardrop' },
3981     {
3982       join     => { cd => 'track' },
3983       order_by => 'artist.name',
3984     }
3985   );
3986
3987 You need to use the relationship (not the table) name in  conditions,
3988 because they are aliased as such. The current table is aliased as "me", so
3989 you need to use me.column_name in order to avoid ambiguity. For example:
3990
3991   # Get CDs from 1984 with a 'Foo' track
3992   my $rs = $schema->resultset('CD')->search(
3993     {
3994       'me.year' => 1984,
3995       'tracks.name' => 'Foo'
3996     },
3997     { join => 'tracks' }
3998   );
3999
4000 If the same join is supplied twice, it will be aliased to <rel>_2 (and
4001 similarly for a third time). For e.g.
4002
4003   my $rs = $schema->resultset('Artist')->search({
4004     'cds.title'   => 'Down to Earth',
4005     'cds_2.title' => 'Popular',
4006   }, {
4007     join => [ qw/cds cds/ ],
4008   });
4009
4010 will return a set of all artists that have both a cd with title 'Down
4011 to Earth' and a cd with title 'Popular'.
4012
4013 If you want to fetch related objects from other tables as well, see C<prefetch>
4014 below.
4015
4016  NOTE: An internal join-chain pruner will discard certain joins while
4017  constructing the actual SQL query, as long as the joins in question do not
4018  affect the retrieved result. This for example includes 1:1 left joins
4019  that are not part of the restriction specification (WHERE/HAVING) nor are
4020  a part of the query selection.
4021
4022 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
4023
4024 =head2 prefetch
4025
4026 =over 4
4027
4028 =item Value: ($rel_name | \@rel_names | \%rel_names)
4029
4030 =back
4031
4032 Contains one or more relationships that should be fetched along with
4033 the main query (when they are accessed afterwards the data will
4034 already be available, without extra queries to the database).  This is
4035 useful for when you know you will need the related objects, because it
4036 saves at least one query:
4037
4038   my $rs = $schema->resultset('Tag')->search(
4039     undef,
4040     {
4041       prefetch => {
4042         cd => 'artist'
4043       }
4044     }
4045   );
4046
4047 The initial search results in SQL like the following:
4048
4049   SELECT tag.*, cd.*, artist.* FROM tag
4050   JOIN cd ON tag.cd = cd.cdid
4051   JOIN artist ON cd.artist = artist.artistid
4052
4053 L<DBIx::Class> has no need to go back to the database when we access the
4054 C<cd> or C<artist> relationships, which saves us two SQL statements in this
4055 case.
4056
4057 Simple prefetches will be joined automatically, so there is no need
4058 for a C<join> attribute in the above search.
4059
4060 L</prefetch> can be used with the any of the relationship types and
4061 multiple prefetches can be specified together. Below is a more complex
4062 example that prefetches a CD's artist, its liner notes (if present),
4063 the cover image, the tracks on that cd, and the guests on those
4064 tracks.
4065
4066  # Assuming:
4067  My::Schema::CD->belongs_to( artist      => 'My::Schema::Artist'     );
4068  My::Schema::CD->might_have( liner_note  => 'My::Schema::LinerNotes' );
4069  My::Schema::CD->has_one(    cover_image => 'My::Schema::Artwork'    );
4070  My::Schema::CD->has_many(   tracks      => 'My::Schema::Track'      );
4071
4072  My::Schema::Artist->belongs_to( record_label => 'My::Schema::RecordLabel' );
4073
4074  My::Schema::Track->has_many( guests => 'My::Schema::Guest' );
4075
4076
4077  my $rs = $schema->resultset('CD')->search(
4078    undef,
4079    {
4080      prefetch => [
4081        { artist => 'record_label'},  # belongs_to => belongs_to
4082        'liner_note',                 # might_have
4083        'cover_image',                # has_one
4084        { tracks => 'guests' },       # has_many => has_many
4085      ]
4086    }
4087  );
4088
4089 This will produce SQL like the following:
4090
4091  SELECT cd.*, artist.*, record_label.*, liner_note.*, cover_image.*,
4092         tracks.*, guests.*
4093    FROM cd me
4094    JOIN artist artist
4095      ON artist.artistid = me.artistid
4096    JOIN record_label record_label
4097      ON record_label.labelid = artist.labelid
4098    LEFT JOIN track tracks
4099      ON tracks.cdid = me.cdid
4100    LEFT JOIN guest guests
4101      ON guests.trackid = track.trackid
4102    LEFT JOIN liner_notes liner_note
4103      ON liner_note.cdid = me.cdid
4104    JOIN cd_artwork cover_image
4105      ON cover_image.cdid = me.cdid
4106  ORDER BY tracks.cd
4107
4108 Now the C<artist>, C<record_label>, C<liner_note>, C<cover_image>,
4109 C<tracks>, and C<guests> of the CD will all be available through the
4110 relationship accessors without the need for additional queries to the
4111 database.
4112
4113 However, there is one caveat to be observed: it can be dangerous to
4114 prefetch more than one L<has_many|DBIx::Class::Relationship/has_many>
4115 relationship on a given level. e.g.:
4116
4117  my $rs = $schema->resultset('CD')->search(
4118    undef,
4119    {
4120      prefetch => [
4121        'tracks',                         # has_many
4122        { cd_to_producer => 'producer' }, # has_many => belongs_to (i.e. m2m)
4123      ]
4124    }
4125  );
4126
4127 The collapser currently can't identify duplicate tuples for multiple
4128 L<has_many|DBIx::Class::Relationship/has_many> relationships and as a
4129 result the second L<has_many|DBIx::Class::Relationship/has_many>
4130 relation could contain redundant objects.
4131
4132 =head3 Using L</prefetch> with L</join>
4133
4134 L</prefetch> implies a L</join> with the equivalent argument, and is
4135 properly merged with any existing L</join> specification. So the
4136 following:
4137
4138   my $rs = $schema->resultset('CD')->search(
4139    {'record_label.name' => 'Music Product Ltd.'},
4140    {
4141      join     => {artist => 'record_label'},
4142      prefetch => 'artist',
4143    }
4144  );
4145
4146 ... will work, searching on the record label's name, but only
4147 prefetching the C<artist>.
4148
4149 =head3 Using L</prefetch> with L</select> / L</+select> / L</as> / L</+as>
4150
4151 L</prefetch> implies a L</+select>/L</+as> with the fields of the
4152 prefetched relations.  So given:
4153
4154   my $rs = $schema->resultset('CD')->search(
4155    undef,
4156    {
4157      select   => ['cd.title'],
4158      as       => ['cd_title'],
4159      prefetch => 'artist',
4160    }
4161  );
4162
4163 The L</select> becomes: C<'cd.title', 'artist.*'> and the L</as>
4164 becomes: C<'cd_title', 'artist.*'>.
4165
4166 =head3 CAVEATS
4167
4168 Prefetch does a lot of deep magic. As such, it may not behave exactly
4169 as you might expect.
4170
4171 =over 4
4172
4173 =item *
4174
4175 Prefetch uses the L</cache> to populate the prefetched relationships. This
4176 may or may not be what you want.
4177
4178 =item *
4179
4180 If you specify a condition on a prefetched relationship, ONLY those
4181 rows that match the prefetched condition will be fetched into that relationship.
4182 This means that adding prefetch to a search() B<may alter> what is returned by
4183 traversing a relationship. So, if you have C<< Artist->has_many(CDs) >> and you do
4184
4185   my $artist_rs = $schema->resultset('Artist')->search({
4186       'cds.year' => 2008,
4187   }, {
4188       join => 'cds',
4189   });
4190
4191   my $count = $artist_rs->first->cds->count;
4192
4193   my $artist_rs_prefetch = $artist_rs->search( {}, { prefetch => 'cds' } );
4194
4195   my $prefetch_count = $artist_rs_prefetch->first->cds->count;
4196
4197   cmp_ok( $count, '==', $prefetch_count, "Counts should be the same" );
4198
4199 that cmp_ok() may or may not pass depending on the datasets involved. This
4200 behavior may or may not survive the 0.09 transition.
4201
4202 =back
4203
4204 =head2 alias
4205
4206 =over 4
4207
4208 =item Value: $source_alias
4209
4210 =back
4211
4212 Sets the source alias for the query.  Normally, this defaults to C<me>, but
4213 nested search queries (sub-SELECTs) might need specific aliases set to
4214 reference inner queries.  For example:
4215
4216    my $q = $rs
4217       ->related_resultset('CDs')
4218       ->related_resultset('Tracks')
4219       ->search({
4220          'track.id' => { -ident => 'none_search.id' },
4221       })
4222       ->as_query;
4223
4224    my $ids = $self->search({
4225       -not_exists => $q,
4226    }, {
4227       alias    => 'none_search',
4228       group_by => 'none_search.id',
4229    })->get_column('id')->as_query;
4230
4231    $self->search({ id => { -in => $ids } })
4232
4233 This attribute is directly tied to L</current_source_alias>.
4234
4235 =head2 page
4236
4237 =over 4
4238
4239 =item Value: $page
4240
4241 =back
4242
4243 Makes the resultset paged and specifies the page to retrieve. Effectively
4244 identical to creating a non-pages resultset and then calling ->page($page)
4245 on it.
4246
4247 If L</rows> attribute is not specified it defaults to 10 rows per page.
4248
4249 When you have a paged resultset, L</count> will only return the number
4250 of rows in the page. To get the total, use the L</pager> and call
4251 C<total_entries> on it.
4252
4253 =head2 rows
4254
4255 =over 4
4256
4257 =item Value: $rows
4258
4259 =back
4260
4261 Specifies the maximum number of rows for direct retrieval or the number of
4262 rows per page if the page attribute or method is used.
4263
4264 =head2 offset
4265
4266 =over 4
4267
4268 =item Value: $offset
4269
4270 =back
4271
4272 Specifies the (zero-based) row number for the  first row to be returned, or the
4273 of the first row of the first page if paging is used.
4274
4275 =head2 software_limit
4276
4277 =over 4
4278
4279 =item Value: (0 | 1)
4280
4281 =back
4282
4283 When combined with L</rows> and/or L</offset> the generated SQL will not
4284 include any limit dialect stanzas. Instead the entire result will be selected
4285 as if no limits were specified, and DBIC will perform the limit locally, by
4286 artificially advancing and finishing the resulting L</cursor>.
4287
4288 This is the recommended way of performing resultset limiting when no sane RDBMS
4289 implementation is available (e.g.
4290 L<Sybase ASE|DBIx::Class::Storage::DBI::Sybase::ASE> using the
4291 L<Generic Sub Query|DBIx::Class::SQLMaker::LimitDialects/GenericSubQ> hack)
4292
4293 =head2 group_by
4294
4295 =over 4
4296
4297 =item Value: \@columns
4298
4299 =back
4300
4301 A arrayref of columns to group by. Can include columns of joined tables.
4302
4303   group_by => [qw/ column1 column2 ... /]
4304
4305 =head2 having
4306
4307 =over 4
4308
4309 =item Value: $condition
4310
4311 =back
4312
4313 HAVING is a select statement attribute that is applied between GROUP BY and
4314 ORDER BY. It is applied to the after the grouping calculations have been
4315 done.
4316
4317   having => { 'count_employee' => { '>=', 100 } }
4318
4319 or with an in-place function in which case literal SQL is required:
4320
4321   having => \[ 'count(employee) >= ?', [ count => 100 ] ]
4322
4323 =head2 distinct
4324
4325 =over 4
4326
4327 =item Value: (0 | 1)
4328
4329 =back
4330
4331 Set to 1 to group by all columns. If the resultset already has a group_by
4332 attribute, this setting is ignored and an appropriate warning is issued.
4333
4334 =head2 where
4335
4336 =over 4
4337
4338 Adds to the WHERE clause.
4339
4340   # only return rows WHERE deleted IS NULL for all searches
4341   __PACKAGE__->resultset_attributes({ where => { deleted => undef } });
4342
4343 Can be overridden by passing C<< { where => undef } >> as an attribute
4344 to a resultset.
4345
4346 For more complicated where clauses see L<SQL::Abstract/WHERE CLAUSES>.
4347
4348 =back
4349
4350 =head2 cache
4351
4352 Set to 1 to cache search results. This prevents extra SQL queries if you
4353 revisit rows in your ResultSet:
4354
4355   my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
4356
4357   while( my $artist = $resultset->next ) {
4358     ... do stuff ...
4359   }
4360
4361   $rs->first; # without cache, this would issue a query
4362
4363 By default, searches are not cached.
4364
4365 For more examples of using these attributes, see
4366 L<DBIx::Class::Manual::Cookbook>.
4367
4368 =head2 for
4369
4370 =over 4
4371
4372 =item Value: ( 'update' | 'shared' | \$scalar )
4373
4374 =back
4375
4376 Set to 'update' for a SELECT ... FOR UPDATE or 'shared' for a SELECT
4377 ... FOR SHARED. If \$scalar is passed, this is taken directly and embedded in the
4378 query.
4379
4380 =head1 DBIC BIND VALUES
4381
4382 Because DBIC may need more information to bind values than just the column name
4383 and value itself, it uses a special format for both passing and receiving bind
4384 values.  Each bind value should be composed of an arrayref of
4385 C<< [ \%args => $val ] >>.  The format of C<< \%args >> is currently:
4386
4387 =over 4
4388
4389 =item dbd_attrs
4390
4391 If present (in any form), this is what is being passed directly to bind_param.
4392 Note that different DBD's expect different bind args.  (e.g. DBD::SQLite takes
4393 a single numerical type, while DBD::Pg takes a hashref if bind options.)
4394
4395 If this is specified, all other bind options described below are ignored.
4396
4397 =item sqlt_datatype
4398
4399 If present, this is used to infer the actual bind attribute by passing to
4400 C<< $resolved_storage->bind_attribute_by_data_type() >>.  Defaults to the
4401 "data_type" from the L<add_columns column info|DBIx::Class::ResultSource/add_columns>.
4402
4403 Note that the data type is somewhat freeform (hence the sqlt_ prefix);
4404 currently drivers are expected to "Do the Right Thing" when given a common
4405 datatype name.  (Not ideal, but that's what we got at this point.)
4406
4407 =item sqlt_size
4408
4409 Currently used to correctly allocate buffers for bind_param_inout().
4410 Defaults to "size" from the L<add_columns column info|DBIx::Class::ResultSource/add_columns>,
4411 or to a sensible value based on the "data_type".
4412
4413 =item dbic_colname
4414
4415 Used to fill in missing sqlt_datatype and sqlt_size attributes (if they are
4416 explicitly specified they are never overriden).  Also used by some weird DBDs,
4417 where the column name should be available at bind_param time (e.g. Oracle).
4418
4419 =back
4420
4421 For backwards compatibility and convenience, the following shortcuts are
4422 supported:
4423
4424   [ $name => $val ] === [ { dbic_colname => $name }, $val ]
4425   [ \$dt  => $val ] === [ { sqlt_datatype => $dt }, $val ]
4426   [ undef,   $val ] === [ {}, $val ]
4427
4428 =head1 AUTHOR AND CONTRIBUTORS
4429
4430 See L<AUTHOR|DBIx::Class/AUTHOR> and L<CONTRIBUTORS|DBIx::Class/CONTRIBUTORS> in DBIx::Class
4431
4432 =head1 LICENSE
4433
4434 You may distribute this code under the same terms as Perl itself.
4435
4436 =cut
4437
4438 1;