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