Improve Documentation.
[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 DBIx::Class::ResultSourceHandle;
14 use base qw/DBIx::Class/;
15
16 __PACKAGE__->mk_group_accessors('simple' => qw/result_class _source_handle/);
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   $source = $source->handle 
89     unless $source->isa('DBIx::Class::ResultSourceHandle');
90   $attrs = { %{$attrs||{}} };
91
92   if ($attrs->{page}) {
93     $attrs->{rows} ||= 10;
94   }
95
96   $attrs->{alias} ||= 'me';
97
98   # Creation of {} and bless separated to mitigate RH perl bug
99   # see https://bugzilla.redhat.com/show_bug.cgi?id=196836
100   my $self = {
101     _source_handle => $source,
102     result_class => $attrs->{result_class} || $source->resolve->result_class,
103     cond => $attrs->{where},
104     count => undef,
105     pager => undef,
106     attrs => $attrs
107   };
108
109   bless $self, $class;
110
111   return $self;
112 }
113
114 =head2 search
115
116 =over 4
117
118 =item Arguments: $cond, \%attrs?
119
120 =item Return Value: $resultset (scalar context), @row_objs (list context)
121
122 =back
123
124   my @cds    = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
125   my $new_rs = $cd_rs->search({ year => 2005 });
126
127   my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
128                  # year = 2005 OR year = 2004
129
130 If you need to pass in additional attributes but no additional condition,
131 call it as C<search(undef, \%attrs)>.
132
133   # "SELECT name, artistid FROM $artist_table"
134   my @all_artists = $schema->resultset('Artist')->search(undef, {
135     columns => [qw/name artistid/],
136   });
137
138 For a list of attributes that can be passed to C<search>, see
139 L</ATTRIBUTES>. For more examples of using this function, see
140 L<Searching|DBIx::Class::Manual::Cookbook/Searching>. For a complete
141 documentation for the first argument, see L<SQL::Abstract>.
142
143 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
144
145 =cut
146
147 sub search {
148   my $self = shift;
149   my $rs = $self->search_rs( @_ );
150   return (wantarray ? $rs->all : $rs);
151 }
152
153 =head2 search_rs
154
155 =over 4
156
157 =item Arguments: $cond, \%attrs?
158
159 =item Return Value: $resultset
160
161 =back
162
163 This method does the same exact thing as search() except it will
164 always return a resultset, even in list context.
165
166 =cut
167
168 sub search_rs {
169   my $self = shift;
170
171   my $rows;
172
173   unless (@_) {                 # no search, effectively just a clone
174     $rows = $self->get_cache;
175   }
176
177   my $attrs = {};
178   $attrs = pop(@_) if @_ > 1 and ref $_[$#_] eq 'HASH';
179   my $our_attrs = { %{$self->{attrs}} };
180   my $having = delete $our_attrs->{having};
181   my $where = delete $our_attrs->{where};
182
183   my $new_attrs = { %{$our_attrs}, %{$attrs} };
184
185   # merge new attrs into inherited
186   foreach my $key (qw/join prefetch/) {
187     next unless exists $attrs->{$key};
188     $new_attrs->{$key} = $self->_merge_attr($our_attrs->{$key}, $attrs->{$key});
189   }
190
191   my $cond = (@_
192     ? (
193         (@_ == 1 || ref $_[0] eq "HASH")
194           ? (
195               (ref $_[0] eq 'HASH')
196                 ? (
197                     (keys %{ $_[0] }  > 0)
198                       ? shift
199                       : undef
200                    )
201                 :  shift
202              )
203           : (
204               (@_ % 2)
205                 ? $self->throw_exception("Odd number of arguments to search")
206                 : {@_}
207              )
208       )
209     : undef
210   );
211
212   if (defined $where) {
213     $new_attrs->{where} = (
214       defined $new_attrs->{where}
215         ? { '-and' => [
216               map {
217                 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
218               } $where, $new_attrs->{where}
219             ]
220           }
221         : $where);
222   }
223
224   if (defined $cond) {
225     $new_attrs->{where} = (
226       defined $new_attrs->{where}
227         ? { '-and' => [
228               map {
229                 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
230               } $cond, $new_attrs->{where}
231             ]
232           }
233         : $cond);
234   }
235
236   if (defined $having) {
237     $new_attrs->{having} = (
238       defined $new_attrs->{having}
239         ? { '-and' => [
240               map {
241                 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
242               } $having, $new_attrs->{having}
243             ]
244           }
245         : $having);
246   }
247
248   my $rs = (ref $self)->new($self->result_source, $new_attrs);
249   if ($rows) {
250     $rs->set_cache($rows);
251   }
252   return $rs;
253 }
254
255 =head2 search_literal
256
257 =over 4
258
259 =item Arguments: $sql_fragment, @bind_values
260
261 =item Return Value: $resultset (scalar context), @row_objs (list context)
262
263 =back
264
265   my @cds   = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
266   my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
267
268 Pass a literal chunk of SQL to be added to the conditional part of the
269 resultset query.
270
271 CAVEAT: C<search_literal> is provided for Class::DBI compatibility and should
272 only be used in that context. There are known problems using C<search_literal>
273 in chained queries; it can result in bind values in the wrong order.  See
274 L<DBIx::Class::Manual::Cookbook/Searching> and
275 L<DBIx::Class::Manual::FAQ/Searching> for searching techniques that do not
276 require C<search_literal>.
277
278 =cut
279
280 sub search_literal {
281   my ($self, $cond, @vals) = @_;
282   my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
283   $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
284   return $self->search(\$cond, $attrs);
285 }
286
287 =head2 find
288
289 =over 4
290
291 =item Arguments: @values | \%cols, \%attrs?
292
293 =item Return Value: $row_object
294
295 =back
296
297 Finds a row based on its primary key or unique constraint. For example, to find
298 a row by its primary key:
299
300   my $cd = $schema->resultset('CD')->find(5);
301
302 You can also find a row by a specific unique constraint using the C<key>
303 attribute. For example:
304
305   my $cd = $schema->resultset('CD')->find('Massive Attack', 'Mezzanine', {
306     key => 'cd_artist_title'
307   });
308
309 Additionally, you can specify the columns explicitly by name:
310
311   my $cd = $schema->resultset('CD')->find(
312     {
313       artist => 'Massive Attack',
314       title  => 'Mezzanine',
315     },
316     { key => 'cd_artist_title' }
317   );
318
319 If the C<key> is specified as C<primary>, it searches only on the primary key.
320
321 If no C<key> is specified, it searches on all unique constraints defined on the
322 source, including the primary key.
323
324 If your table does not have a primary key, you B<must> provide a value for the
325 C<key> attribute matching one of the unique constraints on the source.
326
327 See also L</find_or_create> and L</update_or_create>. For information on how to
328 declare unique constraints, see
329 L<DBIx::Class::ResultSource/add_unique_constraint>.
330
331 =cut
332
333 sub find {
334   my $self = shift;
335   my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
336
337   # Default to the primary key, but allow a specific key
338   my @cols = exists $attrs->{key}
339     ? $self->result_source->unique_constraint_columns($attrs->{key})
340     : $self->result_source->primary_columns;
341   $self->throw_exception(
342     "Can't find unless a primary key is defined or unique constraint is specified"
343   ) unless @cols;
344
345   # Parse out a hashref from input
346   my $input_query;
347   if (ref $_[0] eq 'HASH') {
348     $input_query = { %{$_[0]} };
349   }
350   elsif (@_ == @cols) {
351     $input_query = {};
352     @{$input_query}{@cols} = @_;
353   }
354   else {
355     # Compatibility: Allow e.g. find(id => $value)
356     carp "Find by key => value deprecated; please use a hashref instead";
357     $input_query = {@_};
358   }
359
360   my (%related, $info);
361
362   KEY: foreach my $key (keys %$input_query) {
363     if (ref($input_query->{$key})
364         && ($info = $self->result_source->relationship_info($key))) {
365       my $val = delete $input_query->{$key};
366       next KEY if (ref($val) eq 'ARRAY'); # has_many for multi_create
367       my $rel_q = $self->result_source->resolve_condition(
368                     $info->{cond}, $val, $key
369                   );
370       die "Can't handle OR join condition in find" if ref($rel_q) eq 'ARRAY';
371       @related{keys %$rel_q} = values %$rel_q;
372     }
373   }
374   if (my @keys = keys %related) {
375     @{$input_query}{@keys} = values %related;
376   }
377
378   my @unique_queries = $self->_unique_queries($input_query, $attrs);
379
380   # Build the final query: Default to the disjunction of the unique queries,
381   # but allow the input query in case the ResultSet defines the query or the
382   # user is abusing find
383   my $alias = exists $attrs->{alias} ? $attrs->{alias} : $self->{attrs}{alias};
384   my $query = @unique_queries
385     ? [ map { $self->_add_alias($_, $alias) } @unique_queries ]
386     : $self->_add_alias($input_query, $alias);
387
388   # Run the query
389   if (keys %$attrs) {
390     my $rs = $self->search($query, $attrs);
391     return keys %{$rs->_resolved_attrs->{collapse}} ? $rs->next : $rs->single;
392   }
393   else {
394     return keys %{$self->_resolved_attrs->{collapse}}
395       ? $self->search($query)->next
396       : $self->single($query);
397   }
398 }
399
400 # _add_alias
401 #
402 # Add the specified alias to the specified query hash. A copy is made so the
403 # original query is not modified.
404
405 sub _add_alias {
406   my ($self, $query, $alias) = @_;
407
408   my %aliased = %$query;
409   foreach my $col (grep { ! m/\./ } keys %aliased) {
410     $aliased{"$alias.$col"} = delete $aliased{$col};
411   }
412
413   return \%aliased;
414 }
415
416 # _unique_queries
417 #
418 # Build a list of queries which satisfy unique constraints.
419
420 sub _unique_queries {
421   my ($self, $query, $attrs) = @_;
422
423   my @constraint_names = exists $attrs->{key}
424     ? ($attrs->{key})
425     : $self->result_source->unique_constraint_names;
426
427   my $where = $self->_collapse_cond($self->{attrs}{where} || {});
428   my $num_where = scalar keys %$where;
429
430   my @unique_queries;
431   foreach my $name (@constraint_names) {
432     my @unique_cols = $self->result_source->unique_constraint_columns($name);
433     my $unique_query = $self->_build_unique_query($query, \@unique_cols);
434
435     my $num_cols = scalar @unique_cols;
436     my $num_query = scalar keys %$unique_query;
437
438     my $total = $num_query + $num_where;
439     if ($num_query && ($num_query == $num_cols || $total == $num_cols)) {
440       # The query is either unique on its own or is unique in combination with
441       # the existing where clause
442       push @unique_queries, $unique_query;
443     }
444   }
445
446   return @unique_queries;
447 }
448
449 # _build_unique_query
450 #
451 # Constrain the specified query hash based on the specified column names.
452
453 sub _build_unique_query {
454   my ($self, $query, $unique_cols) = @_;
455
456   return {
457     map  { $_ => $query->{$_} }
458     grep { exists $query->{$_} }
459       @$unique_cols
460   };
461 }
462
463 =head2 search_related
464
465 =over 4
466
467 =item Arguments: $rel, $cond, \%attrs?
468
469 =item Return Value: $new_resultset
470
471 =back
472
473   $new_rs = $cd_rs->search_related('artist', {
474     name => 'Emo-R-Us',
475   });
476
477 Searches the specified relationship, optionally specifying a condition and
478 attributes for matching records. See L</ATTRIBUTES> for more information.
479
480 =cut
481
482 sub search_related {
483   return shift->related_resultset(shift)->search(@_);
484 }
485
486 =head2 cursor
487
488 =over 4
489
490 =item Arguments: none
491
492 =item Return Value: $cursor
493
494 =back
495
496 Returns a storage-driven cursor to the given resultset. See
497 L<DBIx::Class::Cursor> for more information.
498
499 =cut
500
501 sub cursor {
502   my ($self) = @_;
503
504   my $attrs = { %{$self->_resolved_attrs} };
505   return $self->{cursor}
506     ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
507           $attrs->{where},$attrs);
508 }
509
510 =head2 single
511
512 =over 4
513
514 =item Arguments: $cond?
515
516 =item Return Value: $row_object?
517
518 =back
519
520   my $cd = $schema->resultset('CD')->single({ year => 2001 });
521
522 Inflates the first result without creating a cursor if the resultset has
523 any records in it; if not returns nothing. Used by L</find> as an optimisation.
524
525 Can optionally take an additional condition *only* - this is a fast-code-path
526 method; if you need to add extra joins or similar call ->search and then
527 ->single without a condition on the $rs returned from that.
528
529 =cut
530
531 sub single {
532   my ($self, $where) = @_;
533   my $attrs = { %{$self->_resolved_attrs} };
534   if ($where) {
535     if (defined $attrs->{where}) {
536       $attrs->{where} = {
537         '-and' =>
538             [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
539                $where, delete $attrs->{where} ]
540       };
541     } else {
542       $attrs->{where} = $where;
543     }
544   }
545
546 #  XXX: Disabled since it doesn't infer uniqueness in all cases
547 #  unless ($self->_is_unique_query($attrs->{where})) {
548 #    carp "Query not guaranteed to return a single row"
549 #      . "; please declare your unique constraints or use search instead";
550 #  }
551
552   my @data = $self->result_source->storage->select_single(
553     $attrs->{from}, $attrs->{select},
554     $attrs->{where}, $attrs
555   );
556
557   return (@data ? ($self->_construct_object(@data))[0] : undef);
558 }
559
560 # _is_unique_query
561 #
562 # Try to determine if the specified query is guaranteed to be unique, based on
563 # the declared unique constraints.
564
565 sub _is_unique_query {
566   my ($self, $query) = @_;
567
568   my $collapsed = $self->_collapse_query($query);
569   my $alias = $self->{attrs}{alias};
570
571   foreach my $name ($self->result_source->unique_constraint_names) {
572     my @unique_cols = map {
573       "$alias.$_"
574     } $self->result_source->unique_constraint_columns($name);
575
576     # Count the values for each unique column
577     my %seen = map { $_ => 0 } @unique_cols;
578
579     foreach my $key (keys %$collapsed) {
580       my $aliased = $key =~ /\./ ? $key : "$alias.$key";
581       next unless exists $seen{$aliased};  # Additional constraints are okay
582       $seen{$aliased} = scalar keys %{ $collapsed->{$key} };
583     }
584
585     # If we get 0 or more than 1 value for a column, it's not necessarily unique
586     return 1 unless grep { $_ != 1 } values %seen;
587   }
588
589   return 0;
590 }
591
592 # _collapse_query
593 #
594 # Recursively collapse the query, accumulating values for each column.
595
596 sub _collapse_query {
597   my ($self, $query, $collapsed) = @_;
598
599   $collapsed ||= {};
600
601   if (ref $query eq 'ARRAY') {
602     foreach my $subquery (@$query) {
603       next unless ref $subquery;  # -or
604 #      warn "ARRAY: " . Dumper $subquery;
605       $collapsed = $self->_collapse_query($subquery, $collapsed);
606     }
607   }
608   elsif (ref $query eq 'HASH') {
609     if (keys %$query and (keys %$query)[0] eq '-and') {
610       foreach my $subquery (@{$query->{-and}}) {
611 #        warn "HASH: " . Dumper $subquery;
612         $collapsed = $self->_collapse_query($subquery, $collapsed);
613       }
614     }
615     else {
616 #      warn "LEAF: " . Dumper $query;
617       foreach my $col (keys %$query) {
618         my $value = $query->{$col};
619         $collapsed->{$col}{$value}++;
620       }
621     }
622   }
623
624   return $collapsed;
625 }
626
627 =head2 get_column
628
629 =over 4
630
631 =item Arguments: $cond?
632
633 =item Return Value: $resultsetcolumn
634
635 =back
636
637   my $max_length = $rs->get_column('length')->max;
638
639 Returns a L<DBIx::Class::ResultSetColumn> instance for a column of the ResultSet.
640
641 =cut
642
643 sub get_column {
644   my ($self, $column) = @_;
645   my $new = DBIx::Class::ResultSetColumn->new($self, $column);
646   return $new;
647 }
648
649 =head2 search_like
650
651 =over 4
652
653 =item Arguments: $cond, \%attrs?
654
655 =item Return Value: $resultset (scalar context), @row_objs (list context)
656
657 =back
658
659   # WHERE title LIKE '%blue%'
660   $cd_rs = $rs->search_like({ title => '%blue%'});
661
662 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
663 that this is simply a convenience method. You most likely want to use
664 L</search> with specific operators.
665
666 For more information, see L<DBIx::Class::Manual::Cookbook>.
667
668 =cut
669
670 sub search_like {
671   my $class = shift;
672   my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
673   my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
674   $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
675   return $class->search($query, { %$attrs });
676 }
677
678 =head2 slice
679
680 =over 4
681
682 =item Arguments: $first, $last
683
684 =item Return Value: $resultset (scalar context), @row_objs (list context)
685
686 =back
687
688 Returns a resultset or object list representing a subset of elements from the
689 resultset slice is called on. Indexes are from 0, i.e., to get the first
690 three records, call:
691
692   my ($one, $two, $three) = $rs->slice(0, 2);
693
694 =cut
695
696 sub slice {
697   my ($self, $min, $max) = @_;
698   my $attrs = {}; # = { %{ $self->{attrs} || {} } };
699   $attrs->{offset} = $self->{attrs}{offset} || 0;
700   $attrs->{offset} += $min;
701   $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
702   return $self->search(undef(), $attrs);
703   #my $slice = (ref $self)->new($self->result_source, $attrs);
704   #return (wantarray ? $slice->all : $slice);
705 }
706
707 =head2 next
708
709 =over 4
710
711 =item Arguments: none
712
713 =item Return Value: $result?
714
715 =back
716
717 Returns the next element in the resultset (C<undef> is there is none).
718
719 Can be used to efficiently iterate over records in the resultset:
720
721   my $rs = $schema->resultset('CD')->search;
722   while (my $cd = $rs->next) {
723     print $cd->title;
724   }
725
726 Note that you need to store the resultset object, and call C<next> on it.
727 Calling C<< resultset('Table')->next >> repeatedly will always return the
728 first record from the resultset.
729
730 =cut
731
732 sub next {
733   my ($self) = @_;
734   if (my $cache = $self->get_cache) {
735     $self->{all_cache_position} ||= 0;
736     return $cache->[$self->{all_cache_position}++];
737   }
738   if ($self->{attrs}{cache}) {
739     $self->{all_cache_position} = 1;
740     return ($self->all)[0];
741   }
742   if ($self->{stashed_objects}) {
743     my $obj = shift(@{$self->{stashed_objects}});
744     delete $self->{stashed_objects} unless @{$self->{stashed_objects}};
745     return $obj;
746   }
747   my @row = (
748     exists $self->{stashed_row}
749       ? @{delete $self->{stashed_row}}
750       : $self->cursor->next
751   );
752   return undef unless (@row);
753   my ($row, @more) = $self->_construct_object(@row);
754   $self->{stashed_objects} = \@more if @more;
755   return $row;
756 }
757
758 sub _construct_object {
759   my ($self, @row) = @_;
760   my $info = $self->_collapse_result($self->{_attrs}{as}, \@row);
761   my @new = $self->result_class->inflate_result($self->result_source, @$info);
762   @new = $self->{_attrs}{record_filter}->(@new)
763     if exists $self->{_attrs}{record_filter};
764   return @new;
765 }
766
767 sub _collapse_result {
768   my ($self, $as_proto, $row) = @_;
769
770   my @copy = @$row;
771
772   # 'foo'         => [ undef, 'foo' ]
773   # 'foo.bar'     => [ 'foo', 'bar' ]
774   # 'foo.bar.baz' => [ 'foo.bar', 'baz' ]
775
776   my @construct_as = map { [ (/^(?:(.*)\.)?([^.]+)$/) ] } @$as_proto;
777
778   my %collapse = %{$self->{_attrs}{collapse}||{}};
779
780   my @pri_index;
781
782   # if we're doing collapsing (has_many prefetch) we need to grab records
783   # until the PK changes, so fill @pri_index. if not, we leave it empty so
784   # we know we don't have to bother.
785
786   # the reason for not using the collapse stuff directly is because if you
787   # had for e.g. two artists in a row with no cds, the collapse info for
788   # both would be NULL (undef) so you'd lose the second artist
789
790   # store just the index so we can check the array positions from the row
791   # without having to contruct the full hash
792
793   if (keys %collapse) {
794     my %pri = map { ($_ => 1) } $self->result_source->primary_columns;
795     foreach my $i (0 .. $#construct_as) {
796       next if defined($construct_as[$i][0]); # only self table
797       if (delete $pri{$construct_as[$i][1]}) {
798         push(@pri_index, $i);
799       }
800       last unless keys %pri; # short circuit (Johnny Five Is Alive!)
801     }
802   }
803
804   # no need to do an if, it'll be empty if @pri_index is empty anyway
805
806   my %pri_vals = map { ($_ => $copy[$_]) } @pri_index;
807
808   my @const_rows;
809
810   do { # no need to check anything at the front, we always want the first row
811
812     my %const;
813   
814     foreach my $this_as (@construct_as) {
815       $const{$this_as->[0]||''}{$this_as->[1]} = shift(@copy);
816     }
817
818     push(@const_rows, \%const);
819
820   } until ( # no pri_index => no collapse => drop straight out
821       !@pri_index
822     or
823       do { # get another row, stash it, drop out if different PK
824
825         @copy = $self->cursor->next;
826         $self->{stashed_row} = \@copy;
827
828         # last thing in do block, counts as true if anything doesn't match
829
830         # check xor defined first for NULL vs. NOT NULL then if one is
831         # defined the other must be so check string equality
832
833         grep {
834           (defined $pri_vals{$_} ^ defined $copy[$_])
835           || (defined $pri_vals{$_} && ($pri_vals{$_} ne $copy[$_]))
836         } @pri_index;
837       }
838   );
839
840   my $alias = $self->{attrs}{alias};
841   my $info = [];
842
843   my %collapse_pos;
844
845   my @const_keys;
846
847   foreach my $const (@const_rows) {
848     scalar @const_keys or do {
849       @const_keys = sort { length($a) <=> length($b) } keys %$const;
850     };
851     foreach my $key (@const_keys) {
852       if (length $key) {
853         my $target = $info;
854         my @parts = split(/\./, $key);
855         my $cur = '';
856         my $data = $const->{$key};
857         foreach my $p (@parts) {
858           $target = $target->[1]->{$p} ||= [];
859           $cur .= ".${p}";
860           if ($cur eq ".${key}" && (my @ckey = @{$collapse{$cur}||[]})) { 
861             # collapsing at this point and on final part
862             my $pos = $collapse_pos{$cur};
863             CK: foreach my $ck (@ckey) {
864               if (!defined $pos->{$ck} || $pos->{$ck} ne $data->{$ck}) {
865                 $collapse_pos{$cur} = $data;
866                 delete @collapse_pos{ # clear all positioning for sub-entries
867                   grep { m/^\Q${cur}.\E/ } keys %collapse_pos
868                 };
869                 push(@$target, []);
870                 last CK;
871               }
872             }
873           }
874           if (exists $collapse{$cur}) {
875             $target = $target->[-1];
876           }
877         }
878         $target->[0] = $data;
879       } else {
880         $info->[0] = $const->{$key};
881       }
882     }
883   }
884
885   return $info;
886 }
887
888 =head2 result_source
889
890 =over 4
891
892 =item Arguments: $result_source?
893
894 =item Return Value: $result_source
895
896 =back
897
898 An accessor for the primary ResultSource object from which this ResultSet
899 is derived.
900
901 =head2 result_class
902
903 =over 4
904
905 =item Arguments: $result_class?
906
907 =item Return Value: $result_class
908
909 =back
910
911 An accessor for the class to use when creating row objects. Defaults to 
912 C<< result_source->result_class >> - which in most cases is the name of the 
913 L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class.
914
915 =cut
916
917
918 =head2 count
919
920 =over 4
921
922 =item Arguments: $cond, \%attrs??
923
924 =item Return Value: $count
925
926 =back
927
928 Performs an SQL C<COUNT> with the same query as the resultset was built
929 with to find the number of elements. If passed arguments, does a search
930 on the resultset and counts the results of that.
931
932 Note: When using C<count> with C<group_by>, L<DBIX::Class> emulates C<GROUP BY>
933 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
934 not support C<DISTINCT> with multiple columns. If you are using such a
935 database, you should only use columns from the main table in your C<group_by>
936 clause.
937
938 =cut
939
940 sub count {
941   my $self = shift;
942   return $self->search(@_)->count if @_ and defined $_[0];
943   return scalar @{ $self->get_cache } if $self->get_cache;
944   my $count = $self->_count;
945   return 0 unless $count;
946
947   # need to take offset from resolved attrs
948
949   $count -= $self->{_attrs}{offset} if $self->{_attrs}{offset};
950   $count = $self->{attrs}{rows} if
951     $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
952   $count = 0 if ($count < 0);
953   return $count;
954 }
955
956 sub _count { # Separated out so pager can get the full count
957   my $self = shift;
958   my $select = { count => '*' };
959
960   my $attrs = { %{$self->_resolved_attrs} };
961   if (my $group_by = delete $attrs->{group_by}) {
962     delete $attrs->{having};
963     my @distinct = (ref $group_by ?  @$group_by : ($group_by));
964     # todo: try CONCAT for multi-column pk
965     my @pk = $self->result_source->primary_columns;
966     if (@pk == 1) {
967       my $alias = $attrs->{alias};
968       foreach my $column (@distinct) {
969         if ($column =~ qr/^(?:\Q${alias}.\E)?$pk[0]$/) {
970           @distinct = ($column);
971           last;
972         }
973       }
974     }
975
976     $select = { count => { distinct => \@distinct } };
977   }
978
979   $attrs->{select} = $select;
980   $attrs->{as} = [qw/count/];
981
982   # offset, order by and page are not needed to count. record_filter is cdbi
983   delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
984
985   my $tmp_rs = (ref $self)->new($self->result_source, $attrs);
986   my ($count) = $tmp_rs->cursor->next;
987   return $count;
988 }
989
990 =head2 count_literal
991
992 =over 4
993
994 =item Arguments: $sql_fragment, @bind_values
995
996 =item Return Value: $count
997
998 =back
999
1000 Counts the results in a literal query. Equivalent to calling L</search_literal>
1001 with the passed arguments, then L</count>.
1002
1003 =cut
1004
1005 sub count_literal { shift->search_literal(@_)->count; }
1006
1007 =head2 all
1008
1009 =over 4
1010
1011 =item Arguments: none
1012
1013 =item Return Value: @objects
1014
1015 =back
1016
1017 Returns all elements in the resultset. Called implicitly if the resultset
1018 is returned in list context.
1019
1020 =cut
1021
1022 sub all {
1023   my ($self) = @_;
1024   return @{ $self->get_cache } if $self->get_cache;
1025
1026   my @obj;
1027
1028   # TODO: don't call resolve here
1029   if (keys %{$self->_resolved_attrs->{collapse}}) {
1030 #  if ($self->{attrs}{prefetch}) {
1031       # Using $self->cursor->all is really just an optimisation.
1032       # If we're collapsing has_many prefetches it probably makes
1033       # very little difference, and this is cleaner than hacking
1034       # _construct_object to survive the approach
1035     my @row = $self->cursor->next;
1036     while (@row) {
1037       push(@obj, $self->_construct_object(@row));
1038       @row = (exists $self->{stashed_row}
1039                ? @{delete $self->{stashed_row}}
1040                : $self->cursor->next);
1041     }
1042   } else {
1043     @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
1044   }
1045
1046   $self->set_cache(\@obj) if $self->{attrs}{cache};
1047   return @obj;
1048 }
1049
1050 =head2 reset
1051
1052 =over 4
1053
1054 =item Arguments: none
1055
1056 =item Return Value: $self
1057
1058 =back
1059
1060 Resets the resultset's cursor, so you can iterate through the elements again.
1061
1062 =cut
1063
1064 sub reset {
1065   my ($self) = @_;
1066   delete $self->{_attrs} if exists $self->{_attrs};
1067   $self->{all_cache_position} = 0;
1068   $self->cursor->reset;
1069   return $self;
1070 }
1071
1072 =head2 first
1073
1074 =over 4
1075
1076 =item Arguments: none
1077
1078 =item Return Value: $object?
1079
1080 =back
1081
1082 Resets the resultset and returns an object for the first result (if the
1083 resultset returns anything).
1084
1085 =cut
1086
1087 sub first {
1088   return $_[0]->reset->next;
1089 }
1090
1091 # _cond_for_update_delete
1092 #
1093 # update/delete require the condition to be modified to handle
1094 # the differing SQL syntax available.  This transforms the $self->{cond}
1095 # appropriately, returning the new condition.
1096
1097 sub _cond_for_update_delete {
1098   my ($self, $full_cond) = @_;
1099   my $cond = {};
1100
1101   $full_cond ||= $self->{cond};
1102   # No-op. No condition, we're updating/deleting everything
1103   return $cond unless ref $full_cond;
1104
1105   if (ref $full_cond eq 'ARRAY') {
1106     $cond = [
1107       map {
1108         my %hash;
1109         foreach my $key (keys %{$_}) {
1110           $key =~ /([^.]+)$/;
1111           $hash{$1} = $_->{$key};
1112         }
1113         \%hash;
1114       } @{$full_cond}
1115     ];
1116   }
1117   elsif (ref $full_cond eq 'HASH') {
1118     if ((keys %{$full_cond})[0] eq '-and') {
1119       $cond->{-and} = [];
1120
1121       my @cond = @{$full_cond->{-and}};
1122       for (my $i = 0; $i < @cond; $i++) {
1123         my $entry = $cond[$i];
1124
1125         my $hash;
1126         if (ref $entry eq 'HASH') {
1127           $hash = $self->_cond_for_update_delete($entry);
1128         }
1129         else {
1130           $entry =~ /([^.]+)$/;
1131           $hash->{$1} = $cond[++$i];
1132         }
1133
1134         push @{$cond->{-and}}, $hash;
1135       }
1136     }
1137     else {
1138       foreach my $key (keys %{$full_cond}) {
1139         $key =~ /([^.]+)$/;
1140         $cond->{$1} = $full_cond->{$key};
1141       }
1142     }
1143   }
1144   else {
1145     $self->throw_exception(
1146       "Can't update/delete on resultset with condition unless hash or array"
1147     );
1148   }
1149
1150   return $cond;
1151 }
1152
1153
1154 =head2 update
1155
1156 =over 4
1157
1158 =item Arguments: \%values
1159
1160 =item Return Value: $storage_rv
1161
1162 =back
1163
1164 Sets the specified columns in the resultset to the supplied values in a
1165 single query. Return value will be true if the update succeeded or false
1166 if no records were updated; exact type of success value is storage-dependent.
1167
1168 =cut
1169
1170 sub update {
1171   my ($self, $values) = @_;
1172   $self->throw_exception("Values for update must be a hash")
1173     unless ref $values eq 'HASH';
1174
1175   my $cond = $self->_cond_for_update_delete;
1176    
1177   return $self->result_source->storage->update(
1178     $self->result_source, $values, $cond
1179   );
1180 }
1181
1182 =head2 update_all
1183
1184 =over 4
1185
1186 =item Arguments: \%values
1187
1188 =item Return Value: 1
1189
1190 =back
1191
1192 Fetches all objects and updates them one at a time. Note that C<update_all>
1193 will run DBIC cascade triggers, while L</update> will not.
1194
1195 =cut
1196
1197 sub update_all {
1198   my ($self, $values) = @_;
1199   $self->throw_exception("Values for update must be a hash")
1200     unless ref $values eq 'HASH';
1201   foreach my $obj ($self->all) {
1202     $obj->set_columns($values)->update;
1203   }
1204   return 1;
1205 }
1206
1207 =head2 delete
1208
1209 =over 4
1210
1211 =item Arguments: none
1212
1213 =item Return Value: 1
1214
1215 =back
1216
1217 Deletes the contents of the resultset from its result source. Note that this
1218 will not run DBIC cascade triggers. See L</delete_all> if you need triggers
1219 to run. See also L<DBIx::Class::Row/delete>.
1220
1221 =cut
1222
1223 sub delete {
1224   my ($self) = @_;
1225
1226   my $cond = $self->_cond_for_update_delete;
1227
1228   $self->result_source->storage->delete($self->result_source, $cond);
1229   return 1;
1230 }
1231
1232 =head2 delete_all
1233
1234 =over 4
1235
1236 =item Arguments: none
1237
1238 =item Return Value: 1
1239
1240 =back
1241
1242 Fetches all objects and deletes them one at a time. Note that C<delete_all>
1243 will run DBIC cascade triggers, while L</delete> will not.
1244
1245 =cut
1246
1247 sub delete_all {
1248   my ($self) = @_;
1249   $_->delete for $self->all;
1250   return 1;
1251 }
1252
1253 =head2 populate
1254
1255 =over 4
1256
1257 =item Arguments: \@data;
1258
1259 =back
1260
1261 Pass an arrayref of hashrefs. Each hashref should be a structure suitable for
1262 submitting to a $resultset->create(...) method.
1263
1264 In void context, C<insert_bulk> in L<DBIx::Class::Storage::DBI> is used
1265 to insert the data, as this is a faster method.  
1266
1267 Otherwise, each set of data is inserted into the database using
1268 L<DBIx::Class::ResultSet/create>, and a arrayref of the resulting row
1269 objects is returned.
1270
1271 Example:  Assuming an Artist Class that has many CDs Classes relating:
1272
1273   my $Artist_rs = $schema->resultset("Artist");
1274   
1275   ## Void Context Example 
1276   $Artist_rs->populate([
1277      { artistid => 4, name => 'Manufactured Crap', cds => [ 
1278         { title => 'My First CD', year => 2006 },
1279         { title => 'Yet More Tweeny-Pop crap', year => 2007 },
1280       ],
1281      },
1282      { artistid => 5, name => 'Angsty-Whiny Girl', cds => [
1283         { title => 'My parents sold me to a record company' ,year => 2005 },
1284         { title => 'Why Am I So Ugly?', year => 2006 },
1285         { title => 'I Got Surgery and am now Popular', year => 2007 }
1286       ],
1287      },
1288   ]);
1289   
1290   ## Array Context Example
1291   my ($ArtistOne, $ArtistTwo, $ArtistThree) = $Artist_rs->populate([
1292     { name => "Artist One"},
1293     { name => "Artist Two"},
1294     { name => "Artist Three", cds=> [
1295     { title => "First CD", year => 2007},
1296     { title => "Second CD", year => 2008},
1297   ]}
1298   ]);
1299   
1300   print $ArtistOne->name; ## response is 'Artist One'
1301   print $ArtistThree->cds->count ## reponse is '2'
1302   
1303 Please note an important effect on your data when choosing between void and
1304 wantarray context. Since void context goes straight to C<insert_bulk> in 
1305 L<DBIx::Class::Storage::DBI> this will skip any component that is overriding
1306 c<insert>.  So if you are using something like L<DBIx-Class-UUIDColumns> to 
1307 create primary keys for you, you will find that your PKs are empty.  In this 
1308 case you will have to use the wantarray context in order to create those 
1309 values.
1310
1311 =cut
1312
1313 sub populate {
1314   my ($self, $data) = @_;
1315   
1316   if(defined wantarray) {
1317     my @created;
1318     foreach my $item (@$data) {
1319       push(@created, $self->create($item));
1320     }
1321     return @created;
1322   } else {
1323     my ($first, @rest) = @$data;
1324
1325     my @names = grep {!ref $first->{$_}} keys %$first;
1326     my @rels = grep { $self->result_source->has_relationship($_) } keys %$first;
1327     my @pks = $self->result_source->primary_columns;  
1328
1329     ## do the belongs_to relationships  
1330     foreach my $index (0..$#$data) {
1331       if( grep { !defined $data->[$index]->{$_} } @pks ) {
1332         my @ret = $self->populate($data);
1333         return;
1334       }
1335     
1336       foreach my $rel (@rels) {
1337         next unless $data->[$index]->{$rel} && ref $data->[$index]->{$rel} eq "HASH";
1338         my $result = $self->related_resultset($rel)->create($data->[$index]->{$rel});
1339         my ($reverse) = keys %{$self->result_source->reverse_relationship_info($rel)};
1340         my $related = $result->result_source->resolve_condition(
1341           $result->result_source->relationship_info($reverse)->{cond},
1342           $self,        
1343           $result,        
1344         );
1345
1346         delete $data->[$index]->{$rel};
1347         $data->[$index] = {%{$data->[$index]}, %$related};
1348       
1349         push @names, keys %$related if $index == 0;
1350       }
1351     }
1352
1353     ## do bulk insert on current row
1354     my @values = map { [ @$_{@names} ] } @$data;
1355
1356     $self->result_source->storage->insert_bulk(
1357       $self->result_source, 
1358       \@names, 
1359       \@values,
1360     );
1361
1362     ## do the has_many relationships
1363     foreach my $item (@$data) {
1364
1365       foreach my $rel (@rels) {
1366         next unless $item->{$rel} && ref $item->{$rel} eq "ARRAY";
1367
1368         my $parent = $self->find(map {{$_=>$item->{$_}} } @pks) 
1369      || $self->throw_exception('Cannot find the relating object.');
1370      
1371         my $child = $parent->$rel;
1372     
1373         my $related = $child->result_source->resolve_condition(
1374           $parent->result_source->relationship_info($rel)->{cond},
1375           $child,
1376           $parent,
1377         );
1378
1379         my @rows_to_add = ref $item->{$rel} eq 'ARRAY' ? @{$item->{$rel}} : ($item->{$rel});
1380         my @populate = map { {%$_, %$related} } @rows_to_add;
1381
1382         $child->populate( \@populate );
1383       }
1384     }
1385   }
1386 }
1387
1388 =head2 pager
1389
1390 =over 4
1391
1392 =item Arguments: none
1393
1394 =item Return Value: $pager
1395
1396 =back
1397
1398 Return Value a L<Data::Page> object for the current resultset. Only makes
1399 sense for queries with a C<page> attribute.
1400
1401 =cut
1402
1403 sub pager {
1404   my ($self) = @_;
1405   my $attrs = $self->{attrs};
1406   $self->throw_exception("Can't create pager for non-paged rs")
1407     unless $self->{attrs}{page};
1408   $attrs->{rows} ||= 10;
1409   return $self->{pager} ||= Data::Page->new(
1410     $self->_count, $attrs->{rows}, $self->{attrs}{page});
1411 }
1412
1413 =head2 page
1414
1415 =over 4
1416
1417 =item Arguments: $page_number
1418
1419 =item Return Value: $rs
1420
1421 =back
1422
1423 Returns a resultset for the $page_number page of the resultset on which page
1424 is called, where each page contains a number of rows equal to the 'rows'
1425 attribute set on the resultset (10 by default).
1426
1427 =cut
1428
1429 sub page {
1430   my ($self, $page) = @_;
1431   return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
1432 }
1433
1434 =head2 new_result
1435
1436 =over 4
1437
1438 =item Arguments: \%vals
1439
1440 =item Return Value: $object
1441
1442 =back
1443
1444 Creates a new row object in the resultset's result class and returns
1445 it. The row is not inserted into the database at this point, call
1446 L<DBIx::Class::Row/insert> to do that. Calling L<DBIx::Class::Row/in_storage>
1447 will tell you whether the row object has been inserted or not.
1448
1449 Passes the hashref of input on to L<DBIx::Class::Row/new>.
1450
1451 =cut
1452
1453 sub new_result {
1454   my ($self, $values) = @_;
1455   $self->throw_exception( "new_result needs a hash" )
1456     unless (ref $values eq 'HASH');
1457   $self->throw_exception(
1458     "Can't abstract implicit construct, condition not a hash"
1459   ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
1460
1461   my $alias = $self->{attrs}{alias};
1462   my $collapsed_cond = $self->{cond} ? $self->_collapse_cond($self->{cond}) : {};
1463
1464   # precendence must be given to passed values over values inherited from the cond, 
1465   # so the order here is important.
1466   my %new = (
1467     %{ $self->_remove_alias($collapsed_cond, $alias) },
1468     %{ $self->_remove_alias($values, $alias) },
1469     -source_handle => $self->_source_handle,
1470     -result_source => $self->result_source, # DO NOT REMOVE THIS, REQUIRED
1471   );
1472
1473   return $self->result_class->new(\%new);
1474 }
1475
1476 # _collapse_cond
1477 #
1478 # Recursively collapse the condition.
1479
1480 sub _collapse_cond {
1481   my ($self, $cond, $collapsed) = @_;
1482
1483   $collapsed ||= {};
1484
1485   if (ref $cond eq 'ARRAY') {
1486     foreach my $subcond (@$cond) {
1487       next unless ref $subcond;  # -or
1488 #      warn "ARRAY: " . Dumper $subcond;
1489       $collapsed = $self->_collapse_cond($subcond, $collapsed);
1490     }
1491   }
1492   elsif (ref $cond eq 'HASH') {
1493     if (keys %$cond and (keys %$cond)[0] eq '-and') {
1494       foreach my $subcond (@{$cond->{-and}}) {
1495 #        warn "HASH: " . Dumper $subcond;
1496         $collapsed = $self->_collapse_cond($subcond, $collapsed);
1497       }
1498     }
1499     else {
1500 #      warn "LEAF: " . Dumper $cond;
1501       foreach my $col (keys %$cond) {
1502         my $value = $cond->{$col};
1503         $collapsed->{$col} = $value;
1504       }
1505     }
1506   }
1507
1508   return $collapsed;
1509 }
1510
1511 # _remove_alias
1512 #
1513 # Remove the specified alias from the specified query hash. A copy is made so
1514 # the original query is not modified.
1515
1516 sub _remove_alias {
1517   my ($self, $query, $alias) = @_;
1518
1519   my %orig = %{ $query || {} };
1520   my %unaliased;
1521
1522   foreach my $key (keys %orig) {
1523     if ($key !~ /\./) {
1524       $unaliased{$key} = $orig{$key};
1525       next;
1526     }
1527     $unaliased{$1} = $orig{$key}
1528       if $key =~ m/^(?:\Q$alias\E\.)?([^.]+)$/;
1529   }
1530
1531   return \%unaliased;
1532 }
1533
1534 =head2 find_or_new
1535
1536 =over 4
1537
1538 =item Arguments: \%vals, \%attrs?
1539
1540 =item Return Value: $object
1541
1542 =back
1543
1544 Find an existing record from this resultset. If none exists, instantiate a new
1545 result object and return it. The object will not be saved into your storage
1546 until you call L<DBIx::Class::Row/insert> on it.
1547
1548 If you want objects to be saved immediately, use L</find_or_create> instead.
1549
1550 =cut
1551
1552 sub find_or_new {
1553   my $self     = shift;
1554   my $attrs    = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1555   my $hash     = ref $_[0] eq 'HASH' ? shift : {@_};
1556   my $exists   = $self->find($hash, $attrs);
1557   return defined $exists ? $exists : $self->new_result($hash);
1558 }
1559
1560 =head2 create
1561
1562 =over 4
1563
1564 =item Arguments: \%vals
1565
1566 =item Return Value: a L<DBIx::Class::Row> $object
1567
1568 =back
1569
1570 Attempt to create a single new row or a row with multiple related rows
1571 in the table represented by the resultset (and related tables). This
1572 will not check for duplicate rows before inserting, use
1573 L</find_or_create> to do that.
1574
1575 To create one row for this resultset, pass a hashref of key/value
1576 pairs representing the columns of the table and the values you wish to
1577 store. If the appropriate relationships are set up, foreign key fields
1578 can also be passed an object representing the foreign row, and the
1579 value will be set to it's primary key.
1580
1581 To create related objects, pass a hashref for the value if the related
1582 item is a foreign key relationship (L<DBIx::Class::Relationship/belongs_to>),
1583 and use the name of the relationship as the key. (NOT the name of the field,
1584 necessarily). For C<has_many> and C<has_one> relationships, pass an arrayref
1585 of hashrefs containing the data for each of the rows to create in the foreign
1586 tables, again using the relationship name as the key.
1587
1588 Instead of hashrefs of plain related data (key/value pairs), you may
1589 also pass new or inserted objects. New objects (not inserted yet, see
1590 L</new>), will be inserted into their appropriate tables.
1591
1592 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
1593
1594 Example of creating a new row.
1595
1596   $person_rs->create({
1597     name=>"Some Person",
1598         email=>"somebody@someplace.com"
1599   });
1600   
1601 Example of creating a new row and also creating rows in a related C<has_many>
1602 or C<has_one> resultset.  Note Arrayref.
1603
1604   $artist_rs->create(
1605      { artistid => 4, name => 'Manufactured Crap', cds => [ 
1606         { title => 'My First CD', year => 2006 },
1607         { title => 'Yet More Tweeny-Pop crap', year => 2007 },
1608       ],
1609      },
1610   );
1611
1612 Example of creating a new row and also creating a row in a related
1613 C<belongs_to>resultset. Note Hashref.
1614
1615   $cd_rs->create({
1616     title=>"Music for Silly Walks",
1617         year=>2000,
1618         artist => {
1619           name=>"Silly Musician",
1620         }
1621   });
1622
1623 =cut
1624
1625 sub create {
1626   my ($self, $attrs) = @_;
1627   $self->throw_exception( "create needs a hashref" )
1628     unless ref $attrs eq 'HASH';
1629   return $self->new_result($attrs)->insert;
1630 }
1631
1632 =head2 find_or_create
1633
1634 =over 4
1635
1636 =item Arguments: \%vals, \%attrs?
1637
1638 =item Return Value: $object
1639
1640 =back
1641
1642   $class->find_or_create({ key => $val, ... });
1643
1644 Tries to find a record based on its primary key or unique constraint; if none
1645 is found, creates one and returns that instead.
1646
1647   my $cd = $schema->resultset('CD')->find_or_create({
1648     cdid   => 5,
1649     artist => 'Massive Attack',
1650     title  => 'Mezzanine',
1651     year   => 2005,
1652   });
1653
1654 Also takes an optional C<key> attribute, to search by a specific key or unique
1655 constraint. For example:
1656
1657   my $cd = $schema->resultset('CD')->find_or_create(
1658     {
1659       artist => 'Massive Attack',
1660       title  => 'Mezzanine',
1661     },
1662     { key => 'cd_artist_title' }
1663   );
1664
1665 See also L</find> and L</update_or_create>. For information on how to declare
1666 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1667
1668 =cut
1669
1670 sub find_or_create {
1671   my $self     = shift;
1672   my $attrs    = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1673   my $hash     = ref $_[0] eq 'HASH' ? shift : {@_};
1674   my $exists   = $self->find($hash, $attrs);
1675   return defined $exists ? $exists : $self->create($hash);
1676 }
1677
1678 =head2 update_or_create
1679
1680 =over 4
1681
1682 =item Arguments: \%col_values, { key => $unique_constraint }?
1683
1684 =item Return Value: $object
1685
1686 =back
1687
1688   $class->update_or_create({ col => $val, ... });
1689
1690 First, searches for an existing row matching one of the unique constraints
1691 (including the primary key) on the source of this resultset. If a row is
1692 found, updates it with the other given column values. Otherwise, creates a new
1693 row.
1694
1695 Takes an optional C<key> attribute to search on a specific unique constraint.
1696 For example:
1697
1698   # In your application
1699   my $cd = $schema->resultset('CD')->update_or_create(
1700     {
1701       artist => 'Massive Attack',
1702       title  => 'Mezzanine',
1703       year   => 1998,
1704     },
1705     { key => 'cd_artist_title' }
1706   );
1707
1708 If no C<key> is specified, it searches on all unique constraints defined on the
1709 source, including the primary key.
1710
1711 If the C<key> is specified as C<primary>, it searches only on the primary key.
1712
1713 See also L</find> and L</find_or_create>. For information on how to declare
1714 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1715
1716 =cut
1717
1718 sub update_or_create {
1719   my $self = shift;
1720   my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1721   my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
1722
1723   my $row = $self->find($cond, $attrs);
1724   if (defined $row) {
1725     $row->update($cond);
1726     return $row;
1727   }
1728
1729   return $self->create($cond);
1730 }
1731
1732 =head2 get_cache
1733
1734 =over 4
1735
1736 =item Arguments: none
1737
1738 =item Return Value: \@cache_objects?
1739
1740 =back
1741
1742 Gets the contents of the cache for the resultset, if the cache is set.
1743
1744 =cut
1745
1746 sub get_cache {
1747   shift->{all_cache};
1748 }
1749
1750 =head2 set_cache
1751
1752 =over 4
1753
1754 =item Arguments: \@cache_objects
1755
1756 =item Return Value: \@cache_objects
1757
1758 =back
1759
1760 Sets the contents of the cache for the resultset. Expects an arrayref
1761 of objects of the same class as those produced by the resultset. Note that
1762 if the cache is set the resultset will return the cached objects rather
1763 than re-querying the database even if the cache attr is not set.
1764
1765 =cut
1766
1767 sub set_cache {
1768   my ( $self, $data ) = @_;
1769   $self->throw_exception("set_cache requires an arrayref")
1770       if defined($data) && (ref $data ne 'ARRAY');
1771   $self->{all_cache} = $data;
1772 }
1773
1774 =head2 clear_cache
1775
1776 =over 4
1777
1778 =item Arguments: none
1779
1780 =item Return Value: []
1781
1782 =back
1783
1784 Clears the cache for the resultset.
1785
1786 =cut
1787
1788 sub clear_cache {
1789   shift->set_cache(undef);
1790 }
1791
1792 =head2 related_resultset
1793
1794 =over 4
1795
1796 =item Arguments: $relationship_name
1797
1798 =item Return Value: $resultset
1799
1800 =back
1801
1802 Returns a related resultset for the supplied relationship name.
1803
1804   $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1805
1806 =cut
1807
1808 sub related_resultset {
1809   my ($self, $rel) = @_;
1810
1811   $self->{related_resultsets} ||= {};
1812   return $self->{related_resultsets}{$rel} ||= do {
1813     my $rel_obj = $self->result_source->relationship_info($rel);
1814
1815     $self->throw_exception(
1816       "search_related: result source '" . $self->result_source->source_name .
1817         "' has no such relationship $rel")
1818       unless $rel_obj;
1819     
1820     my ($from,$seen) = $self->_resolve_from($rel);
1821
1822     my $join_count = $seen->{$rel};
1823     my $alias = ($join_count > 1 ? join('_', $rel, $join_count) : $rel);
1824
1825     #XXX - temp fix for result_class bug. There likely is a more elegant fix -groditi
1826     my %attrs = %{$self->{attrs}||{}};
1827     delete @attrs{qw(result_class alias)};
1828
1829     my $new_cache;
1830
1831     if (my $cache = $self->get_cache) {
1832       if ($cache->[0] && $cache->[0]->related_resultset($rel)->get_cache) {
1833         $new_cache = [ map { @{$_->related_resultset($rel)->get_cache} }
1834                         @$cache ];
1835       }
1836     }
1837
1838     my $rel_source = $self->result_source->related_source($rel);
1839
1840     my $new = do {
1841
1842       # The reason we do this now instead of passing the alias to the
1843       # search_rs below is that if you wrap/overload resultset on the
1844       # source you need to know what alias it's -going- to have for things
1845       # to work sanely (e.g. RestrictWithObject wants to be able to add
1846       # extra query restrictions, and these may need to be $alias.)
1847
1848       my $attrs = $rel_source->resultset_attributes;
1849       local $attrs->{alias} = $alias;
1850
1851       $rel_source->resultset
1852                  ->search_rs(
1853                      undef, {
1854                        %attrs,
1855                        join => undef,
1856                        prefetch => undef,
1857                        select => undef,
1858                        as => undef,
1859                        where => $self->{cond},
1860                        seen_join => $seen,
1861                        from => $from,
1862                    });
1863     };
1864     $new->set_cache($new_cache) if $new_cache;
1865     $new;
1866   };
1867 }
1868
1869 sub _resolve_from {
1870   my ($self, $extra_join) = @_;
1871   my $source = $self->result_source;
1872   my $attrs = $self->{attrs};
1873   
1874   my $from = $attrs->{from}
1875     || [ { $attrs->{alias} => $source->from } ];
1876     
1877   my $seen = { %{$attrs->{seen_join}||{}} };
1878
1879   my $join = ($attrs->{join}
1880                ? [ $attrs->{join}, $extra_join ]
1881                : $extra_join);
1882
1883   # we need to take the prefetch the attrs into account before we 
1884   # ->resolve_join as otherwise they get lost - captainL
1885   my $merged = $self->_merge_attr( $join, $attrs->{prefetch} );
1886
1887   $from = [
1888     @$from,
1889     ($join ? $source->resolve_join($merged, $attrs->{alias}, $seen) : ()),
1890   ];
1891
1892   return ($from,$seen);
1893 }
1894
1895 sub _resolved_attrs {
1896   my $self = shift;
1897   return $self->{_attrs} if $self->{_attrs};
1898
1899   my $attrs = { %{$self->{attrs}||{}} };
1900   my $source = $self->result_source;
1901   my $alias = $attrs->{alias};
1902
1903   $attrs->{columns} ||= delete $attrs->{cols} if exists $attrs->{cols};
1904   if ($attrs->{columns}) {
1905     delete $attrs->{as};
1906   } elsif (!$attrs->{select}) {
1907     $attrs->{columns} = [ $source->columns ];
1908   }
1909  
1910   $attrs->{select} = 
1911     ($attrs->{select}
1912       ? (ref $attrs->{select} eq 'ARRAY'
1913           ? [ @{$attrs->{select}} ]
1914           : [ $attrs->{select} ])
1915       : [ map { m/\./ ? $_ : "${alias}.$_" } @{delete $attrs->{columns}} ]
1916     );
1917   $attrs->{as} =
1918     ($attrs->{as}
1919       ? (ref $attrs->{as} eq 'ARRAY'
1920           ? [ @{$attrs->{as}} ]
1921           : [ $attrs->{as} ])
1922       : [ map { m/^\Q${alias}.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}} ]
1923     );
1924   
1925   my $adds;
1926   if ($adds = delete $attrs->{include_columns}) {
1927     $adds = [$adds] unless ref $adds eq 'ARRAY';
1928     push(@{$attrs->{select}}, @$adds);
1929     push(@{$attrs->{as}}, map { m/([^.]+)$/; $1 } @$adds);
1930   }
1931   if ($adds = delete $attrs->{'+select'}) {
1932     $adds = [$adds] unless ref $adds eq 'ARRAY';
1933     push(@{$attrs->{select}},
1934            map { /\./ || ref $_ ? $_ : "${alias}.$_" } @$adds);
1935   }
1936   if (my $adds = delete $attrs->{'+as'}) {
1937     $adds = [$adds] unless ref $adds eq 'ARRAY';
1938     push(@{$attrs->{as}}, @$adds);
1939   }
1940
1941   $attrs->{from} ||= [ { 'me' => $source->from } ];
1942
1943   if (exists $attrs->{join} || exists $attrs->{prefetch}) {
1944     my $join = delete $attrs->{join} || {};
1945
1946     if (defined $attrs->{prefetch}) {
1947       $join = $self->_merge_attr(
1948         $join, $attrs->{prefetch}
1949       );
1950       
1951     }
1952
1953     $attrs->{from} =   # have to copy here to avoid corrupting the original
1954       [
1955         @{$attrs->{from}}, 
1956         $source->resolve_join($join, $alias, { %{$attrs->{seen_join}||{}} })
1957       ];
1958
1959   }
1960
1961   $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
1962   if ($attrs->{order_by}) {
1963     $attrs->{order_by} = (ref($attrs->{order_by}) eq 'ARRAY'
1964                            ? [ @{$attrs->{order_by}} ]
1965                            : [ $attrs->{order_by} ]);
1966   } else {
1967     $attrs->{order_by} = [];    
1968   }
1969
1970   my $collapse = $attrs->{collapse} || {};
1971   if (my $prefetch = delete $attrs->{prefetch}) {
1972     $prefetch = $self->_merge_attr({}, $prefetch);
1973     my @pre_order;
1974     my $seen = $attrs->{seen_join} || {};
1975     foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
1976       # bring joins back to level of current class
1977       my @prefetch = $source->resolve_prefetch(
1978         $p, $alias, $seen, \@pre_order, $collapse
1979       );
1980       push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
1981       push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
1982     }
1983     push(@{$attrs->{order_by}}, @pre_order);
1984   }
1985   $attrs->{collapse} = $collapse;
1986
1987   if ($attrs->{page}) {
1988     $attrs->{offset} ||= 0;
1989     $attrs->{offset} += ($attrs->{rows} * ($attrs->{page} - 1));
1990   }
1991
1992   return $self->{_attrs} = $attrs;
1993 }
1994
1995 sub _rollout_attr {
1996   my ($self, $attr) = @_;
1997   
1998   if (ref $attr eq 'HASH') {
1999     return $self->_rollout_hash($attr);
2000   } elsif (ref $attr eq 'ARRAY') {
2001     return $self->_rollout_array($attr);
2002   } else {
2003     return [$attr];
2004   }
2005 }
2006
2007 sub _rollout_array {
2008   my ($self, $attr) = @_;
2009
2010   my @rolled_array;
2011   foreach my $element (@{$attr}) {
2012     if (ref $element eq 'HASH') {
2013       push( @rolled_array, @{ $self->_rollout_hash( $element ) } );
2014     } elsif (ref $element eq 'ARRAY') {
2015       #  XXX - should probably recurse here
2016       push( @rolled_array, @{$self->_rollout_array($element)} );
2017     } else {
2018       push( @rolled_array, $element );
2019     }
2020   }
2021   return \@rolled_array;
2022 }
2023
2024 sub _rollout_hash {
2025   my ($self, $attr) = @_;
2026
2027   my @rolled_array;
2028   foreach my $key (keys %{$attr}) {
2029     push( @rolled_array, { $key => $attr->{$key} } );
2030   }
2031   return \@rolled_array;
2032 }
2033
2034 sub _calculate_score {
2035   my ($self, $a, $b) = @_;
2036
2037   if (ref $b eq 'HASH') {
2038     my ($b_key) = keys %{$b};
2039     if (ref $a eq 'HASH') {
2040       my ($a_key) = keys %{$a};
2041       if ($a_key eq $b_key) {
2042         return (1 + $self->_calculate_score( $a->{$a_key}, $b->{$b_key} ));
2043       } else {
2044         return 0;
2045       }
2046     } else {
2047       return ($a eq $b_key) ? 1 : 0;
2048     }       
2049   } else {
2050     if (ref $a eq 'HASH') {
2051       my ($a_key) = keys %{$a};
2052       return ($b eq $a_key) ? 1 : 0;
2053     } else {
2054       return ($b eq $a) ? 1 : 0;
2055     }
2056   }
2057 }
2058
2059 sub _merge_attr {
2060   my ($self, $a, $b) = @_;
2061
2062   return $b unless defined($a);
2063   return $a unless defined($b);
2064   
2065   $a = $self->_rollout_attr($a);
2066   $b = $self->_rollout_attr($b);
2067
2068   my $seen_keys;
2069   foreach my $b_element ( @{$b} ) {
2070     # find best candidate from $a to merge $b_element into
2071     my $best_candidate = { position => undef, score => 0 }; my $position = 0;
2072     foreach my $a_element ( @{$a} ) {
2073       my $score = $self->_calculate_score( $a_element, $b_element );
2074       if ($score > $best_candidate->{score}) {
2075         $best_candidate->{position} = $position;
2076         $best_candidate->{score} = $score;
2077       }
2078       $position++;
2079     }
2080     my ($b_key) = ( ref $b_element eq 'HASH' ) ? keys %{$b_element} : ($b_element);
2081     if ($best_candidate->{score} == 0 || exists $seen_keys->{$b_key}) {
2082       push( @{$a}, $b_element );
2083     } else {
2084       $seen_keys->{$b_key} = 1; # don't merge the same key twice
2085       my $a_best = $a->[$best_candidate->{position}];
2086       # merge a_best and b_element together and replace original with merged
2087       if (ref $a_best ne 'HASH') {
2088         $a->[$best_candidate->{position}] = $b_element;
2089       } elsif (ref $b_element eq 'HASH') {
2090         my ($key) = keys %{$a_best};
2091         $a->[$best_candidate->{position}] = { $key => $self->_merge_attr($a_best->{$key}, $b_element->{$key}) };
2092       }
2093     }
2094   }
2095
2096   return $a;
2097 }
2098
2099 sub result_source {
2100     my $self = shift;
2101
2102     if (@_) {
2103         $self->_source_handle($_[0]->handle);
2104     } else {
2105         $self->_source_handle->resolve;
2106     }
2107 }
2108
2109 =head2 throw_exception
2110
2111 See L<DBIx::Class::Schema/throw_exception> for details.
2112
2113 =cut
2114
2115 sub throw_exception {
2116   my $self=shift;
2117   $self->_source_handle->schema->throw_exception(@_);
2118 }
2119
2120 # XXX: FIXME: Attributes docs need clearing up
2121
2122 =head1 ATTRIBUTES
2123
2124 The resultset takes various attributes that modify its behavior. Here's an
2125 overview of them:
2126
2127 =head2 order_by
2128
2129 =over 4
2130
2131 =item Value: ($order_by | \@order_by)
2132
2133 =back
2134
2135 Which column(s) to order the results by. This is currently passed
2136 through directly to SQL, so you can give e.g. C<year DESC> for a
2137 descending order on the column `year'.
2138
2139 Please note that if you have C<quote_char> enabled (see
2140 L<DBIx::Class::Storage::DBI/connect_info>) you will need to do C<\'year DESC' > to
2141 specify an order. (The scalar ref causes it to be passed as raw sql to the DB,
2142 so you will need to manually quote things as appropriate.)
2143
2144 =head2 columns
2145
2146 =over 4
2147
2148 =item Value: \@columns
2149
2150 =back
2151
2152 Shortcut to request a particular set of columns to be retrieved.  Adds
2153 C<me.> onto the start of any column without a C<.> in it and sets C<select>
2154 from that, then auto-populates C<as> from C<select> as normal. (You may also
2155 use the C<cols> attribute, as in earlier versions of DBIC.)
2156
2157 =head2 include_columns
2158
2159 =over 4
2160
2161 =item Value: \@columns
2162
2163 =back
2164
2165 Shortcut to include additional columns in the returned results - for example
2166
2167   $schema->resultset('CD')->search(undef, {
2168     include_columns => ['artist.name'],
2169     join => ['artist']
2170   });
2171
2172 would return all CDs and include a 'name' column to the information
2173 passed to object inflation. Note that the 'artist' is the name of the
2174 column (or relationship) accessor, and 'name' is the name of the column
2175 accessor in the related table.
2176
2177 =head2 select
2178
2179 =over 4
2180
2181 =item Value: \@select_columns
2182
2183 =back
2184
2185 Indicates which columns should be selected from the storage. You can use
2186 column names, or in the case of RDBMS back ends, function or stored procedure
2187 names:
2188
2189   $rs = $schema->resultset('Employee')->search(undef, {
2190     select => [
2191       'name',
2192       { count => 'employeeid' },
2193       { sum => 'salary' }
2194     ]
2195   });
2196
2197 When you use function/stored procedure names and do not supply an C<as>
2198 attribute, the column names returned are storage-dependent. E.g. MySQL would
2199 return a column named C<count(employeeid)> in the above example.
2200
2201 =head2 +select
2202
2203 =over 4
2204
2205 Indicates additional columns to be selected from storage.  Works the same as
2206 L<select> but adds columns to the selection.
2207
2208 =back
2209
2210 =head2 +as
2211
2212 =over 4
2213
2214 Indicates additional column names for those added via L<+select>.
2215
2216 =back
2217
2218 =head2 as
2219
2220 =over 4
2221
2222 =item Value: \@inflation_names
2223
2224 =back
2225
2226 Indicates column names for object inflation. That is, C<as>
2227 indicates the name that the column can be accessed as via the
2228 C<get_column> method (or via the object accessor, B<if one already
2229 exists>).  It has nothing to do with the SQL code C<SELECT foo AS bar>.
2230
2231 The C<as> attribute is used in conjunction with C<select>,
2232 usually when C<select> contains one or more function or stored
2233 procedure names:
2234
2235   $rs = $schema->resultset('Employee')->search(undef, {
2236     select => [
2237       'name',
2238       { count => 'employeeid' }
2239     ],
2240     as => ['name', 'employee_count'],
2241   });
2242
2243   my $employee = $rs->first(); # get the first Employee
2244
2245 If the object against which the search is performed already has an accessor
2246 matching a column name specified in C<as>, the value can be retrieved using
2247 the accessor as normal:
2248
2249   my $name = $employee->name();
2250
2251 If on the other hand an accessor does not exist in the object, you need to
2252 use C<get_column> instead:
2253
2254   my $employee_count = $employee->get_column('employee_count');
2255
2256 You can create your own accessors if required - see
2257 L<DBIx::Class::Manual::Cookbook> for details.
2258
2259 Please note: This will NOT insert an C<AS employee_count> into the SQL
2260 statement produced, it is used for internal access only. Thus
2261 attempting to use the accessor in an C<order_by> clause or similar
2262 will fail miserably.
2263
2264 To get around this limitation, you can supply literal SQL to your
2265 C<select> attibute that contains the C<AS alias> text, eg:
2266
2267   select => [\'myfield AS alias']
2268
2269 =head2 join
2270
2271 =over 4
2272
2273 =item Value: ($rel_name | \@rel_names | \%rel_names)
2274
2275 =back
2276
2277 Contains a list of relationships that should be joined for this query.  For
2278 example:
2279
2280   # Get CDs by Nine Inch Nails
2281   my $rs = $schema->resultset('CD')->search(
2282     { 'artist.name' => 'Nine Inch Nails' },
2283     { join => 'artist' }
2284   );
2285
2286 Can also contain a hash reference to refer to the other relation's relations.
2287 For example:
2288
2289   package MyApp::Schema::Track;
2290   use base qw/DBIx::Class/;
2291   __PACKAGE__->table('track');
2292   __PACKAGE__->add_columns(qw/trackid cd position title/);
2293   __PACKAGE__->set_primary_key('trackid');
2294   __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
2295   1;
2296
2297   # In your application
2298   my $rs = $schema->resultset('Artist')->search(
2299     { 'track.title' => 'Teardrop' },
2300     {
2301       join     => { cd => 'track' },
2302       order_by => 'artist.name',
2303     }
2304   );
2305
2306 You need to use the relationship (not the table) name in  conditions, 
2307 because they are aliased as such. The current table is aliased as "me", so 
2308 you need to use me.column_name in order to avoid ambiguity. For example:
2309
2310   # Get CDs from 1984 with a 'Foo' track 
2311   my $rs = $schema->resultset('CD')->search(
2312     { 
2313       'me.year' => 1984,
2314       'tracks.name' => 'Foo'
2315     },
2316     { join => 'tracks' }
2317   );
2318   
2319 If the same join is supplied twice, it will be aliased to <rel>_2 (and
2320 similarly for a third time). For e.g.
2321
2322   my $rs = $schema->resultset('Artist')->search({
2323     'cds.title'   => 'Down to Earth',
2324     'cds_2.title' => 'Popular',
2325   }, {
2326     join => [ qw/cds cds/ ],
2327   });
2328
2329 will return a set of all artists that have both a cd with title 'Down
2330 to Earth' and a cd with title 'Popular'.
2331
2332 If you want to fetch related objects from other tables as well, see C<prefetch>
2333 below.
2334
2335 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
2336 =head2 prefetch
2337
2338 =over 4
2339
2340 =item Value: ($rel_name | \@rel_names | \%rel_names)
2341
2342 =back
2343
2344 Contains one or more relationships that should be fetched along with
2345 the main query (when they are accessed afterwards the data will
2346 already be available, without extra queries to the database).  This is
2347 useful for when you know you will need the related objects, because it
2348 saves at least one query:
2349
2350   my $rs = $schema->resultset('Tag')->search(
2351     undef,
2352     {
2353       prefetch => {
2354         cd => 'artist'
2355       }
2356     }
2357   );
2358
2359 The initial search results in SQL like the following:
2360
2361   SELECT tag.*, cd.*, artist.* FROM tag
2362   JOIN cd ON tag.cd = cd.cdid
2363   JOIN artist ON cd.artist = artist.artistid
2364
2365 L<DBIx::Class> has no need to go back to the database when we access the
2366 C<cd> or C<artist> relationships, which saves us two SQL statements in this
2367 case.
2368
2369 Simple prefetches will be joined automatically, so there is no need
2370 for a C<join> attribute in the above search. If you're prefetching to
2371 depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
2372 specify the join as well.
2373
2374 C<prefetch> can be used with the following relationship types: C<belongs_to>,
2375 C<has_one> (or if you're using C<add_relationship>, any relationship declared
2376 with an accessor type of 'single' or 'filter').
2377
2378 =head2 page
2379
2380 =over 4
2381
2382 =item Value: $page
2383
2384 =back
2385
2386 Makes the resultset paged and specifies the page to retrieve. Effectively
2387 identical to creating a non-pages resultset and then calling ->page($page)
2388 on it.
2389
2390 If L<rows> attribute is not specified it defualts to 10 rows per page.
2391
2392 =head2 rows
2393
2394 =over 4
2395
2396 =item Value: $rows
2397
2398 =back
2399
2400 Specifes the maximum number of rows for direct retrieval or the number of
2401 rows per page if the page attribute or method is used.
2402
2403 =head2 offset
2404
2405 =over 4
2406
2407 =item Value: $offset
2408
2409 =back
2410
2411 Specifies the (zero-based) row number for the  first row to be returned, or the
2412 of the first row of the first page if paging is used.
2413
2414 =head2 group_by
2415
2416 =over 4
2417
2418 =item Value: \@columns
2419
2420 =back
2421
2422 A arrayref of columns to group by. Can include columns of joined tables.
2423
2424   group_by => [qw/ column1 column2 ... /]
2425
2426 =head2 having
2427
2428 =over 4
2429
2430 =item Value: $condition
2431
2432 =back
2433
2434 HAVING is a select statement attribute that is applied between GROUP BY and
2435 ORDER BY. It is applied to the after the grouping calculations have been
2436 done.
2437
2438   having => { 'count(employee)' => { '>=', 100 } }
2439
2440 =head2 distinct
2441
2442 =over 4
2443
2444 =item Value: (0 | 1)
2445
2446 =back
2447
2448 Set to 1 to group by all columns.
2449
2450 =head2 where
2451
2452 =over 4
2453
2454 Adds to the WHERE clause.
2455
2456   # only return rows WHERE deleted IS NULL for all searches
2457   __PACKAGE__->resultset_attributes({ where => { deleted => undef } }); )
2458
2459 Can be overridden by passing C<{ where => undef }> as an attribute
2460 to a resulset.
2461
2462 =back
2463
2464 =head2 cache
2465
2466 Set to 1 to cache search results. This prevents extra SQL queries if you
2467 revisit rows in your ResultSet:
2468
2469   my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
2470
2471   while( my $artist = $resultset->next ) {
2472     ... do stuff ...
2473   }
2474
2475   $rs->first; # without cache, this would issue a query
2476
2477 By default, searches are not cached.
2478
2479 For more examples of using these attributes, see
2480 L<DBIx::Class::Manual::Cookbook>.
2481
2482 =head2 from
2483
2484 =over 4
2485
2486 =item Value: \@from_clause
2487
2488 =back
2489
2490 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
2491 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
2492 clauses.
2493
2494 NOTE: Use this on your own risk.  This allows you to shoot off your foot!
2495
2496 C<join> will usually do what you need and it is strongly recommended that you
2497 avoid using C<from> unless you cannot achieve the desired result using C<join>.
2498 And we really do mean "cannot", not just tried and failed. Attempting to use
2499 this because you're having problems with C<join> is like trying to use x86
2500 ASM because you've got a syntax error in your C. Trust us on this.
2501
2502 Now, if you're still really, really sure you need to use this (and if you're
2503 not 100% sure, ask the mailing list first), here's an explanation of how this
2504 works.
2505
2506 The syntax is as follows -
2507
2508   [
2509     { <alias1> => <table1> },
2510     [
2511       { <alias2> => <table2>, -join_type => 'inner|left|right' },
2512       [], # nested JOIN (optional)
2513       { <table1.column1> => <table2.column2>, ... (more conditions) },
2514     ],
2515     # More of the above [ ] may follow for additional joins
2516   ]
2517
2518   <table1> <alias1>
2519   JOIN
2520     <table2> <alias2>
2521     [JOIN ...]
2522   ON <table1.column1> = <table2.column2>
2523   <more joins may follow>
2524
2525 An easy way to follow the examples below is to remember the following:
2526
2527     Anything inside "[]" is a JOIN
2528     Anything inside "{}" is a condition for the enclosing JOIN
2529
2530 The following examples utilize a "person" table in a family tree application.
2531 In order to express parent->child relationships, this table is self-joined:
2532
2533     # Person->belongs_to('father' => 'Person');
2534     # Person->belongs_to('mother' => 'Person');
2535
2536 C<from> can be used to nest joins. Here we return all children with a father,
2537 then search against all mothers of those children:
2538
2539   $rs = $schema->resultset('Person')->search(
2540       undef,
2541       {
2542           alias => 'mother', # alias columns in accordance with "from"
2543           from => [
2544               { mother => 'person' },
2545               [
2546                   [
2547                       { child => 'person' },
2548                       [
2549                           { father => 'person' },
2550                           { 'father.person_id' => 'child.father_id' }
2551                       ]
2552                   ],
2553                   { 'mother.person_id' => 'child.mother_id' }
2554               ],
2555           ]
2556       },
2557   );
2558
2559   # Equivalent SQL:
2560   # SELECT mother.* FROM person mother
2561   # JOIN (
2562   #   person child
2563   #   JOIN person father
2564   #   ON ( father.person_id = child.father_id )
2565   # )
2566   # ON ( mother.person_id = child.mother_id )
2567
2568 The type of any join can be controlled manually. To search against only people
2569 with a father in the person table, we could explicitly use C<INNER JOIN>:
2570
2571     $rs = $schema->resultset('Person')->search(
2572         undef,
2573         {
2574             alias => 'child', # alias columns in accordance with "from"
2575             from => [
2576                 { child => 'person' },
2577                 [
2578                     { father => 'person', -join_type => 'inner' },
2579                     { 'father.id' => 'child.father_id' }
2580                 ],
2581             ]
2582         },
2583     );
2584
2585     # Equivalent SQL:
2586     # SELECT child.* FROM person child
2587     # INNER JOIN person father ON child.father_id = father.id
2588
2589 =cut
2590
2591 1;