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