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