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