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