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