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