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