1 package DBIx::Class::ResultSet;
9 use Carp::Clan qw/^DBIx::Class/;
12 use Scalar::Util qw/weaken/;
13 use DBIx::Class::ResultSetColumn;
14 use base qw/DBIx::Class/;
15 __PACKAGE__->load_components(qw/AccessorGroup/);
16 __PACKAGE__->mk_group_accessors('simple' => qw/result_source result_class/);
20 DBIx::Class::ResultSet - Responsible for fetching and creating resultset.
24 my $rs = $schema->resultset('User')->search(registered => 1);
25 my @rows = $schema->resultset('CD')->search(year => 2005);
29 The resultset is also known as an iterator. It is responsible for handling
30 queries that may return an arbitrary number of rows, e.g. via L</search>
31 or a C<has_many> relationship.
33 In the examples below, the following table classes are used:
35 package MyApp::Schema::Artist;
36 use base qw/DBIx::Class/;
37 __PACKAGE__->load_components(qw/Core/);
38 __PACKAGE__->table('artist');
39 __PACKAGE__->add_columns(qw/artistid name/);
40 __PACKAGE__->set_primary_key('artistid');
41 __PACKAGE__->has_many(cds => 'MyApp::Schema::CD');
44 package MyApp::Schema::CD;
45 use base qw/DBIx::Class/;
46 __PACKAGE__->load_components(qw/Core/);
47 __PACKAGE__->table('cd');
48 __PACKAGE__->add_columns(qw/cdid artist title year/);
49 __PACKAGE__->set_primary_key('cdid');
50 __PACKAGE__->belongs_to(artist => 'MyApp::Schema::Artist');
59 =item Arguments: $source, \%$attrs
61 =item Return Value: $rs
65 The resultset constructor. Takes a source object (usually a
66 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
67 L</ATTRIBUTES> below). Does not perform any queries -- these are
68 executed as needed by the other methods.
70 Generally you won't need to construct a resultset manually. You'll
71 automatically get one from e.g. a L</search> called in scalar context:
73 my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
75 IMPORTANT: If called on an object, proxies to new_result instead so
77 my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
79 will return a CD object, not a ResultSet.
85 return $class->new_result(@_) if ref $class;
87 my ($source, $attrs) = @_;
91 $attrs->{rows} ||= 10;
92 $attrs->{offset} ||= 0;
93 $attrs->{offset} += ($attrs->{rows} * ($attrs->{page} - 1));
96 $attrs->{alias} ||= 'me';
97 $attrs->{_orig_alias} ||= $attrs->{alias};
100 result_source => $source,
101 result_class => $attrs->{result_class} || $source->result_class,
102 cond => $attrs->{where},
103 # from => $attrs->{from},
104 # collapse => $collapse,
115 =item Arguments: $cond, \%attrs?
117 =item Return Value: $resultset (scalar context), @row_objs (list context)
121 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
122 my $new_rs = $cd_rs->search({ year => 2005 });
124 my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
125 # year = 2005 OR year = 2004
127 If you need to pass in additional attributes but no additional condition,
128 call it as C<search(undef, \%attrs)>.
130 # "SELECT name, artistid FROM $artist_table"
131 my @all_artists = $schema->resultset('Artist')->search(undef, {
132 columns => [qw/name artistid/],
139 my $rs = $self->search_rs( @_ );
140 return (wantarray ? $rs->all : $rs);
147 =item Arguments: $cond, \%attrs?
149 =item Return Value: $resultset
153 This method does the same exact thing as search() except it will
154 always return a resultset, even in list context.
162 $attrs = pop(@_) if @_ > 1 and ref $_[$#_] eq 'HASH';
163 my $our_attrs = exists $attrs->{_parent_attrs}
164 ? { %{delete $attrs->{_parent_attrs}} }
165 : { %{$self->{attrs}} };
166 my $having = delete $our_attrs->{having};
168 # XXX should only maintain _live_join_stack and generate _live_join_h from that
169 if ($attrs->{_live_join_stack}) {
170 foreach my $join (reverse @{$attrs->{_live_join_stack}}) {
171 $attrs->{_live_join_h} = defined $attrs->{_live_join_h}
172 ? { $join => $attrs->{_live_join_h} }
177 # merge new attrs into inherited
178 foreach my $key (qw/join prefetch/) {
179 next unless exists $attrs->{$key};
180 if (my $live_join = $attrs->{_live_join_stack} || $our_attrs->{_live_join_stack}) {
181 foreach my $join (reverse @{$live_join}) {
182 $attrs->{$key} = { $join => $attrs->{$key} };
186 $our_attrs->{$key} = $self->_merge_attr($our_attrs->{$key}, delete $attrs->{$key});
189 $our_attrs->{join} = $self->_merge_attr(
190 $our_attrs->{join}, $attrs->{_live_join_h}
191 ) if ($attrs->{_live_join_h});
193 if (defined $our_attrs->{prefetch}) {
194 $our_attrs->{join} = $self->_merge_attr(
195 $our_attrs->{join}, $our_attrs->{prefetch}
199 my $new_attrs = { %{$our_attrs}, %{$attrs} };
202 (@_ == 1 || ref $_[0] eq "HASH")
206 ? $self->throw_exception("Odd number of arguments to search")
213 if (defined $where) {
214 $new_attrs->{where} = (
215 defined $new_attrs->{where}
218 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
219 } $where, $new_attrs->{where}
225 if (defined $having) {
226 $new_attrs->{having} = (
227 defined $new_attrs->{having}
230 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
231 } $having, $new_attrs->{having}
237 my $rs = (ref $self)->new($self->result_source, $new_attrs);
238 $rs->{_parent_rs} = $self->{_parent_rs} if $self->{_parent_rs};
240 unless (@_) { # no search, effectively just a clone
241 my $rows = $self->get_cache;
243 $rs->set_cache($rows);
249 =head2 search_literal
253 =item Arguments: $sql_fragment, @bind_values
255 =item Return Value: $resultset (scalar context), @row_objs (list context)
259 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
260 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
262 Pass a literal chunk of SQL to be added to the conditional part of the
268 my ($self, $cond, @vals) = @_;
269 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
270 $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
271 return $self->search(\$cond, $attrs);
278 =item Arguments: @values | \%cols, \%attrs?
280 =item Return Value: $row_object
284 Finds a row based on its primary key or unique constraint. For example, to find
285 a row by its primary key:
287 my $cd = $schema->resultset('CD')->find(5);
289 You can also find a row by a specific unique constraint using the C<key>
290 attribute. For example:
292 my $cd = $schema->resultset('CD')->find('Massive Attack', 'Mezzanine', {
293 key => 'cd_artist_title'
296 Additionally, you can specify the columns explicitly by name:
298 my $cd = $schema->resultset('CD')->find(
300 artist => 'Massive Attack',
301 title => 'Mezzanine',
303 { key => 'cd_artist_title' }
306 If the C<key> is specified as C<primary>, it searches only on the primary key.
308 If no C<key> is specified, it searches on all unique constraints defined on the
309 source, including the primary key.
311 See also L</find_or_create> and L</update_or_create>. For information on how to
312 declare unique constraints, see
313 L<DBIx::Class::ResultSource/add_unique_constraint>.
319 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
321 # Default to the primary key, but allow a specific key
322 my @cols = exists $attrs->{key}
323 ? $self->result_source->unique_constraint_columns($attrs->{key})
324 : $self->result_source->primary_columns;
325 $self->throw_exception(
326 "Can't find unless a primary key or unique constraint is defined"
329 # Parse out a hashref from input
331 if (ref $_[0] eq 'HASH') {
332 $input_query = { %{$_[0]} };
334 elsif (@_ == @cols) {
336 @{$input_query}{@cols} = @_;
339 # Compatibility: Allow e.g. find(id => $value)
340 carp "Find by key => value deprecated; please use a hashref instead";
344 my @unique_queries = $self->_unique_queries($input_query, $attrs);
346 # Handle cases where the ResultSet defines the query, or where the user is
348 my $query = @unique_queries ? \@unique_queries : $input_query;
352 my $rs = $self->search($query, $attrs);
354 return keys %{$rs->{_attrs}{collapse}} ? $rs->next : $rs->single;
357 $self->_resolve_attr;
358 return keys %{$self->{_attrs}{collapse}}
359 ? $self->search($query)->next
360 : $self->single($query);
366 # Build a list of queries which satisfy unique constraints.
368 sub _unique_queries {
369 my ($self, $query, $attrs) = @_;
371 my @constraint_names = exists $attrs->{key}
373 : $self->result_source->unique_constraint_names;
376 foreach my $name (@constraint_names) {
377 my @unique_cols = $self->result_source->unique_constraint_columns($name);
378 my $unique_query = $self->_build_unique_query($query, \@unique_cols);
380 next unless scalar keys %$unique_query;
382 # Add the ResultSet's alias
383 my $alias = $self->{attrs}{alias};
384 foreach my $key (grep { ! m/\./ } keys %$unique_query) {
385 $unique_query->{"$alias.$key"} = delete $unique_query->{$key};
388 push @unique_queries, $unique_query;
391 return @unique_queries;
394 # _build_unique_query
396 # Constrain the specified query hash based on the specified column names.
398 sub _build_unique_query {
399 my ($self, $query, $unique_cols) = @_;
402 map { $_ => $query->{$_} }
403 grep { exists $query->{$_} }
408 =head2 search_related
412 =item Arguments: $rel, $cond, \%attrs?
414 =item Return Value: $new_resultset
418 $new_rs = $cd_rs->search_related('artist', {
422 Searches the specified relationship, optionally specifying a condition and
423 attributes for matching records. See L</ATTRIBUTES> for more information.
428 return shift->related_resultset(shift)->search(@_);
435 =item Arguments: none
437 =item Return Value: $cursor
441 Returns a storage-driven cursor to the given resultset. See
442 L<DBIx::Class::Cursor> for more information.
449 $self->_resolve_attr;
450 my $attrs = { %{$self->{_attrs}} };
451 return $self->{cursor}
452 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
453 $attrs->{where},$attrs);
460 =item Arguments: $cond?
462 =item Return Value: $row_object?
466 my $cd = $schema->resultset('CD')->single({ year => 2001 });
468 Inflates the first result without creating a cursor if the resultset has
469 any records in it; if not returns nothing. Used by L</find> as an optimisation.
471 Can optionally take an additional condition *only* - this is a fast-code-path
472 method; if you need to add extra joins or similar call ->search and then
473 ->single without a condition on the $rs returned from that.
478 my ($self, $where) = @_;
479 $self->_resolve_attr;
480 my $attrs = { %{$self->{_attrs}} };
482 if (defined $attrs->{where}) {
485 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
486 $where, delete $attrs->{where} ]
489 $attrs->{where} = $where;
493 unless ($self->_is_unique_query($attrs->{where})) {
494 carp "Query not guaranteed to return a single row"
495 . "; please declare your unique constraints or use search instead";
498 my @data = $self->result_source->storage->select_single(
499 $attrs->{from}, $attrs->{select},
500 $attrs->{where}, $attrs
503 return (@data ? $self->_construct_object(@data) : ());
508 # Try to determine if the specified query is guaranteed to be unique, based on
509 # the declared unique constraints.
511 sub _is_unique_query {
512 my ($self, $query) = @_;
514 my $collapsed = $self->_collapse_query($query);
515 my $alias = $self->{attrs}{alias};
517 foreach my $name ($self->result_source->unique_constraint_names) {
518 my @unique_cols = map {
520 } $self->result_source->unique_constraint_columns($name);
522 # Count the values for each unique column
523 my %seen = map { $_ => 0 } @unique_cols;
525 foreach my $key (keys %$collapsed) {
526 my $aliased = $key =~ /\./ ? $key : "$alias.$key";
527 next unless exists $seen{$aliased}; # Additional constraints are okay
528 $seen{$aliased} = scalar @{ $collapsed->{$key} };
531 # If we get 0 or more than 1 value for a column, it's not necessarily unique
532 return 1 unless grep { $_ != 1 } values %seen;
540 # Recursively collapse the query, accumulating values for each column.
542 sub _collapse_query {
543 my ($self, $query, $collapsed) = @_;
547 if (ref $query eq 'ARRAY') {
548 foreach my $subquery (@$query) {
549 next unless ref $subquery; # -or
550 # warn "ARRAY: " . Dumper $subquery;
551 $collapsed = $self->_collapse_query($subquery, $collapsed);
554 elsif (ref $query eq 'HASH') {
555 if (keys %$query and (keys %$query)[0] eq '-and') {
556 foreach my $subquery (@{$query->{-and}}) {
557 # warn "HASH: " . Dumper $subquery;
558 $collapsed = $self->_collapse_query($subquery, $collapsed);
562 # warn "LEAF: " . Dumper $query;
563 foreach my $key (keys %$query) {
564 push @{$collapsed->{$key}}, $query->{$key};
576 =item Arguments: $cond?
578 =item Return Value: $resultsetcolumn
582 my $max_length = $rs->get_column('length')->max;
584 Returns a ResultSetColumn instance for $column based on $self
589 my ($self, $column) = @_;
590 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
598 =item Arguments: $cond, \%attrs?
600 =item Return Value: $resultset (scalar context), @row_objs (list context)
604 # WHERE title LIKE '%blue%'
605 $cd_rs = $rs->search_like({ title => '%blue%'});
607 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
608 that this is simply a convenience method. You most likely want to use
609 L</search> with specific operators.
611 For more information, see L<DBIx::Class::Manual::Cookbook>.
617 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
618 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
619 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
620 return $class->search($query, { %$attrs });
627 =item Arguments: $first, $last
629 =item Return Value: $resultset (scalar context), @row_objs (list context)
633 Returns a resultset or object list representing a subset of elements from the
634 resultset slice is called on. Indexes are from 0, i.e., to get the first
637 my ($one, $two, $three) = $rs->slice(0, 2);
642 my ($self, $min, $max) = @_;
643 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
644 $attrs->{offset} = $self->{attrs}{offset} || 0;
645 $attrs->{offset} += $min;
646 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
647 return $self->search(undef(), $attrs);
648 #my $slice = (ref $self)->new($self->result_source, $attrs);
649 #return (wantarray ? $slice->all : $slice);
656 =item Arguments: none
658 =item Return Value: $result?
662 Returns the next element in the resultset (C<undef> is there is none).
664 Can be used to efficiently iterate over records in the resultset:
666 my $rs = $schema->resultset('CD')->search;
667 while (my $cd = $rs->next) {
671 Note that you need to store the resultset object, and call C<next> on it.
672 Calling C<< resultset('Table')->next >> repeatedly will always return the
673 first record from the resultset.
679 if (my $cache = $self->get_cache) {
680 $self->{all_cache_position} ||= 0;
681 return $cache->[$self->{all_cache_position}++];
683 if ($self->{attrs}{cache}) {
684 $self->{all_cache_position} = 1;
685 return ($self->all)[0];
688 exists $self->{stashed_row}
689 ? @{delete $self->{stashed_row}}
690 : $self->cursor->next
692 return unless (@row);
693 return $self->_construct_object(@row);
698 return if exists $self->{_attrs}; #return if _resolve_attr has already been called
700 my $attrs = $self->{attrs};
701 my $source = $self->{_parent_rs} || $self->{result_source};
702 my $alias = $attrs->{_orig_alias};
704 # XXX - lose storable dclone
705 my $record_filter = delete $attrs->{record_filter};
706 $attrs = Storable::dclone($attrs || {}); # { %{ $attrs || {} } };
707 $attrs->{record_filter} = $record_filter if $record_filter;
709 $attrs->{columns} ||= delete $attrs->{cols} if exists $attrs->{cols};
710 if ($attrs->{columns}) {
712 } elsif (!$attrs->{select}) {
713 $attrs->{columns} = [ $self->{result_source}->columns ];
716 my $select_alias = $self->{attrs}{alias};
717 $attrs->{select} ||= [
718 map { m/\./ ? $_ : "${select_alias}.$_" } @{delete $attrs->{columns}}
721 map { m/^\Q${alias}.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}}
725 if ($adds = delete $attrs->{include_columns}) {
726 $adds = [$adds] unless ref $adds eq 'ARRAY';
727 push(@{$attrs->{select}}, @$adds);
728 push(@{$attrs->{as}}, map { m/([^.]+)$/; $1 } @$adds);
730 if ($adds = delete $attrs->{'+select'}) {
731 $adds = [$adds] unless ref $adds eq 'ARRAY';
732 push(@{$attrs->{select}}, map { /\./ || ref $_ ? $_ : "${alias}.$_" } @$adds);
734 if (my $adds = delete $attrs->{'+as'}) {
735 $adds = [$adds] unless ref $adds eq 'ARRAY';
736 push(@{$attrs->{as}}, @$adds);
739 $attrs->{from} ||= [ { $alias => $source->from } ];
740 $attrs->{seen_join} ||= {};
742 if (my $join = delete $attrs->{join}) {
743 foreach my $j (ref $join eq 'ARRAY' ? @$join : ($join)) {
744 if (ref $j eq 'HASH') {
745 $seen{$_} = 1 foreach keys %$j;
750 push(@{$attrs->{from}},
751 $source->resolve_join($join, $alias, $attrs->{seen_join})
755 $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
756 if ($attrs->{order_by}) {
757 $attrs->{order_by} = [ $attrs->{order_by} ] unless ref $attrs->{order_by};
759 $attrs->{order_by} ||= [];
762 my $collapse = $attrs->{collapse} || {};
763 if (my $prefetch = delete $attrs->{prefetch}) {
765 foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
766 if ( ref $p eq 'HASH' ) {
767 foreach my $key (keys %$p) {
768 push(@{$attrs->{from}}, $source->resolve_join($p, $alias))
772 push(@{$attrs->{from}}, $source->resolve_join($p, $alias))
775 # bring joins back to level of current class
776 $p = $self->_reduce_joins($p, $attrs) if $attrs->{_live_join_stack};
778 my @prefetch = $self->result_source->resolve_prefetch(
779 $p, $alias, {}, \@pre_order, $collapse
781 push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
782 push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
785 push(@{$attrs->{order_by}}, @pre_order);
787 $attrs->{collapse} = $collapse;
788 $self->{_attrs} = $attrs;
792 my ($self, $a, $b) = @_;
795 if (ref $b eq 'HASH' && ref $a eq 'HASH') {
796 foreach my $key (keys %{$b}) {
797 if (exists $a->{$key}) {
798 $a->{$key} = $self->_merge_attr($a->{$key}, $b->{$key});
800 $a->{$key} = $b->{$key};
805 $a = [$a] unless ref $a eq 'ARRAY';
806 $b = [$b] unless ref $b eq 'ARRAY';
810 foreach my $x ($a, $b) {
811 foreach my $element (@{$x}) {
812 if (ref $element eq 'HASH') {
813 $hash = $self->_merge_attr($hash, $element);
814 } elsif (ref $element eq 'ARRAY') {
815 push(@array, @{$element});
817 push(@array, $element) unless $b == $x
818 && grep { $_ eq $element } @array;
823 @array = grep { !exists $hash->{$_} } @array;
834 # bring the joins (which are from the original class) to the level
835 # of the current class so that we can resolve them properly
837 my ($self, $p, $attrs) = @_;
840 foreach my $join (@{$attrs->{_live_join_stack}}) {
841 if (ref $p eq 'HASH') {
842 return undef unless exists $p->{$join};
844 } elsif (ref $p eq 'ARRAY') {
845 foreach my $pe (@{$p}) {
846 return undef if $pe eq $join;
847 if (ref $pe eq 'HASH' && exists $pe->{$join}) {
860 sub _construct_object {
861 my ($self, @row) = @_;
862 my $info = $self->_collapse_result($self->{_attrs}{as}, \@row);
863 my $new = $self->result_class->inflate_result($self->result_source, @$info);
864 $new = $self->{_attrs}{record_filter}->($new)
865 if exists $self->{_attrs}{record_filter};
869 sub _collapse_result {
870 my ($self, $as, $row, $prefix) = @_;
875 foreach my $this_as (@$as) {
876 my $val = shift @copy;
877 if (defined $prefix) {
878 if ($this_as =~ m/^\Q${prefix}.\E(.+)$/) {
880 $remain =~ /^(?:(.*)\.)?([^.]+)$/;
881 $const{$1||''}{$2} = $val;
884 $this_as =~ /^(?:(.*)\.)?([^.]+)$/;
885 $const{$1||''}{$2} = $val;
889 my $alias = $self->{attrs}{alias};
890 my $info = [ {}, {} ];
891 foreach my $key (keys %const) {
892 if (length $key && $key ne $alias) {
894 my @parts = split(/\./, $key);
895 foreach my $p (@parts) {
896 $target = $target->[1]->{$p} ||= [];
898 $target->[0] = $const{$key};
900 $info->[0] = $const{$key};
905 if (defined $prefix) {
907 m/^\Q${prefix}.\E(.+)$/ ? ($1) : ()
908 } keys %{$self->{_attrs}{collapse}}
910 @collapse = keys %{$self->{_attrs}{collapse}};
914 my ($c) = sort { length $a <=> length $b } @collapse;
916 foreach my $p (split(/\./, $c)) {
917 $target = $target->[1]->{$p} ||= [];
919 my $c_prefix = (defined($prefix) ? "${prefix}.${c}" : $c);
920 my @co_key = @{$self->{_attrs}{collapse}{$c_prefix}};
921 my $tree = $self->_collapse_result($as, $row, $c_prefix);
922 my %co_check = map { ($_, $tree->[0]->{$_}); } @co_key;
928 !defined($tree->[0]->{$_}) || $co_check{$_} ne $tree->[0]->{$_}
933 last unless (@raw = $self->cursor->next);
934 $row = $self->{stashed_row} = \@raw;
935 $tree = $self->_collapse_result($as, $row, $c_prefix);
937 @$target = (@final ? @final : [ {}, {} ]);
938 # single empty result to indicate an empty prefetched has_many
941 #print "final info: " . Dumper($info);
949 =item Arguments: $result_source?
951 =item Return Value: $result_source
955 An accessor for the primary ResultSource object from which this ResultSet
965 =item Arguments: $cond, \%attrs??
967 =item Return Value: $count
971 Performs an SQL C<COUNT> with the same query as the resultset was built
972 with to find the number of elements. If passed arguments, does a search
973 on the resultset and counts the results of that.
975 Note: When using C<count> with C<group_by>, L<DBIX::Class> emulates C<GROUP BY>
976 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
977 not support C<DISTINCT> with multiple columns. If you are using such a
978 database, you should only use columns from the main table in your C<group_by>
985 return $self->search(@_)->count if @_ and defined $_[0];
986 return scalar @{ $self->get_cache } if $self->get_cache;
987 my $count = $self->_count;
988 return 0 unless $count;
990 $count -= $self->{attrs}{offset} if $self->{attrs}{offset};
991 $count = $self->{attrs}{rows} if
992 $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
996 sub _count { # Separated out so pager can get the full count
998 my $select = { count => '*' };
1000 $self->_resolve_attr;
1001 my $attrs = { %{ $self->{_attrs} } };
1002 if (my $group_by = delete $attrs->{group_by}) {
1003 delete $attrs->{having};
1004 my @distinct = (ref $group_by ? @$group_by : ($group_by));
1005 # todo: try CONCAT for multi-column pk
1006 my @pk = $self->result_source->primary_columns;
1008 my $alias = $attrs->{_orig_alias};
1009 foreach my $column (@distinct) {
1010 if ($column =~ qr/^(?:\Q${alias}.\E)?$pk[0]$/) {
1011 @distinct = ($column);
1017 $select = { count => { distinct => \@distinct } };
1020 $attrs->{select} = $select;
1021 $attrs->{as} = [qw/count/];
1023 # offset, order by and page are not needed to count. record_filter is cdbi
1024 delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
1025 my $tmp_rs = (ref $self)->new($self->result_source, $attrs);
1026 $tmp_rs->{_parent_rs} = $self->{_parent_rs} if $self->{_parent_rs};
1027 #XXX - hack to pass through parent of related resultsets
1029 my ($count) = $tmp_rs->cursor->next;
1033 =head2 count_literal
1037 =item Arguments: $sql_fragment, @bind_values
1039 =item Return Value: $count
1043 Counts the results in a literal query. Equivalent to calling L</search_literal>
1044 with the passed arguments, then L</count>.
1048 sub count_literal { shift->search_literal(@_)->count; }
1054 =item Arguments: none
1056 =item Return Value: @objects
1060 Returns all elements in the resultset. Called implicitly if the resultset
1061 is returned in list context.
1067 return @{ $self->get_cache } if $self->get_cache;
1071 # TODO: don't call resolve here
1072 $self->_resolve_attr;
1073 if (keys %{$self->{_attrs}{collapse}}) {
1074 # if ($self->{attrs}{prefetch}) {
1075 # Using $self->cursor->all is really just an optimisation.
1076 # If we're collapsing has_many prefetches it probably makes
1077 # very little difference, and this is cleaner than hacking
1078 # _construct_object to survive the approach
1079 my @row = $self->cursor->next;
1081 push(@obj, $self->_construct_object(@row));
1082 @row = (exists $self->{stashed_row}
1083 ? @{delete $self->{stashed_row}}
1084 : $self->cursor->next);
1087 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
1090 $self->set_cache(\@obj) if $self->{attrs}{cache};
1098 =item Arguments: none
1100 =item Return Value: $self
1104 Resets the resultset's cursor, so you can iterate through the elements again.
1110 delete $self->{_attrs} if exists $self->{_attrs};
1111 $self->{all_cache_position} = 0;
1112 $self->cursor->reset;
1120 =item Arguments: none
1122 =item Return Value: $object?
1126 Resets the resultset and returns an object for the first result (if the
1127 resultset returns anything).
1132 return $_[0]->reset->next;
1135 # _cond_for_update_delete
1137 # update/delete require the condition to be modified to handle
1138 # the differing SQL syntax available. This transforms the $self->{cond}
1139 # appropriately, returning the new condition.
1141 sub _cond_for_update_delete {
1145 # No-op. No condition, we're updating/deleting everything
1146 return $cond unless ref $self->{cond};
1148 if (ref $self->{cond} eq 'ARRAY') {
1152 foreach my $key (keys %{$_}) {
1154 $hash{$1} = $_->{$key};
1160 elsif (ref $self->{cond} eq 'HASH') {
1161 if ((keys %{$self->{cond}})[0] eq '-and') {
1164 my @cond = @{$self->{cond}{-and}};
1165 for (my $i = 0; $i < @cond; $i++) {
1166 my $entry = $cond[$i];
1169 if (ref $entry eq 'HASH') {
1170 foreach my $key (keys %{$entry}) {
1172 $hash{$1} = $entry->{$key};
1176 $entry =~ /([^.]+)$/;
1177 $hash{$1} = $cond[++$i];
1180 push @{$cond->{-and}}, \%hash;
1184 foreach my $key (keys %{$self->{cond}}) {
1186 $cond->{$1} = $self->{cond}{$key};
1191 $self->throw_exception(
1192 "Can't update/delete on resultset with condition unless hash or array"
1204 =item Arguments: \%values
1206 =item Return Value: $storage_rv
1210 Sets the specified columns in the resultset to the supplied values in a
1211 single query. Return value will be true if the update succeeded or false
1212 if no records were updated; exact type of success value is storage-dependent.
1217 my ($self, $values) = @_;
1218 $self->throw_exception("Values for update must be a hash")
1219 unless ref $values eq 'HASH';
1221 my $cond = $self->_cond_for_update_delete;
1223 return $self->result_source->storage->update(
1224 $self->result_source->from, $values, $cond
1232 =item Arguments: \%values
1234 =item Return Value: 1
1238 Fetches all objects and updates them one at a time. Note that C<update_all>
1239 will run DBIC cascade triggers, while L</update> will not.
1244 my ($self, $values) = @_;
1245 $self->throw_exception("Values for update must be a hash")
1246 unless ref $values eq 'HASH';
1247 foreach my $obj ($self->all) {
1248 $obj->set_columns($values)->update;
1257 =item Arguments: none
1259 =item Return Value: 1
1263 Deletes the contents of the resultset from its result source. Note that this
1264 will not run DBIC cascade triggers. See L</delete_all> if you need triggers
1272 my $cond = $self->_cond_for_update_delete;
1274 $self->result_source->storage->delete($self->result_source->from, $cond);
1282 =item Arguments: none
1284 =item Return Value: 1
1288 Fetches all objects and deletes them one at a time. Note that C<delete_all>
1289 will run DBIC cascade triggers, while L</delete> will not.
1295 $_->delete for $self->all;
1303 =item Arguments: none
1305 =item Return Value: $pager
1309 Return Value a L<Data::Page> object for the current resultset. Only makes
1310 sense for queries with a C<page> attribute.
1316 my $attrs = $self->{attrs};
1317 $self->throw_exception("Can't create pager for non-paged rs")
1318 unless $self->{attrs}{page};
1319 $attrs->{rows} ||= 10;
1320 return $self->{pager} ||= Data::Page->new(
1321 $self->_count, $attrs->{rows}, $self->{attrs}{page});
1328 =item Arguments: $page_number
1330 =item Return Value: $rs
1334 Returns a resultset for the $page_number page of the resultset on which page
1335 is called, where each page contains a number of rows equal to the 'rows'
1336 attribute set on the resultset (10 by default).
1341 my ($self, $page) = @_;
1342 return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
1349 =item Arguments: \%vals
1351 =item Return Value: $object
1355 Creates an object in the resultset's result class and returns it.
1360 my ($self, $values) = @_;
1361 $self->throw_exception( "new_result needs a hash" )
1362 unless (ref $values eq 'HASH');
1363 $self->throw_exception(
1364 "Can't abstract implicit construct, condition not a hash"
1365 ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
1367 my $alias = $self->{attrs}{_orig_alias};
1368 foreach my $key (keys %{$self->{cond}||{}}) {
1369 $new{$1} = $self->{cond}{$key} if ($key =~ m/^(?:\Q${alias}.\E)?([^.]+)$/);
1371 my $obj = $self->result_class->new(\%new);
1372 $obj->result_source($self->result_source) if $obj->can('result_source');
1380 =item Arguments: \%vals, \%attrs?
1382 =item Return Value: $object
1386 Find an existing record from this resultset. If none exists, instantiate a new
1387 result object and return it. The object will not be saved into your storage
1388 until you call L<DBIx::Class::Row/insert> on it.
1390 If you want objects to be saved immediately, use L</find_or_create> instead.
1396 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1397 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1398 my $exists = $self->find($hash, $attrs);
1399 return defined $exists ? $exists : $self->new_result($hash);
1406 =item Arguments: \%vals
1408 =item Return Value: $object
1412 Inserts a record into the resultset and returns the object representing it.
1414 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
1419 my ($self, $attrs) = @_;
1420 $self->throw_exception( "create needs a hashref" )
1421 unless ref $attrs eq 'HASH';
1422 return $self->new_result($attrs)->insert;
1425 =head2 find_or_create
1429 =item Arguments: \%vals, \%attrs?
1431 =item Return Value: $object
1435 $class->find_or_create({ key => $val, ... });
1437 Tries to find a record based on its primary key or unique constraint; if none
1438 is found, creates one and returns that instead.
1440 my $cd = $schema->resultset('CD')->find_or_create({
1442 artist => 'Massive Attack',
1443 title => 'Mezzanine',
1447 Also takes an optional C<key> attribute, to search by a specific key or unique
1448 constraint. For example:
1450 my $cd = $schema->resultset('CD')->find_or_create(
1452 artist => 'Massive Attack',
1453 title => 'Mezzanine',
1455 { key => 'cd_artist_title' }
1458 See also L</find> and L</update_or_create>. For information on how to declare
1459 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1463 sub find_or_create {
1465 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1466 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1467 my $exists = $self->find($hash, $attrs);
1468 return defined $exists ? $exists : $self->create($hash);
1471 =head2 update_or_create
1475 =item Arguments: \%col_values, { key => $unique_constraint }?
1477 =item Return Value: $object
1481 $class->update_or_create({ col => $val, ... });
1483 First, searches for an existing row matching one of the unique constraints
1484 (including the primary key) on the source of this resultset. If a row is
1485 found, updates it with the other given column values. Otherwise, creates a new
1488 Takes an optional C<key> attribute to search on a specific unique constraint.
1491 # In your application
1492 my $cd = $schema->resultset('CD')->update_or_create(
1494 artist => 'Massive Attack',
1495 title => 'Mezzanine',
1498 { key => 'cd_artist_title' }
1501 If no C<key> is specified, it searches on all unique constraints defined on the
1502 source, including the primary key.
1504 If the C<key> is specified as C<primary>, it searches only on the primary key.
1506 See also L</find> and L</find_or_create>. For information on how to declare
1507 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1511 sub update_or_create {
1513 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1514 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
1516 my $row = $self->find($cond);
1518 $row->update($cond);
1522 return $self->create($cond);
1529 =item Arguments: none
1531 =item Return Value: \@cache_objects?
1535 Gets the contents of the cache for the resultset, if the cache is set.
1547 =item Arguments: \@cache_objects
1549 =item Return Value: \@cache_objects
1553 Sets the contents of the cache for the resultset. Expects an arrayref
1554 of objects of the same class as those produced by the resultset. Note that
1555 if the cache is set the resultset will return the cached objects rather
1556 than re-querying the database even if the cache attr is not set.
1561 my ( $self, $data ) = @_;
1562 $self->throw_exception("set_cache requires an arrayref")
1563 if defined($data) && (ref $data ne 'ARRAY');
1564 $self->{all_cache} = $data;
1571 =item Arguments: none
1573 =item Return Value: []
1577 Clears the cache for the resultset.
1582 shift->set_cache(undef);
1585 =head2 related_resultset
1589 =item Arguments: $relationship_name
1591 =item Return Value: $resultset
1595 Returns a related resultset for the supplied relationship name.
1597 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1601 sub related_resultset {
1602 my ($self, $rel) = @_;
1604 $self->{related_resultsets} ||= {};
1605 return $self->{related_resultsets}{$rel} ||= do {
1606 my $rel_obj = $self->result_source->relationship_info($rel);
1608 $self->throw_exception(
1609 "search_related: result source '" . $self->result_source->name .
1610 "' has no such relationship $rel")
1613 my @live_join_stack = (@{$self->{attrs}{_live_join_stack}||[]}, $rel);
1615 my $rs = $self->result_source->schema->resultset($rel_obj->{class})->search(
1619 alias => $rel, #the most recent
1620 _live_join_stack => \@live_join_stack, #the trail of rels
1621 _parent_attrs => $self->{attrs}}
1624 # keep reference of the original resultset
1625 $rs->{_parent_rs} = $self->{_parent_rs} || $self->result_source;
1631 =head2 throw_exception
1633 See L<DBIx::Class::Schema/throw_exception> for details.
1637 sub throw_exception {
1639 $self->result_source->schema->throw_exception(@_);
1642 # XXX: FIXME: Attributes docs need clearing up
1646 The resultset takes various attributes that modify its behavior. Here's an
1653 =item Value: ($order_by | \@order_by)
1657 Which column(s) to order the results by. This is currently passed
1658 through directly to SQL, so you can give e.g. C<year DESC> for a
1659 descending order on the column `year'.
1661 Please note that if you have quoting enabled (see
1662 L<DBIx::Class::Storage/quote_char>) you will need to do C<\'year DESC' > to
1663 specify an order. (The scalar ref causes it to be passed as raw sql to the DB,
1664 so you will need to manually quote things as appropriate.)
1670 =item Value: \@columns
1674 Shortcut to request a particular set of columns to be retrieved. Adds
1675 C<me.> onto the start of any column without a C<.> in it and sets C<select>
1676 from that, then auto-populates C<as> from C<select> as normal. (You may also
1677 use the C<cols> attribute, as in earlier versions of DBIC.)
1679 =head2 include_columns
1683 =item Value: \@columns
1687 Shortcut to include additional columns in the returned results - for example
1689 $schema->resultset('CD')->search(undef, {
1690 include_columns => ['artist.name'],
1694 would return all CDs and include a 'name' column to the information
1695 passed to object inflation
1701 =item Value: \@select_columns
1705 Indicates which columns should be selected from the storage. You can use
1706 column names, or in the case of RDBMS back ends, function or stored procedure
1709 $rs = $schema->resultset('Employee')->search(undef, {
1712 { count => 'employeeid' },
1717 When you use function/stored procedure names and do not supply an C<as>
1718 attribute, the column names returned are storage-dependent. E.g. MySQL would
1719 return a column named C<count(employeeid)> in the above example.
1725 Indicates additional columns to be selected from storage. Works the same as
1726 L<select> but adds columns to the selection.
1734 Indicates additional column names for those added via L<+select>.
1742 =item Value: \@inflation_names
1746 Indicates column names for object inflation. This is used in conjunction with
1747 C<select>, usually when C<select> contains one or more function or stored
1750 $rs = $schema->resultset('Employee')->search(undef, {
1753 { count => 'employeeid' }
1755 as => ['name', 'employee_count'],
1758 my $employee = $rs->first(); # get the first Employee
1760 If the object against which the search is performed already has an accessor
1761 matching a column name specified in C<as>, the value can be retrieved using
1762 the accessor as normal:
1764 my $name = $employee->name();
1766 If on the other hand an accessor does not exist in the object, you need to
1767 use C<get_column> instead:
1769 my $employee_count = $employee->get_column('employee_count');
1771 You can create your own accessors if required - see
1772 L<DBIx::Class::Manual::Cookbook> for details.
1774 Please note: This will NOT insert an C<AS employee_count> into the SQL statement
1775 produced, it is used for internal access only. Thus attempting to use the accessor
1776 in an C<order_by> clause or similar will fail misrably.
1782 =item Value: ($rel_name | \@rel_names | \%rel_names)
1786 Contains a list of relationships that should be joined for this query. For
1789 # Get CDs by Nine Inch Nails
1790 my $rs = $schema->resultset('CD')->search(
1791 { 'artist.name' => 'Nine Inch Nails' },
1792 { join => 'artist' }
1795 Can also contain a hash reference to refer to the other relation's relations.
1798 package MyApp::Schema::Track;
1799 use base qw/DBIx::Class/;
1800 __PACKAGE__->table('track');
1801 __PACKAGE__->add_columns(qw/trackid cd position title/);
1802 __PACKAGE__->set_primary_key('trackid');
1803 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
1806 # In your application
1807 my $rs = $schema->resultset('Artist')->search(
1808 { 'track.title' => 'Teardrop' },
1810 join => { cd => 'track' },
1811 order_by => 'artist.name',
1815 If the same join is supplied twice, it will be aliased to <rel>_2 (and
1816 similarly for a third time). For e.g.
1818 my $rs = $schema->resultset('Artist')->search({
1819 'cds.title' => 'Down to Earth',
1820 'cds_2.title' => 'Popular',
1822 join => [ qw/cds cds/ ],
1825 will return a set of all artists that have both a cd with title 'Down
1826 to Earth' and a cd with title 'Popular'.
1828 If you want to fetch related objects from other tables as well, see C<prefetch>
1835 =item Value: ($rel_name | \@rel_names | \%rel_names)
1839 Contains one or more relationships that should be fetched along with the main
1840 query (when they are accessed afterwards they will have already been
1841 "prefetched"). This is useful for when you know you will need the related
1842 objects, because it saves at least one query:
1844 my $rs = $schema->resultset('Tag')->search(
1853 The initial search results in SQL like the following:
1855 SELECT tag.*, cd.*, artist.* FROM tag
1856 JOIN cd ON tag.cd = cd.cdid
1857 JOIN artist ON cd.artist = artist.artistid
1859 L<DBIx::Class> has no need to go back to the database when we access the
1860 C<cd> or C<artist> relationships, which saves us two SQL statements in this
1863 Simple prefetches will be joined automatically, so there is no need
1864 for a C<join> attribute in the above search. If you're prefetching to
1865 depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
1866 specify the join as well.
1868 C<prefetch> can be used with the following relationship types: C<belongs_to>,
1869 C<has_one> (or if you're using C<add_relationship>, any relationship declared
1870 with an accessor type of 'single' or 'filter').
1880 Makes the resultset paged and specifies the page to retrieve. Effectively
1881 identical to creating a non-pages resultset and then calling ->page($page)
1884 If L<rows> attribute is not specified it defualts to 10 rows per page.
1894 Specifes the maximum number of rows for direct retrieval or the number of
1895 rows per page if the page attribute or method is used.
1901 =item Value: $offset
1905 Specifies the (zero-based) row number for the first row to be returned, or the
1906 of the first row of the first page if paging is used.
1912 =item Value: \@columns
1916 A arrayref of columns to group by. Can include columns of joined tables.
1918 group_by => [qw/ column1 column2 ... /]
1924 =item Value: $condition
1928 HAVING is a select statement attribute that is applied between GROUP BY and
1929 ORDER BY. It is applied to the after the grouping calculations have been
1932 having => { 'count(employee)' => { '>=', 100 } }
1938 =item Value: (0 | 1)
1942 Set to 1 to group by all columns.
1948 Adds to the WHERE clause.
1950 # only return rows WHERE deleted IS NULL for all searches
1951 __PACKAGE__->resultset_attributes({ where => { deleted => undef } }); )
1953 Can be overridden by passing C<{ where => undef }> as an attribute
1960 Set to 1 to cache search results. This prevents extra SQL queries if you
1961 revisit rows in your ResultSet:
1963 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
1965 while( my $artist = $resultset->next ) {
1969 $rs->first; # without cache, this would issue a query
1971 By default, searches are not cached.
1973 For more examples of using these attributes, see
1974 L<DBIx::Class::Manual::Cookbook>.
1980 =item Value: \@from_clause
1984 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
1985 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
1988 NOTE: Use this on your own risk. This allows you to shoot off your foot!
1990 C<join> will usually do what you need and it is strongly recommended that you
1991 avoid using C<from> unless you cannot achieve the desired result using C<join>.
1992 And we really do mean "cannot", not just tried and failed. Attempting to use
1993 this because you're having problems with C<join> is like trying to use x86
1994 ASM because you've got a syntax error in your C. Trust us on this.
1996 Now, if you're still really, really sure you need to use this (and if you're
1997 not 100% sure, ask the mailing list first), here's an explanation of how this
2000 The syntax is as follows -
2003 { <alias1> => <table1> },
2005 { <alias2> => <table2>, -join_type => 'inner|left|right' },
2006 [], # nested JOIN (optional)
2007 { <table1.column1> => <table2.column2>, ... (more conditions) },
2009 # More of the above [ ] may follow for additional joins
2016 ON <table1.column1> = <table2.column2>
2017 <more joins may follow>
2019 An easy way to follow the examples below is to remember the following:
2021 Anything inside "[]" is a JOIN
2022 Anything inside "{}" is a condition for the enclosing JOIN
2024 The following examples utilize a "person" table in a family tree application.
2025 In order to express parent->child relationships, this table is self-joined:
2027 # Person->belongs_to('father' => 'Person');
2028 # Person->belongs_to('mother' => 'Person');
2030 C<from> can be used to nest joins. Here we return all children with a father,
2031 then search against all mothers of those children:
2033 $rs = $schema->resultset('Person')->search(
2036 alias => 'mother', # alias columns in accordance with "from"
2038 { mother => 'person' },
2041 { child => 'person' },
2043 { father => 'person' },
2044 { 'father.person_id' => 'child.father_id' }
2047 { 'mother.person_id' => 'child.mother_id' }
2054 # SELECT mother.* FROM person mother
2057 # JOIN person father
2058 # ON ( father.person_id = child.father_id )
2060 # ON ( mother.person_id = child.mother_id )
2062 The type of any join can be controlled manually. To search against only people
2063 with a father in the person table, we could explicitly use C<INNER JOIN>:
2065 $rs = $schema->resultset('Person')->search(
2068 alias => 'child', # alias columns in accordance with "from"
2070 { child => 'person' },
2072 { father => 'person', -join_type => 'inner' },
2073 { 'father.id' => 'child.father_id' }
2080 # SELECT child.* FROM person child
2081 # INNER JOIN person father ON child.father_id = father.id