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