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