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