Merge 'find_changes' into 'DBIx-Class-current'
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultSet.pm
1 package DBIx::Class::ResultSet;
2
3 use strict;
4 use warnings;
5 use overload
6         '0+'     => \&count,
7         'bool'   => sub { 1; },
8         fallback => 1;
9 use Data::Page;
10 use Storable;
11 use Scalar::Util qw/weaken/;
12
13 use DBIx::Class::ResultSetColumn;
14 use base qw/DBIx::Class/;
15 __PACKAGE__->load_components(qw/AccessorGroup/);
16 __PACKAGE__->mk_group_accessors('simple' => qw/result_source result_class/);
17
18 =head1 NAME
19
20 DBIx::Class::ResultSet - Responsible for fetching and creating resultset.
21
22 =head1 SYNOPSIS
23
24   my $rs   = $schema->resultset('User')->search(registered => 1);
25   my @rows = $schema->resultset('CD')->search(year => 2005);
26
27 =head1 DESCRIPTION
28
29 The resultset is also known as an iterator. It is responsible for handling
30 queries that may return an arbitrary number of rows, e.g. via L</search>
31 or a C<has_many> relationship.
32
33 In the examples below, the following table classes are used:
34
35   package MyApp::Schema::Artist;
36   use base qw/DBIx::Class/;
37   __PACKAGE__->load_components(qw/Core/);
38   __PACKAGE__->table('artist');
39   __PACKAGE__->add_columns(qw/artistid name/);
40   __PACKAGE__->set_primary_key('artistid');
41   __PACKAGE__->has_many(cds => 'MyApp::Schema::CD');
42   1;
43
44   package MyApp::Schema::CD;
45   use base qw/DBIx::Class/;
46   __PACKAGE__->load_components(qw/Core/);
47   __PACKAGE__->table('cd');
48   __PACKAGE__->add_columns(qw/cdid artist title year/);
49   __PACKAGE__->set_primary_key('cdid');
50   __PACKAGE__->belongs_to(artist => 'MyApp::Schema::Artist');
51   1;
52
53 =head1 METHODS
54
55 =head2 new
56
57 =over 4
58
59 =item Arguments: $source, \%$attrs
60
61 =item Return Value: $rs
62
63 =back
64
65 The resultset constructor. Takes a source object (usually a
66 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
67 L</ATTRIBUTES> below).  Does not perform any queries -- these are
68 executed as needed by the other methods.
69
70 Generally you won't need to construct a resultset manually.  You'll
71 automatically get one from e.g. a L</search> called in scalar context:
72
73   my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
74
75 IMPORTANT: If called on an object, proxies to new_result instead so
76
77   my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
78
79 will return a CD object, not a ResultSet.
80
81 =cut
82
83 sub new {
84   my $class = shift;
85   return $class->new_result(@_) if ref $class;
86   
87   my ($source, $attrs) = @_;
88   weaken $source;
89   $attrs = Storable::dclone($attrs || {}); # { %{ $attrs || {} } };
90   #use Data::Dumper; warn Dumper($attrs);
91   my $alias = ($attrs->{alias} ||= 'me');
92   
93   $attrs->{columns} ||= delete $attrs->{cols} if $attrs->{cols};
94   delete $attrs->{as} if $attrs->{columns};
95   $attrs->{columns} ||= [ $source->columns ] unless $attrs->{select};
96   $attrs->{select} = [
97     map { m/\./ ? $_ : "${alias}.$_" } @{delete $attrs->{columns}}
98   ] if $attrs->{columns};
99   $attrs->{as} ||= [
100     map { m/^\Q$alias.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}}
101   ];
102   if (my $include = delete $attrs->{include_columns}) {
103     push(@{$attrs->{select}}, @$include);
104     push(@{$attrs->{as}}, map { m/([^.]+)$/; $1; } @$include);
105   }
106   #use Data::Dumper; warn Dumper(@{$attrs}{qw/select as/});
107
108   $attrs->{from} ||= [ { $alias => $source->from } ];
109   $attrs->{seen_join} ||= {};
110   my %seen;
111   if (my $join = delete $attrs->{join}) {
112     foreach my $j (ref $join eq 'ARRAY' ? @$join : ($join)) {
113       if (ref $j eq 'HASH') {
114         $seen{$_} = 1 foreach keys %$j;
115       } else {
116         $seen{$j} = 1;
117       }
118     }
119     push(@{$attrs->{from}}, $source->resolve_join(
120       $join, $attrs->{alias}, $attrs->{seen_join})
121     );
122   }
123   
124   $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
125   $attrs->{order_by} = [ $attrs->{order_by} ] if
126     $attrs->{order_by} and !ref($attrs->{order_by});
127   $attrs->{order_by} ||= [];
128
129   my $collapse = $attrs->{collapse} || {};
130   if (my $prefetch = delete $attrs->{prefetch}) {
131     my @pre_order;
132     foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
133       if ( ref $p eq 'HASH' ) {
134         foreach my $key (keys %$p) {
135           push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
136             unless $seen{$key};
137         }
138       } else {
139         push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
140             unless $seen{$p};
141       }
142       my @prefetch = $source->resolve_prefetch(
143            $p, $attrs->{alias}, {}, \@pre_order, $collapse);
144       push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
145       push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
146     }
147     push(@{$attrs->{order_by}}, @pre_order);
148   }
149   $attrs->{collapse} = $collapse;
150 #  use Data::Dumper; warn Dumper($collapse) if keys %{$collapse};
151
152   if ($attrs->{page}) {
153     $attrs->{rows} ||= 10;
154     $attrs->{offset} ||= 0;
155     $attrs->{offset} += ($attrs->{rows} * ($attrs->{page} - 1));
156   }
157
158   bless {
159     result_source => $source,
160     result_class => $attrs->{result_class} || $source->result_class,
161     cond => $attrs->{where},
162     from => $attrs->{from},
163     collapse => $collapse,
164     count => undef,
165     page => delete $attrs->{page},
166     pager => undef,
167     attrs => $attrs
168   }, $class;
169 }
170
171 =head2 search
172
173 =over 4
174
175 =item Arguments: $cond, \%attrs?
176
177 =item Return Value: $resultset (scalar context), @row_objs (list context)
178
179 =back
180
181   my @cds    = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
182   my $new_rs = $cd_rs->search({ year => 2005 });
183
184   my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
185                  # year = 2005 OR year = 2004
186
187 If you need to pass in additional attributes but no additional condition,
188 call it as C<search(undef, \%attrs)>.
189
190   # "SELECT name, artistid FROM $artist_table"
191   my @all_artists = $schema->resultset('Artist')->search(undef, {
192     columns => [qw/name artistid/],
193   });
194
195 =cut
196
197 sub search {
198   my $self = shift;
199     
200   my $attrs = { %{$self->{attrs}} };
201   my $having = delete $attrs->{having};
202   $attrs = { %$attrs, %{ pop(@_) } } if @_ > 1 and ref $_[$#_] eq 'HASH';
203
204   my $where = (@_
205                 ? ((@_ == 1 || ref $_[0] eq "HASH")
206                     ? shift
207                     : ((@_ % 2)
208                         ? $self->throw_exception(
209                             "Odd number of arguments to search")
210                         : {@_}))
211                 : undef());
212   if (defined $where) {
213     $attrs->{where} = (defined $attrs->{where}
214               ? { '-and' =>
215                   [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
216                       $where, $attrs->{where} ] }
217               : $where);
218   }
219
220   if (defined $having) {
221     $attrs->{having} = (defined $attrs->{having}
222               ? { '-and' =>
223                   [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
224                       $having, $attrs->{having} ] }
225               : $having);
226   }
227
228   my $rs = (ref $self)->new($self->result_source, $attrs);
229
230   my $rows = $self->get_cache;
231   if( @{$rows} ) {
232     $rs->set_cache($rows);
233   }
234   
235   return (wantarray ? $rs->all : $rs);
236 }
237
238 =head2 search_literal
239
240 =over 4
241
242 =item Arguments: $sql_fragment, @bind_values
243
244 =item Return Value: $resultset (scalar context), @row_objs (list context)
245
246 =back
247
248   my @cds   = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
249   my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
250
251 Pass a literal chunk of SQL to be added to the conditional part of the
252 resultset query.
253
254 =cut
255
256 sub search_literal {
257   my ($self, $cond, @vals) = @_;
258   my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
259   $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
260   return $self->search(\$cond, $attrs);
261 }
262
263 =head2 find
264
265 =over 4
266
267 =item Arguments: @values | \%cols, \%attrs?
268
269 =item Return Value: $row_object
270
271 =back
272
273 Finds a row based on its primary key or unique constraint. For example, to find
274 a row by its primary key:
275
276   my $cd = $schema->resultset('CD')->find(5);
277
278 You can also find a row by a specific unique constraint using the C<key>
279 attribute. For example:
280
281   my $cd = $schema->resultset('CD')->find('Massive Attack', 'Mezzanine', { key => 'artist_title' });
282
283 Additionally, you can specify the columns explicitly by name:
284
285   my $cd = $schema->resultset('CD')->find(
286     {
287       artist => 'Massive Attack',
288       title  => 'Mezzanine',
289     },
290     { key => 'artist_title' }
291   );
292
293 If no C<key> is specified and you explicitly name columns, it searches on all
294 unique constraints defined on the source, including the primary key.
295
296 If the C<key> is specified as C<primary>, it searches only on the primary key.
297
298 See also L</find_or_create> and L</update_or_create>. For information on how to
299 declare unique constraints, see
300 L<DBIx::Class::ResultSource/add_unique_constraint>.
301
302 =cut
303
304 sub find {
305   my $self = shift;
306   my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
307
308   # Parse out a hash from input
309   my @cols = exists $attrs->{key}
310     ? $self->result_source->unique_constraint_columns($attrs->{key})
311     : $self->result_source->primary_columns;
312
313   my $hash;
314   if (ref $_[0] eq 'HASH') {
315     $hash = { %{$_[0]} };
316   }
317   elsif (@_ == @cols) {
318     $hash = {};
319     @{$hash}{@cols} = @_;
320   }
321   else {
322     $self->throw_exception(
323       "Arguments to find must be a hashref or match the number of columns in the "
324         . exists $attrs->{key} ? "$attrs->{key} unique constraint" : "primary key"
325     );
326   }
327
328   # Check the hash we just parsed against our source's unique constraints
329   my @constraint_names = exists $attrs->{key}
330     ? ($attrs->{key})
331     : $self->result_source->unique_constraint_names;
332   $self->throw_exception(
333     "Can't find unless a primary key or unique constraint is defined"
334   ) unless @constraint_names;
335
336   my @unique_queries;
337   foreach my $name (@constraint_names) {
338     my @unique_cols = $self->result_source->unique_constraint_columns($name);
339     my $unique_query = $self->_build_unique_query($hash, \@unique_cols);
340
341     # Add the ResultSet's alias
342     foreach my $key (grep { ! m/\./ } keys %$unique_query) {
343       $unique_query->{"$self->{attrs}{alias}.$key"} = delete $unique_query->{$key};
344     }
345
346     push @unique_queries, $unique_query if %$unique_query;
347   }
348
349   # Handle cases where the ResultSet already defines the query
350   my $query = @unique_queries ? \@unique_queries : undef;
351
352   # Run the query
353   if (keys %$attrs) {
354     my $rs = $self->search($query, $attrs);
355     return keys %{$rs->{collapse}} ? $rs->next : $rs->single;
356   }
357   else {
358     return keys %{$self->{collapse}}
359       ? $self->search($query)->next
360       : $self->single($query);
361   }
362 }
363
364 # _build_unique_query
365 #
366 # Constrain the specified query hash based on the specified column names.
367
368 sub _build_unique_query {
369   my ($self, $query, $unique_cols) = @_;
370
371   my %unique_query =
372     map  { $_ => $query->{$_} }
373     grep { exists $query->{$_} }
374     @$unique_cols;
375
376   return \%unique_query;
377 }
378
379 =head2 search_related
380
381 =over 4
382
383 =item Arguments: $cond, \%attrs?
384
385 =item Return Value: $new_resultset
386
387 =back
388
389   $new_rs = $cd_rs->search_related('artist', {
390     name => 'Emo-R-Us',
391   });
392
393 Searches the specified relationship, optionally specifying a condition and
394 attributes for matching records. See L</ATTRIBUTES> for more information.
395
396 =cut
397
398 sub search_related {
399   return shift->related_resultset(shift)->search(@_);
400 }
401
402 =head2 cursor
403
404 =over 4
405
406 =item Arguments: none
407
408 =item Return Value: $cursor
409
410 =back
411
412 Returns a storage-driven cursor to the given resultset. See
413 L<DBIx::Class::Cursor> for more information.
414
415 =cut
416
417 sub cursor {
418   my ($self) = @_;
419   my $attrs = { %{$self->{attrs}} };
420   return $self->{cursor}
421     ||= $self->result_source->storage->select($self->{from}, $attrs->{select},
422           $attrs->{where},$attrs);
423 }
424
425 =head2 single
426
427 =over 4
428
429 =item Arguments: $cond?
430
431 =item Return Value: $row_object?
432
433 =back
434
435   my $cd = $schema->resultset('CD')->single({ year => 2001 });
436
437 Inflates the first result without creating a cursor if the resultset has
438 any records in it; if not returns nothing. Used by L</find> as an optimisation.
439
440 =cut
441
442 sub single {
443   my ($self, $where) = @_;
444   my $attrs = { %{$self->{attrs}} };
445   if ($where) {
446     if (defined $attrs->{where}) {
447       $attrs->{where} = {
448         '-and' =>
449             [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
450                $where, delete $attrs->{where} ]
451       };
452     } else {
453       $attrs->{where} = $where;
454     }
455   }
456   my @data = $self->result_source->storage->select_single(
457           $self->{from}, $attrs->{select},
458           $attrs->{where},$attrs);
459   return (@data ? $self->_construct_object(@data) : ());
460 }
461
462 =head2 get_column
463
464 =over 4
465
466 =item Arguments: $cond?
467
468 =item Return Value: $resultsetcolumn
469
470 =back
471
472   my $max_length = $rs->get_column('length')->max;
473
474 Returns a ResultSetColumn instance for $column based on $self
475
476 =cut
477
478 sub get_column {
479   my ($self, $column) = @_;
480
481   my $new = DBIx::Class::ResultSetColumn->new($self, $column);
482   return $new;
483 }
484
485 =head2 search_like
486
487 =over 4
488
489 =item Arguments: $cond, \%attrs?
490
491 =item Return Value: $resultset (scalar context), @row_objs (list context)
492
493 =back
494
495   # WHERE title LIKE '%blue%'
496   $cd_rs = $rs->search_like({ title => '%blue%'});
497
498 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
499 that this is simply a convenience method. You most likely want to use
500 L</search> with specific operators.
501
502 For more information, see L<DBIx::Class::Manual::Cookbook>.
503
504 =cut
505
506 sub search_like {
507   my $class = shift;
508   my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
509   my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
510   $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
511   return $class->search($query, { %$attrs });
512 }
513
514 =head2 slice
515
516 =over 4
517
518 =item Arguments: $first, $last
519
520 =item Return Value: $resultset (scalar context), @row_objs (list context)
521
522 =back
523
524 Returns a resultset or object list representing a subset of elements from the
525 resultset slice is called on. Indexes are from 0, i.e., to get the first
526 three records, call:
527
528   my ($one, $two, $three) = $rs->slice(0, 2);
529
530 =cut
531
532 sub slice {
533   my ($self, $min, $max) = @_;
534   my $attrs = {}; # = { %{ $self->{attrs} || {} } };
535   $attrs->{offset} = $self->{attrs}{offset} || 0;
536   $attrs->{offset} += $min;
537   $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
538   return $self->search(undef(), $attrs);
539   #my $slice = (ref $self)->new($self->result_source, $attrs);
540   #return (wantarray ? $slice->all : $slice);
541 }
542
543 =head2 next
544
545 =over 4
546
547 =item Arguments: none
548
549 =item Return Value: $result?
550
551 =back
552
553 Returns the next element in the resultset (C<undef> is there is none).
554
555 Can be used to efficiently iterate over records in the resultset:
556
557   my $rs = $schema->resultset('CD')->search;
558   while (my $cd = $rs->next) {
559     print $cd->title;
560   }
561
562 Note that you need to store the resultset object, and call C<next> on it. 
563 Calling C<< resultset('Table')->next >> repeatedly will always return the
564 first record from the resultset.
565
566 =cut
567
568 sub next {
569   my ($self) = @_;
570   if (@{$self->{all_cache} || []}) {
571     $self->{all_cache_position} ||= 0;
572     return $self->{all_cache}->[$self->{all_cache_position}++];
573   }
574   if ($self->{attrs}{cache}) {
575     $self->{all_cache_position} = 1;
576     return ($self->all)[0];
577   }
578   my @row = (exists $self->{stashed_row} ?
579                @{delete $self->{stashed_row}} :
580                $self->cursor->next
581   );
582 #  warn Dumper(\@row); use Data::Dumper;
583   return unless (@row);
584   return $self->_construct_object(@row);
585 }
586
587 sub _construct_object {
588   my ($self, @row) = @_;
589   my @as = @{ $self->{attrs}{as} };
590   
591   my $info = $self->_collapse_result(\@as, \@row);
592   
593   my $new = $self->result_class->inflate_result($self->result_source, @$info);
594   
595   $new = $self->{attrs}{record_filter}->($new)
596     if exists $self->{attrs}{record_filter};
597   return $new;
598 }
599
600 sub _collapse_result {
601   my ($self, $as, $row, $prefix) = @_;
602
603   my %const;
604
605   my @copy = @$row;
606   foreach my $this_as (@$as) {
607     my $val = shift @copy;
608     if (defined $prefix) {
609       if ($this_as =~ m/^\Q${prefix}.\E(.+)$/) {
610         my $remain = $1;
611         $remain =~ /^(?:(.*)\.)?([^.]+)$/;
612         $const{$1||''}{$2} = $val;
613       }
614     } else {
615       $this_as =~ /^(?:(.*)\.)?([^.]+)$/;
616       $const{$1||''}{$2} = $val;
617     }
618   }
619
620   my $info = [ {}, {} ];
621   foreach my $key (keys %const) {
622     if (length $key) {
623       my $target = $info;
624       my @parts = split(/\./, $key);
625       foreach my $p (@parts) {
626         $target = $target->[1]->{$p} ||= [];
627       }
628       $target->[0] = $const{$key};
629     } else {
630       $info->[0] = $const{$key};
631     }
632   }
633
634   my @collapse;
635   if (defined $prefix) {
636     @collapse = map {
637         m/^\Q${prefix}.\E(.+)$/ ? ($1) : ()
638     } keys %{$self->{collapse}}
639   } else {
640     @collapse = keys %{$self->{collapse}};
641   };
642
643   if (@collapse) {
644     my ($c) = sort { length $a <=> length $b } @collapse;
645     my $target = $info;
646     foreach my $p (split(/\./, $c)) {
647       $target = $target->[1]->{$p} ||= [];
648     }
649     my $c_prefix = (defined($prefix) ? "${prefix}.${c}" : $c);
650     my @co_key = @{$self->{collapse}{$c_prefix}};
651     my %co_check = map { ($_, $target->[0]->{$_}); } @co_key;
652     my $tree = $self->_collapse_result($as, $row, $c_prefix);
653     my (@final, @raw);
654     while ( !(grep {
655                 !defined($tree->[0]->{$_}) ||
656                 $co_check{$_} ne $tree->[0]->{$_}
657               } @co_key) ) {
658       push(@final, $tree);
659       last unless (@raw = $self->cursor->next);
660       $row = $self->{stashed_row} = \@raw;
661       $tree = $self->_collapse_result($as, $row, $c_prefix);
662       #warn Data::Dumper::Dumper($tree, $row);
663     }
664     @$target = @final;
665   }
666
667   return $info;
668 }
669
670 =head2 result_source
671
672 =over 4
673
674 =item Arguments: $result_source?
675
676 =item Return Value: $result_source
677
678 =back
679
680 An accessor for the primary ResultSource object from which this ResultSet
681 is derived.
682
683 =cut
684
685
686 =head2 count
687
688 =over 4
689
690 =item Arguments: $cond, \%attrs??
691
692 =item Return Value: $count
693
694 =back
695
696 Performs an SQL C<COUNT> with the same query as the resultset was built
697 with to find the number of elements. If passed arguments, does a search
698 on the resultset and counts the results of that.
699
700 Note: When using C<count> with C<group_by>, L<DBIX::Class> emulates C<GROUP BY>
701 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
702 not support C<DISTINCT> with multiple columns. If you are using such a
703 database, you should only use columns from the main table in your C<group_by>
704 clause.
705
706 =cut
707
708 sub count {
709   my $self = shift;
710   return $self->search(@_)->count if @_ and defined $_[0];
711   return scalar @{ $self->get_cache } if @{ $self->get_cache };
712
713   my $count = $self->_count;
714   return 0 unless $count;
715
716   $count -= $self->{attrs}{offset} if $self->{attrs}{offset};
717   $count = $self->{attrs}{rows} if
718     $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
719   return $count;
720 }
721
722 sub _count { # Separated out so pager can get the full count
723   my $self = shift;
724   my $select = { count => '*' };
725   my $attrs = { %{ $self->{attrs} } };
726   if (my $group_by = delete $attrs->{group_by}) {
727     delete $attrs->{having};
728     my @distinct = (ref $group_by ?  @$group_by : ($group_by));
729     # todo: try CONCAT for multi-column pk
730     my @pk = $self->result_source->primary_columns;
731     if (@pk == 1) {
732       foreach my $column (@distinct) {
733         if ($column =~ qr/^(?:\Q$attrs->{alias}.\E)?$pk[0]$/) {
734           @distinct = ($column);
735           last;
736         }
737       }
738     }
739
740     $select = { count => { distinct => \@distinct } };
741     #use Data::Dumper; die Dumper $select;
742   }
743
744   $attrs->{select} = $select;
745   $attrs->{as} = [qw/count/];
746
747   # offset, order by and page are not needed to count. record_filter is cdbi
748   delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
749         
750   my ($count) = (ref $self)->new($self->result_source, $attrs)->cursor->next;
751   return $count;
752 }
753
754 =head2 count_literal
755
756 =over 4
757
758 =item Arguments: $sql_fragment, @bind_values
759
760 =item Return Value: $count
761
762 =back
763
764 Counts the results in a literal query. Equivalent to calling L</search_literal>
765 with the passed arguments, then L</count>.
766
767 =cut
768
769 sub count_literal { shift->search_literal(@_)->count; }
770
771 =head2 all
772
773 =over 4
774
775 =item Arguments: none
776
777 =item Return Value: @objects
778
779 =back
780
781 Returns all elements in the resultset. Called implicitly if the resultset
782 is returned in list context.
783
784 =cut
785
786 sub all {
787   my ($self) = @_;
788   return @{ $self->get_cache } if @{ $self->get_cache };
789
790   my @obj;
791
792   if (keys %{$self->{collapse}}) {
793       # Using $self->cursor->all is really just an optimisation.
794       # If we're collapsing has_many prefetches it probably makes
795       # very little difference, and this is cleaner than hacking
796       # _construct_object to survive the approach
797     $self->cursor->reset;
798     my @row = $self->cursor->next;
799     while (@row) {
800       push(@obj, $self->_construct_object(@row));
801       @row = (exists $self->{stashed_row}
802                ? @{delete $self->{stashed_row}}
803                : $self->cursor->next);
804     }
805   } else {
806     @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
807   }
808
809   $self->set_cache(\@obj) if $self->{attrs}{cache};
810   return @obj;
811 }
812
813 =head2 reset
814
815 =over 4
816
817 =item Arguments: none
818
819 =item Return Value: $self
820
821 =back
822
823 Resets the resultset's cursor, so you can iterate through the elements again.
824
825 =cut
826
827 sub reset {
828   my ($self) = @_;
829   $self->{all_cache_position} = 0;
830   $self->cursor->reset;
831   return $self;
832 }
833
834 =head2 first
835
836 =over 4
837
838 =item Arguments: none
839
840 =item Return Value: $object?
841
842 =back
843
844 Resets the resultset and returns an object for the first result (if the
845 resultset returns anything).
846
847 =cut
848
849 sub first {
850   return $_[0]->reset->next;
851 }
852
853 # _cond_for_update_delete
854 #
855 # update/delete require the condition to be modified to handle
856 # the differing SQL syntax available.  This transforms the $self->{cond}
857 # appropriately, returning the new condition.
858
859 sub _cond_for_update_delete {
860   my ($self) = @_;
861   my $cond = {};
862
863   if (!ref($self->{cond})) {
864     # No-op. No condition, we're updating/deleting everything
865   }
866   elsif (ref $self->{cond} eq 'ARRAY') {
867     $cond = [
868       map {
869         my %hash;
870         foreach my $key (keys %{$_}) {
871           $key =~ /([^.]+)$/;
872           $hash{$1} = $_->{$key};
873         }
874         \%hash;
875       } @{$self->{cond}}
876     ];
877   }
878   elsif (ref $self->{cond} eq 'HASH') {
879     if ((keys %{$self->{cond}})[0] eq '-and') {
880       $cond->{-and} = [];
881
882       my @cond = @{$self->{cond}{-and}};
883       for (my $i = 0; $i < @cond - 1; $i++) {
884         my $entry = $cond[$i];
885
886         my %hash;
887         if (ref $entry eq 'HASH') {
888           foreach my $key (keys %{$entry}) {
889             $key =~ /([^.]+)$/;
890             $hash{$1} = $entry->{$key};
891           }
892         }
893         else {
894           $entry =~ /([^.]+)$/;
895           $hash{$entry} = $cond[++$i];
896         }
897
898         push @{$cond->{-and}}, \%hash;
899       }
900     }
901     else {
902       foreach my $key (keys %{$self->{cond}}) {
903         $key =~ /([^.]+)$/;
904         $cond->{$1} = $self->{cond}{$key};
905       }
906     }
907   }
908   else {
909     $self->throw_exception(
910       "Can't update/delete on resultset with condition unless hash or array"
911     );
912   }
913
914   return $cond;
915 }
916
917
918 =head2 update
919
920 =over 4
921
922 =item Arguments: \%values
923
924 =item Return Value: $storage_rv
925
926 =back
927
928 Sets the specified columns in the resultset to the supplied values in a
929 single query. Return value will be true if the update succeeded or false
930 if no records were updated; exact type of success value is storage-dependent.
931
932 =cut
933
934 sub update {
935   my ($self, $values) = @_;
936   $self->throw_exception("Values for update must be a hash")
937     unless ref $values eq 'HASH';
938
939   my $cond = $self->_cond_for_update_delete;
940
941   return $self->result_source->storage->update(
942     $self->result_source->from, $values, $cond
943   );
944 }
945
946 =head2 update_all
947
948 =over 4
949
950 =item Arguments: \%values
951
952 =item Return Value: 1
953
954 =back
955
956 Fetches all objects and updates them one at a time. Note that C<update_all>
957 will run DBIC cascade triggers, while L</update> will not.
958
959 =cut
960
961 sub update_all {
962   my ($self, $values) = @_;
963   $self->throw_exception("Values for update must be a hash")
964     unless ref $values eq 'HASH';
965   foreach my $obj ($self->all) {
966     $obj->set_columns($values)->update;
967   }
968   return 1;
969 }
970
971 =head2 delete
972
973 =over 4
974
975 =item Arguments: none
976
977 =item Return Value: 1
978
979 =back
980
981 Deletes the contents of the resultset from its result source. Note that this
982 will not run DBIC cascade triggers. See L</delete_all> if you need triggers
983 to run.
984
985 =cut
986
987 sub delete {
988   my ($self) = @_;
989   my $del = {};
990
991   my $cond = $self->_cond_for_update_delete;
992
993   $self->result_source->storage->delete($self->result_source->from, $cond);
994   return 1;
995 }
996
997 =head2 delete_all
998
999 =over 4
1000
1001 =item Arguments: none
1002
1003 =item Return Value: 1
1004
1005 =back
1006
1007 Fetches all objects and deletes them one at a time. Note that C<delete_all>
1008 will run DBIC cascade triggers, while L</delete> will not.
1009
1010 =cut
1011
1012 sub delete_all {
1013   my ($self) = @_;
1014   $_->delete for $self->all;
1015   return 1;
1016 }
1017
1018 =head2 pager
1019
1020 =over 4
1021
1022 =item Arguments: none
1023
1024 =item Return Value: $pager
1025
1026 =back
1027
1028 Return Value a L<Data::Page> object for the current resultset. Only makes
1029 sense for queries with a C<page> attribute.
1030
1031 =cut
1032
1033 sub pager {
1034   my ($self) = @_;
1035   my $attrs = $self->{attrs};
1036   $self->throw_exception("Can't create pager for non-paged rs")
1037     unless $self->{page};
1038   $attrs->{rows} ||= 10;
1039   return $self->{pager} ||= Data::Page->new(
1040     $self->_count, $attrs->{rows}, $self->{page});
1041 }
1042
1043 =head2 page
1044
1045 =over 4
1046
1047 =item Arguments: $page_number
1048
1049 =item Return Value: $rs
1050
1051 =back
1052
1053 Returns a resultset for the $page_number page of the resultset on which page
1054 is called, where each page contains a number of rows equal to the 'rows'
1055 attribute set on the resultset (10 by default).
1056
1057 =cut
1058
1059 sub page {
1060   my ($self, $page) = @_;
1061   my $attrs = { %{$self->{attrs}} };
1062   $attrs->{page} = $page;
1063   return (ref $self)->new($self->result_source, $attrs);
1064 }
1065
1066 =head2 new_result
1067
1068 =over 4
1069
1070 =item Arguments: \%vals
1071
1072 =item Return Value: $object
1073
1074 =back
1075
1076 Creates an object in the resultset's result class and returns it.
1077
1078 =cut
1079
1080 sub new_result {
1081   my ($self, $values) = @_;
1082   $self->throw_exception( "new_result needs a hash" )
1083     unless (ref $values eq 'HASH');
1084   $self->throw_exception(
1085     "Can't abstract implicit construct, condition not a hash"
1086   ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
1087   my %new = %$values;
1088   my $alias = $self->{attrs}{alias};
1089   foreach my $key (keys %{$self->{cond}||{}}) {
1090     $new{$1} = $self->{cond}{$key} if ($key =~ m/^(?:\Q${alias}.\E)?([^.]+)$/);
1091   }
1092   my $obj = $self->result_class->new(\%new);
1093   $obj->result_source($self->result_source) if $obj->can('result_source');
1094   return $obj;
1095 }
1096
1097 =head2 find_or_new
1098
1099 =over 4
1100
1101 =item Arguments: \%vals, \%attrs?
1102
1103 =item Return Value: $object
1104
1105 =back
1106
1107 Find an existing record from this resultset. If none exists, instantiate a new
1108 result object and return it. The object will not be saved into your storage
1109 until you call L<DBIx::Class::Row/insert> on it.
1110
1111 If you want objects to be saved immediately, use L</find_or_create> instead.
1112
1113 =cut
1114
1115 sub find_or_new {
1116   my $self     = shift;
1117   my $attrs    = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1118   my $hash     = ref $_[0] eq 'HASH' ? shift : {@_};
1119   my $exists   = $self->find($hash, $attrs);
1120   return defined $exists ? $exists : $self->new_result($hash);
1121 }
1122
1123 =head2 create
1124
1125 =over 4
1126
1127 =item Arguments: \%vals
1128
1129 =item Return Value: $object
1130
1131 =back
1132
1133 Inserts a record into the resultset and returns the object representing it.
1134
1135 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
1136
1137 =cut
1138
1139 sub create {
1140   my ($self, $attrs) = @_;
1141   $self->throw_exception( "create needs a hashref" )
1142     unless ref $attrs eq 'HASH';
1143   return $self->new_result($attrs)->insert;
1144 }
1145
1146 =head2 find_or_create
1147
1148 =over 4
1149
1150 =item Arguments: \%vals, \%attrs?
1151
1152 =item Return Value: $object
1153
1154 =back
1155
1156   $class->find_or_create({ key => $val, ... });
1157
1158 Searches for a record matching the search condition; if it doesn't find one,
1159 creates one and returns that instead.
1160
1161   my $cd = $schema->resultset('CD')->find_or_create({
1162     cdid   => 5,
1163     artist => 'Massive Attack',
1164     title  => 'Mezzanine',
1165     year   => 2005,
1166   });
1167
1168 Also takes an optional C<key> attribute, to search by a specific key or unique
1169 constraint. For example:
1170
1171   my $cd = $schema->resultset('CD')->find_or_create(
1172     {
1173       artist => 'Massive Attack',
1174       title  => 'Mezzanine',
1175     },
1176     { key => 'artist_title' }
1177   );
1178
1179 See also L</find> and L</update_or_create>. For information on how to declare
1180 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1181
1182 =cut
1183
1184 sub find_or_create {
1185   my $self     = shift;
1186   my $attrs    = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1187   my $hash     = ref $_[0] eq 'HASH' ? shift : {@_};
1188   my $exists   = $self->find($hash, $attrs);
1189   return defined $exists ? $exists : $self->create($hash);
1190 }
1191
1192 =head2 update_or_create
1193
1194 =over 4
1195
1196 =item Arguments: \%col_values, { key => $unique_constraint }?
1197
1198 =item Return Value: $object
1199
1200 =back
1201
1202   $class->update_or_create({ col => $val, ... });
1203
1204 First, searches for an existing row matching one of the unique constraints
1205 (including the primary key) on the source of this resultset. If a row is
1206 found, updates it with the other given column values. Otherwise, creates a new
1207 row.
1208
1209 Takes an optional C<key> attribute to search on a specific unique constraint.
1210 For example:
1211
1212   # In your application
1213   my $cd = $schema->resultset('CD')->update_or_create(
1214     {
1215       artist => 'Massive Attack',
1216       title  => 'Mezzanine',
1217       year   => 1998,
1218     },
1219     { key => 'artist_title' }
1220   );
1221
1222 If no C<key> is specified, it searches on all unique constraints defined on the
1223 source, including the primary key.
1224
1225 If the C<key> is specified as C<primary>, it searches only on the primary key.
1226
1227 See also L</find> and L</find_or_create>. For information on how to declare
1228 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1229
1230 =cut
1231
1232 sub update_or_create {
1233   my $self = shift;
1234   my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1235   my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1236
1237   my $row = $self->find($hash, $attrs);
1238   if (defined $row) {
1239     $row->set_columns($hash);
1240     $row->update;
1241     return $row;
1242   }
1243
1244   return $self->create($hash);
1245 }
1246
1247 =head2 get_cache
1248
1249 =over 4
1250
1251 =item Arguments: none
1252
1253 =item Return Value: \@cache_objects?
1254
1255 =back
1256
1257 Gets the contents of the cache for the resultset, if the cache is set.
1258
1259 =cut
1260
1261 sub get_cache {
1262   shift->{all_cache} || [];
1263 }
1264
1265 =head2 set_cache
1266
1267 =over 4
1268
1269 =item Arguments: \@cache_objects
1270
1271 =item Return Value: \@cache_objects
1272
1273 =back
1274
1275 Sets the contents of the cache for the resultset. Expects an arrayref
1276 of objects of the same class as those produced by the resultset. Note that
1277 if the cache is set the resultset will return the cached objects rather
1278 than re-querying the database even if the cache attr is not set.
1279
1280 =cut
1281
1282 sub set_cache {
1283   my ( $self, $data ) = @_;
1284   $self->throw_exception("set_cache requires an arrayref")
1285     if ref $data ne 'ARRAY';
1286   my $result_class = $self->result_class;
1287   foreach( @$data ) {
1288     $self->throw_exception(
1289       "cannot cache object of type '$_', expected '$result_class'"
1290     ) if ref $_ ne $result_class;
1291   }
1292   $self->{all_cache} = $data;
1293 }
1294
1295 =head2 clear_cache
1296
1297 =over 4
1298
1299 =item Arguments: none
1300
1301 =item Return Value: []
1302
1303 =back
1304
1305 Clears the cache for the resultset.
1306
1307 =cut
1308
1309 sub clear_cache {
1310   shift->set_cache([]);
1311 }
1312
1313 =head2 related_resultset
1314
1315 =over 4
1316
1317 =item Arguments: $relationship_name
1318
1319 =item Return Value: $resultset
1320
1321 =back
1322
1323 Returns a related resultset for the supplied relationship name.
1324
1325   $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1326
1327 =cut
1328
1329 sub related_resultset {
1330   my ( $self, $rel ) = @_;
1331   $self->{related_resultsets} ||= {};
1332   return $self->{related_resultsets}{$rel} ||= do {
1333       #warn "fetching related resultset for rel '$rel'";
1334       my $rel_obj = $self->result_source->relationship_info($rel);
1335       $self->throw_exception(
1336         "search_related: result source '" . $self->result_source->name .
1337         "' has no such relationship ${rel}")
1338         unless $rel_obj; #die Dumper $self->{attrs};
1339
1340       my $rs = $self->search(undef, { join => $rel });
1341       my $alias = defined $rs->{attrs}{seen_join}{$rel}
1342                     && $rs->{attrs}{seen_join}{$rel} > 1
1343                   ? join('_', $rel, $rs->{attrs}{seen_join}{$rel})
1344                   : $rel;
1345
1346       $self->result_source->schema->resultset($rel_obj->{class}
1347            )->search( undef,
1348              { %{$rs->{attrs}},
1349                alias => $alias,
1350                select => undef,
1351                as => undef }
1352            );
1353   };
1354 }
1355
1356 =head2 throw_exception
1357
1358 See L<DBIx::Class::Schema/throw_exception> for details.
1359
1360 =cut
1361
1362 sub throw_exception {
1363   my $self=shift;
1364   $self->result_source->schema->throw_exception(@_);
1365 }
1366
1367 # XXX: FIXME: Attributes docs need clearing up
1368
1369 =head1 ATTRIBUTES
1370
1371 The resultset takes various attributes that modify its behavior. Here's an
1372 overview of them:
1373
1374 =head2 order_by
1375
1376 =over 4
1377
1378 =item Value: ($order_by | \@order_by)
1379
1380 =back
1381
1382 Which column(s) to order the results by. This is currently passed
1383 through directly to SQL, so you can give e.g. C<year DESC> for a
1384 descending order on the column `year'.
1385
1386 =head2 columns
1387
1388 =over 4
1389
1390 =item Value: \@columns
1391
1392 =back
1393
1394 Shortcut to request a particular set of columns to be retrieved.  Adds
1395 C<me.> onto the start of any column without a C<.> in it and sets C<select>
1396 from that, then auto-populates C<as> from C<select> as normal. (You may also
1397 use the C<cols> attribute, as in earlier versions of DBIC.)
1398
1399 =head2 include_columns
1400
1401 =over 4
1402
1403 =item Value: \@columns
1404
1405 =back
1406
1407 Shortcut to include additional columns in the returned results - for example
1408
1409   $schema->resultset('CD')->search(undef, {
1410     include_columns => ['artist.name'],
1411     join => ['artist']
1412   });
1413
1414 would return all CDs and include a 'name' column to the information
1415 passed to object inflation
1416
1417 =head2 select
1418
1419 =over 4
1420
1421 =item Value: \@select_columns
1422
1423 =back
1424
1425 Indicates which columns should be selected from the storage. You can use
1426 column names, or in the case of RDBMS back ends, function or stored procedure
1427 names:
1428
1429   $rs = $schema->resultset('Employee')->search(undef, {
1430     select => [
1431       'name',
1432       { count => 'employeeid' },
1433       { sum => 'salary' }
1434     ]
1435   });
1436
1437 When you use function/stored procedure names and do not supply an C<as>
1438 attribute, the column names returned are storage-dependent. E.g. MySQL would
1439 return a column named C<count(employeeid)> in the above example.
1440
1441 =head2 as
1442
1443 =over 4
1444
1445 =item Value: \@inflation_names
1446
1447 =back
1448
1449 Indicates column names for object inflation. This is used in conjunction with
1450 C<select>, usually when C<select> contains one or more function or stored
1451 procedure names:
1452
1453   $rs = $schema->resultset('Employee')->search(undef, {
1454     select => [
1455       'name',
1456       { count => 'employeeid' }
1457     ],
1458     as => ['name', 'employee_count'],
1459   });
1460
1461   my $employee = $rs->first(); # get the first Employee
1462
1463 If the object against which the search is performed already has an accessor
1464 matching a column name specified in C<as>, the value can be retrieved using
1465 the accessor as normal:
1466
1467   my $name = $employee->name();
1468
1469 If on the other hand an accessor does not exist in the object, you need to
1470 use C<get_column> instead:
1471
1472   my $employee_count = $employee->get_column('employee_count');
1473
1474 You can create your own accessors if required - see
1475 L<DBIx::Class::Manual::Cookbook> for details.
1476
1477 =head2 join
1478
1479 =over 4
1480
1481 =item Value: ($rel_name | \@rel_names | \%rel_names)
1482
1483 =back
1484
1485 Contains a list of relationships that should be joined for this query.  For
1486 example:
1487
1488   # Get CDs by Nine Inch Nails
1489   my $rs = $schema->resultset('CD')->search(
1490     { 'artist.name' => 'Nine Inch Nails' },
1491     { join => 'artist' }
1492   );
1493
1494 Can also contain a hash reference to refer to the other relation's relations.
1495 For example:
1496
1497   package MyApp::Schema::Track;
1498   use base qw/DBIx::Class/;
1499   __PACKAGE__->table('track');
1500   __PACKAGE__->add_columns(qw/trackid cd position title/);
1501   __PACKAGE__->set_primary_key('trackid');
1502   __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
1503   1;
1504
1505   # In your application
1506   my $rs = $schema->resultset('Artist')->search(
1507     { 'track.title' => 'Teardrop' },
1508     {
1509       join     => { cd => 'track' },
1510       order_by => 'artist.name',
1511     }
1512   );
1513
1514 If the same join is supplied twice, it will be aliased to <rel>_2 (and
1515 similarly for a third time). For e.g.
1516
1517   my $rs = $schema->resultset('Artist')->search({
1518     'cds.title'   => 'Down to Earth',
1519     'cds_2.title' => 'Popular',
1520   }, {
1521     join => [ qw/cds cds/ ],
1522   });
1523
1524 will return a set of all artists that have both a cd with title 'Down
1525 to Earth' and a cd with title 'Popular'.
1526
1527 If you want to fetch related objects from other tables as well, see C<prefetch>
1528 below.
1529
1530 =head2 prefetch
1531
1532 =over 4
1533
1534 =item Value: ($rel_name | \@rel_names | \%rel_names)
1535
1536 =back
1537
1538 Contains one or more relationships that should be fetched along with the main
1539 query (when they are accessed afterwards they will have already been
1540 "prefetched").  This is useful for when you know you will need the related
1541 objects, because it saves at least one query:
1542
1543   my $rs = $schema->resultset('Tag')->search(
1544     undef,
1545     {
1546       prefetch => {
1547         cd => 'artist'
1548       }
1549     }
1550   );
1551
1552 The initial search results in SQL like the following:
1553
1554   SELECT tag.*, cd.*, artist.* FROM tag
1555   JOIN cd ON tag.cd = cd.cdid
1556   JOIN artist ON cd.artist = artist.artistid
1557
1558 L<DBIx::Class> has no need to go back to the database when we access the
1559 C<cd> or C<artist> relationships, which saves us two SQL statements in this
1560 case.
1561
1562 Simple prefetches will be joined automatically, so there is no need
1563 for a C<join> attribute in the above search. If you're prefetching to
1564 depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
1565 specify the join as well.
1566
1567 C<prefetch> can be used with the following relationship types: C<belongs_to>,
1568 C<has_one> (or if you're using C<add_relationship>, any relationship declared
1569 with an accessor type of 'single' or 'filter').
1570
1571 =head2 from
1572
1573 =over 4
1574
1575 =item Value: \@from_clause
1576
1577 =back
1578
1579 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
1580 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
1581 clauses.
1582
1583 NOTE: Use this on your own risk.  This allows you to shoot off your foot!
1584 C<join> will usually do what you need and it is strongly recommended that you
1585 avoid using C<from> unless you cannot achieve the desired result using C<join>.
1586
1587 In simple terms, C<from> works as follows:
1588
1589     [
1590         { <alias> => <table>, -join_type => 'inner|left|right' }
1591         [] # nested JOIN (optional)
1592         { <table.column> => <foreign_table.foreign_key> }
1593     ]
1594
1595     JOIN
1596         <alias> <table>
1597         [JOIN ...]
1598     ON <table.column> = <foreign_table.foreign_key>
1599
1600 An easy way to follow the examples below is to remember the following:
1601
1602     Anything inside "[]" is a JOIN
1603     Anything inside "{}" is a condition for the enclosing JOIN
1604
1605 The following examples utilize a "person" table in a family tree application.
1606 In order to express parent->child relationships, this table is self-joined:
1607
1608     # Person->belongs_to('father' => 'Person');
1609     # Person->belongs_to('mother' => 'Person');
1610
1611 C<from> can be used to nest joins. Here we return all children with a father,
1612 then search against all mothers of those children:
1613
1614   $rs = $schema->resultset('Person')->search(
1615       undef,
1616       {
1617           alias => 'mother', # alias columns in accordance with "from"
1618           from => [
1619               { mother => 'person' },
1620               [
1621                   [
1622                       { child => 'person' },
1623                       [
1624                           { father => 'person' },
1625                           { 'father.person_id' => 'child.father_id' }
1626                       ]
1627                   ],
1628                   { 'mother.person_id' => 'child.mother_id' }
1629               ],
1630           ]
1631       },
1632   );
1633
1634   # Equivalent SQL:
1635   # SELECT mother.* FROM person mother
1636   # JOIN (
1637   #   person child
1638   #   JOIN person father
1639   #   ON ( father.person_id = child.father_id )
1640   # )
1641   # ON ( mother.person_id = child.mother_id )
1642
1643 The type of any join can be controlled manually. To search against only people
1644 with a father in the person table, we could explicitly use C<INNER JOIN>:
1645
1646     $rs = $schema->resultset('Person')->search(
1647         undef,
1648         {
1649             alias => 'child', # alias columns in accordance with "from"
1650             from => [
1651                 { child => 'person' },
1652                 [
1653                     { father => 'person', -join_type => 'inner' },
1654                     { 'father.id' => 'child.father_id' }
1655                 ],
1656             ]
1657         },
1658     );
1659
1660     # Equivalent SQL:
1661     # SELECT child.* FROM person child
1662     # INNER JOIN person father ON child.father_id = father.id
1663
1664 =head2 page
1665
1666 =over 4
1667
1668 =item Value: $page
1669
1670 =back
1671
1672 Makes the resultset paged and specifies the page to retrieve. Effectively
1673 identical to creating a non-pages resultset and then calling ->page($page)
1674 on it.
1675
1676 =head2 rows
1677
1678 =over 4
1679
1680 =item Value: $rows
1681
1682 =back
1683
1684 Specifes the maximum number of rows for direct retrieval or the number of
1685 rows per page if the page attribute or method is used.
1686
1687 =head2 group_by
1688
1689 =over 4
1690
1691 =item Value: \@columns
1692
1693 =back
1694
1695 A arrayref of columns to group by. Can include columns of joined tables.
1696
1697   group_by => [qw/ column1 column2 ... /]
1698
1699 =head2 having
1700
1701 =over 4
1702
1703 =item Value: $condition
1704
1705 =back
1706
1707 HAVING is a select statement attribute that is applied between GROUP BY and
1708 ORDER BY. It is applied to the after the grouping calculations have been
1709 done. 
1710
1711   having => { 'count(employee)' => { '>=', 100 } }
1712
1713 =head2 distinct
1714
1715 =over 4
1716
1717 =item Value: (0 | 1)
1718
1719 =back
1720
1721 Set to 1 to group by all columns.
1722
1723 =head2 cache
1724
1725 Set to 1 to cache search results. This prevents extra SQL queries if you
1726 revisit rows in your ResultSet:
1727
1728   my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
1729   
1730   while( my $artist = $resultset->next ) {
1731     ... do stuff ...
1732   }
1733
1734   $rs->first; # without cache, this would issue a query
1735
1736 By default, searches are not cached.
1737
1738 For more examples of using these attributes, see
1739 L<DBIx::Class::Manual::Cookbook>.
1740
1741 =cut
1742
1743 1;