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