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