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