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