Reduce warnings introduced in 450e6dbf to one per callsite
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultSet.pm
1 package DBIx::Class::ResultSet;
2
3 use strict;
4 use warnings;
5 use base qw/DBIx::Class/;
6 use Carp::Clan qw/^DBIx::Class/;
7 use DBIx::Class::Exception;
8 use Data::Page;
9 use Storable;
10 use DBIx::Class::ResultSetColumn;
11 use DBIx::Class::ResultSourceHandle;
12 use Hash::Merge ();
13 use Scalar::Util qw/blessed weaken/;
14 use Try::Tiny;
15 use Storable qw/nfreeze thaw/;
16
17 # not importing first() as it will clash with our own method
18 use List::Util ();
19
20 use namespace::clean;
21
22
23 BEGIN {
24   # De-duplication in _merge_attr() is disabled, but left in for reference
25   *__HM_DEDUP = sub () { 0 };
26 }
27
28 use overload
29         '0+'     => "count",
30         'bool'   => "_bool",
31         fallback => 1;
32
33 __PACKAGE__->mk_group_accessors('simple' => qw/_result_class _source_handle/);
34
35 =head1 NAME
36
37 DBIx::Class::ResultSet - Represents a query used for fetching a set of results.
38
39 =head1 SYNOPSIS
40
41   my $users_rs   = $schema->resultset('User');
42   while( $user = $users_rs->next) {
43     print $user->username;
44   }
45
46   my $registered_users_rs   = $schema->resultset('User')->search({ registered => 1 });
47   my @cds_in_2005 = $schema->resultset('CD')->search({ year => 2005 })->all();
48
49 =head1 DESCRIPTION
50
51 A ResultSet is an object which stores a set of conditions representing
52 a query. It is the backbone of DBIx::Class (i.e. the really
53 important/useful bit).
54
55 No SQL is executed on the database when a ResultSet is created, it
56 just stores all the conditions needed to create the query.
57
58 A basic ResultSet representing the data of an entire table is returned
59 by calling C<resultset> on a L<DBIx::Class::Schema> and passing in a
60 L<Source|DBIx::Class::Manual::Glossary/Source> name.
61
62   my $users_rs = $schema->resultset('User');
63
64 A new ResultSet is returned from calling L</search> on an existing
65 ResultSet. The new one will contain all the conditions of the
66 original, plus any new conditions added in the C<search> call.
67
68 A ResultSet also incorporates an implicit iterator. L</next> and L</reset>
69 can be used to walk through all the L<DBIx::Class::Row>s the ResultSet
70 represents.
71
72 The query that the ResultSet represents is B<only> executed against
73 the database when these methods are called:
74 L</find>, L</next>, L</all>, L</first>, L</single>, L</count>.
75
76 If a resultset is used in a numeric context it returns the L</count>.
77 However, if it is used in a boolean context it is B<always> true.  So if
78 you want to check if a resultset has any results, you must use C<if $rs
79 != 0>.
80
81 =head1 EXAMPLES
82
83 =head2 Chaining resultsets
84
85 Let's say you've got a query that needs to be run to return some data
86 to the user. But, you have an authorization system in place that
87 prevents certain users from seeing certain information. So, you want
88 to construct the basic query in one method, but add constraints to it in
89 another.
90
91   sub get_data {
92     my $self = shift;
93     my $request = $self->get_request; # Get a request object somehow.
94     my $schema = $self->get_schema;   # Get the DBIC schema object somehow.
95
96     my $cd_rs = $schema->resultset('CD')->search({
97       title => $request->param('title'),
98       year => $request->param('year'),
99     });
100
101     $self->apply_security_policy( $cd_rs );
102
103     return $cd_rs->all();
104   }
105
106   sub apply_security_policy {
107     my $self = shift;
108     my ($rs) = @_;
109
110     return $rs->search({
111       subversive => 0,
112     });
113   }
114
115 =head3 Resolving conditions and attributes
116
117 When a resultset is chained from another resultset, conditions and
118 attributes with the same keys need resolving.
119
120 L</join>, L</prefetch>, L</+select>, L</+as> attributes are merged
121 into the existing ones from the original resultset.
122
123 The L</where> and L</having> attributes, and any search conditions, are
124 merged with an SQL C<AND> to the existing condition from the original
125 resultset.
126
127 All other attributes are overridden by any new ones supplied in the
128 search attributes.
129
130 =head2 Multiple queries
131
132 Since a resultset just defines a query, you can do all sorts of
133 things with it with the same object.
134
135   # Don't hit the DB yet.
136   my $cd_rs = $schema->resultset('CD')->search({
137     title => 'something',
138     year => 2009,
139   });
140
141   # Each of these hits the DB individually.
142   my $count = $cd_rs->count;
143   my $most_recent = $cd_rs->get_column('date_released')->max();
144   my @records = $cd_rs->all;
145
146 And it's not just limited to SELECT statements.
147
148   $cd_rs->delete();
149
150 This is even cooler:
151
152   $cd_rs->create({ artist => 'Fred' });
153
154 Which is the same as:
155
156   $schema->resultset('CD')->create({
157     title => 'something',
158     year => 2009,
159     artist => 'Fred'
160   });
161
162 See: L</search>, L</count>, L</get_column>, L</all>, L</create>.
163
164 =head1 METHODS
165
166 =head2 new
167
168 =over 4
169
170 =item Arguments: $source, \%$attrs
171
172 =item Return Value: $rs
173
174 =back
175
176 The resultset constructor. Takes a source object (usually a
177 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
178 L</ATTRIBUTES> below).  Does not perform any queries -- these are
179 executed as needed by the other methods.
180
181 Generally you won't need to construct a resultset manually.  You'll
182 automatically get one from e.g. a L</search> called in scalar context:
183
184   my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
185
186 IMPORTANT: If called on an object, proxies to new_result instead so
187
188   my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
189
190 will return a CD object, not a ResultSet.
191
192 =cut
193
194 sub new {
195   my $class = shift;
196   return $class->new_result(@_) if ref $class;
197
198   my ($source, $attrs) = @_;
199   $source = $source->handle
200     unless $source->isa('DBIx::Class::ResultSourceHandle');
201   $attrs = { %{$attrs||{}} };
202
203   if ($attrs->{page}) {
204     $attrs->{rows} ||= 10;
205   }
206
207   $attrs->{alias} ||= 'me';
208
209   # Creation of {} and bless separated to mitigate RH perl bug
210   # see https://bugzilla.redhat.com/show_bug.cgi?id=196836
211   my $self = {
212     _source_handle => $source,
213     cond => $attrs->{where},
214     pager => undef,
215     attrs => $attrs
216   };
217
218   bless $self, $class;
219
220   $self->result_class(
221     $attrs->{result_class} || $source->resolve->result_class
222   );
223
224   return $self;
225 }
226
227 =head2 search
228
229 =over 4
230
231 =item Arguments: $cond, \%attrs?
232
233 =item Return Value: $resultset (scalar context), @row_objs (list context)
234
235 =back
236
237   my @cds    = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
238   my $new_rs = $cd_rs->search({ year => 2005 });
239
240   my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
241                  # year = 2005 OR year = 2004
242
243 If you need to pass in additional attributes but no additional condition,
244 call it as C<search(undef, \%attrs)>.
245
246   # "SELECT name, artistid FROM $artist_table"
247   my @all_artists = $schema->resultset('Artist')->search(undef, {
248     columns => [qw/name artistid/],
249   });
250
251 For a list of attributes that can be passed to C<search>, see
252 L</ATTRIBUTES>. For more examples of using this function, see
253 L<Searching|DBIx::Class::Manual::Cookbook/Searching>. For a complete
254 documentation for the first argument, see L<SQL::Abstract>.
255
256 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
257
258 =head3 CAVEAT
259
260 Note that L</search> does not process/deflate any of the values passed in the
261 L<SQL::Abstract>-compatible search condition structure. This is unlike other
262 condition-bound methods L</new>, L</create> and L</find>. The user must ensure
263 manually that any value passed to this method will stringify to something the
264 RDBMS knows how to deal with. A notable example is the handling of L<DateTime>
265 objects, for more info see:
266 L<DBIx::Class::Manual::Cookbook/Formatting_DateTime_objects_in_queries>.
267
268 =cut
269
270 sub search {
271   my $self = shift;
272   my $rs = $self->search_rs( @_ );
273
274   if (wantarray) {
275     return $rs->all;
276   }
277   elsif (defined wantarray) {
278     return $rs;
279   }
280   else {
281     # we can be called by a relationship helper, which in
282     # turn may be called in void context due to some braindead
283     # overload or whatever else the user decided to be clever
284     # at this particular day. Thus limit the exception to
285     # external code calls only
286     $self->throw_exception ('->search is *not* a mutator, calling it in void context makes no sense')
287       if (caller)[0] !~ /^\QDBIx::Class::/;
288
289     return ();
290   }
291 }
292
293 =head2 search_rs
294
295 =over 4
296
297 =item Arguments: $cond, \%attrs?
298
299 =item Return Value: $resultset
300
301 =back
302
303 This method does the same exact thing as search() except it will
304 always return a resultset, even in list context.
305
306 =cut
307
308 my $callsites_warned;
309 sub search_rs {
310   my $self = shift;
311
312   # Special-case handling for (undef, undef).
313   if ( @_ == 2 && !defined $_[1] && !defined $_[0] ) {
314     @_ = ();
315   }
316
317   my $call_attrs = {};
318   $call_attrs = pop(@_) if (
319    @_ > 1 and ( ! defined $_[-1] or ref $_[-1] eq 'HASH' )
320   );
321
322   # see if we can keep the cache (no $rs changes)
323   my $cache;
324   my %safe = (alias => 1, cache => 1);
325   if ( ! List::Util::first { !$safe{$_} } keys %$call_attrs and (
326     ! defined $_[0]
327       or
328     ref $_[0] eq 'HASH' && ! keys %{$_[0]}
329       or
330     ref $_[0] eq 'ARRAY' && ! @{$_[0]}
331   )) {
332     $cache = $self->get_cache;
333   }
334
335   my $old_attrs = { %{$self->{attrs}} };
336   my $old_having = delete $old_attrs->{having};
337   my $old_where = delete $old_attrs->{where};
338
339   # reset the selector list
340   if (List::Util::first { exists $call_attrs->{$_} } qw{columns select as}) {
341      delete @{$old_attrs}{qw{select as columns +select +as +columns include_columns}};
342   }
343
344   my $new_attrs = { %{$old_attrs}, %{$call_attrs} };
345
346   # merge new attrs into inherited
347   foreach my $key (qw/join prefetch/) {
348     next unless exists $call_attrs->{$key};
349     $new_attrs->{$key} = $self->_merge_joinpref_attr($old_attrs->{$key}, $call_attrs->{$key});
350   }
351   foreach my $key (qw/+select +as +columns include_columns bind/) {
352     next unless exists $call_attrs->{$key};
353     $new_attrs->{$key} = $self->_merge_attr($old_attrs->{$key}, $call_attrs->{$key});
354   }
355
356   # rip apart the rest of @_, parse a condition
357   my $call_cond = do {
358
359     if (ref $_[0] eq 'HASH') {
360       (keys %{$_[0]}) ? $_[0] : undef
361     }
362     elsif (@_ == 1) {
363       $_[0]
364     }
365     elsif (@_ % 2) {
366       $self->throw_exception('Odd number of arguments to search')
367     }
368     else {
369       +{ @_ }
370     }
371
372   } if @_;
373
374   if( @_ > 1 and ! $self->result_source->result_class->isa('DBIx::Class::CDBICompat') ) {
375     # determine callsite obeying Carp::Clan rules (fucking ugly but don't have better ideas)
376     my $callsite = do {
377       my $w;
378       local $SIG{__WARN__} = sub { $w = shift };
379       carp;
380       $w
381     };
382     carp 'search( %condition ) is deprecated, use search( \%condition ) instead'
383       unless $callsites_warned->{$callsite}++;
384   }
385
386   for ($old_where, $call_cond) {
387     if (defined $_) {
388       $new_attrs->{where} = $self->_stack_cond (
389         $_, $new_attrs->{where}
390       );
391     }
392   }
393
394   if (defined $old_having) {
395     $new_attrs->{having} = $self->_stack_cond (
396       $old_having, $new_attrs->{having}
397     )
398   }
399
400   my $rs = (ref $self)->new($self->result_source, $new_attrs);
401
402   $rs->set_cache($cache) if ($cache);
403
404   return $rs;
405 }
406
407 sub _stack_cond {
408   my ($self, $left, $right) = @_;
409   if (defined $left xor defined $right) {
410     return defined $left ? $left : $right;
411   }
412   elsif (defined $left) {
413     return { -and => [ map
414       { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
415       ($left, $right)
416     ]};
417   }
418
419   return undef;
420 }
421
422 =head2 search_literal
423
424 =over 4
425
426 =item Arguments: $sql_fragment, @bind_values
427
428 =item Return Value: $resultset (scalar context), @row_objs (list context)
429
430 =back
431
432   my @cds   = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
433   my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
434
435 Pass a literal chunk of SQL to be added to the conditional part of the
436 resultset query.
437
438 CAVEAT: C<search_literal> is provided for Class::DBI compatibility and should
439 only be used in that context. C<search_literal> is a convenience method.
440 It is equivalent to calling $schema->search(\[]), but if you want to ensure
441 columns are bound correctly, use C<search>.
442
443 Example of how to use C<search> instead of C<search_literal>
444
445   my @cds = $cd_rs->search_literal('cdid = ? AND (artist = ? OR artist = ?)', (2, 1, 2));
446   my @cds = $cd_rs->search(\[ 'cdid = ? AND (artist = ? OR artist = ?)', [ 'cdid', 2 ], [ 'artist', 1 ], [ 'artist', 2 ] ]);
447
448
449 See L<DBIx::Class::Manual::Cookbook/Searching> and
450 L<DBIx::Class::Manual::FAQ/Searching> for searching techniques that do not
451 require C<search_literal>.
452
453 =cut
454
455 sub search_literal {
456   my ($self, $sql, @bind) = @_;
457   my $attr;
458   if ( @bind && ref($bind[-1]) eq 'HASH' ) {
459     $attr = pop @bind;
460   }
461   return $self->search(\[ $sql, map [ __DUMMY__ => $_ ], @bind ], ($attr || () ));
462 }
463
464 =head2 find
465
466 =over 4
467
468 =item Arguments: \%columns_values | @pk_values, \%attrs?
469
470 =item Return Value: $row_object | undef
471
472 =back
473
474 Finds and returns a single row based on supplied criteria. Takes either a
475 hashref with the same format as L</create> (including inference of foreign
476 keys from related objects), or a list of primary key values in the same
477 order as the L<primary columns|DBIx::Class::ResultSource/primary_columns>
478 declaration on the L</result_source>.
479
480 In either case an attempt is made to combine conditions already existing on
481 the resultset with the condition passed to this method.
482
483 To aid with preparing the correct query for the storage you may supply the
484 C<key> attribute, which is the name of a
485 L<unique constraint|DBIx::Class::ResultSource/add_unique_constraint> (the
486 unique constraint corresponding to the
487 L<primary columns|DBIx::Class::ResultSource/primary_columns> is always named
488 C<primary>). If the C<key> attribute has been supplied, and DBIC is unable
489 to construct a query that satisfies the named unique constraint fully (
490 non-NULL values for each column member of the constraint) an exception is
491 thrown.
492
493 If no C<key> is specified, the search is carried over all unique constraints
494 which are fully defined by the available condition.
495
496 If no such constraint is found, C<find> currently defaults to a simple
497 C<< search->(\%column_values) >> which may or may not do what you expect.
498 Note that this fallback behavior may be deprecated in further versions. If
499 you need to search with arbitrary conditions - use L</search>. If the query
500 resulting from this fallback produces more than one row, a warning to the
501 effect is issued, though only the first row is constructed and returned as
502 C<$row_object>.
503
504 In addition to C<key>, L</find> recognizes and applies standard
505 L<resultset attributes|/ATTRIBUTES> in the same way as L</search> does.
506
507 Note that if you have extra concerns about the correctness of the resulting
508 query you need to specify the C<key> attribute and supply the entire condition
509 as an argument to find (since it is not always possible to perform the
510 combination of the resultset condition with the supplied one, especially if
511 the resultset condition contains literal sql).
512
513 For example, to find a row by its primary key:
514
515   my $cd = $schema->resultset('CD')->find(5);
516
517 You can also find a row by a specific unique constraint:
518
519   my $cd = $schema->resultset('CD')->find(
520     {
521       artist => 'Massive Attack',
522       title  => 'Mezzanine',
523     },
524     { key => 'cd_artist_title' }
525   );
526
527 See also L</find_or_create> and L</update_or_create>.
528
529 =cut
530
531 sub find {
532   my $self = shift;
533   my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
534
535   my $rsrc = $self->result_source;
536
537   # Parse out the condition from input
538   my $call_cond;
539   if (ref $_[0] eq 'HASH') {
540     $call_cond = { %{$_[0]} };
541   }
542   else {
543     my $constraint = exists $attrs->{key} ? $attrs->{key} : 'primary';
544     my @c_cols = $rsrc->unique_constraint_columns($constraint);
545
546     $self->throw_exception(
547       "No constraint columns, maybe a malformed '$constraint' constraint?"
548     ) unless @c_cols;
549
550     $self->throw_exception (
551       'find() expects either a column/value hashref, or a list of values '
552     . "corresponding to the columns of the specified unique constraint '$constraint'"
553     ) unless @c_cols == @_;
554
555     $call_cond = {};
556     @{$call_cond}{@c_cols} = @_;
557   }
558
559   my %related;
560   for my $key (keys %$call_cond) {
561     if (
562       my $keyref = ref($call_cond->{$key})
563         and
564       my $relinfo = $rsrc->relationship_info($key)
565     ) {
566       my $val = delete $call_cond->{$key};
567
568       next if $keyref eq 'ARRAY'; # has_many for multi_create
569
570       my $rel_q = $rsrc->_resolve_condition(
571         $relinfo->{cond}, $val, $key
572       );
573       die "Can't handle complex relationship conditions in find" if ref($rel_q) ne 'HASH';
574       @related{keys %$rel_q} = values %$rel_q;
575     }
576   }
577
578   # relationship conditions take precedence (?)
579   @{$call_cond}{keys %related} = values %related;
580
581   my $alias = exists $attrs->{alias} ? $attrs->{alias} : $self->{attrs}{alias};
582   my $final_cond;
583   if (exists $attrs->{key}) {
584     $final_cond = $self->_qualify_cond_columns (
585
586       $self->_build_unique_cond (
587         $attrs->{key},
588         $call_cond,
589       ),
590
591       $alias,
592     );
593   }
594   elsif ($self->{attrs}{accessor} and $self->{attrs}{accessor} eq 'single') {
595     # This means that we got here after a merger of relationship conditions
596     # in ::Relationship::Base::search_related (the row method), and furthermore
597     # the relationship is of the 'single' type. This means that the condition
598     # provided by the relationship (already attached to $self) is sufficient,
599     # as there can be only one row in the database that would satisfy the
600     # relationship
601   }
602   else {
603     # no key was specified - fall down to heuristics mode:
604     # run through all unique queries registered on the resultset, and
605     # 'OR' all qualifying queries together
606     my (@unique_queries, %seen_column_combinations);
607     for my $c_name ($rsrc->unique_constraint_names) {
608       next if $seen_column_combinations{
609         join "\x00", sort $rsrc->unique_constraint_columns($c_name)
610       }++;
611
612       push @unique_queries, try {
613         $self->_build_unique_cond ($c_name, $call_cond)
614       } || ();
615     }
616
617     $final_cond = @unique_queries
618       ? [ map { $self->_qualify_cond_columns($_, $alias) } @unique_queries ]
619       : $self->_non_unique_find_fallback ($call_cond, $attrs)
620     ;
621   }
622
623   # Run the query, passing the result_class since it should propagate for find
624   my $rs = $self->search ($final_cond, {result_class => $self->result_class, %$attrs});
625   if (keys %{$rs->_resolved_attrs->{collapse}}) {
626     my $row = $rs->next;
627     carp "Query returned more than one row" if $rs->next;
628     return $row;
629   }
630   else {
631     return $rs->single;
632   }
633 }
634
635 # This is a stop-gap method as agreed during the discussion on find() cleanup:
636 # http://lists.scsys.co.uk/pipermail/dbix-class/2010-October/009535.html
637 #
638 # It is invoked when find() is called in legacy-mode with insufficiently-unique
639 # condition. It is provided for overrides until a saner way forward is devised
640 #
641 # *NOTE* This is not a public method, and it's *GUARANTEED* to disappear down
642 # the road. Please adjust your tests accordingly to catch this situation early
643 # DBIx::Class::ResultSet->can('_non_unique_find_fallback') is reasonable
644 #
645 # The method will not be removed without an adequately complete replacement
646 # for strict-mode enforcement
647 sub _non_unique_find_fallback {
648   my ($self, $cond, $attrs) = @_;
649
650   return $self->_qualify_cond_columns(
651     $cond,
652     exists $attrs->{alias}
653       ? $attrs->{alias}
654       : $self->{attrs}{alias}
655   );
656 }
657
658
659 sub _qualify_cond_columns {
660   my ($self, $cond, $alias) = @_;
661
662   my %aliased = %$cond;
663   for (keys %aliased) {
664     $aliased{"$alias.$_"} = delete $aliased{$_}
665       if $_ !~ /\./;
666   }
667
668   return \%aliased;
669 }
670
671 sub _build_unique_cond {
672   my ($self, $constraint_name, $extra_cond) = @_;
673
674   my @c_cols = $self->result_source->unique_constraint_columns($constraint_name);
675
676   # combination may fail if $self->{cond} is non-trivial
677   my ($final_cond) = try {
678     $self->_merge_with_rscond ($extra_cond)
679   } catch {
680     +{ %$extra_cond }
681   };
682
683   # trim out everything not in $columns
684   $final_cond = { map { $_ => $final_cond->{$_} } @c_cols };
685
686   if (my @missing = grep { ! defined $final_cond->{$_} } (@c_cols) ) {
687     $self->throw_exception( sprintf ( "Unable to satisfy requested constraint '%s', no values for column(s): %s",
688       $constraint_name,
689       join (', ', map { "'$_'" } @missing),
690     ) );
691   }
692
693   return $final_cond;
694 }
695
696 =head2 search_related
697
698 =over 4
699
700 =item Arguments: $rel, $cond, \%attrs?
701
702 =item Return Value: $new_resultset
703
704 =back
705
706   $new_rs = $cd_rs->search_related('artist', {
707     name => 'Emo-R-Us',
708   });
709
710 Searches the specified relationship, optionally specifying a condition and
711 attributes for matching records. See L</ATTRIBUTES> for more information.
712
713 =cut
714
715 sub search_related {
716   return shift->related_resultset(shift)->search(@_);
717 }
718
719 =head2 search_related_rs
720
721 This method works exactly the same as search_related, except that
722 it guarantees a resultset, even in list context.
723
724 =cut
725
726 sub search_related_rs {
727   return shift->related_resultset(shift)->search_rs(@_);
728 }
729
730 =head2 cursor
731
732 =over 4
733
734 =item Arguments: none
735
736 =item Return Value: $cursor
737
738 =back
739
740 Returns a storage-driven cursor to the given resultset. See
741 L<DBIx::Class::Cursor> for more information.
742
743 =cut
744
745 sub cursor {
746   my ($self) = @_;
747
748   my $attrs = $self->_resolved_attrs_copy;
749
750   return $self->{cursor}
751     ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
752           $attrs->{where},$attrs);
753 }
754
755 =head2 single
756
757 =over 4
758
759 =item Arguments: $cond?
760
761 =item Return Value: $row_object | undef
762
763 =back
764
765   my $cd = $schema->resultset('CD')->single({ year => 2001 });
766
767 Inflates the first result without creating a cursor if the resultset has
768 any records in it; if not returns C<undef>. Used by L</find> as a lean version
769 of L</search>.
770
771 While this method can take an optional search condition (just like L</search>)
772 being a fast-code-path it does not recognize search attributes. If you need to
773 add extra joins or similar, call L</search> and then chain-call L</single> on the
774 L<DBIx::Class::ResultSet> returned.
775
776 =over
777
778 =item B<Note>
779
780 As of 0.08100, this method enforces the assumption that the preceding
781 query returns only one row. If more than one row is returned, you will receive
782 a warning:
783
784   Query returned more than one row
785
786 In this case, you should be using L</next> or L</find> instead, or if you really
787 know what you are doing, use the L</rows> attribute to explicitly limit the size
788 of the resultset.
789
790 This method will also throw an exception if it is called on a resultset prefetching
791 has_many, as such a prefetch implies fetching multiple rows from the database in
792 order to assemble the resulting object.
793
794 =back
795
796 =cut
797
798 sub single {
799   my ($self, $where) = @_;
800   if(@_ > 2) {
801       $self->throw_exception('single() only takes search conditions, no attributes. You want ->search( $cond, $attrs )->single()');
802   }
803
804   my $attrs = $self->_resolved_attrs_copy;
805
806   if (keys %{$attrs->{collapse}}) {
807     $self->throw_exception(
808       'single() can not be used on resultsets prefetching has_many. Use find( \%cond ) or next() instead'
809     );
810   }
811
812   if ($where) {
813     if (defined $attrs->{where}) {
814       $attrs->{where} = {
815         '-and' =>
816             [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
817                $where, delete $attrs->{where} ]
818       };
819     } else {
820       $attrs->{where} = $where;
821     }
822   }
823
824   my @data = $self->result_source->storage->select_single(
825     $attrs->{from}, $attrs->{select},
826     $attrs->{where}, $attrs
827   );
828
829   return (@data ? ($self->_construct_object(@data))[0] : undef);
830 }
831
832
833 # _collapse_query
834 #
835 # Recursively collapse the query, accumulating values for each column.
836
837 sub _collapse_query {
838   my ($self, $query, $collapsed) = @_;
839
840   $collapsed ||= {};
841
842   if (ref $query eq 'ARRAY') {
843     foreach my $subquery (@$query) {
844       next unless ref $subquery;  # -or
845       $collapsed = $self->_collapse_query($subquery, $collapsed);
846     }
847   }
848   elsif (ref $query eq 'HASH') {
849     if (keys %$query and (keys %$query)[0] eq '-and') {
850       foreach my $subquery (@{$query->{-and}}) {
851         $collapsed = $self->_collapse_query($subquery, $collapsed);
852       }
853     }
854     else {
855       foreach my $col (keys %$query) {
856         my $value = $query->{$col};
857         $collapsed->{$col}{$value}++;
858       }
859     }
860   }
861
862   return $collapsed;
863 }
864
865 =head2 get_column
866
867 =over 4
868
869 =item Arguments: $cond?
870
871 =item Return Value: $resultsetcolumn
872
873 =back
874
875   my $max_length = $rs->get_column('length')->max;
876
877 Returns a L<DBIx::Class::ResultSetColumn> instance for a column of the ResultSet.
878
879 =cut
880
881 sub get_column {
882   my ($self, $column) = @_;
883   my $new = DBIx::Class::ResultSetColumn->new($self, $column);
884   return $new;
885 }
886
887 =head2 search_like
888
889 =over 4
890
891 =item Arguments: $cond, \%attrs?
892
893 =item Return Value: $resultset (scalar context), @row_objs (list context)
894
895 =back
896
897   # WHERE title LIKE '%blue%'
898   $cd_rs = $rs->search_like({ title => '%blue%'});
899
900 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
901 that this is simply a convenience method retained for ex Class::DBI users.
902 You most likely want to use L</search> with specific operators.
903
904 For more information, see L<DBIx::Class::Manual::Cookbook>.
905
906 This method is deprecated and will be removed in 0.09. Use L</search()>
907 instead. An example conversion is:
908
909   ->search_like({ foo => 'bar' });
910
911   # Becomes
912
913   ->search({ foo => { like => 'bar' } });
914
915 =cut
916
917 sub search_like {
918   my $class = shift;
919   carp (
920     'search_like() is deprecated and will be removed in DBIC version 0.09.'
921    .' Instead use ->search({ x => { -like => "y%" } })'
922    .' (note the outer pair of {}s - they are important!)'
923   );
924   my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
925   my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
926   $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
927   return $class->search($query, { %$attrs });
928 }
929
930 =head2 slice
931
932 =over 4
933
934 =item Arguments: $first, $last
935
936 =item Return Value: $resultset (scalar context), @row_objs (list context)
937
938 =back
939
940 Returns a resultset or object list representing a subset of elements from the
941 resultset slice is called on. Indexes are from 0, i.e., to get the first
942 three records, call:
943
944   my ($one, $two, $three) = $rs->slice(0, 2);
945
946 =cut
947
948 sub slice {
949   my ($self, $min, $max) = @_;
950   my $attrs = {}; # = { %{ $self->{attrs} || {} } };
951   $attrs->{offset} = $self->{attrs}{offset} || 0;
952   $attrs->{offset} += $min;
953   $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
954   return $self->search(undef, $attrs);
955   #my $slice = (ref $self)->new($self->result_source, $attrs);
956   #return (wantarray ? $slice->all : $slice);
957 }
958
959 =head2 next
960
961 =over 4
962
963 =item Arguments: none
964
965 =item Return Value: $result | undef
966
967 =back
968
969 Returns the next element in the resultset (C<undef> is there is none).
970
971 Can be used to efficiently iterate over records in the resultset:
972
973   my $rs = $schema->resultset('CD')->search;
974   while (my $cd = $rs->next) {
975     print $cd->title;
976   }
977
978 Note that you need to store the resultset object, and call C<next> on it.
979 Calling C<< resultset('Table')->next >> repeatedly will always return the
980 first record from the resultset.
981
982 =cut
983
984 sub next {
985   my ($self) = @_;
986   if (my $cache = $self->get_cache) {
987     $self->{all_cache_position} ||= 0;
988     return $cache->[$self->{all_cache_position}++];
989   }
990   if ($self->{attrs}{cache}) {
991     delete $self->{pager};
992     $self->{all_cache_position} = 1;
993     return ($self->all)[0];
994   }
995   if ($self->{stashed_objects}) {
996     my $obj = shift(@{$self->{stashed_objects}});
997     delete $self->{stashed_objects} unless @{$self->{stashed_objects}};
998     return $obj;
999   }
1000   my @row = (
1001     exists $self->{stashed_row}
1002       ? @{delete $self->{stashed_row}}
1003       : $self->cursor->next
1004   );
1005   return undef unless (@row);
1006   my ($row, @more) = $self->_construct_object(@row);
1007   $self->{stashed_objects} = \@more if @more;
1008   return $row;
1009 }
1010
1011 sub _construct_object {
1012   my ($self, @row) = @_;
1013
1014   my $info = $self->_collapse_result($self->{_attrs}{as}, \@row)
1015     or return ();
1016   my @new = $self->result_class->inflate_result($self->result_source, @$info);
1017   @new = $self->{_attrs}{record_filter}->(@new)
1018     if exists $self->{_attrs}{record_filter};
1019   return @new;
1020 }
1021
1022 sub _collapse_result {
1023   my ($self, $as_proto, $row) = @_;
1024
1025   my @copy = @$row;
1026
1027   # 'foo'         => [ undef, 'foo' ]
1028   # 'foo.bar'     => [ 'foo', 'bar' ]
1029   # 'foo.bar.baz' => [ 'foo.bar', 'baz' ]
1030
1031   my @construct_as = map { [ (/^(?:(.*)\.)?([^.]+)$/) ] } @$as_proto;
1032
1033   my %collapse = %{$self->{_attrs}{collapse}||{}};
1034
1035   my @pri_index;
1036
1037   # if we're doing collapsing (has_many prefetch) we need to grab records
1038   # until the PK changes, so fill @pri_index. if not, we leave it empty so
1039   # we know we don't have to bother.
1040
1041   # the reason for not using the collapse stuff directly is because if you
1042   # had for e.g. two artists in a row with no cds, the collapse info for
1043   # both would be NULL (undef) so you'd lose the second artist
1044
1045   # store just the index so we can check the array positions from the row
1046   # without having to contruct the full hash
1047
1048   if (keys %collapse) {
1049     my %pri = map { ($_ => 1) } $self->result_source->_pri_cols;
1050     foreach my $i (0 .. $#construct_as) {
1051       next if defined($construct_as[$i][0]); # only self table
1052       if (delete $pri{$construct_as[$i][1]}) {
1053         push(@pri_index, $i);
1054       }
1055       last unless keys %pri; # short circuit (Johnny Five Is Alive!)
1056     }
1057   }
1058
1059   # no need to do an if, it'll be empty if @pri_index is empty anyway
1060
1061   my %pri_vals = map { ($_ => $copy[$_]) } @pri_index;
1062
1063   my @const_rows;
1064
1065   do { # no need to check anything at the front, we always want the first row
1066
1067     my %const;
1068
1069     foreach my $this_as (@construct_as) {
1070       $const{$this_as->[0]||''}{$this_as->[1]} = shift(@copy);
1071     }
1072
1073     push(@const_rows, \%const);
1074
1075   } until ( # no pri_index => no collapse => drop straight out
1076       !@pri_index
1077     or
1078       do { # get another row, stash it, drop out if different PK
1079
1080         @copy = $self->cursor->next;
1081         $self->{stashed_row} = \@copy;
1082
1083         # last thing in do block, counts as true if anything doesn't match
1084
1085         # check xor defined first for NULL vs. NOT NULL then if one is
1086         # defined the other must be so check string equality
1087
1088         grep {
1089           (defined $pri_vals{$_} ^ defined $copy[$_])
1090           || (defined $pri_vals{$_} && ($pri_vals{$_} ne $copy[$_]))
1091         } @pri_index;
1092       }
1093   );
1094
1095   my $alias = $self->{attrs}{alias};
1096   my $info = [];
1097
1098   my %collapse_pos;
1099
1100   my @const_keys;
1101
1102   foreach my $const (@const_rows) {
1103     scalar @const_keys or do {
1104       @const_keys = sort { length($a) <=> length($b) } keys %$const;
1105     };
1106     foreach my $key (@const_keys) {
1107       if (length $key) {
1108         my $target = $info;
1109         my @parts = split(/\./, $key);
1110         my $cur = '';
1111         my $data = $const->{$key};
1112         foreach my $p (@parts) {
1113           $target = $target->[1]->{$p} ||= [];
1114           $cur .= ".${p}";
1115           if ($cur eq ".${key}" && (my @ckey = @{$collapse{$cur}||[]})) {
1116             # collapsing at this point and on final part
1117             my $pos = $collapse_pos{$cur};
1118             CK: foreach my $ck (@ckey) {
1119               if (!defined $pos->{$ck} || $pos->{$ck} ne $data->{$ck}) {
1120                 $collapse_pos{$cur} = $data;
1121                 delete @collapse_pos{ # clear all positioning for sub-entries
1122                   grep { m/^\Q${cur}.\E/ } keys %collapse_pos
1123                 };
1124                 push(@$target, []);
1125                 last CK;
1126               }
1127             }
1128           }
1129           if (exists $collapse{$cur}) {
1130             $target = $target->[-1];
1131           }
1132         }
1133         $target->[0] = $data;
1134       } else {
1135         $info->[0] = $const->{$key};
1136       }
1137     }
1138   }
1139
1140   return $info;
1141 }
1142
1143 =head2 result_source
1144
1145 =over 4
1146
1147 =item Arguments: $result_source?
1148
1149 =item Return Value: $result_source
1150
1151 =back
1152
1153 An accessor for the primary ResultSource object from which this ResultSet
1154 is derived.
1155
1156 =head2 result_class
1157
1158 =over 4
1159
1160 =item Arguments: $result_class?
1161
1162 =item Return Value: $result_class
1163
1164 =back
1165
1166 An accessor for the class to use when creating row objects. Defaults to
1167 C<< result_source->result_class >> - which in most cases is the name of the
1168 L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class.
1169
1170 Note that changing the result_class will also remove any components
1171 that were originally loaded in the source class via
1172 L<DBIx::Class::ResultSource/load_components>. Any overloaded methods
1173 in the original source class will not run.
1174
1175 =cut
1176
1177 sub result_class {
1178   my ($self, $result_class) = @_;
1179   if ($result_class) {
1180     unless (ref $result_class) { # don't fire this for an object
1181       $self->ensure_class_loaded($result_class);
1182     }
1183     $self->_result_class($result_class);
1184     # THIS LINE WOULD BE A BUG - this accessor specifically exists to
1185     # permit the user to set result class on one result set only; it only
1186     # chains if provided to search()
1187     #$self->{attrs}{result_class} = $result_class if ref $self;
1188   }
1189   $self->_result_class;
1190 }
1191
1192 =head2 count
1193
1194 =over 4
1195
1196 =item Arguments: $cond, \%attrs??
1197
1198 =item Return Value: $count
1199
1200 =back
1201
1202 Performs an SQL C<COUNT> with the same query as the resultset was built
1203 with to find the number of elements. Passing arguments is equivalent to
1204 C<< $rs->search ($cond, \%attrs)->count >>
1205
1206 =cut
1207
1208 sub count {
1209   my $self = shift;
1210   return $self->search(@_)->count if @_ and defined $_[0];
1211   return scalar @{ $self->get_cache } if $self->get_cache;
1212
1213   my $attrs = $self->_resolved_attrs_copy;
1214
1215   # this is a little optimization - it is faster to do the limit
1216   # adjustments in software, instead of a subquery
1217   my $rows = delete $attrs->{rows};
1218   my $offset = delete $attrs->{offset};
1219
1220   my $crs;
1221   if ($self->_has_resolved_attr (qw/collapse group_by/)) {
1222     $crs = $self->_count_subq_rs ($attrs);
1223   }
1224   else {
1225     $crs = $self->_count_rs ($attrs);
1226   }
1227   my $count = $crs->next;
1228
1229   $count -= $offset if $offset;
1230   $count = $rows if $rows and $rows < $count;
1231   $count = 0 if ($count < 0);
1232
1233   return $count;
1234 }
1235
1236 =head2 count_rs
1237
1238 =over 4
1239
1240 =item Arguments: $cond, \%attrs??
1241
1242 =item Return Value: $count_rs
1243
1244 =back
1245
1246 Same as L</count> but returns a L<DBIx::Class::ResultSetColumn> object.
1247 This can be very handy for subqueries:
1248
1249   ->search( { amount => $some_rs->count_rs->as_query } )
1250
1251 As with regular resultsets the SQL query will be executed only after
1252 the resultset is accessed via L</next> or L</all>. That would return
1253 the same single value obtainable via L</count>.
1254
1255 =cut
1256
1257 sub count_rs {
1258   my $self = shift;
1259   return $self->search(@_)->count_rs if @_;
1260
1261   # this may look like a lack of abstraction (count() does about the same)
1262   # but in fact an _rs *must* use a subquery for the limits, as the
1263   # software based limiting can not be ported if this $rs is to be used
1264   # in a subquery itself (i.e. ->as_query)
1265   if ($self->_has_resolved_attr (qw/collapse group_by offset rows/)) {
1266     return $self->_count_subq_rs;
1267   }
1268   else {
1269     return $self->_count_rs;
1270   }
1271 }
1272
1273 #
1274 # returns a ResultSetColumn object tied to the count query
1275 #
1276 sub _count_rs {
1277   my ($self, $attrs) = @_;
1278
1279   my $rsrc = $self->result_source;
1280   $attrs ||= $self->_resolved_attrs;
1281
1282   my $tmp_attrs = { %$attrs };
1283   # take off any limits, record_filter is cdbi, and no point of ordering nor locking a count
1284   delete @{$tmp_attrs}{qw/rows offset order_by record_filter for/};
1285
1286   # overwrite the selector (supplied by the storage)
1287   $tmp_attrs->{select} = $rsrc->storage->_count_select ($rsrc, $attrs);
1288   $tmp_attrs->{as} = 'count';
1289
1290   my $tmp_rs = $rsrc->resultset_class->new($rsrc, $tmp_attrs)->get_column ('count');
1291
1292   return $tmp_rs;
1293 }
1294
1295 #
1296 # same as above but uses a subquery
1297 #
1298 sub _count_subq_rs {
1299   my ($self, $attrs) = @_;
1300
1301   my $rsrc = $self->result_source;
1302   $attrs ||= $self->_resolved_attrs;
1303
1304   my $sub_attrs = { %$attrs };
1305   # extra selectors do not go in the subquery and there is no point of ordering it, nor locking it
1306   delete @{$sub_attrs}{qw/collapse select _prefetch_select as order_by for/};
1307
1308   # if we multi-prefetch we group_by primary keys only as this is what we would
1309   # get out of the rs via ->next/->all. We *DO WANT* to clobber old group_by regardless
1310   if ( keys %{$attrs->{collapse}}  ) {
1311     $sub_attrs->{group_by} = [ map { "$attrs->{alias}.$_" } ($rsrc->_pri_cols) ]
1312   }
1313
1314   # Calculate subquery selector
1315   if (my $g = $sub_attrs->{group_by}) {
1316
1317     my $sql_maker = $rsrc->storage->sql_maker;
1318
1319     # necessary as the group_by may refer to aliased functions
1320     my $sel_index;
1321     for my $sel (@{$attrs->{select}}) {
1322       $sel_index->{$sel->{-as}} = $sel
1323         if (ref $sel eq 'HASH' and $sel->{-as});
1324     }
1325
1326     # anything from the original select mentioned on the group-by needs to make it to the inner selector
1327     # also look for named aggregates referred in the having clause
1328     # having often contains scalarrefs - thus parse it out entirely
1329     my @parts = @$g;
1330     if ($attrs->{having}) {
1331       local $sql_maker->{having_bind};
1332       local $sql_maker->{quote_char} = $sql_maker->{quote_char};
1333       local $sql_maker->{name_sep} = $sql_maker->{name_sep};
1334       unless (defined $sql_maker->{quote_char} and length $sql_maker->{quote_char}) {
1335         $sql_maker->{quote_char} = [ "\x00", "\xFF" ];
1336         # if we don't unset it we screw up retarded but unfortunately working
1337         # 'MAX(foo.bar)' => { '>', 3 }
1338         $sql_maker->{name_sep} = '';
1339       }
1340
1341       my ($lquote, $rquote, $sep) = map { quotemeta $_ } ($sql_maker->_quote_chars, $sql_maker->name_sep);
1342
1343       my $sql = $sql_maker->_parse_rs_attrs ({ having => $attrs->{having} });
1344
1345       # search for both a proper quoted qualified string, for a naive unquoted scalarref
1346       # and if all fails for an utterly naive quoted scalar-with-function
1347       while ($sql =~ /
1348         $rquote $sep $lquote (.+?) $rquote
1349           |
1350         [\s,] \w+ \. (\w+) [\s,]
1351           |
1352         [\s,] $lquote (.+?) $rquote [\s,]
1353       /gx) {
1354         push @parts, ($1 || $2 || $3);  # one of them matched if we got here
1355       }
1356     }
1357
1358     for (@parts) {
1359       my $colpiece = $sel_index->{$_} || $_;
1360
1361       # unqualify join-based group_by's. Arcane but possible query
1362       # also horrible horrible hack to alias a column (not a func.)
1363       # (probably need to introduce SQLA syntax)
1364       if ($colpiece =~ /\./ && $colpiece !~ /^$attrs->{alias}\./) {
1365         my $as = $colpiece;
1366         $as =~ s/\./__/;
1367         $colpiece = \ sprintf ('%s AS %s', map { $sql_maker->_quote ($_) } ($colpiece, $as) );
1368       }
1369       push @{$sub_attrs->{select}}, $colpiece;
1370     }
1371   }
1372   else {
1373     my @pcols = map { "$attrs->{alias}.$_" } ($rsrc->primary_columns);
1374     $sub_attrs->{select} = @pcols ? \@pcols : [ 1 ];
1375   }
1376
1377   return $rsrc->resultset_class
1378                ->new ($rsrc, $sub_attrs)
1379                 ->as_subselect_rs
1380                  ->search ({}, { columns => { count => $rsrc->storage->_count_select ($rsrc, $attrs) } })
1381                   ->get_column ('count');
1382 }
1383
1384 sub _bool {
1385   return 1;
1386 }
1387
1388 =head2 count_literal
1389
1390 =over 4
1391
1392 =item Arguments: $sql_fragment, @bind_values
1393
1394 =item Return Value: $count
1395
1396 =back
1397
1398 Counts the results in a literal query. Equivalent to calling L</search_literal>
1399 with the passed arguments, then L</count>.
1400
1401 =cut
1402
1403 sub count_literal { shift->search_literal(@_)->count; }
1404
1405 =head2 all
1406
1407 =over 4
1408
1409 =item Arguments: none
1410
1411 =item Return Value: @objects
1412
1413 =back
1414
1415 Returns all elements in the resultset. Called implicitly if the resultset
1416 is returned in list context.
1417
1418 =cut
1419
1420 sub all {
1421   my $self = shift;
1422   if(@_) {
1423       $self->throw_exception("all() doesn't take any arguments, you probably wanted ->search(...)->all()");
1424   }
1425
1426   return @{ $self->get_cache } if $self->get_cache;
1427
1428   my @obj;
1429
1430   if (keys %{$self->_resolved_attrs->{collapse}}) {
1431     # Using $self->cursor->all is really just an optimisation.
1432     # If we're collapsing has_many prefetches it probably makes
1433     # very little difference, and this is cleaner than hacking
1434     # _construct_object to survive the approach
1435     $self->cursor->reset;
1436     my @row = $self->cursor->next;
1437     while (@row) {
1438       push(@obj, $self->_construct_object(@row));
1439       @row = (exists $self->{stashed_row}
1440                ? @{delete $self->{stashed_row}}
1441                : $self->cursor->next);
1442     }
1443   } else {
1444     @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
1445   }
1446
1447   $self->set_cache(\@obj) if $self->{attrs}{cache};
1448
1449   return @obj;
1450 }
1451
1452 =head2 reset
1453
1454 =over 4
1455
1456 =item Arguments: none
1457
1458 =item Return Value: $self
1459
1460 =back
1461
1462 Resets the resultset's cursor, so you can iterate through the elements again.
1463 Implicitly resets the storage cursor, so a subsequent L</next> will trigger
1464 another query.
1465
1466 =cut
1467
1468 sub reset {
1469   my ($self) = @_;
1470   delete $self->{_attrs} if exists $self->{_attrs};
1471   $self->{all_cache_position} = 0;
1472   $self->cursor->reset;
1473   return $self;
1474 }
1475
1476 =head2 first
1477
1478 =over 4
1479
1480 =item Arguments: none
1481
1482 =item Return Value: $object | undef
1483
1484 =back
1485
1486 Resets the resultset and returns an object for the first result (or C<undef>
1487 if the resultset is empty).
1488
1489 =cut
1490
1491 sub first {
1492   return $_[0]->reset->next;
1493 }
1494
1495
1496 # _rs_update_delete
1497 #
1498 # Determines whether and what type of subquery is required for the $rs operation.
1499 # If grouping is necessary either supplies its own, or verifies the current one
1500 # After all is done delegates to the proper storage method.
1501
1502 sub _rs_update_delete {
1503   my ($self, $op, $values) = @_;
1504
1505   my $rsrc = $self->result_source;
1506
1507   # if a condition exists we need to strip all table qualifiers
1508   # if this is not possible we'll force a subquery below
1509   my $cond = $rsrc->schema->storage->_strip_cond_qualifiers ($self->{cond});
1510
1511   my $needs_group_by_subq = $self->_has_resolved_attr (qw/collapse group_by -join/);
1512   my $needs_subq = $needs_group_by_subq || (not defined $cond) || $self->_has_resolved_attr(qw/rows offset/);
1513
1514   if ($needs_group_by_subq or $needs_subq) {
1515
1516     # make a new $rs selecting only the PKs (that's all we really need)
1517     my $attrs = $self->_resolved_attrs_copy;
1518
1519
1520     delete $attrs->{$_} for qw/collapse _collapse_order_by select _prefetch_select as/;
1521     $attrs->{columns} = [ map { "$attrs->{alias}.$_" } ($self->result_source->_pri_cols) ];
1522
1523     if ($needs_group_by_subq) {
1524       # make sure no group_by was supplied, or if there is one - make sure it matches
1525       # the columns compiled above perfectly. Anything else can not be sanely executed
1526       # on most databases so croak right then and there
1527
1528       if (my $g = $attrs->{group_by}) {
1529         my @current_group_by = map
1530           { $_ =~ /\./ ? $_ : "$attrs->{alias}.$_" }
1531           @$g
1532         ;
1533
1534         if (
1535           join ("\x00", sort @current_group_by)
1536             ne
1537           join ("\x00", sort @{$attrs->{columns}} )
1538         ) {
1539           $self->throw_exception (
1540             "You have just attempted a $op operation on a resultset which does group_by"
1541             . ' on columns other than the primary keys, while DBIC internally needs to retrieve'
1542             . ' the primary keys in a subselect. All sane RDBMS engines do not support this'
1543             . ' kind of queries. Please retry the operation with a modified group_by or'
1544             . ' without using one at all.'
1545           );
1546         }
1547       }
1548       else {
1549         $attrs->{group_by} = $attrs->{columns};
1550       }
1551     }
1552
1553     my $subrs = (ref $self)->new($rsrc, $attrs);
1554     return $self->result_source->storage->_subq_update_delete($subrs, $op, $values);
1555   }
1556   else {
1557     return $rsrc->storage->$op(
1558       $rsrc,
1559       $op eq 'update' ? $values : (),
1560       $cond,
1561     );
1562   }
1563 }
1564
1565 =head2 update
1566
1567 =over 4
1568
1569 =item Arguments: \%values
1570
1571 =item Return Value: $storage_rv
1572
1573 =back
1574
1575 Sets the specified columns in the resultset to the supplied values in a
1576 single query. Note that this will not run any accessor/set_column/update
1577 triggers, nor will it update any row object instances derived from this
1578 resultset (this includes the contents of the L<resultset cache|/set_cache>
1579 if any). See L</update_all> if you need to execute any on-update
1580 triggers or cascades defined either by you or a
1581 L<result component|DBIx::Class::Manual::Component/WHAT_IS_A_COMPONENT>.
1582
1583 The return value is a pass through of what the underlying
1584 storage backend returned, and may vary. See L<DBI/execute> for the most
1585 common case.
1586
1587 =head3 CAVEAT
1588
1589 Note that L</update> does not process/deflate any of the values passed in.
1590 This is unlike the corresponding L<DBIx::Class::Row/update>. The user must
1591 ensure manually that any value passed to this method will stringify to
1592 something the RDBMS knows how to deal with. A notable example is the
1593 handling of L<DateTime> objects, for more info see:
1594 L<DBIx::Class::Manual::Cookbook/Formatting_DateTime_objects_in_queries>.
1595
1596 =cut
1597
1598 sub update {
1599   my ($self, $values) = @_;
1600   $self->throw_exception('Values for update must be a hash')
1601     unless ref $values eq 'HASH';
1602
1603   return $self->_rs_update_delete ('update', $values);
1604 }
1605
1606 =head2 update_all
1607
1608 =over 4
1609
1610 =item Arguments: \%values
1611
1612 =item Return Value: 1
1613
1614 =back
1615
1616 Fetches all objects and updates them one at a time via
1617 L<DBIx::Class::Row/update>. Note that C<update_all> will run DBIC defined
1618 triggers, while L</update> will not.
1619
1620 =cut
1621
1622 sub update_all {
1623   my ($self, $values) = @_;
1624   $self->throw_exception('Values for update_all must be a hash')
1625     unless ref $values eq 'HASH';
1626
1627   my $guard = $self->result_source->schema->txn_scope_guard;
1628   $_->update($values) for $self->all;
1629   $guard->commit;
1630   return 1;
1631 }
1632
1633 =head2 delete
1634
1635 =over 4
1636
1637 =item Arguments: none
1638
1639 =item Return Value: $storage_rv
1640
1641 =back
1642
1643 Deletes the rows matching this resultset in a single query. Note that this
1644 will not run any delete triggers, nor will it alter the
1645 L<in_storage|DBIx::Class::Row/in_storage> status of any row object instances
1646 derived from this resultset (this includes the contents of the
1647 L<resultset cache|/set_cache> if any). See L</delete_all> if you need to
1648 execute any on-delete triggers or cascades defined either by you or a
1649 L<result component|DBIx::Class::Manual::Component/WHAT_IS_A_COMPONENT>.
1650
1651 The return value is a pass through of what the underlying storage backend
1652 returned, and may vary. See L<DBI/execute> for the most common case.
1653
1654 =cut
1655
1656 sub delete {
1657   my $self = shift;
1658   $self->throw_exception('delete does not accept any arguments')
1659     if @_;
1660
1661   return $self->_rs_update_delete ('delete');
1662 }
1663
1664 =head2 delete_all
1665
1666 =over 4
1667
1668 =item Arguments: none
1669
1670 =item Return Value: 1
1671
1672 =back
1673
1674 Fetches all objects and deletes them one at a time via
1675 L<DBIx::Class::Row/delete>. Note that C<delete_all> will run DBIC defined
1676 triggers, while L</delete> will not.
1677
1678 =cut
1679
1680 sub delete_all {
1681   my $self = shift;
1682   $self->throw_exception('delete_all does not accept any arguments')
1683     if @_;
1684
1685   my $guard = $self->result_source->schema->txn_scope_guard;
1686   $_->delete for $self->all;
1687   $guard->commit;
1688   return 1;
1689 }
1690
1691 =head2 populate
1692
1693 =over 4
1694
1695 =item Arguments: \@data;
1696
1697 =back
1698
1699 Accepts either an arrayref of hashrefs or alternatively an arrayref of arrayrefs.
1700 For the arrayref of hashrefs style each hashref should be a structure suitable
1701 forsubmitting to a $resultset->create(...) method.
1702
1703 In void context, C<insert_bulk> in L<DBIx::Class::Storage::DBI> is used
1704 to insert the data, as this is a faster method.
1705
1706 Otherwise, each set of data is inserted into the database using
1707 L<DBIx::Class::ResultSet/create>, and the resulting objects are
1708 accumulated into an array. The array itself, or an array reference
1709 is returned depending on scalar or list context.
1710
1711 Example:  Assuming an Artist Class that has many CDs Classes relating:
1712
1713   my $Artist_rs = $schema->resultset("Artist");
1714
1715   ## Void Context Example
1716   $Artist_rs->populate([
1717      { artistid => 4, name => 'Manufactured Crap', cds => [
1718         { title => 'My First CD', year => 2006 },
1719         { title => 'Yet More Tweeny-Pop crap', year => 2007 },
1720       ],
1721      },
1722      { artistid => 5, name => 'Angsty-Whiny Girl', cds => [
1723         { title => 'My parents sold me to a record company', year => 2005 },
1724         { title => 'Why Am I So Ugly?', year => 2006 },
1725         { title => 'I Got Surgery and am now Popular', year => 2007 }
1726       ],
1727      },
1728   ]);
1729
1730   ## Array Context Example
1731   my ($ArtistOne, $ArtistTwo, $ArtistThree) = $Artist_rs->populate([
1732     { name => "Artist One"},
1733     { name => "Artist Two"},
1734     { name => "Artist Three", cds=> [
1735     { title => "First CD", year => 2007},
1736     { title => "Second CD", year => 2008},
1737   ]}
1738   ]);
1739
1740   print $ArtistOne->name; ## response is 'Artist One'
1741   print $ArtistThree->cds->count ## reponse is '2'
1742
1743 For the arrayref of arrayrefs style,  the first element should be a list of the
1744 fieldsnames to which the remaining elements are rows being inserted.  For
1745 example:
1746
1747   $Arstist_rs->populate([
1748     [qw/artistid name/],
1749     [100, 'A Formally Unknown Singer'],
1750     [101, 'A singer that jumped the shark two albums ago'],
1751     [102, 'An actually cool singer'],
1752   ]);
1753
1754 Please note an important effect on your data when choosing between void and
1755 wantarray context. Since void context goes straight to C<insert_bulk> in
1756 L<DBIx::Class::Storage::DBI> this will skip any component that is overriding
1757 C<insert>.  So if you are using something like L<DBIx-Class-UUIDColumns> to
1758 create primary keys for you, you will find that your PKs are empty.  In this
1759 case you will have to use the wantarray context in order to create those
1760 values.
1761
1762 =cut
1763
1764 sub populate {
1765   my $self = shift;
1766
1767   # cruft placed in standalone method
1768   my $data = $self->_normalize_populate_args(@_);
1769
1770   if(defined wantarray) {
1771     my @created;
1772     foreach my $item (@$data) {
1773       push(@created, $self->create($item));
1774     }
1775     return wantarray ? @created : \@created;
1776   } else {
1777     my $first = $data->[0];
1778
1779     # if a column is a registered relationship, and is a non-blessed hash/array, consider
1780     # it relationship data
1781     my (@rels, @columns);
1782     for (keys %$first) {
1783       my $ref = ref $first->{$_};
1784       $self->result_source->has_relationship($_) && ($ref eq 'ARRAY' or $ref eq 'HASH')
1785         ? push @rels, $_
1786         : push @columns, $_
1787       ;
1788     }
1789
1790     my @pks = $self->result_source->primary_columns;
1791
1792     ## do the belongs_to relationships
1793     foreach my $index (0..$#$data) {
1794
1795       # delegate to create() for any dataset without primary keys with specified relationships
1796       if (grep { !defined $data->[$index]->{$_} } @pks ) {
1797         for my $r (@rels) {
1798           if (grep { ref $data->[$index]{$r} eq $_ } qw/HASH ARRAY/) {  # a related set must be a HASH or AoH
1799             my @ret = $self->populate($data);
1800             return;
1801           }
1802         }
1803       }
1804
1805       foreach my $rel (@rels) {
1806         next unless ref $data->[$index]->{$rel} eq "HASH";
1807         my $result = $self->related_resultset($rel)->create($data->[$index]->{$rel});
1808         my ($reverse) = keys %{$self->result_source->reverse_relationship_info($rel)};
1809         my $related = $result->result_source->_resolve_condition(
1810           $result->result_source->relationship_info($reverse)->{cond},
1811           $self,
1812           $result,
1813         );
1814
1815         delete $data->[$index]->{$rel};
1816         $data->[$index] = {%{$data->[$index]}, %$related};
1817
1818         push @columns, keys %$related if $index == 0;
1819       }
1820     }
1821
1822     ## inherit the data locked in the conditions of the resultset
1823     my ($rs_data) = $self->_merge_with_rscond({});
1824     delete @{$rs_data}{@columns};
1825     my @inherit_cols = keys %$rs_data;
1826     my @inherit_data = values %$rs_data;
1827
1828     ## do bulk insert on current row
1829     $self->result_source->storage->insert_bulk(
1830       $self->result_source,
1831       [@columns, @inherit_cols],
1832       [ map { [ @$_{@columns}, @inherit_data ] } @$data ],
1833     );
1834
1835     ## do the has_many relationships
1836     foreach my $item (@$data) {
1837
1838       foreach my $rel (@rels) {
1839         next unless $item->{$rel} && ref $item->{$rel} eq "ARRAY";
1840
1841         my $parent = $self->find({map { $_ => $item->{$_} } @pks})
1842      || $self->throw_exception('Cannot find the relating object.');
1843
1844         my $child = $parent->$rel;
1845
1846         my $related = $child->result_source->_resolve_condition(
1847           $parent->result_source->relationship_info($rel)->{cond},
1848           $child,
1849           $parent,
1850         );
1851
1852         my @rows_to_add = ref $item->{$rel} eq 'ARRAY' ? @{$item->{$rel}} : ($item->{$rel});
1853         my @populate = map { {%$_, %$related} } @rows_to_add;
1854
1855         $child->populate( \@populate );
1856       }
1857     }
1858   }
1859 }
1860
1861
1862 # populate() argumnets went over several incarnations
1863 # What we ultimately support is AoH
1864 sub _normalize_populate_args {
1865   my ($self, $arg) = @_;
1866
1867   if (ref $arg eq 'ARRAY') {
1868     if (ref $arg->[0] eq 'HASH') {
1869       return $arg;
1870     }
1871     elsif (ref $arg->[0] eq 'ARRAY') {
1872       my @ret;
1873       my @colnames = @{$arg->[0]};
1874       foreach my $values (@{$arg}[1 .. $#$arg]) {
1875         push @ret, { map { $colnames[$_] => $values->[$_] } (0 .. $#colnames) };
1876       }
1877       return \@ret;
1878     }
1879   }
1880
1881   $self->throw_exception('Populate expects an arrayref of hashrefs or arrayref of arrayrefs');
1882 }
1883
1884 =head2 pager
1885
1886 =over 4
1887
1888 =item Arguments: none
1889
1890 =item Return Value: $pager
1891
1892 =back
1893
1894 Return Value a L<Data::Page> object for the current resultset. Only makes
1895 sense for queries with a C<page> attribute.
1896
1897 To get the full count of entries for a paged resultset, call
1898 C<total_entries> on the L<Data::Page> object.
1899
1900 =cut
1901
1902 # make a wizard good for both a scalar and a hashref
1903 my $mk_lazy_count_wizard = sub {
1904   require Variable::Magic;
1905
1906   my $stash = { total_rs => shift };
1907   my $slot = shift; # only used by the hashref magic
1908
1909   my $magic = Variable::Magic::wizard (
1910     data => sub { $stash },
1911
1912     (!$slot)
1913     ? (
1914       # the scalar magic
1915       get => sub {
1916         # set value lazily, and dispell for good
1917         ${$_[0]} = $_[1]{total_rs}->count;
1918         Variable::Magic::dispell (${$_[0]}, $_[1]{magic_selfref});
1919         return 1;
1920       },
1921       set => sub {
1922         # an explicit set implies dispell as well
1923         # the unless() is to work around "fun and giggles" below
1924         Variable::Magic::dispell (${$_[0]}, $_[1]{magic_selfref})
1925           unless (caller(2))[3] eq 'DBIx::Class::ResultSet::pager';
1926         return 1;
1927       },
1928     )
1929     : (
1930       # the uvar magic
1931       fetch => sub {
1932         if ($_[2] eq $slot and !$_[1]{inactive}) {
1933           my $cnt = $_[1]{total_rs}->count;
1934           $_[0]->{$slot} = $cnt;
1935
1936           # attempting to dispell in a fetch handle (works in store), seems
1937           # to invariable segfault on 5.10, 5.12, 5.13 :(
1938           # so use an inactivator instead
1939           #Variable::Magic::dispell (%{$_[0]}, $_[1]{magic_selfref});
1940           $_[1]{inactive}++;
1941         }
1942         return 1;
1943       },
1944       store => sub {
1945         if (! $_[1]{inactive} and $_[2] eq $slot) {
1946           #Variable::Magic::dispell (%{$_[0]}, $_[1]{magic_selfref});
1947           $_[1]{inactive}++
1948             unless (caller(2))[3] eq 'DBIx::Class::ResultSet::pager';
1949         }
1950         return 1;
1951       },
1952     ),
1953   );
1954
1955   $stash->{magic_selfref} = $magic;
1956   weaken ($stash->{magic_selfref}); # this fails on 5.8.1
1957
1958   return $magic;
1959 };
1960
1961 # the tie class for 5.8.1
1962 {
1963   package # hide from pause
1964     DBIx::Class::__DBIC_LAZY_RS_COUNT__;
1965   use base qw/Tie::Hash/;
1966
1967   sub FIRSTKEY { my $dummy = scalar keys %{$_[0]{data}}; each %{$_[0]{data}} }
1968   sub NEXTKEY  { each %{$_[0]{data}} }
1969   sub EXISTS   { exists $_[0]{data}{$_[1]} }
1970   sub DELETE   { delete $_[0]{data}{$_[1]} }
1971   sub CLEAR    { %{$_[0]{data}} = () }
1972   sub SCALAR   { scalar %{$_[0]{data}} }
1973
1974   sub TIEHASH {
1975     $_[1]{data} = {%{$_[1]{selfref}}};
1976     %{$_[1]{selfref}} = ();
1977     Scalar::Util::weaken ($_[1]{selfref});
1978     return bless ($_[1], $_[0]);
1979   };
1980
1981   sub FETCH {
1982     if ($_[1] eq $_[0]{slot}) {
1983       my $cnt = $_[0]{data}{$_[1]} = $_[0]{total_rs}->count;
1984       untie %{$_[0]{selfref}};
1985       %{$_[0]{selfref}} = %{$_[0]{data}};
1986       return $cnt;
1987     }
1988     else {
1989       $_[0]{data}{$_[1]};
1990     }
1991   }
1992
1993   sub STORE {
1994     $_[0]{data}{$_[1]} = $_[2];
1995     if ($_[1] eq $_[0]{slot}) {
1996       untie %{$_[0]{selfref}};
1997       %{$_[0]{selfref}} = %{$_[0]{data}};
1998     }
1999     $_[2];
2000   }
2001 }
2002
2003 sub pager {
2004   my ($self) = @_;
2005
2006   return $self->{pager} if $self->{pager};
2007
2008   if ($self->get_cache) {
2009     $self->throw_exception ('Pagers on cached resultsets are not supported');
2010   }
2011
2012   my $attrs = $self->{attrs};
2013   if (!defined $attrs->{page}) {
2014     $self->throw_exception("Can't create pager for non-paged rs");
2015   }
2016   elsif ($attrs->{page} <= 0) {
2017     $self->throw_exception('Invalid page number (page-numbers are 1-based)');
2018   }
2019   $attrs->{rows} ||= 10;
2020
2021   # throw away the paging flags and re-run the count (possibly
2022   # with a subselect) to get the real total count
2023   my $count_attrs = { %$attrs };
2024   delete $count_attrs->{$_} for qw/rows offset page pager/;
2025   my $total_rs = (ref $self)->new($self->result_source, $count_attrs);
2026
2027
2028 ### the following may seem awkward and dirty, but it's a thought-experiment
2029 ### necessary for future development of DBIx::DS. Do *NOT* change this code
2030 ### before talking to ribasushi/mst
2031
2032   my $pager = Data::Page->new(
2033     0,  #start with an empty set
2034     $attrs->{rows},
2035     $self->{attrs}{page},
2036   );
2037
2038   my $data_slot = 'total_entries';
2039
2040   # Since we are interested in a cached value (once it's set - it's set), every
2041   # technique will detach from the magic-host once the time comes to fire the
2042   # ->count (or in the segfaulting case of >= 5.10 it will deactivate itself)
2043
2044   if ($] < 5.008003) {
2045     # 5.8.1 throws 'Modification of a read-only value attempted' when one tries
2046     # to weakref the magic container :(
2047     # tested on 5.8.1
2048     tie (%$pager, 'DBIx::Class::__DBIC_LAZY_RS_COUNT__',
2049       { slot => $data_slot, total_rs => $total_rs, selfref => $pager }
2050     );
2051   }
2052   elsif ($] < 5.010) {
2053     # We can use magic on the hash value slot. It's interesting that the magic is
2054     # attached to the hash-slot, and does *not* stop working once I do the dummy
2055     # assignments after the cast()
2056     # tested on 5.8.3 and 5.8.9
2057     my $magic = $mk_lazy_count_wizard->($total_rs);
2058     Variable::Magic::cast ( $pager->{$data_slot}, $magic );
2059
2060     # this is for fun and giggles
2061     $pager->{$data_slot} = -1;
2062     $pager->{$data_slot} = 0;
2063
2064     # this does not work for scalars, but works with
2065     # uvar magic below
2066     #my %vals = %$pager;
2067     #%$pager = ();
2068     #%{$pager} = %vals;
2069   }
2070   else {
2071     # And the uvar magic
2072     # works on 5.10.1, 5.12.1 and 5.13.4 in its current form,
2073     # however see the wizard maker for more notes
2074     my $magic = $mk_lazy_count_wizard->($total_rs, $data_slot);
2075     Variable::Magic::cast ( %$pager, $magic );
2076
2077     # still works
2078     $pager->{$data_slot} = -1;
2079     $pager->{$data_slot} = 0;
2080
2081     # this now works
2082     my %vals = %$pager;
2083     %$pager = ();
2084     %{$pager} = %vals;
2085   }
2086
2087   return $self->{pager} = $pager;
2088 }
2089
2090 =head2 page
2091
2092 =over 4
2093
2094 =item Arguments: $page_number
2095
2096 =item Return Value: $rs
2097
2098 =back
2099
2100 Returns a resultset for the $page_number page of the resultset on which page
2101 is called, where each page contains a number of rows equal to the 'rows'
2102 attribute set on the resultset (10 by default).
2103
2104 =cut
2105
2106 sub page {
2107   my ($self, $page) = @_;
2108   return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
2109 }
2110
2111 =head2 new_result
2112
2113 =over 4
2114
2115 =item Arguments: \%vals
2116
2117 =item Return Value: $rowobject
2118
2119 =back
2120
2121 Creates a new row object in the resultset's result class and returns
2122 it. The row is not inserted into the database at this point, call
2123 L<DBIx::Class::Row/insert> to do that. Calling L<DBIx::Class::Row/in_storage>
2124 will tell you whether the row object has been inserted or not.
2125
2126 Passes the hashref of input on to L<DBIx::Class::Row/new>.
2127
2128 =cut
2129
2130 sub new_result {
2131   my ($self, $values) = @_;
2132   $self->throw_exception( "new_result needs a hash" )
2133     unless (ref $values eq 'HASH');
2134
2135   my ($merged_cond, $cols_from_relations) = $self->_merge_with_rscond($values);
2136
2137   my %new = (
2138     %$merged_cond,
2139     @$cols_from_relations
2140       ? (-cols_from_relations => $cols_from_relations)
2141       : (),
2142     -source_handle => $self->_source_handle,
2143     -result_source => $self->result_source, # DO NOT REMOVE THIS, REQUIRED
2144   );
2145
2146   return $self->result_class->new(\%new);
2147 }
2148
2149 # _merge_with_rscond
2150 #
2151 # Takes a simple hash of K/V data and returns its copy merged with the
2152 # condition already present on the resultset. Additionally returns an
2153 # arrayref of value/condition names, which were inferred from related
2154 # objects (this is needed for in-memory related objects)
2155 sub _merge_with_rscond {
2156   my ($self, $data) = @_;
2157
2158   my (%new_data, @cols_from_relations);
2159
2160   my $alias = $self->{attrs}{alias};
2161
2162   if (! defined $self->{cond}) {
2163     # just massage $data below
2164   }
2165   elsif ($self->{cond} eq $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION) {
2166     %new_data = %{ $self->{attrs}{related_objects} || {} };  # nothing might have been inserted yet
2167     @cols_from_relations = keys %new_data;
2168   }
2169   elsif (ref $self->{cond} ne 'HASH') {
2170     $self->throw_exception(
2171       "Can't abstract implicit construct, resultset condition not a hash"
2172     );
2173   }
2174   else {
2175     # precendence must be given to passed values over values inherited from
2176     # the cond, so the order here is important.
2177     my $collapsed_cond = $self->_collapse_cond($self->{cond});
2178     my %implied = %{$self->_remove_alias($collapsed_cond, $alias)};
2179
2180     while ( my($col, $value) = each %implied ) {
2181       my $vref = ref $value;
2182       if ($vref eq 'HASH' && keys(%$value) && (keys %$value)[0] eq '=') {
2183         $new_data{$col} = $value->{'='};
2184       }
2185       elsif( !$vref or $vref eq 'SCALAR' or blessed($value) ) {
2186         $new_data{$col} = $value;
2187       }
2188     }
2189   }
2190
2191   %new_data = (
2192     %new_data,
2193     %{ $self->_remove_alias($data, $alias) },
2194   );
2195
2196   return (\%new_data, \@cols_from_relations);
2197 }
2198
2199 # _has_resolved_attr
2200 #
2201 # determines if the resultset defines at least one
2202 # of the attributes supplied
2203 #
2204 # used to determine if a subquery is neccessary
2205 #
2206 # supports some virtual attributes:
2207 #   -join
2208 #     This will scan for any joins being present on the resultset.
2209 #     It is not a mere key-search but a deep inspection of {from}
2210 #
2211
2212 sub _has_resolved_attr {
2213   my ($self, @attr_names) = @_;
2214
2215   my $attrs = $self->_resolved_attrs;
2216
2217   my %extra_checks;
2218
2219   for my $n (@attr_names) {
2220     if (grep { $n eq $_ } (qw/-join/) ) {
2221       $extra_checks{$n}++;
2222       next;
2223     }
2224
2225     my $attr =  $attrs->{$n};
2226
2227     next if not defined $attr;
2228
2229     if (ref $attr eq 'HASH') {
2230       return 1 if keys %$attr;
2231     }
2232     elsif (ref $attr eq 'ARRAY') {
2233       return 1 if @$attr;
2234     }
2235     else {
2236       return 1 if $attr;
2237     }
2238   }
2239
2240   # a resolved join is expressed as a multi-level from
2241   return 1 if (
2242     $extra_checks{-join}
2243       and
2244     ref $attrs->{from} eq 'ARRAY'
2245       and
2246     @{$attrs->{from}} > 1
2247   );
2248
2249   return 0;
2250 }
2251
2252 # _collapse_cond
2253 #
2254 # Recursively collapse the condition.
2255
2256 sub _collapse_cond {
2257   my ($self, $cond, $collapsed) = @_;
2258
2259   $collapsed ||= {};
2260
2261   if (ref $cond eq 'ARRAY') {
2262     foreach my $subcond (@$cond) {
2263       next unless ref $subcond;  # -or
2264       $collapsed = $self->_collapse_cond($subcond, $collapsed);
2265     }
2266   }
2267   elsif (ref $cond eq 'HASH') {
2268     if (keys %$cond and (keys %$cond)[0] eq '-and') {
2269       foreach my $subcond (@{$cond->{-and}}) {
2270         $collapsed = $self->_collapse_cond($subcond, $collapsed);
2271       }
2272     }
2273     else {
2274       foreach my $col (keys %$cond) {
2275         my $value = $cond->{$col};
2276         $collapsed->{$col} = $value;
2277       }
2278     }
2279   }
2280
2281   return $collapsed;
2282 }
2283
2284 # _remove_alias
2285 #
2286 # Remove the specified alias from the specified query hash. A copy is made so
2287 # the original query is not modified.
2288
2289 sub _remove_alias {
2290   my ($self, $query, $alias) = @_;
2291
2292   my %orig = %{ $query || {} };
2293   my %unaliased;
2294
2295   foreach my $key (keys %orig) {
2296     if ($key !~ /\./) {
2297       $unaliased{$key} = $orig{$key};
2298       next;
2299     }
2300     $unaliased{$1} = $orig{$key}
2301       if $key =~ m/^(?:\Q$alias\E\.)?([^.]+)$/;
2302   }
2303
2304   return \%unaliased;
2305 }
2306
2307 =head2 as_query
2308
2309 =over 4
2310
2311 =item Arguments: none
2312
2313 =item Return Value: \[ $sql, @bind ]
2314
2315 =back
2316
2317 Returns the SQL query and bind vars associated with the invocant.
2318
2319 This is generally used as the RHS for a subquery.
2320
2321 =cut
2322
2323 sub as_query {
2324   my $self = shift;
2325
2326   my $attrs = $self->_resolved_attrs_copy;
2327
2328   # For future use:
2329   #
2330   # in list ctx:
2331   # my ($sql, \@bind, \%dbi_bind_attrs) = _select_args_to_query (...)
2332   # $sql also has no wrapping parenthesis in list ctx
2333   #
2334   my $sqlbind = $self->result_source->storage
2335     ->_select_args_to_query ($attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs);
2336
2337   return $sqlbind;
2338 }
2339
2340 =head2 find_or_new
2341
2342 =over 4
2343
2344 =item Arguments: \%vals, \%attrs?
2345
2346 =item Return Value: $rowobject
2347
2348 =back
2349
2350   my $artist = $schema->resultset('Artist')->find_or_new(
2351     { artist => 'fred' }, { key => 'artists' });
2352
2353   $cd->cd_to_producer->find_or_new({ producer => $producer },
2354                                    { key => 'primary });
2355
2356 Find an existing record from this resultset using L</find>. if none exists,
2357 instantiate a new result object and return it. The object will not be saved
2358 into your storage until you call L<DBIx::Class::Row/insert> on it.
2359
2360 You most likely want this method when looking for existing rows using a unique
2361 constraint that is not the primary key, or looking for related rows.
2362
2363 If you want objects to be saved immediately, use L</find_or_create> instead.
2364
2365 B<Note>: Make sure to read the documentation of L</find> and understand the
2366 significance of the C<key> attribute, as its lack may skew your search, and
2367 subsequently result in spurious new objects.
2368
2369 B<Note>: Take care when using C<find_or_new> with a table having
2370 columns with default values that you intend to be automatically
2371 supplied by the database (e.g. an auto_increment primary key column).
2372 In normal usage, the value of such columns should NOT be included at
2373 all in the call to C<find_or_new>, even when set to C<undef>.
2374
2375 =cut
2376
2377 sub find_or_new {
2378   my $self     = shift;
2379   my $attrs    = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2380   my $hash     = ref $_[0] eq 'HASH' ? shift : {@_};
2381   if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2382     return $row;
2383   }
2384   return $self->new_result($hash);
2385 }
2386
2387 =head2 create
2388
2389 =over 4
2390
2391 =item Arguments: \%vals
2392
2393 =item Return Value: a L<DBIx::Class::Row> $object
2394
2395 =back
2396
2397 Attempt to create a single new row or a row with multiple related rows
2398 in the table represented by the resultset (and related tables). This
2399 will not check for duplicate rows before inserting, use
2400 L</find_or_create> to do that.
2401
2402 To create one row for this resultset, pass a hashref of key/value
2403 pairs representing the columns of the table and the values you wish to
2404 store. If the appropriate relationships are set up, foreign key fields
2405 can also be passed an object representing the foreign row, and the
2406 value will be set to its primary key.
2407
2408 To create related objects, pass a hashref of related-object column values
2409 B<keyed on the relationship name>. If the relationship is of type C<multi>
2410 (L<DBIx::Class::Relationship/has_many>) - pass an arrayref of hashrefs.
2411 The process will correctly identify columns holding foreign keys, and will
2412 transparently populate them from the keys of the corresponding relation.
2413 This can be applied recursively, and will work correctly for a structure
2414 with an arbitrary depth and width, as long as the relationships actually
2415 exists and the correct column data has been supplied.
2416
2417
2418 Instead of hashrefs of plain related data (key/value pairs), you may
2419 also pass new or inserted objects. New objects (not inserted yet, see
2420 L</new>), will be inserted into their appropriate tables.
2421
2422 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
2423
2424 Example of creating a new row.
2425
2426   $person_rs->create({
2427     name=>"Some Person",
2428     email=>"somebody@someplace.com"
2429   });
2430
2431 Example of creating a new row and also creating rows in a related C<has_many>
2432 or C<has_one> resultset.  Note Arrayref.
2433
2434   $artist_rs->create(
2435      { artistid => 4, name => 'Manufactured Crap', cds => [
2436         { title => 'My First CD', year => 2006 },
2437         { title => 'Yet More Tweeny-Pop crap', year => 2007 },
2438       ],
2439      },
2440   );
2441
2442 Example of creating a new row and also creating a row in a related
2443 C<belongs_to> resultset. Note Hashref.
2444
2445   $cd_rs->create({
2446     title=>"Music for Silly Walks",
2447     year=>2000,
2448     artist => {
2449       name=>"Silly Musician",
2450     }
2451   });
2452
2453 =over
2454
2455 =item WARNING
2456
2457 When subclassing ResultSet never attempt to override this method. Since
2458 it is a simple shortcut for C<< $self->new_result($attrs)->insert >>, a
2459 lot of the internals simply never call it, so your override will be
2460 bypassed more often than not. Override either L<new|DBIx::Class::Row/new>
2461 or L<insert|DBIx::Class::Row/insert> depending on how early in the
2462 L</create> process you need to intervene.
2463
2464 =back
2465
2466 =cut
2467
2468 sub create {
2469   my ($self, $attrs) = @_;
2470   $self->throw_exception( "create needs a hashref" )
2471     unless ref $attrs eq 'HASH';
2472   return $self->new_result($attrs)->insert;
2473 }
2474
2475 =head2 find_or_create
2476
2477 =over 4
2478
2479 =item Arguments: \%vals, \%attrs?
2480
2481 =item Return Value: $rowobject
2482
2483 =back
2484
2485   $cd->cd_to_producer->find_or_create({ producer => $producer },
2486                                       { key => 'primary' });
2487
2488 Tries to find a record based on its primary key or unique constraints; if none
2489 is found, creates one and returns that instead.
2490
2491   my $cd = $schema->resultset('CD')->find_or_create({
2492     cdid   => 5,
2493     artist => 'Massive Attack',
2494     title  => 'Mezzanine',
2495     year   => 2005,
2496   });
2497
2498 Also takes an optional C<key> attribute, to search by a specific key or unique
2499 constraint. For example:
2500
2501   my $cd = $schema->resultset('CD')->find_or_create(
2502     {
2503       artist => 'Massive Attack',
2504       title  => 'Mezzanine',
2505     },
2506     { key => 'cd_artist_title' }
2507   );
2508
2509 B<Note>: Make sure to read the documentation of L</find> and understand the
2510 significance of the C<key> attribute, as its lack may skew your search, and
2511 subsequently result in spurious row creation.
2512
2513 B<Note>: Because find_or_create() reads from the database and then
2514 possibly inserts based on the result, this method is subject to a race
2515 condition. Another process could create a record in the table after
2516 the find has completed and before the create has started. To avoid
2517 this problem, use find_or_create() inside a transaction.
2518
2519 B<Note>: Take care when using C<find_or_create> with a table having
2520 columns with default values that you intend to be automatically
2521 supplied by the database (e.g. an auto_increment primary key column).
2522 In normal usage, the value of such columns should NOT be included at
2523 all in the call to C<find_or_create>, even when set to C<undef>.
2524
2525 See also L</find> and L</update_or_create>. For information on how to declare
2526 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2527
2528 =cut
2529
2530 sub find_or_create {
2531   my $self     = shift;
2532   my $attrs    = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2533   my $hash     = ref $_[0] eq 'HASH' ? shift : {@_};
2534   if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2535     return $row;
2536   }
2537   return $self->create($hash);
2538 }
2539
2540 =head2 update_or_create
2541
2542 =over 4
2543
2544 =item Arguments: \%col_values, { key => $unique_constraint }?
2545
2546 =item Return Value: $row_object
2547
2548 =back
2549
2550   $resultset->update_or_create({ col => $val, ... });
2551
2552 Like L</find_or_create>, but if a row is found it is immediately updated via
2553 C<< $found_row->update (\%col_values) >>.
2554
2555
2556 Takes an optional C<key> attribute to search on a specific unique constraint.
2557 For example:
2558
2559   # In your application
2560   my $cd = $schema->resultset('CD')->update_or_create(
2561     {
2562       artist => 'Massive Attack',
2563       title  => 'Mezzanine',
2564       year   => 1998,
2565     },
2566     { key => 'cd_artist_title' }
2567   );
2568
2569   $cd->cd_to_producer->update_or_create({
2570     producer => $producer,
2571     name => 'harry',
2572   }, {
2573     key => 'primary',
2574   });
2575
2576 B<Note>: Make sure to read the documentation of L</find> and understand the
2577 significance of the C<key> attribute, as its lack may skew your search, and
2578 subsequently result in spurious row creation.
2579
2580 B<Note>: Take care when using C<update_or_create> with a table having
2581 columns with default values that you intend to be automatically
2582 supplied by the database (e.g. an auto_increment primary key column).
2583 In normal usage, the value of such columns should NOT be included at
2584 all in the call to C<update_or_create>, even when set to C<undef>.
2585
2586 See also L</find> and L</find_or_create>. For information on how to declare
2587 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2588
2589 =cut
2590
2591 sub update_or_create {
2592   my $self = shift;
2593   my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2594   my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
2595
2596   my $row = $self->find($cond, $attrs);
2597   if (defined $row) {
2598     $row->update($cond);
2599     return $row;
2600   }
2601
2602   return $self->create($cond);
2603 }
2604
2605 =head2 update_or_new
2606
2607 =over 4
2608
2609 =item Arguments: \%col_values, { key => $unique_constraint }?
2610
2611 =item Return Value: $rowobject
2612
2613 =back
2614
2615   $resultset->update_or_new({ col => $val, ... });
2616
2617 Like L</find_or_new> but if a row is found it is immediately updated via
2618 C<< $found_row->update (\%col_values) >>.
2619
2620 For example:
2621
2622   # In your application
2623   my $cd = $schema->resultset('CD')->update_or_new(
2624     {
2625       artist => 'Massive Attack',
2626       title  => 'Mezzanine',
2627       year   => 1998,
2628     },
2629     { key => 'cd_artist_title' }
2630   );
2631
2632   if ($cd->in_storage) {
2633       # the cd was updated
2634   }
2635   else {
2636       # the cd is not yet in the database, let's insert it
2637       $cd->insert;
2638   }
2639
2640 B<Note>: Make sure to read the documentation of L</find> and understand the
2641 significance of the C<key> attribute, as its lack may skew your search, and
2642 subsequently result in spurious new objects.
2643
2644 B<Note>: Take care when using C<update_or_new> with a table having
2645 columns with default values that you intend to be automatically
2646 supplied by the database (e.g. an auto_increment primary key column).
2647 In normal usage, the value of such columns should NOT be included at
2648 all in the call to C<update_or_new>, even when set to C<undef>.
2649
2650 See also L</find>, L</find_or_create> and L</find_or_new>. 
2651
2652 =cut
2653
2654 sub update_or_new {
2655     my $self  = shift;
2656     my $attrs = ( @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {} );
2657     my $cond  = ref $_[0] eq 'HASH' ? shift : {@_};
2658
2659     my $row = $self->find( $cond, $attrs );
2660     if ( defined $row ) {
2661         $row->update($cond);
2662         return $row;
2663     }
2664
2665     return $self->new_result($cond);
2666 }
2667
2668 =head2 get_cache
2669
2670 =over 4
2671
2672 =item Arguments: none
2673
2674 =item Return Value: \@cache_objects | undef
2675
2676 =back
2677
2678 Gets the contents of the cache for the resultset, if the cache is set.
2679
2680 The cache is populated either by using the L</prefetch> attribute to
2681 L</search> or by calling L</set_cache>.
2682
2683 =cut
2684
2685 sub get_cache {
2686   shift->{all_cache};
2687 }
2688
2689 =head2 set_cache
2690
2691 =over 4
2692
2693 =item Arguments: \@cache_objects
2694
2695 =item Return Value: \@cache_objects
2696
2697 =back
2698
2699 Sets the contents of the cache for the resultset. Expects an arrayref
2700 of objects of the same class as those produced by the resultset. Note that
2701 if the cache is set the resultset will return the cached objects rather
2702 than re-querying the database even if the cache attr is not set.
2703
2704 The contents of the cache can also be populated by using the
2705 L</prefetch> attribute to L</search>.
2706
2707 =cut
2708
2709 sub set_cache {
2710   my ( $self, $data ) = @_;
2711   $self->throw_exception("set_cache requires an arrayref")
2712       if defined($data) && (ref $data ne 'ARRAY');
2713   $self->{all_cache} = $data;
2714 }
2715
2716 =head2 clear_cache
2717
2718 =over 4
2719
2720 =item Arguments: none
2721
2722 =item Return Value: undef
2723
2724 =back
2725
2726 Clears the cache for the resultset.
2727
2728 =cut
2729
2730 sub clear_cache {
2731   shift->set_cache(undef);
2732 }
2733
2734 =head2 is_paged
2735
2736 =over 4
2737
2738 =item Arguments: none
2739
2740 =item Return Value: true, if the resultset has been paginated
2741
2742 =back
2743
2744 =cut
2745
2746 sub is_paged {
2747   my ($self) = @_;
2748   return !!$self->{attrs}{page};
2749 }
2750
2751 =head2 is_ordered
2752
2753 =over 4
2754
2755 =item Arguments: none
2756
2757 =item Return Value: true, if the resultset has been ordered with C<order_by>.
2758
2759 =back
2760
2761 =cut
2762
2763 sub is_ordered {
2764   my ($self) = @_;
2765   return scalar $self->result_source->storage->_extract_order_criteria($self->{attrs}{order_by});
2766 }
2767
2768 =head2 related_resultset
2769
2770 =over 4
2771
2772 =item Arguments: $relationship_name
2773
2774 =item Return Value: $resultset
2775
2776 =back
2777
2778 Returns a related resultset for the supplied relationship name.
2779
2780   $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
2781
2782 =cut
2783
2784 sub related_resultset {
2785   my ($self, $rel) = @_;
2786
2787   $self->{related_resultsets} ||= {};
2788   return $self->{related_resultsets}{$rel} ||= do {
2789     my $rsrc = $self->result_source;
2790     my $rel_info = $rsrc->relationship_info($rel);
2791
2792     $self->throw_exception(
2793       "search_related: result source '" . $rsrc->source_name .
2794         "' has no such relationship $rel")
2795       unless $rel_info;
2796
2797     my $attrs = $self->_chain_relationship($rel);
2798
2799     my $join_count = $attrs->{seen_join}{$rel};
2800
2801     my $alias = $self->result_source->storage
2802         ->relname_to_table_alias($rel, $join_count);
2803
2804     # since this is search_related, and we already slid the select window inwards
2805     # (the select/as attrs were deleted in the beginning), we need to flip all
2806     # left joins to inner, so we get the expected results
2807     # read the comment on top of the actual function to see what this does
2808     $attrs->{from} = $rsrc->schema->storage->_inner_join_to_node ($attrs->{from}, $alias);
2809
2810
2811     #XXX - temp fix for result_class bug. There likely is a more elegant fix -groditi
2812     delete @{$attrs}{qw(result_class alias)};
2813
2814     my $new_cache;
2815
2816     if (my $cache = $self->get_cache) {
2817       if ($cache->[0] && $cache->[0]->related_resultset($rel)->get_cache) {
2818         $new_cache = [ map { @{$_->related_resultset($rel)->get_cache} }
2819                         @$cache ];
2820       }
2821     }
2822
2823     my $rel_source = $rsrc->related_source($rel);
2824
2825     my $new = do {
2826
2827       # The reason we do this now instead of passing the alias to the
2828       # search_rs below is that if you wrap/overload resultset on the
2829       # source you need to know what alias it's -going- to have for things
2830       # to work sanely (e.g. RestrictWithObject wants to be able to add
2831       # extra query restrictions, and these may need to be $alias.)
2832
2833       my $rel_attrs = $rel_source->resultset_attributes;
2834       local $rel_attrs->{alias} = $alias;
2835
2836       $rel_source->resultset
2837                  ->search_rs(
2838                      undef, {
2839                        %$attrs,
2840                        where => $attrs->{where},
2841                    });
2842     };
2843     $new->set_cache($new_cache) if $new_cache;
2844     $new;
2845   };
2846 }
2847
2848 =head2 current_source_alias
2849
2850 =over 4
2851
2852 =item Arguments: none
2853
2854 =item Return Value: $source_alias
2855
2856 =back
2857
2858 Returns the current table alias for the result source this resultset is built
2859 on, that will be used in the SQL query. Usually it is C<me>.
2860
2861 Currently the source alias that refers to the result set returned by a
2862 L</search>/L</find> family method depends on how you got to the resultset: it's
2863 C<me> by default, but eg. L</search_related> aliases it to the related result
2864 source name (and keeps C<me> referring to the original result set). The long
2865 term goal is to make L<DBIx::Class> always alias the current resultset as C<me>
2866 (and make this method unnecessary).
2867
2868 Thus it's currently necessary to use this method in predefined queries (see
2869 L<DBIx::Class::Manual::Cookbook/Predefined searches>) when referring to the
2870 source alias of the current result set:
2871
2872   # in a result set class
2873   sub modified_by {
2874     my ($self, $user) = @_;
2875
2876     my $me = $self->current_source_alias;
2877
2878     return $self->search(
2879       "$me.modified" => $user->id,
2880     );
2881   }
2882
2883 =cut
2884
2885 sub current_source_alias {
2886   my ($self) = @_;
2887
2888   return ($self->{attrs} || {})->{alias} || 'me';
2889 }
2890
2891 =head2 as_subselect_rs
2892
2893 =over 4
2894
2895 =item Arguments: none
2896
2897 =item Return Value: $resultset
2898
2899 =back
2900
2901 Act as a barrier to SQL symbols.  The resultset provided will be made into a
2902 "virtual view" by including it as a subquery within the from clause.  From this
2903 point on, any joined tables are inaccessible to ->search on the resultset (as if
2904 it were simply where-filtered without joins).  For example:
2905
2906  my $rs = $schema->resultset('Bar')->search({'x.name' => 'abc'},{ join => 'x' });
2907
2908  # 'x' now pollutes the query namespace
2909
2910  # So the following works as expected
2911  my $ok_rs = $rs->search({'x.other' => 1});
2912
2913  # But this doesn't: instead of finding a 'Bar' related to two x rows (abc and
2914  # def) we look for one row with contradictory terms and join in another table
2915  # (aliased 'x_2') which we never use
2916  my $broken_rs = $rs->search({'x.name' => 'def'});
2917
2918  my $rs2 = $rs->as_subselect_rs;
2919
2920  # doesn't work - 'x' is no longer accessible in $rs2, having been sealed away
2921  my $not_joined_rs = $rs2->search({'x.other' => 1});
2922
2923  # works as expected: finds a 'table' row related to two x rows (abc and def)
2924  my $correctly_joined_rs = $rs2->search({'x.name' => 'def'});
2925
2926 Another example of when one might use this would be to select a subset of
2927 columns in a group by clause:
2928
2929  my $rs = $schema->resultset('Bar')->search(undef, {
2930    group_by => [qw{ id foo_id baz_id }],
2931  })->as_subselect_rs->search(undef, {
2932    columns => [qw{ id foo_id }]
2933  });
2934
2935 In the above example normally columns would have to be equal to the group by,
2936 but because we isolated the group by into a subselect the above works.
2937
2938 =cut
2939
2940 sub as_subselect_rs {
2941   my $self = shift;
2942
2943   my $attrs = $self->_resolved_attrs;
2944
2945   my $fresh_rs = (ref $self)->new (
2946     $self->result_source
2947   );
2948
2949   # these pieces will be locked in the subquery
2950   delete $fresh_rs->{cond};
2951   delete @{$fresh_rs->{attrs}}{qw/where bind/};
2952
2953   return $fresh_rs->search( {}, {
2954     from => [{
2955       $attrs->{alias} => $self->as_query,
2956       -alias         => $attrs->{alias},
2957       -source_handle => $self->result_source->handle,
2958     }],
2959     alias => $attrs->{alias},
2960   });
2961 }
2962
2963 # This code is called by search_related, and makes sure there
2964 # is clear separation between the joins before, during, and
2965 # after the relationship. This information is needed later
2966 # in order to properly resolve prefetch aliases (any alias
2967 # with a relation_chain_depth less than the depth of the
2968 # current prefetch is not considered)
2969 #
2970 # The increments happen twice per join. An even number means a
2971 # relationship specified via a search_related, whereas an odd
2972 # number indicates a join/prefetch added via attributes
2973 #
2974 # Also this code will wrap the current resultset (the one we
2975 # chain to) in a subselect IFF it contains limiting attributes
2976 sub _chain_relationship {
2977   my ($self, $rel) = @_;
2978   my $source = $self->result_source;
2979   my $attrs = { %{$self->{attrs}||{}} };
2980
2981   # we need to take the prefetch the attrs into account before we
2982   # ->_resolve_join as otherwise they get lost - captainL
2983   my $join = $self->_merge_joinpref_attr( $attrs->{join}, $attrs->{prefetch} );
2984
2985   delete @{$attrs}{qw/join prefetch collapse group_by distinct select as columns +select +as +columns/};
2986
2987   my $seen = { %{ (delete $attrs->{seen_join}) || {} } };
2988
2989   my $from;
2990   my @force_subq_attrs = qw/offset rows group_by having/;
2991
2992   if (
2993     ($attrs->{from} && ref $attrs->{from} ne 'ARRAY')
2994       ||
2995     $self->_has_resolved_attr (@force_subq_attrs)
2996   ) {
2997     # Nuke the prefetch (if any) before the new $rs attrs
2998     # are resolved (prefetch is useless - we are wrapping
2999     # a subquery anyway).
3000     my $rs_copy = $self->search;
3001     $rs_copy->{attrs}{join} = $self->_merge_joinpref_attr (
3002       $rs_copy->{attrs}{join},
3003       delete $rs_copy->{attrs}{prefetch},
3004     );
3005
3006     $from = [{
3007       -source_handle => $source->handle,
3008       -alias => $attrs->{alias},
3009       $attrs->{alias} => $rs_copy->as_query,
3010     }];
3011     delete @{$attrs}{@force_subq_attrs, qw/where bind/};
3012     $seen->{-relation_chain_depth} = 0;
3013   }
3014   elsif ($attrs->{from}) {  #shallow copy suffices
3015     $from = [ @{$attrs->{from}} ];
3016   }
3017   else {
3018     $from = [{
3019       -source_handle => $source->handle,
3020       -alias => $attrs->{alias},
3021       $attrs->{alias} => $source->from,
3022     }];
3023   }
3024
3025   my $jpath = ($seen->{-relation_chain_depth})
3026     ? $from->[-1][0]{-join_path}
3027     : [];
3028
3029   my @requested_joins = $source->_resolve_join(
3030     $join,
3031     $attrs->{alias},
3032     $seen,
3033     $jpath,
3034   );
3035
3036   push @$from, @requested_joins;
3037
3038   $seen->{-relation_chain_depth}++;
3039
3040   # if $self already had a join/prefetch specified on it, the requested
3041   # $rel might very well be already included. What we do in this case
3042   # is effectively a no-op (except that we bump up the chain_depth on
3043   # the join in question so we could tell it *is* the search_related)
3044   my $already_joined;
3045
3046   # we consider the last one thus reverse
3047   for my $j (reverse @requested_joins) {
3048     my ($last_j) = keys %{$j->[0]{-join_path}[-1]};
3049     if ($rel eq $last_j) {
3050       $j->[0]{-relation_chain_depth}++;
3051       $already_joined++;
3052       last;
3053     }
3054   }
3055
3056   unless ($already_joined) {
3057     push @$from, $source->_resolve_join(
3058       $rel,
3059       $attrs->{alias},
3060       $seen,
3061       $jpath,
3062     );
3063   }
3064
3065   $seen->{-relation_chain_depth}++;
3066
3067   return {%$attrs, from => $from, seen_join => $seen};
3068 }
3069
3070 # too many times we have to do $attrs = { %{$self->_resolved_attrs} }
3071 sub _resolved_attrs_copy {
3072   my $self = shift;
3073   return { %{$self->_resolved_attrs (@_)} };
3074 }
3075
3076 sub _resolved_attrs {
3077   my $self = shift;
3078   return $self->{_attrs} if $self->{_attrs};
3079
3080   my $attrs  = { %{ $self->{attrs} || {} } };
3081   my $source = $self->result_source;
3082   my $alias  = $attrs->{alias};
3083
3084 ########
3085 # resolve selectors, this one is quite hairy
3086
3087   my $selection_pieces;
3088
3089   $attrs->{columns} ||= delete $attrs->{cols}
3090     if exists $attrs->{cols};
3091
3092   # disassemble columns / +columns
3093   (
3094     $selection_pieces->{columns}{select},
3095     $selection_pieces->{columns}{as},
3096     $selection_pieces->{'+columns'}{select},
3097     $selection_pieces->{'+columns'}{as},
3098   ) = map
3099     {
3100       my (@sel, @as);
3101
3102       for my $colbit (@$_) {
3103
3104         if (ref $colbit eq 'HASH') {
3105           for my $as (keys %$colbit) {
3106             push @sel, $colbit->{$as};
3107             push @as, $as;
3108           }
3109         }
3110         elsif ($colbit) {
3111           push @sel, $colbit;
3112           push @as, $colbit;
3113         }
3114       }
3115
3116       (\@sel, \@as)
3117     }
3118     (
3119       (ref $attrs->{columns} eq 'ARRAY' ? delete $attrs->{columns} : [ delete $attrs->{columns} ]),
3120       # include_columns is a legacy add-on to +columns
3121       [ map { ref $_ eq 'ARRAY' ? @$_ : ($_ || () ) } delete @{$attrs}{qw/+columns include_columns/} ] )
3122   ;
3123
3124   # make copies of select/as and +select/+as
3125   (
3126     $selection_pieces->{'select/as'}{select},
3127     $selection_pieces->{'select/as'}{as},
3128     $selection_pieces->{'+select/+as'}{select},
3129     $selection_pieces->{'+select/+as'}{as},
3130   ) = map
3131     { $_ ? [ ref $_ eq 'ARRAY' ? @$_ : $_ ] : [] }
3132     ( delete @{$attrs}{qw/select as +select +as/} )
3133   ;
3134
3135   # default to * only when neither no non-plus selectors are available
3136   if (
3137     ! @{$selection_pieces->{'select/as'}{select}}
3138       and
3139     ! @{$selection_pieces->{'columns'}{select}}
3140   ) {
3141     for ($source->columns) {
3142       push @{$selection_pieces->{'select/as'}{select}}, $_;
3143       push @{$selection_pieces->{'select/as'}{as}}, $_;
3144     }
3145   }
3146
3147   # final composition order (important)
3148   my @sel_pairs = grep {
3149     $selection_pieces->{$_}
3150       &&
3151     (
3152       ( $selection_pieces->{$_}{select} && @{$selection_pieces->{$_}{select}} )
3153         ||
3154       ( $selection_pieces->{$_}{as} && @{$selection_pieces->{$_}{as}} )
3155     )
3156   } qw|columns select/as +columns +select/+as|;
3157
3158   # fill in missing as bits for each pair
3159   # if it's the last pair we can let things slide ( bare +select is sadly popular)
3160   my $out_of_sync;
3161
3162   for my $i (0 .. $#sel_pairs) {
3163
3164     my $pairname = $sel_pairs[$i];
3165
3166     my ($sel, $as) = @{$selection_pieces->{$pairname}}{qw/select as/};
3167
3168     $self->throw_exception(
3169       "Unable to assemble final selection list: $pairname specified in addition to unbalanced $sel_pairs[$i-1]"
3170     ) if ($out_of_sync);
3171
3172     if (@$sel == @$as) {
3173       next;
3174     }
3175     elsif (@$sel < @$as) {
3176       $self->throw_exception(
3177         "More 'as' elements than 'select' elements for $pairname, unable to continue"
3178       );
3179     }
3180     else {
3181       # try to deduce the 'as' part, will work only if all the selectors are "plain", or contain an explicit -as
3182       # if we can not deduce something - stop right there and leave the rest of the selector un-as'ed
3183       # if there is an extra selection pair coming after that - it will die due to out_of_sync being set
3184       for my $j ($#$as+1 .. $#$sel) {
3185         if (my $ref = ref $sel->[$j]) {
3186           if ($ref eq 'HASH' and exists $sel->[$j]{-as}) {
3187             push @$as, $sel->[$j]{-as};
3188           }
3189           else {
3190             $out_of_sync++;
3191             last;
3192           }
3193         }
3194         else {
3195           push @$as, $sel->[$j];
3196         }
3197       }
3198     }
3199   }
3200
3201   # assume all unqualified selectors to apply to the current alias (legacy stuff)
3202   # disqualify all $alias.col as-bits (collapser mandated)
3203   for (values %$selection_pieces) {
3204     $_->{select} = [ map { (ref $_ or $_ =~ /\./) ? $_ : "$alias.$_" } @{$_->{select}} ];
3205     $_->{as} = [  map { $_ =~ /^\Q$alias.\E(.+)$/ ? $1 : $_ } @{$_->{as}} ];
3206   }
3207
3208   # merge everything
3209   for (@sel_pairs) {
3210     $attrs->{select} = $self->_merge_attr ($attrs->{select}, $selection_pieces->{$_}{select});
3211     $attrs->{as} = $self->_merge_attr ($attrs->{as}, $selection_pieces->{$_}{as});
3212   }
3213
3214   # de-duplicate the result (remove *identical* select/as pairs)
3215   # and also die on duplicate {as} pointing to different {select}s
3216   # not using a c-style for as the condition is prone to shrinkage
3217   my $seen;
3218   my $i = 0;
3219   while ($i <= $#{$attrs->{as}} ) {
3220     my ($sel, $as) = map { $attrs->{$_}[$i] } (qw/select as/);
3221
3222     if ($seen->{"$sel \x00\x00 $as"}++) {
3223       splice @$_, $i, 1
3224         for @{$attrs}{qw/select as/};
3225     }
3226     elsif ($seen->{$as}++) {
3227       $self->throw_exception(
3228         "inflate_result() alias '$as' specified twice with different SQL-side {select}-ors"
3229       );
3230     }
3231     else {
3232       $i++;
3233     }
3234   }
3235
3236 ## selector resolution done
3237 ########
3238
3239
3240   $attrs->{from} ||= [{
3241     -source_handle => $source->handle,
3242     -alias => $self->{attrs}{alias},
3243     $self->{attrs}{alias} => $source->from,
3244   }];
3245
3246   if ( $attrs->{join} || $attrs->{prefetch} ) {
3247
3248     $self->throw_exception ('join/prefetch can not be used with a custom {from}')
3249       if ref $attrs->{from} ne 'ARRAY';
3250
3251     my $join = delete $attrs->{join} || {};
3252
3253     if ( defined $attrs->{prefetch} ) {
3254       $join = $self->_merge_joinpref_attr( $join, $attrs->{prefetch} );
3255     }
3256
3257     $attrs->{from} =    # have to copy here to avoid corrupting the original
3258       [
3259         @{ $attrs->{from} },
3260         $source->_resolve_join(
3261           $join,
3262           $alias,
3263           { %{ $attrs->{seen_join} || {} } },
3264           ( $attrs->{seen_join} && keys %{$attrs->{seen_join}})
3265             ? $attrs->{from}[-1][0]{-join_path}
3266             : []
3267           ,
3268         )
3269       ];
3270   }
3271
3272   if ( defined $attrs->{order_by} ) {
3273     $attrs->{order_by} = (
3274       ref( $attrs->{order_by} ) eq 'ARRAY'
3275       ? [ @{ $attrs->{order_by} } ]
3276       : [ $attrs->{order_by} || () ]
3277     );
3278   }
3279
3280   if ($attrs->{group_by} and ref $attrs->{group_by} ne 'ARRAY') {
3281     $attrs->{group_by} = [ $attrs->{group_by} ];
3282   }
3283
3284   # generate the distinct induced group_by early, as prefetch will be carried via a
3285   # subquery (since a group_by is present)
3286   if (delete $attrs->{distinct}) {
3287     if ($attrs->{group_by}) {
3288       carp ("Useless use of distinct on a grouped resultset ('distinct' is ignored when a 'group_by' is present)");
3289     }
3290     else {
3291       $attrs->{group_by} = $source->storage->_group_over_selection (
3292         @{$attrs}{qw/from select order_by/}
3293       );
3294     }
3295   }
3296
3297   $attrs->{collapse} ||= {};
3298   if ( my $prefetch = delete $attrs->{prefetch} ) {
3299     $prefetch = $self->_merge_joinpref_attr( {}, $prefetch );
3300
3301     my $prefetch_ordering = [];
3302
3303     # this is a separate structure (we don't look in {from} directly)
3304     # as the resolver needs to shift things off the lists to work
3305     # properly (identical-prefetches on different branches)
3306     my $join_map = {};
3307     if (ref $attrs->{from} eq 'ARRAY') {
3308
3309       my $start_depth = $attrs->{seen_join}{-relation_chain_depth} || 0;
3310
3311       for my $j ( @{$attrs->{from}}[1 .. $#{$attrs->{from}} ] ) {
3312         next unless $j->[0]{-alias};
3313         next unless $j->[0]{-join_path};
3314         next if ($j->[0]{-relation_chain_depth} || 0) < $start_depth;
3315
3316         my @jpath = map { keys %$_ } @{$j->[0]{-join_path}};
3317
3318         my $p = $join_map;
3319         $p = $p->{$_} ||= {} for @jpath[ ($start_depth/2) .. $#jpath]; #only even depths are actual jpath boundaries
3320         push @{$p->{-join_aliases} }, $j->[0]{-alias};
3321       }
3322     }
3323
3324     my @prefetch =
3325       $source->_resolve_prefetch( $prefetch, $alias, $join_map, $prefetch_ordering, $attrs->{collapse} );
3326
3327     # we need to somehow mark which columns came from prefetch
3328     $attrs->{_prefetch_select} = [ map { $_->[0] } @prefetch ];
3329
3330     push @{ $attrs->{select} }, @{$attrs->{_prefetch_select}};
3331     push @{ $attrs->{as} }, (map { $_->[1] } @prefetch);
3332
3333     push( @{$attrs->{order_by}}, @$prefetch_ordering );
3334     $attrs->{_collapse_order_by} = \@$prefetch_ordering;
3335   }
3336
3337   # if both page and offset are specified, produce a combined offset
3338   # even though it doesn't make much sense, this is what pre 081xx has
3339   # been doing
3340   if (my $page = delete $attrs->{page}) {
3341     $attrs->{offset} =
3342       ($attrs->{rows} * ($page - 1))
3343             +
3344       ($attrs->{offset} || 0)
3345     ;
3346   }
3347
3348   return $self->{_attrs} = $attrs;
3349 }
3350
3351 sub _rollout_attr {
3352   my ($self, $attr) = @_;
3353
3354   if (ref $attr eq 'HASH') {
3355     return $self->_rollout_hash($attr);
3356   } elsif (ref $attr eq 'ARRAY') {
3357     return $self->_rollout_array($attr);
3358   } else {
3359     return [$attr];
3360   }
3361 }
3362
3363 sub _rollout_array {
3364   my ($self, $attr) = @_;
3365
3366   my @rolled_array;
3367   foreach my $element (@{$attr}) {
3368     if (ref $element eq 'HASH') {
3369       push( @rolled_array, @{ $self->_rollout_hash( $element ) } );
3370     } elsif (ref $element eq 'ARRAY') {
3371       #  XXX - should probably recurse here
3372       push( @rolled_array, @{$self->_rollout_array($element)} );
3373     } else {
3374       push( @rolled_array, $element );
3375     }
3376   }
3377   return \@rolled_array;
3378 }
3379
3380 sub _rollout_hash {
3381   my ($self, $attr) = @_;
3382
3383   my @rolled_array;
3384   foreach my $key (keys %{$attr}) {
3385     push( @rolled_array, { $key => $attr->{$key} } );
3386   }
3387   return \@rolled_array;
3388 }
3389
3390 sub _calculate_score {
3391   my ($self, $a, $b) = @_;
3392
3393   if (defined $a xor defined $b) {
3394     return 0;
3395   }
3396   elsif (not defined $a) {
3397     return 1;
3398   }
3399
3400   if (ref $b eq 'HASH') {
3401     my ($b_key) = keys %{$b};
3402     if (ref $a eq 'HASH') {
3403       my ($a_key) = keys %{$a};
3404       if ($a_key eq $b_key) {
3405         return (1 + $self->_calculate_score( $a->{$a_key}, $b->{$b_key} ));
3406       } else {
3407         return 0;
3408       }
3409     } else {
3410       return ($a eq $b_key) ? 1 : 0;
3411     }
3412   } else {
3413     if (ref $a eq 'HASH') {
3414       my ($a_key) = keys %{$a};
3415       return ($b eq $a_key) ? 1 : 0;
3416     } else {
3417       return ($b eq $a) ? 1 : 0;
3418     }
3419   }
3420 }
3421
3422 sub _merge_joinpref_attr {
3423   my ($self, $orig, $import) = @_;
3424
3425   return $import unless defined($orig);
3426   return $orig unless defined($import);
3427
3428   $orig = $self->_rollout_attr($orig);
3429   $import = $self->_rollout_attr($import);
3430
3431   my $seen_keys;
3432   foreach my $import_element ( @{$import} ) {
3433     # find best candidate from $orig to merge $b_element into
3434     my $best_candidate = { position => undef, score => 0 }; my $position = 0;
3435     foreach my $orig_element ( @{$orig} ) {
3436       my $score = $self->_calculate_score( $orig_element, $import_element );
3437       if ($score > $best_candidate->{score}) {
3438         $best_candidate->{position} = $position;
3439         $best_candidate->{score} = $score;
3440       }
3441       $position++;
3442     }
3443     my ($import_key) = ( ref $import_element eq 'HASH' ) ? keys %{$import_element} : ($import_element);
3444
3445     if ($best_candidate->{score} == 0 || exists $seen_keys->{$import_key}) {
3446       push( @{$orig}, $import_element );
3447     } else {
3448       my $orig_best = $orig->[$best_candidate->{position}];
3449       # merge orig_best and b_element together and replace original with merged
3450       if (ref $orig_best ne 'HASH') {
3451         $orig->[$best_candidate->{position}] = $import_element;
3452       } elsif (ref $import_element eq 'HASH') {
3453         my ($key) = keys %{$orig_best};
3454         $orig->[$best_candidate->{position}] = { $key => $self->_merge_joinpref_attr($orig_best->{$key}, $import_element->{$key}) };
3455       }
3456     }
3457     $seen_keys->{$import_key} = 1; # don't merge the same key twice
3458   }
3459
3460   return $orig;
3461 }
3462
3463 {
3464   my $hm;
3465
3466   sub _merge_attr {
3467     $hm ||= do {
3468       my $hm = Hash::Merge->new;
3469
3470       $hm->specify_behavior({
3471         SCALAR => {
3472           SCALAR => sub {
3473             my ($defl, $defr) = map { defined $_ } (@_[0,1]);
3474
3475             if ($defl xor $defr) {
3476               return $defl ? $_[0] : $_[1];
3477             }
3478             elsif (! $defl) {
3479               return ();
3480             }
3481             elsif (__HM_DEDUP and $_[0] eq $_[1]) {
3482               return $_[0];
3483             }
3484             else {
3485               return [$_[0], $_[1]];
3486             }
3487           },
3488           ARRAY => sub {
3489             return $_[1] if !defined $_[0];
3490             return $_[1] if __HM_DEDUP and List::Util::first { $_ eq $_[0] } @{$_[1]};
3491             return [$_[0], @{$_[1]}]
3492           },
3493           HASH  => sub {
3494             return $_[1] if !defined $_[0];
3495             return $_[0] if !keys %{$_[1]};
3496             return [$_[0], $_[1]]
3497           },
3498         },
3499         ARRAY => {
3500           SCALAR => sub {
3501             return $_[0] if !defined $_[1];
3502             return $_[0] if __HM_DEDUP and List::Util::first { $_ eq $_[1] } @{$_[0]};
3503             return [@{$_[0]}, $_[1]]
3504           },
3505           ARRAY => sub {
3506             my @ret = @{$_[0]} or return $_[1];
3507             return [ @ret, @{$_[1]} ] unless __HM_DEDUP;
3508             my %idx = map { $_ => 1 } @ret;
3509             push @ret, grep { ! defined $idx{$_} } (@{$_[1]});
3510             \@ret;
3511           },
3512           HASH => sub {
3513             return [ $_[1] ] if ! @{$_[0]};
3514             return $_[0] if !keys %{$_[1]};
3515             return $_[0] if __HM_DEDUP and List::Util::first { $_ eq $_[1] } @{$_[0]};
3516             return [ @{$_[0]}, $_[1] ];
3517           },
3518         },
3519         HASH => {
3520           SCALAR => sub {
3521             return $_[0] if !defined $_[1];
3522             return $_[1] if !keys %{$_[0]};
3523             return [$_[0], $_[1]]
3524           },
3525           ARRAY => sub {
3526             return $_[0] if !@{$_[1]};
3527             return $_[1] if !keys %{$_[0]};
3528             return $_[1] if __HM_DEDUP and List::Util::first { $_ eq $_[0] } @{$_[1]};
3529             return [ $_[0], @{$_[1]} ];
3530           },
3531           HASH => sub {
3532             return $_[0] if !keys %{$_[1]};
3533             return $_[1] if !keys %{$_[0]};
3534             return $_[0] if $_[0] eq $_[1];
3535             return [ $_[0], $_[1] ];
3536           },
3537         }
3538       } => 'DBIC_RS_ATTR_MERGER');
3539       $hm;
3540     };
3541
3542     return $hm->merge ($_[1], $_[2]);
3543   }
3544 }
3545
3546 sub result_source {
3547     my $self = shift;
3548
3549     if (@_) {
3550         $self->_source_handle($_[0]->handle);
3551     } else {
3552         $self->_source_handle->resolve;
3553     }
3554 }
3555
3556
3557 sub STORABLE_freeze {
3558   my ($self, $cloning) = @_;
3559   my $to_serialize = { %$self };
3560
3561   # A cursor in progress can't be serialized (and would make little sense anyway)
3562   delete $to_serialize->{cursor};
3563
3564   return nfreeze($to_serialize);
3565 }
3566
3567 # need this hook for symmetry
3568 sub STORABLE_thaw {
3569   my ($self, $cloning, $serialized) = @_;
3570
3571   %$self = %{ thaw($serialized) };
3572
3573   return $self;
3574 }
3575
3576
3577 =head2 throw_exception
3578
3579 See L<DBIx::Class::Schema/throw_exception> for details.
3580
3581 =cut
3582
3583 sub throw_exception {
3584   my $self=shift;
3585
3586   if (ref $self && $self->_source_handle->schema) {
3587     $self->_source_handle->schema->throw_exception(@_)
3588   }
3589   else {
3590     DBIx::Class::Exception->throw(@_);
3591   }
3592 }
3593
3594 # XXX: FIXME: Attributes docs need clearing up
3595
3596 =head1 ATTRIBUTES
3597
3598 Attributes are used to refine a ResultSet in various ways when
3599 searching for data. They can be passed to any method which takes an
3600 C<\%attrs> argument. See L</search>, L</search_rs>, L</find>,
3601 L</count>.
3602
3603 These are in no particular order:
3604
3605 =head2 order_by
3606
3607 =over 4
3608
3609 =item Value: ( $order_by | \@order_by | \%order_by )
3610
3611 =back
3612
3613 Which column(s) to order the results by.
3614
3615 [The full list of suitable values is documented in
3616 L<SQL::Abstract/"ORDER BY CLAUSES">; the following is a summary of
3617 common options.]
3618
3619 If a single column name, or an arrayref of names is supplied, the
3620 argument is passed through directly to SQL. The hashref syntax allows
3621 for connection-agnostic specification of ordering direction:
3622
3623  For descending order:
3624
3625   order_by => { -desc => [qw/col1 col2 col3/] }
3626
3627  For explicit ascending order:
3628
3629   order_by => { -asc => 'col' }
3630
3631 The old scalarref syntax (i.e. order_by => \'year DESC') is still
3632 supported, although you are strongly encouraged to use the hashref
3633 syntax as outlined above.
3634
3635 =head2 columns
3636
3637 =over 4
3638
3639 =item Value: \@columns
3640
3641 =back
3642
3643 Shortcut to request a particular set of columns to be retrieved. Each
3644 column spec may be a string (a table column name), or a hash (in which
3645 case the key is the C<as> value, and the value is used as the C<select>
3646 expression). Adds C<me.> onto the start of any column without a C<.> in
3647 it and sets C<select> from that, then auto-populates C<as> from
3648 C<select> as normal. (You may also use the C<cols> attribute, as in
3649 earlier versions of DBIC.)
3650
3651 Essentially C<columns> does the same as L</select> and L</as>.
3652
3653     columns => [ 'foo', { bar => 'baz' } ]
3654
3655 is the same as
3656
3657     select => [qw/foo baz/],
3658     as => [qw/foo bar/]
3659
3660 =head2 +columns
3661
3662 =over 4
3663
3664 =item Value: \@columns
3665
3666 =back
3667
3668 Indicates additional columns to be selected from storage. Works the same
3669 as L</columns> but adds columns to the selection. (You may also use the
3670 C<include_columns> attribute, as in earlier versions of DBIC). For
3671 example:-
3672
3673   $schema->resultset('CD')->search(undef, {
3674     '+columns' => ['artist.name'],
3675     join => ['artist']
3676   });
3677
3678 would return all CDs and include a 'name' column to the information
3679 passed to object inflation. Note that the 'artist' is the name of the
3680 column (or relationship) accessor, and 'name' is the name of the column
3681 accessor in the related table.
3682
3683 =head2 include_columns
3684
3685 =over 4
3686
3687 =item Value: \@columns
3688
3689 =back
3690
3691 Deprecated.  Acts as a synonym for L</+columns> for backward compatibility.
3692
3693 =head2 select
3694
3695 =over 4
3696
3697 =item Value: \@select_columns
3698
3699 =back
3700
3701 Indicates which columns should be selected from the storage. You can use
3702 column names, or in the case of RDBMS back ends, function or stored procedure
3703 names:
3704
3705   $rs = $schema->resultset('Employee')->search(undef, {
3706     select => [
3707       'name',
3708       { count => 'employeeid' },
3709       { max => { length => 'name' }, -as => 'longest_name' }
3710     ]
3711   });
3712
3713   # Equivalent SQL
3714   SELECT name, COUNT( employeeid ), MAX( LENGTH( name ) ) AS longest_name FROM employee
3715
3716 B<NOTE:> You will almost always need a corresponding L</as> attribute when you
3717 use L</select>, to instruct DBIx::Class how to store the result of the column.
3718 Also note that the L</as> attribute has nothing to do with the SQL-side 'AS'
3719 identifier aliasing. You can however alias a function, so you can use it in
3720 e.g. an C<ORDER BY> clause. This is done via the C<-as> B<select function
3721 attribute> supplied as shown in the example above.
3722
3723 =head2 +select
3724
3725 =over 4
3726
3727 Indicates additional columns to be selected from storage.  Works the same as
3728 L</select> but adds columns to the default selection, instead of specifying
3729 an explicit list.
3730
3731 =back
3732
3733 =head2 +as
3734
3735 =over 4
3736
3737 Indicates additional column names for those added via L</+select>. See L</as>.
3738
3739 =back
3740
3741 =head2 as
3742
3743 =over 4
3744
3745 =item Value: \@inflation_names
3746
3747 =back
3748
3749 Indicates column names for object inflation. That is L</as> indicates the
3750 slot name in which the column value will be stored within the
3751 L<Row|DBIx::Class::Row> object. The value will then be accessible via this
3752 identifier by the C<get_column> method (or via the object accessor B<if one
3753 with the same name already exists>) as shown below. The L</as> attribute has
3754 B<nothing to do> with the SQL-side C<AS>. See L</select> for details.
3755
3756   $rs = $schema->resultset('Employee')->search(undef, {
3757     select => [
3758       'name',
3759       { count => 'employeeid' },
3760       { max => { length => 'name' }, -as => 'longest_name' }
3761     ],
3762     as => [qw/
3763       name
3764       employee_count
3765       max_name_length
3766     /],
3767   });
3768
3769 If the object against which the search is performed already has an accessor
3770 matching a column name specified in C<as>, the value can be retrieved using
3771 the accessor as normal:
3772
3773   my $name = $employee->name();
3774
3775 If on the other hand an accessor does not exist in the object, you need to
3776 use C<get_column> instead:
3777
3778   my $employee_count = $employee->get_column('employee_count');
3779
3780 You can create your own accessors if required - see
3781 L<DBIx::Class::Manual::Cookbook> for details.
3782
3783 =head2 join
3784
3785 =over 4
3786
3787 =item Value: ($rel_name | \@rel_names | \%rel_names)
3788
3789 =back
3790
3791 Contains a list of relationships that should be joined for this query.  For
3792 example:
3793
3794   # Get CDs by Nine Inch Nails
3795   my $rs = $schema->resultset('CD')->search(
3796     { 'artist.name' => 'Nine Inch Nails' },
3797     { join => 'artist' }
3798   );
3799
3800 Can also contain a hash reference to refer to the other relation's relations.
3801 For example:
3802
3803   package MyApp::Schema::Track;
3804   use base qw/DBIx::Class/;
3805   __PACKAGE__->table('track');
3806   __PACKAGE__->add_columns(qw/trackid cd position title/);
3807   __PACKAGE__->set_primary_key('trackid');
3808   __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
3809   1;
3810
3811   # In your application
3812   my $rs = $schema->resultset('Artist')->search(
3813     { 'track.title' => 'Teardrop' },
3814     {
3815       join     => { cd => 'track' },
3816       order_by => 'artist.name',
3817     }
3818   );
3819
3820 You need to use the relationship (not the table) name in  conditions,
3821 because they are aliased as such. The current table is aliased as "me", so
3822 you need to use me.column_name in order to avoid ambiguity. For example:
3823
3824   # Get CDs from 1984 with a 'Foo' track
3825   my $rs = $schema->resultset('CD')->search(
3826     {
3827       'me.year' => 1984,
3828       'tracks.name' => 'Foo'
3829     },
3830     { join => 'tracks' }
3831   );
3832
3833 If the same join is supplied twice, it will be aliased to <rel>_2 (and
3834 similarly for a third time). For e.g.
3835
3836   my $rs = $schema->resultset('Artist')->search({
3837     'cds.title'   => 'Down to Earth',
3838     'cds_2.title' => 'Popular',
3839   }, {
3840     join => [ qw/cds cds/ ],
3841   });
3842
3843 will return a set of all artists that have both a cd with title 'Down
3844 to Earth' and a cd with title 'Popular'.
3845
3846 If you want to fetch related objects from other tables as well, see C<prefetch>
3847 below.
3848
3849 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
3850
3851 =head2 prefetch
3852
3853 =over 4
3854
3855 =item Value: ($rel_name | \@rel_names | \%rel_names)
3856
3857 =back
3858
3859 Contains one or more relationships that should be fetched along with
3860 the main query (when they are accessed afterwards the data will
3861 already be available, without extra queries to the database).  This is
3862 useful for when you know you will need the related objects, because it
3863 saves at least one query:
3864
3865   my $rs = $schema->resultset('Tag')->search(
3866     undef,
3867     {
3868       prefetch => {
3869         cd => 'artist'
3870       }
3871     }
3872   );
3873
3874 The initial search results in SQL like the following:
3875
3876   SELECT tag.*, cd.*, artist.* FROM tag
3877   JOIN cd ON tag.cd = cd.cdid
3878   JOIN artist ON cd.artist = artist.artistid
3879
3880 L<DBIx::Class> has no need to go back to the database when we access the
3881 C<cd> or C<artist> relationships, which saves us two SQL statements in this
3882 case.
3883
3884 Simple prefetches will be joined automatically, so there is no need
3885 for a C<join> attribute in the above search.
3886
3887 C<prefetch> can be used with the following relationship types: C<belongs_to>,
3888 C<has_one> (or if you're using C<add_relationship>, any relationship declared
3889 with an accessor type of 'single' or 'filter'). A more complex example that
3890 prefetches an artists cds, the tracks on those cds, and the tags associated
3891 with that artist is given below (assuming many-to-many from artists to tags):
3892
3893  my $rs = $schema->resultset('Artist')->search(
3894    undef,
3895    {
3896      prefetch => [
3897        { cds => 'tracks' },
3898        { artist_tags => 'tags' }
3899      ]
3900    }
3901  );
3902
3903
3904 B<NOTE:> If you specify a C<prefetch> attribute, the C<join> and C<select>
3905 attributes will be ignored.
3906
3907 B<CAVEATs>: Prefetch does a lot of deep magic. As such, it may not behave
3908 exactly as you might expect.
3909
3910 =over 4
3911
3912 =item *
3913
3914 Prefetch uses the L</cache> to populate the prefetched relationships. This
3915 may or may not be what you want.
3916
3917 =item *
3918
3919 If you specify a condition on a prefetched relationship, ONLY those
3920 rows that match the prefetched condition will be fetched into that relationship.
3921 This means that adding prefetch to a search() B<may alter> what is returned by
3922 traversing a relationship. So, if you have C<< Artist->has_many(CDs) >> and you do
3923
3924   my $artist_rs = $schema->resultset('Artist')->search({
3925       'cds.year' => 2008,
3926   }, {
3927       join => 'cds',
3928   });
3929
3930   my $count = $artist_rs->first->cds->count;
3931
3932   my $artist_rs_prefetch = $artist_rs->search( {}, { prefetch => 'cds' } );
3933
3934   my $prefetch_count = $artist_rs_prefetch->first->cds->count;
3935
3936   cmp_ok( $count, '==', $prefetch_count, "Counts should be the same" );
3937
3938 that cmp_ok() may or may not pass depending on the datasets involved. This
3939 behavior may or may not survive the 0.09 transition.
3940
3941 =back
3942
3943 =head2 page
3944
3945 =over 4
3946
3947 =item Value: $page
3948
3949 =back
3950
3951 Makes the resultset paged and specifies the page to retrieve. Effectively
3952 identical to creating a non-pages resultset and then calling ->page($page)
3953 on it.
3954
3955 If L<rows> attribute is not specified it defaults to 10 rows per page.
3956
3957 When you have a paged resultset, L</count> will only return the number
3958 of rows in the page. To get the total, use the L</pager> and call
3959 C<total_entries> on it.
3960
3961 =head2 rows
3962
3963 =over 4
3964
3965 =item Value: $rows
3966
3967 =back
3968
3969 Specifies the maximum number of rows for direct retrieval or the number of
3970 rows per page if the page attribute or method is used.
3971
3972 =head2 offset
3973
3974 =over 4
3975
3976 =item Value: $offset
3977
3978 =back
3979
3980 Specifies the (zero-based) row number for the  first row to be returned, or the
3981 of the first row of the first page if paging is used.
3982
3983 =head2 group_by
3984
3985 =over 4
3986
3987 =item Value: \@columns
3988
3989 =back
3990
3991 A arrayref of columns to group by. Can include columns of joined tables.
3992
3993   group_by => [qw/ column1 column2 ... /]
3994
3995 =head2 having
3996
3997 =over 4
3998
3999 =item Value: $condition
4000
4001 =back
4002
4003 HAVING is a select statement attribute that is applied between GROUP BY and
4004 ORDER BY. It is applied to the after the grouping calculations have been
4005 done.
4006
4007   having => { 'count_employee' => { '>=', 100 } }
4008
4009 or with an in-place function in which case literal SQL is required:
4010
4011   having => \[ 'count(employee) >= ?', [ count => 100 ] ]
4012
4013 =head2 distinct
4014
4015 =over 4
4016
4017 =item Value: (0 | 1)
4018
4019 =back
4020
4021 Set to 1 to group by all columns. If the resultset already has a group_by
4022 attribute, this setting is ignored and an appropriate warning is issued.
4023
4024 =head2 where
4025
4026 =over 4
4027
4028 Adds to the WHERE clause.
4029
4030   # only return rows WHERE deleted IS NULL for all searches
4031   __PACKAGE__->resultset_attributes({ where => { deleted => undef } }); )
4032
4033 Can be overridden by passing C<< { where => undef } >> as an attribute
4034 to a resultset.
4035
4036 =back
4037
4038 =head2 cache
4039
4040 Set to 1 to cache search results. This prevents extra SQL queries if you
4041 revisit rows in your ResultSet:
4042
4043   my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
4044
4045   while( my $artist = $resultset->next ) {
4046     ... do stuff ...
4047   }
4048
4049   $rs->first; # without cache, this would issue a query
4050
4051 By default, searches are not cached.
4052
4053 For more examples of using these attributes, see
4054 L<DBIx::Class::Manual::Cookbook>.
4055
4056 =head2 for
4057
4058 =over 4
4059
4060 =item Value: ( 'update' | 'shared' )
4061
4062 =back
4063
4064 Set to 'update' for a SELECT ... FOR UPDATE or 'shared' for a SELECT
4065 ... FOR SHARED.
4066
4067 =cut
4068
4069 1;