1 package DBIx::Class::ResultSet;
9 use Carp::Clan qw/^DBIx::Class/;
13 use Scalar::Util qw/weaken/;
15 use DBIx::Class::ResultSetColumn;
16 use base qw/DBIx::Class/;
17 __PACKAGE__->load_components(qw/AccessorGroup/);
18 __PACKAGE__->mk_group_accessors('simple' => qw/result_source result_class/);
22 DBIx::Class::ResultSet - Responsible for fetching and creating resultset.
26 my $rs = $schema->resultset('User')->search(registered => 1);
27 my @rows = $schema->resultset('CD')->search(year => 2005);
31 The resultset is also known as an iterator. It is responsible for handling
32 queries that may return an arbitrary number of rows, e.g. via L</search>
33 or a C<has_many> relationship.
35 In the examples below, the following table classes are used:
37 package MyApp::Schema::Artist;
38 use base qw/DBIx::Class/;
39 __PACKAGE__->load_components(qw/Core/);
40 __PACKAGE__->table('artist');
41 __PACKAGE__->add_columns(qw/artistid name/);
42 __PACKAGE__->set_primary_key('artistid');
43 __PACKAGE__->has_many(cds => 'MyApp::Schema::CD');
46 package MyApp::Schema::CD;
47 use base qw/DBIx::Class/;
48 __PACKAGE__->load_components(qw/Core/);
49 __PACKAGE__->table('cd');
50 __PACKAGE__->add_columns(qw/cdid artist title year/);
51 __PACKAGE__->set_primary_key('cdid');
52 __PACKAGE__->belongs_to(artist => 'MyApp::Schema::Artist');
61 =item Arguments: $source, \%$attrs
63 =item Return Value: $rs
67 The resultset constructor. Takes a source object (usually a
68 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
69 L</ATTRIBUTES> below). Does not perform any queries -- these are
70 executed as needed by the other methods.
72 Generally you won't need to construct a resultset manually. You'll
73 automatically get one from e.g. a L</search> called in scalar context:
75 my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
77 IMPORTANT: If called on an object, proxies to new_result instead so
79 my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
81 will return a CD object, not a ResultSet.
87 return $class->new_result(@_) if ref $class;
89 my ($source, $attrs) = @_;
93 $attrs->{rows} ||= 10;
94 $attrs->{offset} ||= 0;
95 $attrs->{offset} += ($attrs->{rows} * ($attrs->{page} - 1));
98 $attrs->{alias} ||= 'me';
101 result_source => $source,
102 result_class => $attrs->{result_class} || $source->result_class,
103 cond => $attrs->{where},
104 # from => $attrs->{from},
105 # collapse => $collapse,
107 page => delete $attrs->{page},
117 =item Arguments: $cond, \%attrs?
119 =item Return Value: $resultset (scalar context), @row_objs (list context)
123 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
124 my $new_rs = $cd_rs->search({ year => 2005 });
126 my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
127 # year = 2005 OR year = 2004
129 If you need to pass in additional attributes but no additional condition,
130 call it as C<search(undef, \%attrs)>.
132 # "SELECT name, artistid FROM $artist_table"
133 my @all_artists = $schema->resultset('Artist')->search(undef, {
134 columns => [qw/name artistid/],
141 my $rs = $self->search_rs( @_ );
142 return (wantarray ? $rs->all : $rs);
149 =item Arguments: $cond, \%attrs?
151 =item Return Value: $resultset
155 This method does the same exact thing as search() except it will
156 always return a resultset, even in list context.
164 $attrs = pop(@_) if @_ > 1 and ref $_[$#_] eq 'HASH';
165 my $our_attrs = ($attrs->{_parent_attrs})
166 ? { %{$attrs->{_parent_attrs}} }
167 : { %{$self->{attrs}} };
168 my $having = delete $our_attrs->{having};
170 # XXX this is getting messy
171 if ($attrs->{_live_join_stack}) {
172 my $live_join = $attrs->{_live_join_stack};
173 foreach (reverse @{$live_join}) {
174 $attrs->{_live_join_h} = (defined $attrs->{_live_join_h}) ? { $_ => $attrs->{_live_join_h} } : $_;
178 # merge new attrs into old
179 foreach my $key (qw/join prefetch/) {
180 next unless (exists $attrs->{$key});
181 if ($attrs->{_live_join_stack} || $our_attrs->{_live_join_stack}) {
182 my $live_join = $attrs->{_live_join_stack} ||
183 $our_attrs->{_live_join_stack};
184 foreach (reverse @{$live_join}) {
185 $attrs->{$key} = { $_ => $attrs->{$key} };
189 if (exists $our_attrs->{$key}) {
190 $our_attrs->{$key} = $self->_merge_attr($our_attrs->{$key}, $attrs->{$key});
192 $our_attrs->{$key} = $attrs->{$key};
194 delete $attrs->{$key};
197 $our_attrs->{join} = $self->_merge_attr(
198 $our_attrs->{join}, $attrs->{_live_join_h}, 1
199 ) if ($attrs->{_live_join_h});
201 if (defined $our_attrs->{prefetch}) {
202 $our_attrs->{join} = $self->_merge_attr(
203 $our_attrs->{join}, $our_attrs->{prefetch}, 1
207 my $new_attrs = { %{$our_attrs}, %{$attrs} };
210 (@_ == 1 || ref $_[0] eq "HASH")
214 ? $self->throw_exception("Odd number of arguments to search")
221 if (defined $where) {
222 $new_attrs->{where} = (
223 defined $new_attrs->{where}
226 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
227 } $where, $new_attrs->{where}
233 if (defined $having) {
234 $new_attrs->{having} = (
235 defined $new_attrs->{having}
238 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
239 } $having, $new_attrs->{having}
245 my $rs = (ref $self)->new($self->result_source, $new_attrs);
246 $rs->{_parent_rs} = $self->{_parent_rs} if ($self->{_parent_rs});
247 #XXX - hack to pass through parent of related resultsets
249 unless (@_) { # no search, effectively just a clone
250 my $rows = $self->get_cache;
252 $rs->set_cache($rows);
259 =head2 search_literal
263 =item Arguments: $sql_fragment, @bind_values
265 =item Return Value: $resultset (scalar context), @row_objs (list context)
269 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
270 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
272 Pass a literal chunk of SQL to be added to the conditional part of the
278 my ($self, $cond, @vals) = @_;
279 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
280 $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
281 return $self->search(\$cond, $attrs);
288 =item Arguments: @values | \%cols, \%attrs?
290 =item Return Value: $row_object
294 Finds a row based on its primary key or unique constraint. For example, to find
295 a row by its primary key:
297 my $cd = $schema->resultset('CD')->find(5);
299 You can also find a row by a specific unique constraint using the C<key>
300 attribute. For example:
302 my $cd = $schema->resultset('CD')->find('Massive Attack', 'Mezzanine', {
303 key => 'cd_artist_title'
306 Additionally, you can specify the columns explicitly by name:
308 my $cd = $schema->resultset('CD')->find(
310 artist => 'Massive Attack',
311 title => 'Mezzanine',
313 { key => 'cd_artist_title' }
316 If the C<key> is specified as C<primary>, it searches only on the primary key.
318 If no C<key> is specified, it searches on all unique constraints defined on the
319 source, including the primary key.
321 See also L</find_or_create> and L</update_or_create>. For information on how to
322 declare unique constraints, see
323 L<DBIx::Class::ResultSource/add_unique_constraint>.
329 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
331 # Default to the primary key, but allow a specific key
332 my @cols = exists $attrs->{key}
333 ? $self->result_source->unique_constraint_columns($attrs->{key})
334 : $self->result_source->primary_columns;
335 $self->throw_exception(
336 "Can't find unless a primary key or unique constraint is defined"
339 # Parse out a hashref from input
341 if (ref $_[0] eq 'HASH') {
342 $input_query = { %{$_[0]} };
344 elsif (@_ == @cols) {
346 @{$input_query}{@cols} = @_;
349 # Compatibility: Allow e.g. find(id => $value)
350 carp "Find by key => value deprecated; please use a hashref instead";
354 my @unique_queries = $self->_unique_queries($input_query, $attrs);
356 # Handle cases where the ResultSet defines the query, or where the user is
358 my $query = @unique_queries ? \@unique_queries : $input_query;
362 my $rs = $self->search($query, $attrs);
364 return keys %{$rs->{_attrs}->{collapse}} ? $rs->next : $rs->single;
368 return (keys %{$self->{_attrs}->{collapse}})
369 ? $self->search($query)->next
370 : $self->single($query);
376 # Build a list of queries which satisfy unique constraints.
378 sub _unique_queries {
379 my ($self, $query, $attrs) = @_;
381 my @constraint_names = exists $attrs->{key}
383 : $self->result_source->unique_constraint_names;
386 foreach my $name (@constraint_names) {
387 my @unique_cols = $self->result_source->unique_constraint_columns($name);
388 my $unique_query = $self->_build_unique_query($query, \@unique_cols);
390 next unless scalar keys %$unique_query;
392 # Add the ResultSet's alias
393 foreach my $key (grep { ! m/\./ } keys %$unique_query) {
394 my $alias = ($self->{attrs}->{_live_join})
395 ? $self->{attrs}->{_live_join}
396 : $self->{attrs}->{alias};
397 $unique_query->{"$alias.$key"} = delete $unique_query->{$key};
400 push @unique_queries, $unique_query;
403 return @unique_queries;
406 # _build_unique_query
408 # Constrain the specified query hash based on the specified column names.
410 sub _build_unique_query {
411 my ($self, $query, $unique_cols) = @_;
414 map { $_ => $query->{$_} }
415 grep { exists $query->{$_} }
418 return \%unique_query;
421 =head2 search_related
425 =item Arguments: $rel, $cond, \%attrs?
427 =item Return Value: $new_resultset
431 $new_rs = $cd_rs->search_related('artist', {
435 Searches the specified relationship, optionally specifying a condition and
436 attributes for matching records. See L</ATTRIBUTES> for more information.
441 return shift->related_resultset(shift)->search(@_);
448 =item Arguments: none
450 =item Return Value: $cursor
454 Returns a storage-driven cursor to the given resultset. See
455 L<DBIx::Class::Cursor> for more information.
463 my $attrs = { %{$self->{_attrs}} };
464 return $self->{cursor}
465 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
466 $attrs->{where},$attrs);
473 =item Arguments: $cond?
475 =item Return Value: $row_object?
479 my $cd = $schema->resultset('CD')->single({ year => 2001 });
481 Inflates the first result without creating a cursor if the resultset has
482 any records in it; if not returns nothing. Used by L</find> as an optimisation.
484 Can optionally take an additional condition *only* - this is a fast-code-path
485 method; if you need to add extra joins or similar call ->search and then
486 ->single without a condition on the $rs returned from that.
491 my ($self, $where) = @_;
493 my $attrs = { %{$self->{_attrs}} };
495 if (defined $attrs->{where}) {
498 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
499 $where, delete $attrs->{where} ]
502 $attrs->{where} = $where;
506 unless ($self->_is_unique_query($attrs->{where})) {
507 carp "Query not guaranteed to return a single row"
508 . "; please declare your unique constraints or use search instead";
511 my @data = $self->result_source->storage->select_single(
512 $attrs->{from}, $attrs->{select},
513 $attrs->{where},$attrs
516 return (@data ? $self->_construct_object(@data) : ());
521 # Try to determine if the specified query is guaranteed to be unique, based on
522 # the declared unique constraints.
524 sub _is_unique_query {
525 my ($self, $query) = @_;
527 my $collapsed = $self->_collapse_query($query);
528 my $alias = ($self->{attrs}->{_live_join})
529 ? $self->{attrs}->{_live_join}
530 : $self->{attrs}->{alias};
532 foreach my $name ($self->result_source->unique_constraint_names) {
533 my @unique_cols = map {
535 } $self->result_source->unique_constraint_columns($name);
537 # Count the values for each unique column
538 my %seen = map { $_ => 0 } @unique_cols;
540 foreach my $key (keys %$collapsed) {
542 $aliased = "$alias.$key" unless $key =~ /\./;
544 next unless exists $seen{$aliased}; # Additional constraints are okay
545 $seen{$aliased} = scalar @{ $collapsed->{$key} };
548 # If we get 0 or more than 1 value for a column, it's not necessarily unique
549 return 1 unless grep { $_ != 1 } values %seen;
557 # Recursively collapse the query, accumulating values for each column.
559 sub _collapse_query {
560 my ($self, $query, $collapsed) = @_;
564 if (ref $query eq 'ARRAY') {
565 foreach my $subquery (@$query) {
566 next unless ref $subquery; # -or
567 # warn "ARRAY: " . Dumper $subquery;
568 $collapsed = $self->_collapse_query($subquery, $collapsed);
571 elsif (ref $query eq 'HASH') {
572 if (keys %$query and (keys %$query)[0] eq '-and') {
573 foreach my $subquery (@{$query->{-and}}) {
574 # warn "HASH: " . Dumper $subquery;
575 $collapsed = $self->_collapse_query($subquery, $collapsed);
579 # warn "LEAF: " . Dumper $query;
580 foreach my $key (keys %$query) {
581 push @{$collapsed->{$key}}, $query->{$key};
593 =item Arguments: $cond?
595 =item Return Value: $resultsetcolumn
599 my $max_length = $rs->get_column('length')->max;
601 Returns a ResultSetColumn instance for $column based on $self
606 my ($self, $column) = @_;
607 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
615 =item Arguments: $cond, \%attrs?
617 =item Return Value: $resultset (scalar context), @row_objs (list context)
621 # WHERE title LIKE '%blue%'
622 $cd_rs = $rs->search_like({ title => '%blue%'});
624 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
625 that this is simply a convenience method. You most likely want to use
626 L</search> with specific operators.
628 For more information, see L<DBIx::Class::Manual::Cookbook>.
634 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
635 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
636 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
637 return $class->search($query, { %$attrs });
644 =item Arguments: $first, $last
646 =item Return Value: $resultset (scalar context), @row_objs (list context)
650 Returns a resultset or object list representing a subset of elements from the
651 resultset slice is called on. Indexes are from 0, i.e., to get the first
654 my ($one, $two, $three) = $rs->slice(0, 2);
659 my ($self, $min, $max) = @_;
660 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
661 $attrs->{offset} = $self->{attrs}{offset} || 0;
662 $attrs->{offset} += $min;
663 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
664 return $self->search(undef(), $attrs);
665 #my $slice = (ref $self)->new($self->result_source, $attrs);
666 #return (wantarray ? $slice->all : $slice);
673 =item Arguments: none
675 =item Return Value: $result?
679 Returns the next element in the resultset (C<undef> is there is none).
681 Can be used to efficiently iterate over records in the resultset:
683 my $rs = $schema->resultset('CD')->search;
684 while (my $cd = $rs->next) {
688 Note that you need to store the resultset object, and call C<next> on it.
689 Calling C<< resultset('Table')->next >> repeatedly will always return the
690 first record from the resultset.
696 if (my $cache = $self->get_cache) {
697 $self->{all_cache_position} ||= 0;
698 return $cache->[$self->{all_cache_position}++];
700 if ($self->{attrs}{cache}) {
701 $self->{all_cache_position} = 1;
702 return ($self->all)[0];
705 exists $self->{stashed_row}
706 ? @{delete $self->{stashed_row}}
707 : $self->cursor->next
709 return unless (@row);
710 return $self->_construct_object(@row);
716 return if(exists $self->{_attrs}); #return if _resolve has already been called
718 my $attrs = $self->{attrs};
719 my $source = ($self->{_parent_rs})
720 ? $self->{_parent_rs}
721 : $self->{result_source};
723 # XXX - lose storable dclone
724 my $record_filter = delete $attrs->{record_filter}
725 if (defined $attrs->{record_filter});
726 $attrs = Storable::dclone($attrs || {}); # { %{ $attrs || {} } };
727 $attrs->{record_filter} = $record_filter if ($record_filter);
728 $self->{attrs}->{record_filter} = $record_filter if ($record_filter);
730 my $alias = $attrs->{alias};
732 $attrs->{columns} ||= delete $attrs->{cols} if $attrs->{cols};
733 delete $attrs->{as} if $attrs->{columns};
734 $attrs->{columns} ||= [ $self->{result_source}->columns ]
735 unless $attrs->{select};
736 my $select_alias = ($self->{_parent_rs})
737 ? $self->{attrs}->{_live_join}
740 map { m/\./ ? $_ : "${select_alias}.$_" } @{delete $attrs->{columns}}
741 ] if $attrs->{columns};
743 map { m/^\Q$alias.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}}
745 if (my $include = delete $attrs->{include_columns}) {
746 push(@{$attrs->{select}}, @$include);
747 push(@{$attrs->{as}}, map { m/([^.]+)$/; $1; } @$include);
750 $attrs->{from} ||= [ { $alias => $source->from } ];
751 $attrs->{seen_join} ||= {};
753 if (my $join = delete $attrs->{join}) {
754 foreach my $j (ref $join eq 'ARRAY' ? @$join : ($join)) {
755 if (ref $j eq 'HASH') {
756 $seen{$_} = 1 foreach keys %$j;
761 push(@{$attrs->{from}},
762 $source->resolve_join($join, $attrs->{alias}, $attrs->{seen_join})
765 $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
766 $attrs->{order_by} = [ $attrs->{order_by} ] if
767 $attrs->{order_by} and !ref($attrs->{order_by});
768 $attrs->{order_by} ||= [];
770 if(my $seladds = delete($attrs->{'+select'})) {
771 my @seladds = (ref($seladds) eq 'ARRAY' ? @$seladds : ($seladds));
773 @{ $attrs->{select} },
774 map { (m/\./ || ref($_)) ? $_ : "${alias}.$_" } $seladds
777 if(my $asadds = delete($attrs->{'+as'})) {
778 my @asadds = (ref($asadds) eq 'ARRAY' ? @$asadds : ($asadds));
779 $attrs->{as} = [ @{ $attrs->{as} }, @asadds ];
781 my $collapse = $attrs->{collapse} || {};
782 if (my $prefetch = delete $attrs->{prefetch}) {
784 foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
785 if ( ref $p eq 'HASH' ) {
786 foreach my $key (keys %$p) {
787 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
791 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
795 # we're about to resolve_join on the current class, so we need to bring
796 # the joins (which are from the original class) to the right level
797 # XXX the below alg is ridiculous
798 if ($attrs->{_live_join_stack}) {
800 foreach (@{$attrs->{_live_join_stack}}) {
801 if (ref $p eq 'HASH') {
802 if (exists $p->{$_}) {
808 } elsif (ref $p eq 'ARRAY') {
809 foreach my $pe (@{$p}) {
814 next unless(ref $pe eq 'HASH');
815 next unless(exists $pe->{$_});
829 my @prefetch = $self->result_source->resolve_prefetch(
830 $p, $attrs->{alias}, {}, \@pre_order, $collapse
833 push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
834 push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
837 push(@{$attrs->{order_by}}, @pre_order);
839 $attrs->{collapse} = $collapse;
840 $self->{_attrs} = $attrs;
844 my ($self, $a, $b, $is_prefetch) = @_;
847 if (ref $b eq 'HASH' && ref $a eq 'HASH') {
848 foreach my $key (keys %{$b}) {
849 if (exists $a->{$key}) {
850 $a->{$key} = $self->_merge_attr($a->{$key}, $b->{$key}, $is_prefetch);
852 $a->{$key} = $b->{$key};
857 $a = [$a] unless (ref $a eq 'ARRAY');
858 $b = [$b] unless (ref $b eq 'ARRAY');
863 foreach my $element (@{$_}) {
864 if (ref $element eq 'HASH') {
865 $hash = $self->_merge_attr($hash, $element, $is_prefetch);
866 } elsif (ref $element eq 'ARRAY') {
867 $array = [@{$array}, @{$element}];
869 if (($b == $_) && $is_prefetch) {
870 $self->_merge_array($array, $element, $is_prefetch);
872 push(@{$array}, $element);
878 my $final_array = [];
879 foreach my $element (@{$array}) {
880 push(@{$final_array}, $element) unless (exists $hash->{$element});
882 $array = $final_array;
884 if ((keys %{$hash}) && (scalar(@{$array} > 0))) {
885 return [$hash, @{$array}];
887 return (keys %{$hash}) ? $hash : $array;
893 my ($self, $a, $b) = @_;
895 $b = [$b] unless (ref $b eq 'ARRAY');
896 # add elements from @{$b} to @{$a} which aren't already in @{$a}
897 foreach my $b_element (@{$b}) {
898 push(@{$a}, $b_element) unless grep {$b_element eq $_} @{$a};
902 sub _construct_object {
903 my ($self, @row) = @_;
904 my @as = @{ $self->{_attrs}{as} };
906 my $info = $self->_collapse_result(\@as, \@row);
907 my $new = $self->result_class->inflate_result($self->result_source, @$info);
908 $new = $self->{_attrs}{record_filter}->($new)
909 if exists $self->{_attrs}{record_filter};
913 sub _collapse_result {
914 my ($self, $as, $row, $prefix) = @_;
916 my $live_join = $self->{attrs}->{_live_join} ||="";
920 foreach my $this_as (@$as) {
921 my $val = shift @copy;
922 if (defined $prefix) {
923 if ($this_as =~ m/^\Q${prefix}.\E(.+)$/) {
925 $remain =~ /^(?:(.*)\.)?([^.]+)$/;
926 $const{$1||''}{$2} = $val;
929 $this_as =~ /^(?:(.*)\.)?([^.]+)$/;
930 $const{$1||''}{$2} = $val;
934 my $info = [ {}, {} ];
935 foreach my $key (keys %const) {
936 if (length $key && $key ne $live_join) {
938 my @parts = split(/\./, $key);
939 foreach my $p (@parts) {
940 $target = $target->[1]->{$p} ||= [];
942 $target->[0] = $const{$key};
944 $info->[0] = $const{$key};
949 if (defined $prefix) {
951 m/^\Q${prefix}.\E(.+)$/ ? ($1) : ()
952 } keys %{$self->{_attrs}->{collapse}}
954 @collapse = keys %{$self->{_attrs}->{collapse}};
958 my ($c) = sort { length $a <=> length $b } @collapse;
960 foreach my $p (split(/\./, $c)) {
961 $target = $target->[1]->{$p} ||= [];
963 my $c_prefix = (defined($prefix) ? "${prefix}.${c}" : $c);
964 my @co_key = @{$self->{_attrs}->{collapse}{$c_prefix}};
965 my $tree = $self->_collapse_result($as, $row, $c_prefix);
966 my %co_check = map { ($_, $tree->[0]->{$_}); } @co_key;
972 !defined($tree->[0]->{$_}) || $co_check{$_} ne $tree->[0]->{$_}
977 last unless (@raw = $self->cursor->next);
978 $row = $self->{stashed_row} = \@raw;
979 $tree = $self->_collapse_result($as, $row, $c_prefix);
981 @$target = (@final ? @final : [ {}, {} ]);
982 # single empty result to indicate an empty prefetched has_many
985 #print "final info: " . Dumper($info);
993 =item Arguments: $result_source?
995 =item Return Value: $result_source
999 An accessor for the primary ResultSource object from which this ResultSet
1009 =item Arguments: $cond, \%attrs??
1011 =item Return Value: $count
1015 Performs an SQL C<COUNT> with the same query as the resultset was built
1016 with to find the number of elements. If passed arguments, does a search
1017 on the resultset and counts the results of that.
1019 Note: When using C<count> with C<group_by>, L<DBIX::Class> emulates C<GROUP BY>
1020 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
1021 not support C<DISTINCT> with multiple columns. If you are using such a
1022 database, you should only use columns from the main table in your C<group_by>
1029 return $self->search(@_)->count if @_ and defined $_[0];
1030 return scalar @{ $self->get_cache } if $self->get_cache;
1031 my $count = $self->_count;
1032 return 0 unless $count;
1034 $count -= $self->{attrs}{offset} if $self->{attrs}{offset};
1035 $count = $self->{attrs}{rows} if
1036 $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
1040 sub _count { # Separated out so pager can get the full count
1042 my $select = { count => '*' };
1045 my $attrs = { %{ $self->{_attrs} } };
1046 if (my $group_by = delete $attrs->{group_by}) {
1047 delete $attrs->{having};
1048 my @distinct = (ref $group_by ? @$group_by : ($group_by));
1049 # todo: try CONCAT for multi-column pk
1050 my @pk = $self->result_source->primary_columns;
1052 foreach my $column (@distinct) {
1053 if ($column =~ qr/^(?:\Q$attrs->{alias}.\E)?$pk[0]$/) {
1054 @distinct = ($column);
1060 $select = { count => { distinct => \@distinct } };
1063 $attrs->{select} = $select;
1064 $attrs->{as} = [qw/count/];
1066 # offset, order by and page are not needed to count. record_filter is cdbi
1067 delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
1068 my $tmp_rs = (ref $self)->new($self->result_source, $attrs);
1069 $tmp_rs->{_parent_rs} = $self->{_parent_rs} if ($self->{_parent_rs});
1070 #XXX - hack to pass through parent of related resultsets
1072 my ($count) = $tmp_rs->cursor->next;
1076 =head2 count_literal
1080 =item Arguments: $sql_fragment, @bind_values
1082 =item Return Value: $count
1086 Counts the results in a literal query. Equivalent to calling L</search_literal>
1087 with the passed arguments, then L</count>.
1091 sub count_literal { shift->search_literal(@_)->count; }
1097 =item Arguments: none
1099 =item Return Value: @objects
1103 Returns all elements in the resultset. Called implicitly if the resultset
1104 is returned in list context.
1110 return @{ $self->get_cache } if $self->get_cache;
1114 # TODO: don't call resolve here
1116 if (keys %{$self->{_attrs}->{collapse}}) {
1117 # if ($self->{attrs}->{prefetch}) {
1118 # Using $self->cursor->all is really just an optimisation.
1119 # If we're collapsing has_many prefetches it probably makes
1120 # very little difference, and this is cleaner than hacking
1121 # _construct_object to survive the approach
1122 my @row = $self->cursor->next;
1124 push(@obj, $self->_construct_object(@row));
1125 @row = (exists $self->{stashed_row}
1126 ? @{delete $self->{stashed_row}}
1127 : $self->cursor->next);
1130 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
1133 $self->set_cache(\@obj) if $self->{attrs}{cache};
1141 =item Arguments: none
1143 =item Return Value: $self
1147 Resets the resultset's cursor, so you can iterate through the elements again.
1153 delete $self->{_attrs} if (exists $self->{_attrs});
1155 $self->{all_cache_position} = 0;
1156 $self->cursor->reset;
1164 =item Arguments: none
1166 =item Return Value: $object?
1170 Resets the resultset and returns an object for the first result (if the
1171 resultset returns anything).
1176 return $_[0]->reset->next;
1179 # _cond_for_update_delete
1181 # update/delete require the condition to be modified to handle
1182 # the differing SQL syntax available. This transforms the $self->{cond}
1183 # appropriately, returning the new condition.
1185 sub _cond_for_update_delete {
1189 if (!ref($self->{cond})) {
1190 # No-op. No condition, we're updating/deleting everything
1192 elsif (ref $self->{cond} eq 'ARRAY') {
1196 foreach my $key (keys %{$_}) {
1198 $hash{$1} = $_->{$key};
1204 elsif (ref $self->{cond} eq 'HASH') {
1205 if ((keys %{$self->{cond}})[0] eq '-and') {
1208 my @cond = @{$self->{cond}{-and}};
1209 for (my $i = 0; $i <= @cond - 1; $i++) {
1210 my $entry = $cond[$i];
1213 if (ref $entry eq 'HASH') {
1214 foreach my $key (keys %{$entry}) {
1216 $hash{$1} = $entry->{$key};
1220 $entry =~ /([^.]+)$/;
1221 $hash{$1} = $cond[++$i];
1224 push @{$cond->{-and}}, \%hash;
1228 foreach my $key (keys %{$self->{cond}}) {
1230 $cond->{$1} = $self->{cond}{$key};
1235 $self->throw_exception(
1236 "Can't update/delete on resultset with condition unless hash or array"
1248 =item Arguments: \%values
1250 =item Return Value: $storage_rv
1254 Sets the specified columns in the resultset to the supplied values in a
1255 single query. Return value will be true if the update succeeded or false
1256 if no records were updated; exact type of success value is storage-dependent.
1261 my ($self, $values) = @_;
1262 $self->throw_exception("Values for update must be a hash")
1263 unless ref $values eq 'HASH';
1265 my $cond = $self->_cond_for_update_delete;
1267 return $self->result_source->storage->update(
1268 $self->result_source->from, $values, $cond
1276 =item Arguments: \%values
1278 =item Return Value: 1
1282 Fetches all objects and updates them one at a time. Note that C<update_all>
1283 will run DBIC cascade triggers, while L</update> will not.
1288 my ($self, $values) = @_;
1289 $self->throw_exception("Values for update must be a hash")
1290 unless ref $values eq 'HASH';
1291 foreach my $obj ($self->all) {
1292 $obj->set_columns($values)->update;
1301 =item Arguments: none
1303 =item Return Value: 1
1307 Deletes the contents of the resultset from its result source. Note that this
1308 will not run DBIC cascade triggers. See L</delete_all> if you need triggers
1317 my $cond = $self->_cond_for_update_delete;
1319 $self->result_source->storage->delete($self->result_source->from, $cond);
1327 =item Arguments: none
1329 =item Return Value: 1
1333 Fetches all objects and deletes them one at a time. Note that C<delete_all>
1334 will run DBIC cascade triggers, while L</delete> will not.
1340 $_->delete for $self->all;
1348 =item Arguments: none
1350 =item Return Value: $pager
1354 Return Value a L<Data::Page> object for the current resultset. Only makes
1355 sense for queries with a C<page> attribute.
1361 my $attrs = $self->{attrs};
1362 $self->throw_exception("Can't create pager for non-paged rs")
1363 unless $self->{page};
1364 $attrs->{rows} ||= 10;
1365 return $self->{pager} ||= Data::Page->new(
1366 $self->_count, $attrs->{rows}, $self->{page});
1373 =item Arguments: $page_number
1375 =item Return Value: $rs
1379 Returns a resultset for the $page_number page of the resultset on which page
1380 is called, where each page contains a number of rows equal to the 'rows'
1381 attribute set on the resultset (10 by default).
1386 my ($self, $page) = @_;
1387 my $attrs = { %{$self->{attrs}} };
1388 $attrs->{page} = $page;
1389 return (ref $self)->new($self->result_source, $attrs);
1396 =item Arguments: \%vals
1398 =item Return Value: $object
1402 Creates an object in the resultset's result class and returns it.
1407 my ($self, $values) = @_;
1408 $self->throw_exception( "new_result needs a hash" )
1409 unless (ref $values eq 'HASH');
1410 $self->throw_exception(
1411 "Can't abstract implicit construct, condition not a hash"
1412 ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
1414 my $alias = $self->{attrs}{alias};
1415 foreach my $key (keys %{$self->{cond}||{}}) {
1416 $new{$1} = $self->{cond}{$key} if ($key =~ m/^(?:\Q${alias}.\E)?([^.]+)$/);
1418 my $obj = $self->result_class->new(\%new);
1419 $obj->result_source($self->result_source) if $obj->can('result_source');
1427 =item Arguments: \%vals, \%attrs?
1429 =item Return Value: $object
1433 Find an existing record from this resultset. If none exists, instantiate a new
1434 result object and return it. The object will not be saved into your storage
1435 until you call L<DBIx::Class::Row/insert> on it.
1437 If you want objects to be saved immediately, use L</find_or_create> instead.
1443 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1444 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1445 my $exists = $self->find($hash, $attrs);
1446 return defined $exists ? $exists : $self->new_result($hash);
1453 =item Arguments: \%vals
1455 =item Return Value: $object
1459 Inserts a record into the resultset and returns the object representing it.
1461 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
1466 my ($self, $attrs) = @_;
1467 $self->throw_exception( "create needs a hashref" )
1468 unless ref $attrs eq 'HASH';
1469 return $self->new_result($attrs)->insert;
1472 =head2 find_or_create
1476 =item Arguments: \%vals, \%attrs?
1478 =item Return Value: $object
1482 $class->find_or_create({ key => $val, ... });
1484 Tries to find a record based on its primary key or unique constraint; if none
1485 is found, creates one and returns that instead.
1487 my $cd = $schema->resultset('CD')->find_or_create({
1489 artist => 'Massive Attack',
1490 title => 'Mezzanine',
1494 Also takes an optional C<key> attribute, to search by a specific key or unique
1495 constraint. For example:
1497 my $cd = $schema->resultset('CD')->find_or_create(
1499 artist => 'Massive Attack',
1500 title => 'Mezzanine',
1502 { key => 'cd_artist_title' }
1505 See also L</find> and L</update_or_create>. For information on how to declare
1506 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1510 sub find_or_create {
1512 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1513 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1514 my $exists = $self->find($hash, $attrs);
1515 return defined $exists ? $exists : $self->create($hash);
1518 =head2 update_or_create
1522 =item Arguments: \%col_values, { key => $unique_constraint }?
1524 =item Return Value: $object
1528 $class->update_or_create({ col => $val, ... });
1530 First, searches for an existing row matching one of the unique constraints
1531 (including the primary key) on the source of this resultset. If a row is
1532 found, updates it with the other given column values. Otherwise, creates a new
1535 Takes an optional C<key> attribute to search on a specific unique constraint.
1538 # In your application
1539 my $cd = $schema->resultset('CD')->update_or_create(
1541 artist => 'Massive Attack',
1542 title => 'Mezzanine',
1545 { key => 'cd_artist_title' }
1548 If no C<key> is specified, it searches on all unique constraints defined on the
1549 source, including the primary key.
1551 If the C<key> is specified as C<primary>, it searches only on the primary key.
1553 See also L</find> and L</find_or_create>. For information on how to declare
1554 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1558 sub update_or_create {
1560 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1561 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
1563 my $row = $self->find($cond);
1565 $row->update($cond);
1569 return $self->create($cond);
1576 =item Arguments: none
1578 =item Return Value: \@cache_objects?
1582 Gets the contents of the cache for the resultset, if the cache is set.
1594 =item Arguments: \@cache_objects
1596 =item Return Value: \@cache_objects
1600 Sets the contents of the cache for the resultset. Expects an arrayref
1601 of objects of the same class as those produced by the resultset. Note that
1602 if the cache is set the resultset will return the cached objects rather
1603 than re-querying the database even if the cache attr is not set.
1608 my ( $self, $data ) = @_;
1609 $self->throw_exception("set_cache requires an arrayref")
1610 if defined($data) && (ref $data ne 'ARRAY');
1611 $self->{all_cache} = $data;
1618 =item Arguments: none
1620 =item Return Value: []
1624 Clears the cache for the resultset.
1629 shift->set_cache(undef);
1632 =head2 related_resultset
1636 =item Arguments: $relationship_name
1638 =item Return Value: $resultset
1642 Returns a related resultset for the supplied relationship name.
1644 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1648 sub related_resultset {
1649 my ( $self, $rel ) = @_;
1651 $self->{related_resultsets} ||= {};
1652 return $self->{related_resultsets}{$rel} ||= do {
1653 #warn "fetching related resultset for rel '$rel' " . $self->result_source->{name};
1654 my $rel_obj = $self->result_source->relationship_info($rel);
1655 #print Dumper($self->result_source->_relationships);
1656 $self->throw_exception(
1657 "search_related: result source '" . $self->result_source->name .
1658 "' has no such relationship ${rel}")
1659 unless $rel_obj; #die Dumper $self->{attrs};
1661 my @live_join_stack = (
1662 exists $self->{attrs}->{_live_join_stack})
1663 ? @{$self->{attrs}->{_live_join_stack}}
1666 push(@live_join_stack, $rel);
1668 my $rs = $self->result_source->schema->resultset($rel_obj->{class})->search(
1672 _live_join => $rel, #the most recent
1673 _live_join_stack => \@live_join_stack, #the trail of rels
1674 _parent_attrs => $self->{attrs}}
1677 # keep reference of the original resultset
1678 $rs->{_parent_rs} = ($self->{_parent_rs})
1679 ? $self->{_parent_rs}
1680 : $self->result_source;
1686 =head2 throw_exception
1688 See L<DBIx::Class::Schema/throw_exception> for details.
1692 sub throw_exception {
1694 $self->result_source->schema->throw_exception(@_);
1697 # XXX: FIXME: Attributes docs need clearing up
1701 The resultset takes various attributes that modify its behavior. Here's an
1708 =item Value: ($order_by | \@order_by)
1712 Which column(s) to order the results by. This is currently passed
1713 through directly to SQL, so you can give e.g. C<year DESC> for a
1714 descending order on the column `year'.
1716 Please note that if you have quoting enabled (see
1717 L<DBIx::Class::Storage/quote_char>) you will need to do C<\'year DESC' > to
1718 specify an order. (The scalar ref causes it to be passed as raw sql to the DB,
1719 so you will need to manually quote things as appropriate.)
1725 =item Value: \@columns
1729 Shortcut to request a particular set of columns to be retrieved. Adds
1730 C<me.> onto the start of any column without a C<.> in it and sets C<select>
1731 from that, then auto-populates C<as> from C<select> as normal. (You may also
1732 use the C<cols> attribute, as in earlier versions of DBIC.)
1734 =head2 include_columns
1738 =item Value: \@columns
1742 Shortcut to include additional columns in the returned results - for example
1744 $schema->resultset('CD')->search(undef, {
1745 include_columns => ['artist.name'],
1749 would return all CDs and include a 'name' column to the information
1750 passed to object inflation
1756 =item Value: \@select_columns
1760 Indicates which columns should be selected from the storage. You can use
1761 column names, or in the case of RDBMS back ends, function or stored procedure
1764 $rs = $schema->resultset('Employee')->search(undef, {
1767 { count => 'employeeid' },
1772 When you use function/stored procedure names and do not supply an C<as>
1773 attribute, the column names returned are storage-dependent. E.g. MySQL would
1774 return a column named C<count(employeeid)> in the above example.
1780 Indicates additional columns to be selected from storage. Works the same as
1781 L<select> but adds columns to the selection.
1789 Indicates additional column names for those added via L<+select>.
1797 =item Value: \@inflation_names
1801 Indicates column names for object inflation. This is used in conjunction with
1802 C<select>, usually when C<select> contains one or more function or stored
1805 $rs = $schema->resultset('Employee')->search(undef, {
1808 { count => 'employeeid' }
1810 as => ['name', 'employee_count'],
1813 my $employee = $rs->first(); # get the first Employee
1815 If the object against which the search is performed already has an accessor
1816 matching a column name specified in C<as>, the value can be retrieved using
1817 the accessor as normal:
1819 my $name = $employee->name();
1821 If on the other hand an accessor does not exist in the object, you need to
1822 use C<get_column> instead:
1824 my $employee_count = $employee->get_column('employee_count');
1826 You can create your own accessors if required - see
1827 L<DBIx::Class::Manual::Cookbook> for details.
1829 Please note: This will NOT insert an C<AS employee_count> into the SQL statement
1830 produced, it is used for internal access only. Thus attempting to use the accessor
1831 in an C<order_by> clause or similar will fail misrably.
1837 =item Value: ($rel_name | \@rel_names | \%rel_names)
1841 Contains a list of relationships that should be joined for this query. For
1844 # Get CDs by Nine Inch Nails
1845 my $rs = $schema->resultset('CD')->search(
1846 { 'artist.name' => 'Nine Inch Nails' },
1847 { join => 'artist' }
1850 Can also contain a hash reference to refer to the other relation's relations.
1853 package MyApp::Schema::Track;
1854 use base qw/DBIx::Class/;
1855 __PACKAGE__->table('track');
1856 __PACKAGE__->add_columns(qw/trackid cd position title/);
1857 __PACKAGE__->set_primary_key('trackid');
1858 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
1861 # In your application
1862 my $rs = $schema->resultset('Artist')->search(
1863 { 'track.title' => 'Teardrop' },
1865 join => { cd => 'track' },
1866 order_by => 'artist.name',
1870 If the same join is supplied twice, it will be aliased to <rel>_2 (and
1871 similarly for a third time). For e.g.
1873 my $rs = $schema->resultset('Artist')->search({
1874 'cds.title' => 'Down to Earth',
1875 'cds_2.title' => 'Popular',
1877 join => [ qw/cds cds/ ],
1880 will return a set of all artists that have both a cd with title 'Down
1881 to Earth' and a cd with title 'Popular'.
1883 If you want to fetch related objects from other tables as well, see C<prefetch>
1890 =item Value: ($rel_name | \@rel_names | \%rel_names)
1894 Contains one or more relationships that should be fetched along with the main
1895 query (when they are accessed afterwards they will have already been
1896 "prefetched"). This is useful for when you know you will need the related
1897 objects, because it saves at least one query:
1899 my $rs = $schema->resultset('Tag')->search(
1908 The initial search results in SQL like the following:
1910 SELECT tag.*, cd.*, artist.* FROM tag
1911 JOIN cd ON tag.cd = cd.cdid
1912 JOIN artist ON cd.artist = artist.artistid
1914 L<DBIx::Class> has no need to go back to the database when we access the
1915 C<cd> or C<artist> relationships, which saves us two SQL statements in this
1918 Simple prefetches will be joined automatically, so there is no need
1919 for a C<join> attribute in the above search. If you're prefetching to
1920 depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
1921 specify the join as well.
1923 C<prefetch> can be used with the following relationship types: C<belongs_to>,
1924 C<has_one> (or if you're using C<add_relationship>, any relationship declared
1925 with an accessor type of 'single' or 'filter').
1935 Makes the resultset paged and specifies the page to retrieve. Effectively
1936 identical to creating a non-pages resultset and then calling ->page($page)
1939 If L<rows> attribute is not specified it defualts to 10 rows per page.
1949 Specifes the maximum number of rows for direct retrieval or the number of
1950 rows per page if the page attribute or method is used.
1956 =item Value: $offset
1960 Specifies the (zero-based) row number for the first row to be returned, or the
1961 of the first row of the first page if paging is used.
1967 =item Value: \@columns
1971 A arrayref of columns to group by. Can include columns of joined tables.
1973 group_by => [qw/ column1 column2 ... /]
1979 =item Value: $condition
1983 HAVING is a select statement attribute that is applied between GROUP BY and
1984 ORDER BY. It is applied to the after the grouping calculations have been
1987 having => { 'count(employee)' => { '>=', 100 } }
1993 =item Value: (0 | 1)
1997 Set to 1 to group by all columns.
2001 Set to 1 to cache search results. This prevents extra SQL queries if you
2002 revisit rows in your ResultSet:
2004 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
2006 while( my $artist = $resultset->next ) {
2010 $rs->first; # without cache, this would issue a query
2012 By default, searches are not cached.
2014 For more examples of using these attributes, see
2015 L<DBIx::Class::Manual::Cookbook>.
2021 =item Value: \@from_clause
2025 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
2026 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
2029 NOTE: Use this on your own risk. This allows you to shoot off your foot!
2031 C<join> will usually do what you need and it is strongly recommended that you
2032 avoid using C<from> unless you cannot achieve the desired result using C<join>.
2033 And we really do mean "cannot", not just tried and failed. Attempting to use
2034 this because you're having problems with C<join> is like trying to use x86
2035 ASM because you've got a syntax error in your C. Trust us on this.
2037 Now, if you're still really, really sure you need to use this (and if you're
2038 not 100% sure, ask the mailing list first), here's an explanation of how this
2041 The syntax is as follows -
2044 { <alias1> => <table1> },
2046 { <alias2> => <table2>, -join_type => 'inner|left|right' },
2047 [], # nested JOIN (optional)
2048 { <table1.column1> => <table2.column2>, ... (more conditions) },
2050 # More of the above [ ] may follow for additional joins
2057 ON <table1.column1> = <table2.column2>
2058 <more joins may follow>
2060 An easy way to follow the examples below is to remember the following:
2062 Anything inside "[]" is a JOIN
2063 Anything inside "{}" is a condition for the enclosing JOIN
2065 The following examples utilize a "person" table in a family tree application.
2066 In order to express parent->child relationships, this table is self-joined:
2068 # Person->belongs_to('father' => 'Person');
2069 # Person->belongs_to('mother' => 'Person');
2071 C<from> can be used to nest joins. Here we return all children with a father,
2072 then search against all mothers of those children:
2074 $rs = $schema->resultset('Person')->search(
2077 alias => 'mother', # alias columns in accordance with "from"
2079 { mother => 'person' },
2082 { child => 'person' },
2084 { father => 'person' },
2085 { 'father.person_id' => 'child.father_id' }
2088 { 'mother.person_id' => 'child.mother_id' }
2095 # SELECT mother.* FROM person mother
2098 # JOIN person father
2099 # ON ( father.person_id = child.father_id )
2101 # ON ( mother.person_id = child.mother_id )
2103 The type of any join can be controlled manually. To search against only people
2104 with a father in the person table, we could explicitly use C<INNER JOIN>:
2106 $rs = $schema->resultset('Person')->search(
2109 alias => 'child', # alias columns in accordance with "from"
2111 { child => 'person' },
2113 { father => 'person', -join_type => 'inner' },
2114 { 'father.id' => 'child.father_id' }
2121 # SELECT child.* FROM person child
2122 # INNER JOIN person father ON child.father_id = father.id