1 package DBIx::Class::ResultSet;
11 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';
99 result_source => $source,
100 result_class => $attrs->{result_class} || $source->result_class,
101 cond => $attrs->{where},
102 # from => $attrs->{from},
103 # collapse => $collapse,
105 page => delete $attrs->{page},
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.
161 my $our_attrs = { %{$self->{attrs}} };
162 my $having = delete $our_attrs->{having};
164 $attrs = pop(@_) if @_ > 1 and ref $_[$#_] eq 'HASH';
166 # merge new attrs into old
167 foreach my $key (qw/join prefetch/) {
168 next unless (exists $attrs->{$key});
169 if (exists $our_attrs->{$key}) {
170 $our_attrs->{$key} = $self->_merge_attr($our_attrs->{$key}, $attrs->{$key});
172 $our_attrs->{$key} = $attrs->{$key};
174 delete $attrs->{$key};
176 my $new_attrs = { %{$our_attrs}, %{$attrs} };
178 # merge new where and having into old
180 ? ((@_ == 1 || ref $_[0] eq "HASH")
183 ? $self->throw_exception(
184 "Odd number of arguments to search")
187 if (defined $where) {
188 $new_attrs->{where} = (defined $new_attrs->{where}
190 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
191 $where, $new_attrs->{where} ] }
195 if (defined $having) {
196 $new_attrs->{having} = (defined $new_attrs->{having}
198 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
199 $having, $new_attrs->{having} ] }
203 my $rs = (ref $self)->new($self->result_source, $new_attrs);
204 $rs->{_parent_rs} = $self->{_parent_rs} if ($self->{_parent_rs}); #XXX - hack to pass through parent of related resultsets
206 unless (@_) { # no search, effectively just a clone
207 my $rows = $self->get_cache;
209 $rs->set_cache($rows);
216 =head2 search_literal
220 =item Arguments: $sql_fragment, @bind_values
222 =item Return Value: $resultset (scalar context), @row_objs (list context)
226 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
227 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
229 Pass a literal chunk of SQL to be added to the conditional part of the
235 my ($self, $cond, @vals) = @_;
236 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
237 $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
238 return $self->search(\$cond, $attrs);
245 =item Arguments: @values | \%cols, \%attrs?
247 =item Return Value: $row_object
251 Finds a row based on its primary key or unique constraint. For example, to find
252 a row by its primary key:
254 my $cd = $schema->resultset('CD')->find(5);
256 You can also find a row by a specific unique constraint using the C<key>
257 attribute. For example:
259 my $cd = $schema->resultset('CD')->find('Massive Attack', 'Mezzanine', { key => 'artist_title' });
261 Additionally, you can specify the columns explicitly by name:
263 my $cd = $schema->resultset('CD')->find(
265 artist => 'Massive Attack',
266 title => 'Mezzanine',
268 { key => 'artist_title' }
271 If no C<key> is specified and you explicitly name columns, it searches on all
272 unique constraints defined on the source, including the primary key.
274 If the C<key> is specified as C<primary>, it searches only on the primary key.
276 See also L</find_or_create> and L</update_or_create>. For information on how to
277 declare unique constraints, see
278 L<DBIx::Class::ResultSource/add_unique_constraint>.
284 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
286 # Parse out a hash from input
287 my @cols = exists $attrs->{key}
288 ? $self->result_source->unique_constraint_columns($attrs->{key})
289 : $self->result_source->primary_columns;
292 if (ref $_[0] eq 'HASH') {
293 $hash = { %{$_[0]} };
295 elsif (@_ == @cols) {
297 @{$hash}{@cols} = @_;
300 # For backwards compatibility
304 $self->throw_exception(
305 "Arguments to find must be a hashref or match the number of columns in the "
306 . (exists $attrs->{key} ? "$attrs->{key} unique constraint" : "primary key")
310 # Check the hash we just parsed against our source's unique constraints
311 my @constraint_names = exists $attrs->{key}
313 : $self->result_source->unique_constraint_names;
314 $self->throw_exception(
315 "Can't find unless a primary key or unique constraint is defined"
316 ) unless @constraint_names;
319 foreach my $name (@constraint_names) {
320 my @unique_cols = $self->result_source->unique_constraint_columns($name);
321 my $unique_query = $self->_build_unique_query($hash, \@unique_cols);
323 # Add the ResultSet's alias
324 foreach my $key (grep { ! m/\./ } keys %$unique_query) {
325 my $alias = $self->{attrs}->{alias};
326 $unique_query->{"$alias.$key"} = delete $unique_query->{$key};
329 push @unique_queries, $unique_query if %$unique_query;
332 # Handle cases where the ResultSet already defines the query
333 my $query = @unique_queries ? \@unique_queries : undef;
338 my $rs = $self->search($query, $attrs);
340 return keys %{$rs->{_attrs}->{collapse}} ? $rs->next : $rs->single;
344 return (keys %{$self->{_attrs}->{collapse}})
345 ? $self->search($query)->next
346 : $self->single($query);
350 # _build_unique_query
352 # Constrain the specified query hash based on the specified column names.
354 sub _build_unique_query {
355 my ($self, $query, $unique_cols) = @_;
358 map { $_ => $query->{$_} }
359 grep { exists $query->{$_} }
362 return \%unique_query;
365 =head2 search_related
369 =item Arguments: $cond, \%attrs?
371 =item Return Value: $new_resultset
375 $new_rs = $cd_rs->search_related('artist', {
379 Searches the specified relationship, optionally specifying a condition and
380 attributes for matching records. See L</ATTRIBUTES> for more information.
385 return shift->related_resultset(shift)->search(@_);
392 =item Arguments: none
394 =item Return Value: $cursor
398 Returns a storage-driven cursor to the given resultset. See
399 L<DBIx::Class::Cursor> for more information.
407 my $attrs = { %{$self->{_attrs}} };
408 return $self->{cursor}
409 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
410 $attrs->{where},$attrs);
417 =item Arguments: $cond?
419 =item Return Value: $row_object?
423 my $cd = $schema->resultset('CD')->single({ year => 2001 });
425 Inflates the first result without creating a cursor if the resultset has
426 any records in it; if not returns nothing. Used by L</find> as an optimisation.
431 my ($self, $where) = @_;
433 my $attrs = { %{$self->{_attrs}} };
435 if (defined $attrs->{where}) {
438 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
439 $where, delete $attrs->{where} ]
442 $attrs->{where} = $where;
446 my @data = $self->result_source->storage->select_single(
447 $attrs->{from}, $attrs->{select},
448 $attrs->{where},$attrs);
449 return (@data ? $self->_construct_object(@data) : ());
456 =item Arguments: $cond?
458 =item Return Value: $resultsetcolumn
462 my $max_length = $rs->get_column('length')->max;
464 Returns a ResultSetColumn instance for $column based on $self
469 my ($self, $column) = @_;
471 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
479 =item Arguments: $cond, \%attrs?
481 =item Return Value: $resultset (scalar context), @row_objs (list context)
485 # WHERE title LIKE '%blue%'
486 $cd_rs = $rs->search_like({ title => '%blue%'});
488 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
489 that this is simply a convenience method. You most likely want to use
490 L</search> with specific operators.
492 For more information, see L<DBIx::Class::Manual::Cookbook>.
498 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
499 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
500 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
501 return $class->search($query, { %$attrs });
508 =item Arguments: $first, $last
510 =item Return Value: $resultset (scalar context), @row_objs (list context)
514 Returns a resultset or object list representing a subset of elements from the
515 resultset slice is called on. Indexes are from 0, i.e., to get the first
518 my ($one, $two, $three) = $rs->slice(0, 2);
523 my ($self, $min, $max) = @_;
524 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
525 $attrs->{offset} = $self->{attrs}{offset} || 0;
526 $attrs->{offset} += $min;
527 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
528 return $self->search(undef(), $attrs);
529 #my $slice = (ref $self)->new($self->result_source, $attrs);
530 #return (wantarray ? $slice->all : $slice);
537 =item Arguments: none
539 =item Return Value: $result?
543 Returns the next element in the resultset (C<undef> is there is none).
545 Can be used to efficiently iterate over records in the resultset:
547 my $rs = $schema->resultset('CD')->search;
548 while (my $cd = $rs->next) {
552 Note that you need to store the resultset object, and call C<next> on it.
553 Calling C<< resultset('Table')->next >> repeatedly will always return the
554 first record from the resultset.
560 if (my $cache = $self->get_cache) {
561 $self->{all_cache_position} ||= 0;
562 return $cache->[$self->{all_cache_position}++];
564 if ($self->{attrs}{cache}) {
565 $self->{all_cache_position} = 1;
566 return ($self->all)[0];
568 my @row = (exists $self->{stashed_row} ?
569 @{delete $self->{stashed_row}} :
572 return unless (@row);
573 return $self->_construct_object(@row);
576 # XXX - this is essentially just the old new(). rewrite / tidy up?
580 return if(exists $self->{_attrs}); #return if _resolve has already been called
582 my $attrs = $self->{attrs};
583 my $source = ($self->{_parent_rs}) ? $self->{_parent_rs} : $self->{result_source};
585 # XXX - this is a hack to prevent dclone dieing because of the code ref, get's put back in $attrs afterwards
586 my $record_filter = delete $attrs->{record_filter} if (defined $attrs->{record_filter});
587 $attrs = Storable::dclone($attrs || {}); # { %{ $attrs || {} } };
588 $attrs->{record_filter} = $record_filter if ($record_filter);
589 $self->{attrs}->{record_filter} = $record_filter if ($record_filter);
591 my $alias = $attrs->{alias};
593 $attrs->{columns} ||= delete $attrs->{cols} if $attrs->{cols};
594 delete $attrs->{as} if $attrs->{columns};
595 $attrs->{columns} ||= [ $self->{result_source}->columns ] unless $attrs->{select};
596 my $select_alias = ($self->{_parent_rs}) ? $self->{attrs}->{_live_join} : $alias;
598 map { m/\./ ? $_ : "${select_alias}.$_" } @{delete $attrs->{columns}}
599 ] if $attrs->{columns};
601 map { m/^\Q$alias.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}}
603 if (my $include = delete $attrs->{include_columns}) {
604 push(@{$attrs->{select}}, @$include);
605 push(@{$attrs->{as}}, map { m/([^.]+)$/; $1; } @$include);
608 $attrs->{from} ||= [ { $alias => $source->from } ];
609 $attrs->{seen_join} ||= {};
611 if (my $join = delete $attrs->{join}) {
612 foreach my $j (ref $join eq 'ARRAY' ? @$join : ($join)) {
613 if (ref $j eq 'HASH') {
614 $seen{$_} = 1 foreach keys %$j;
620 push(@{$attrs->{from}}, $source->resolve_join($join, $attrs->{alias}, $attrs->{seen_join}));
622 $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
623 $attrs->{order_by} = [ $attrs->{order_by} ] if
624 $attrs->{order_by} and !ref($attrs->{order_by});
625 $attrs->{order_by} ||= [];
627 my $collapse = $attrs->{collapse} || {};
628 if (my $prefetch = delete $attrs->{prefetch}) {
630 foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
631 if ( ref $p eq 'HASH' ) {
632 foreach my $key (keys %$p) {
633 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
637 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
640 my @prefetch = $source->resolve_prefetch(
641 $p, $attrs->{alias}, {}, \@pre_order, $collapse);
642 push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
643 push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
645 push(@{$attrs->{order_by}}, @pre_order);
647 $attrs->{collapse} = $collapse;
648 $self->{_attrs} = $attrs;
652 my ($self, $a, $b) = @_;
654 if (ref $b eq 'HASH' && ref $a eq 'HASH') {
655 return $self->_merge_hash($a, $b);
657 $a = [$a] unless (ref $a eq 'ARRAY');
658 $b = [$b] unless (ref $b eq 'ARRAY');
659 my @new_array = (@{$a}, @{$b});
660 foreach my $a_element (@new_array) {
662 foreach my $b_element (@new_array) {
663 if ((ref $a_element eq 'HASH') && (ref $b_element eq 'HASH') && ($a_element ne $b_element)) {
664 $a_element = $self->_merge_hash($a_element, $b_element);
665 $new_array[$i] = undef;
670 @new_array = grep($_, @new_array);
676 my ($self, $a, $b) = @_;
678 foreach my $key (keys %{$b}) {
679 if (exists $a->{$key}) {
680 $a->{$key} = $self->_merge_attr($a->{$key}, $b->{$key});
682 $a->{$key} = delete $b->{$key};
688 sub _construct_object {
689 my ($self, @row) = @_;
690 my @as = @{ $self->{_attrs}{as} };
692 my $info = $self->_collapse_result(\@as, \@row);
693 my $new = $self->result_class->inflate_result($self->result_source, @$info);
694 $new = $self->{_attrs}{record_filter}->($new)
695 if exists $self->{_attrs}{record_filter};
699 sub _collapse_result {
700 my ($self, $as, $row, $prefix) = @_;
702 my $live_join = $self->{attrs}->{_live_join} ||="";
706 foreach my $this_as (@$as) {
707 my $val = shift @copy;
708 if (defined $prefix) {
709 if ($this_as =~ m/^\Q${prefix}.\E(.+)$/) {
711 $remain =~ /^(?:(.*)\.)?([^.]+)$/;
712 $const{$1||''}{$2} = $val;
715 $this_as =~ /^(?:(.*)\.)?([^.]+)$/;
716 $const{$1||''}{$2} = $val;
720 my $info = [ {}, {} ];
721 foreach my $key (keys %const) {
722 if (length $key && $key ne $live_join) {
724 my @parts = split(/\./, $key);
725 foreach my $p (@parts) {
726 $target = $target->[1]->{$p} ||= [];
728 $target->[0] = $const{$key};
730 $info->[0] = $const{$key};
735 if (defined $prefix) {
737 m/^\Q${prefix}.\E(.+)$/ ? ($1) : ()
738 } keys %{$self->{_attrs}->{collapse}}
740 @collapse = keys %{$self->{_attrs}->{collapse}};
744 my ($c) = sort { length $a <=> length $b } @collapse;
746 foreach my $p (split(/\./, $c)) {
747 $target = $target->[1]->{$p} ||= [];
749 my $c_prefix = (defined($prefix) ? "${prefix}.${c}" : $c);
750 my @co_key = @{$self->{_attrs}->{collapse}{$c_prefix}};
751 my %co_check = map { ($_, $target->[0]->{$_}); } @co_key;
752 my $tree = $self->_collapse_result($as, $row, $c_prefix);
755 !defined($tree->[0]->{$_}) ||
756 $co_check{$_} ne $tree->[0]->{$_}
759 last unless (@raw = $self->cursor->next);
760 $row = $self->{stashed_row} = \@raw;
761 $tree = $self->_collapse_result($as, $row, $c_prefix);
763 @$target = (@final ? @final : [ {}, {} ]);
764 # single empty result to indicate an empty prefetched has_many
773 =item Arguments: $result_source?
775 =item Return Value: $result_source
779 An accessor for the primary ResultSource object from which this ResultSet
789 =item Arguments: $cond, \%attrs??
791 =item Return Value: $count
795 Performs an SQL C<COUNT> with the same query as the resultset was built
796 with to find the number of elements. If passed arguments, does a search
797 on the resultset and counts the results of that.
799 Note: When using C<count> with C<group_by>, L<DBIX::Class> emulates C<GROUP BY>
800 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
801 not support C<DISTINCT> with multiple columns. If you are using such a
802 database, you should only use columns from the main table in your C<group_by>
809 return $self->search(@_)->count if @_ and defined $_[0];
810 return scalar @{ $self->get_cache } if $self->get_cache;
812 my $count = $self->_count;
813 return 0 unless $count;
815 $count -= $self->{attrs}{offset} if $self->{attrs}{offset};
816 $count = $self->{attrs}{rows} if
817 $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
821 sub _count { # Separated out so pager can get the full count
823 my $select = { count => '*' };
826 my $attrs = { %{ $self->{_attrs} } };
827 if ($attrs->{distinct} && (my $group_by = $attrs->{group_by} || $attrs->{select})) {
828 delete $attrs->{having};
829 my @distinct = (ref $group_by ? @$group_by : ($group_by));
830 # todo: try CONCAT for multi-column pk
831 my @pk = $self->result_source->primary_columns;
833 foreach my $column (@distinct) {
834 if ($column =~ qr/^(?:\Q$attrs->{alias}.\E)?$pk[0]$/) {
835 @distinct = ($column);
841 $select = { count => { distinct => \@distinct } };
842 #use Data::Dumper; die Dumper $select;
845 $attrs->{select} = $select;
846 $attrs->{as} = [qw/count/];
848 # offset, order by and page are not needed to count. record_filter is cdbi
849 delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
850 my ($count) = (ref $self)->new($self->result_source, $attrs)->cursor->next;
858 =item Arguments: $sql_fragment, @bind_values
860 =item Return Value: $count
864 Counts the results in a literal query. Equivalent to calling L</search_literal>
865 with the passed arguments, then L</count>.
869 sub count_literal { shift->search_literal(@_)->count; }
875 =item Arguments: none
877 =item Return Value: @objects
881 Returns all elements in the resultset. Called implicitly if the resultset
882 is returned in list context.
888 return @{ $self->get_cache } if $self->get_cache;
892 # TODO: don't call resolve here
894 if (keys %{$self->{_attrs}->{collapse}}) {
895 # if ($self->{attrs}->{prefetch}) {
896 # Using $self->cursor->all is really just an optimisation.
897 # If we're collapsing has_many prefetches it probably makes
898 # very little difference, and this is cleaner than hacking
899 # _construct_object to survive the approach
900 my @row = $self->cursor->next;
902 push(@obj, $self->_construct_object(@row));
903 @row = (exists $self->{stashed_row}
904 ? @{delete $self->{stashed_row}}
905 : $self->cursor->next);
908 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
911 $self->set_cache(\@obj) if $self->{attrs}{cache};
919 =item Arguments: none
921 =item Return Value: $self
925 Resets the resultset's cursor, so you can iterate through the elements again.
931 delete $self->{_attrs} if (exists $self->{_attrs});
933 $self->{all_cache_position} = 0;
934 $self->cursor->reset;
942 =item Arguments: none
944 =item Return Value: $object?
948 Resets the resultset and returns an object for the first result (if the
949 resultset returns anything).
954 return $_[0]->reset->next;
957 # _cond_for_update_delete
959 # update/delete require the condition to be modified to handle
960 # the differing SQL syntax available. This transforms the $self->{cond}
961 # appropriately, returning the new condition.
963 sub _cond_for_update_delete {
967 if (!ref($self->{cond})) {
968 # No-op. No condition, we're updating/deleting everything
970 elsif (ref $self->{cond} eq 'ARRAY') {
974 foreach my $key (keys %{$_}) {
976 $hash{$1} = $_->{$key};
982 elsif (ref $self->{cond} eq 'HASH') {
983 if ((keys %{$self->{cond}})[0] eq '-and') {
986 my @cond = @{$self->{cond}{-and}};
987 for (my $i = 0; $i < @cond - 1; $i++) {
988 my $entry = $cond[$i];
991 if (ref $entry eq 'HASH') {
992 foreach my $key (keys %{$entry}) {
994 $hash{$1} = $entry->{$key};
998 $entry =~ /([^.]+)$/;
999 $hash{$entry} = $cond[++$i];
1002 push @{$cond->{-and}}, \%hash;
1006 foreach my $key (keys %{$self->{cond}}) {
1008 $cond->{$1} = $self->{cond}{$key};
1013 $self->throw_exception(
1014 "Can't update/delete on resultset with condition unless hash or array"
1026 =item Arguments: \%values
1028 =item Return Value: $storage_rv
1032 Sets the specified columns in the resultset to the supplied values in a
1033 single query. Return value will be true if the update succeeded or false
1034 if no records were updated; exact type of success value is storage-dependent.
1039 my ($self, $values) = @_;
1040 $self->throw_exception("Values for update must be a hash")
1041 unless ref $values eq 'HASH';
1043 my $cond = $self->_cond_for_update_delete;
1045 return $self->result_source->storage->update(
1046 $self->result_source->from, $values, $cond
1054 =item Arguments: \%values
1056 =item Return Value: 1
1060 Fetches all objects and updates them one at a time. Note that C<update_all>
1061 will run DBIC cascade triggers, while L</update> will not.
1066 my ($self, $values) = @_;
1067 $self->throw_exception("Values for update must be a hash")
1068 unless ref $values eq 'HASH';
1069 foreach my $obj ($self->all) {
1070 $obj->set_columns($values)->update;
1079 =item Arguments: none
1081 =item Return Value: 1
1085 Deletes the contents of the resultset from its result source. Note that this
1086 will not run DBIC cascade triggers. See L</delete_all> if you need triggers
1095 my $cond = $self->_cond_for_update_delete;
1097 $self->result_source->storage->delete($self->result_source->from, $cond);
1105 =item Arguments: none
1107 =item Return Value: 1
1111 Fetches all objects and deletes them one at a time. Note that C<delete_all>
1112 will run DBIC cascade triggers, while L</delete> will not.
1118 $_->delete for $self->all;
1126 =item Arguments: none
1128 =item Return Value: $pager
1132 Return Value a L<Data::Page> object for the current resultset. Only makes
1133 sense for queries with a C<page> attribute.
1139 my $attrs = $self->{attrs};
1140 $self->throw_exception("Can't create pager for non-paged rs")
1141 unless $self->{page};
1142 $attrs->{rows} ||= 10;
1143 return $self->{pager} ||= Data::Page->new(
1144 $self->_count, $attrs->{rows}, $self->{page});
1151 =item Arguments: $page_number
1153 =item Return Value: $rs
1157 Returns a resultset for the $page_number page of the resultset on which page
1158 is called, where each page contains a number of rows equal to the 'rows'
1159 attribute set on the resultset (10 by default).
1164 my ($self, $page) = @_;
1165 my $attrs = { %{$self->{attrs}} };
1166 $attrs->{page} = $page;
1167 return (ref $self)->new($self->result_source, $attrs);
1174 =item Arguments: \%vals
1176 =item Return Value: $object
1180 Creates an object in the resultset's result class and returns it.
1185 my ($self, $values) = @_;
1186 $self->throw_exception( "new_result needs a hash" )
1187 unless (ref $values eq 'HASH');
1188 $self->throw_exception(
1189 "Can't abstract implicit construct, condition not a hash"
1190 ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
1192 my $alias = $self->{attrs}{alias};
1193 foreach my $key (keys %{$self->{cond}||{}}) {
1194 $new{$1} = $self->{cond}{$key} if ($key =~ m/^(?:\Q${alias}.\E)?([^.]+)$/);
1196 my $obj = $self->result_class->new(\%new);
1197 $obj->result_source($self->result_source) if $obj->can('result_source');
1205 =item Arguments: \%vals, \%attrs?
1207 =item Return Value: $object
1211 Find an existing record from this resultset. If none exists, instantiate a new
1212 result object and return it. The object will not be saved into your storage
1213 until you call L<DBIx::Class::Row/insert> on it.
1215 If you want objects to be saved immediately, use L</find_or_create> instead.
1221 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1222 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1223 my $exists = $self->find($hash, $attrs);
1224 return defined $exists ? $exists : $self->new_result($hash);
1231 =item Arguments: \%vals
1233 =item Return Value: $object
1237 Inserts a record into the resultset and returns the object representing it.
1239 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
1244 my ($self, $attrs) = @_;
1245 $self->throw_exception( "create needs a hashref" )
1246 unless ref $attrs eq 'HASH';
1247 return $self->new_result($attrs)->insert;
1250 =head2 find_or_create
1254 =item Arguments: \%vals, \%attrs?
1256 =item Return Value: $object
1260 $class->find_or_create({ key => $val, ... });
1262 Searches for a record matching the search condition; if it doesn't find one,
1263 creates one and returns that instead.
1265 my $cd = $schema->resultset('CD')->find_or_create({
1267 artist => 'Massive Attack',
1268 title => 'Mezzanine',
1272 Also takes an optional C<key> attribute, to search by a specific key or unique
1273 constraint. For example:
1275 my $cd = $schema->resultset('CD')->find_or_create(
1277 artist => 'Massive Attack',
1278 title => 'Mezzanine',
1280 { key => 'artist_title' }
1283 See also L</find> and L</update_or_create>. For information on how to declare
1284 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1288 sub find_or_create {
1290 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1291 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1292 my $exists = $self->find($hash, $attrs);
1293 return defined $exists ? $exists : $self->create($hash);
1296 =head2 update_or_create
1300 =item Arguments: \%col_values, { key => $unique_constraint }?
1302 =item Return Value: $object
1306 $class->update_or_create({ col => $val, ... });
1308 First, searches for an existing row matching one of the unique constraints
1309 (including the primary key) on the source of this resultset. If a row is
1310 found, updates it with the other given column values. Otherwise, creates a new
1313 Takes an optional C<key> attribute to search on a specific unique constraint.
1316 # In your application
1317 my $cd = $schema->resultset('CD')->update_or_create(
1319 artist => 'Massive Attack',
1320 title => 'Mezzanine',
1323 { key => 'artist_title' }
1326 If no C<key> is specified, it searches on all unique constraints defined on the
1327 source, including the primary key.
1329 If the C<key> is specified as C<primary>, it searches only on the primary key.
1331 See also L</find> and L</find_or_create>. For information on how to declare
1332 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1336 sub update_or_create {
1338 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1339 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1341 my $row = $self->find($hash, $attrs);
1343 $row->update($hash);
1347 return $self->create($hash);
1354 =item Arguments: none
1356 =item Return Value: \@cache_objects?
1360 Gets the contents of the cache for the resultset, if the cache is set.
1372 =item Arguments: \@cache_objects
1374 =item Return Value: \@cache_objects
1378 Sets the contents of the cache for the resultset. Expects an arrayref
1379 of objects of the same class as those produced by the resultset. Note that
1380 if the cache is set the resultset will return the cached objects rather
1381 than re-querying the database even if the cache attr is not set.
1386 my ( $self, $data ) = @_;
1387 $self->throw_exception("set_cache requires an arrayref")
1388 if defined($data) && (ref $data ne 'ARRAY');
1389 $self->{all_cache} = $data;
1396 =item Arguments: none
1398 =item Return Value: []
1402 Clears the cache for the resultset.
1407 shift->set_cache(undef);
1410 =head2 related_resultset
1414 =item Arguments: $relationship_name
1416 =item Return Value: $resultset
1420 Returns a related resultset for the supplied relationship name.
1422 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1426 sub related_resultset {
1427 my ( $self, $rel ) = @_;
1429 $self->{related_resultsets} ||= {};
1430 return $self->{related_resultsets}{$rel} ||= do {
1431 #warn "fetching related resultset for rel '$rel' " . $self->result_source->{name};
1432 my $rel_obj = $self->result_source->relationship_info($rel);
1433 $self->throw_exception(
1434 "search_related: result source '" . $self->result_source->name .
1435 "' has no such relationship ${rel}")
1436 unless $rel_obj; #die Dumper $self->{attrs};
1438 my $rs = $self->result_source->schema->resultset($rel_obj->{class}
1440 { %{$self->{attrs}},
1444 _live_join => $rel }
1447 # keep reference of the original resultset
1448 $rs->{_parent_rs} = $self->result_source;
1453 =head2 throw_exception
1455 See L<DBIx::Class::Schema/throw_exception> for details.
1459 sub throw_exception {
1461 $self->result_source->schema->throw_exception(@_);
1464 # XXX: FIXME: Attributes docs need clearing up
1468 The resultset takes various attributes that modify its behavior. Here's an
1475 =item Value: ($order_by | \@order_by)
1479 Which column(s) to order the results by. This is currently passed
1480 through directly to SQL, so you can give e.g. C<year DESC> for a
1481 descending order on the column `year'.
1487 =item Value: \@columns
1491 Shortcut to request a particular set of columns to be retrieved. Adds
1492 C<me.> onto the start of any column without a C<.> in it and sets C<select>
1493 from that, then auto-populates C<as> from C<select> as normal. (You may also
1494 use the C<cols> attribute, as in earlier versions of DBIC.)
1496 =head2 include_columns
1500 =item Value: \@columns
1504 Shortcut to include additional columns in the returned results - for example
1506 $schema->resultset('CD')->search(undef, {
1507 include_columns => ['artist.name'],
1511 would return all CDs and include a 'name' column to the information
1512 passed to object inflation
1518 =item Value: \@select_columns
1522 Indicates which columns should be selected from the storage. You can use
1523 column names, or in the case of RDBMS back ends, function or stored procedure
1526 $rs = $schema->resultset('Employee')->search(undef, {
1529 { count => 'employeeid' },
1534 When you use function/stored procedure names and do not supply an C<as>
1535 attribute, the column names returned are storage-dependent. E.g. MySQL would
1536 return a column named C<count(employeeid)> in the above example.
1542 =item Value: \@inflation_names
1546 Indicates column names for object inflation. This is used in conjunction with
1547 C<select>, usually when C<select> contains one or more function or stored
1550 $rs = $schema->resultset('Employee')->search(undef, {
1553 { count => 'employeeid' }
1555 as => ['name', 'employee_count'],
1558 my $employee = $rs->first(); # get the first Employee
1560 If the object against which the search is performed already has an accessor
1561 matching a column name specified in C<as>, the value can be retrieved using
1562 the accessor as normal:
1564 my $name = $employee->name();
1566 If on the other hand an accessor does not exist in the object, you need to
1567 use C<get_column> instead:
1569 my $employee_count = $employee->get_column('employee_count');
1571 You can create your own accessors if required - see
1572 L<DBIx::Class::Manual::Cookbook> for details.
1578 =item Value: ($rel_name | \@rel_names | \%rel_names)
1582 Contains a list of relationships that should be joined for this query. For
1585 # Get CDs by Nine Inch Nails
1586 my $rs = $schema->resultset('CD')->search(
1587 { 'artist.name' => 'Nine Inch Nails' },
1588 { join => 'artist' }
1591 Can also contain a hash reference to refer to the other relation's relations.
1594 package MyApp::Schema::Track;
1595 use base qw/DBIx::Class/;
1596 __PACKAGE__->table('track');
1597 __PACKAGE__->add_columns(qw/trackid cd position title/);
1598 __PACKAGE__->set_primary_key('trackid');
1599 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
1602 # In your application
1603 my $rs = $schema->resultset('Artist')->search(
1604 { 'track.title' => 'Teardrop' },
1606 join => { cd => 'track' },
1607 order_by => 'artist.name',
1611 If the same join is supplied twice, it will be aliased to <rel>_2 (and
1612 similarly for a third time). For e.g.
1614 my $rs = $schema->resultset('Artist')->search({
1615 'cds.title' => 'Down to Earth',
1616 'cds_2.title' => 'Popular',
1618 join => [ qw/cds cds/ ],
1621 will return a set of all artists that have both a cd with title 'Down
1622 to Earth' and a cd with title 'Popular'.
1624 If you want to fetch related objects from other tables as well, see C<prefetch>
1631 =item Value: ($rel_name | \@rel_names | \%rel_names)
1635 Contains one or more relationships that should be fetched along with the main
1636 query (when they are accessed afterwards they will have already been
1637 "prefetched"). This is useful for when you know you will need the related
1638 objects, because it saves at least one query:
1640 my $rs = $schema->resultset('Tag')->search(
1649 The initial search results in SQL like the following:
1651 SELECT tag.*, cd.*, artist.* FROM tag
1652 JOIN cd ON tag.cd = cd.cdid
1653 JOIN artist ON cd.artist = artist.artistid
1655 L<DBIx::Class> has no need to go back to the database when we access the
1656 C<cd> or C<artist> relationships, which saves us two SQL statements in this
1659 Simple prefetches will be joined automatically, so there is no need
1660 for a C<join> attribute in the above search. If you're prefetching to
1661 depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
1662 specify the join as well.
1664 C<prefetch> can be used with the following relationship types: C<belongs_to>,
1665 C<has_one> (or if you're using C<add_relationship>, any relationship declared
1666 with an accessor type of 'single' or 'filter').
1672 =item Value: \@from_clause
1676 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
1677 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
1680 NOTE: Use this on your own risk. This allows you to shoot off your foot!
1681 C<join> will usually do what you need and it is strongly recommended that you
1682 avoid using C<from> unless you cannot achieve the desired result using C<join>.
1684 In simple terms, C<from> works as follows:
1687 { <alias> => <table>, -join_type => 'inner|left|right' }
1688 [] # nested JOIN (optional)
1689 { <table.column> => <foreign_table.foreign_key> }
1695 ON <table.column> = <foreign_table.foreign_key>
1697 An easy way to follow the examples below is to remember the following:
1699 Anything inside "[]" is a JOIN
1700 Anything inside "{}" is a condition for the enclosing JOIN
1702 The following examples utilize a "person" table in a family tree application.
1703 In order to express parent->child relationships, this table is self-joined:
1705 # Person->belongs_to('father' => 'Person');
1706 # Person->belongs_to('mother' => 'Person');
1708 C<from> can be used to nest joins. Here we return all children with a father,
1709 then search against all mothers of those children:
1711 $rs = $schema->resultset('Person')->search(
1714 alias => 'mother', # alias columns in accordance with "from"
1716 { mother => 'person' },
1719 { child => 'person' },
1721 { father => 'person' },
1722 { 'father.person_id' => 'child.father_id' }
1725 { 'mother.person_id' => 'child.mother_id' }
1732 # SELECT mother.* FROM person mother
1735 # JOIN person father
1736 # ON ( father.person_id = child.father_id )
1738 # ON ( mother.person_id = child.mother_id )
1740 The type of any join can be controlled manually. To search against only people
1741 with a father in the person table, we could explicitly use C<INNER JOIN>:
1743 $rs = $schema->resultset('Person')->search(
1746 alias => 'child', # alias columns in accordance with "from"
1748 { child => 'person' },
1750 { father => 'person', -join_type => 'inner' },
1751 { 'father.id' => 'child.father_id' }
1758 # SELECT child.* FROM person child
1759 # INNER JOIN person father ON child.father_id = father.id
1769 Makes the resultset paged and specifies the page to retrieve. Effectively
1770 identical to creating a non-pages resultset and then calling ->page($page)
1781 Specifes the maximum number of rows for direct retrieval or the number of
1782 rows per page if the page attribute or method is used.
1788 =item Value: \@columns
1792 A arrayref of columns to group by. Can include columns of joined tables.
1794 group_by => [qw/ column1 column2 ... /]
1800 =item Value: $condition
1804 HAVING is a select statement attribute that is applied between GROUP BY and
1805 ORDER BY. It is applied to the after the grouping calculations have been
1808 having => { 'count(employee)' => { '>=', 100 } }
1814 =item Value: (0 | 1)
1818 Set to 1 to group by all columns.
1822 Set to 1 to cache search results. This prevents extra SQL queries if you
1823 revisit rows in your ResultSet:
1825 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
1827 while( my $artist = $resultset->next ) {
1831 $rs->first; # without cache, this would issue a query
1833 By default, searches are not cached.
1835 For more examples of using these attributes, see
1836 L<DBIx::Class::Manual::Cookbook>.