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