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} = [$our_attrs->{$key}] if (ref $our_attrs->{$key} ne 'ARRAY');
171 push(@{$our_attrs->{$key}}, (ref $attrs->{$key} eq 'ARRAY') ? @{$attrs->{$key}} : $attrs->{$key});
173 $our_attrs->{$key} = $attrs->{$key};
175 delete $attrs->{$key};
177 my $new_attrs = { %{$our_attrs}, %{$attrs} };
179 # merge new where and having into old
181 ? ((@_ == 1 || ref $_[0] eq "HASH")
184 ? $self->throw_exception(
185 "Odd number of arguments to search")
188 if (defined $where) {
189 $new_attrs->{where} = (defined $new_attrs->{where}
191 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
192 $where, $new_attrs->{where} ] }
196 if (defined $having) {
197 $new_attrs->{having} = (defined $new_attrs->{having}
199 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
200 $having, $new_attrs->{having} ] }
204 my $rs = (ref $self)->new($self->result_source, $new_attrs);
205 $rs->{_parent_rs} = $self->{_parent_rs} if ($self->{_parent_rs}); #XXX - hack to pass through parent of related resultsets
207 unless (@_) { # no search, effectively just a clone
208 my $rows = $self->get_cache;
210 $rs->set_cache($rows);
217 =head2 search_literal
221 =item Arguments: $sql_fragment, @bind_values
223 =item Return Value: $resultset (scalar context), @row_objs (list context)
227 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
228 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
230 Pass a literal chunk of SQL to be added to the conditional part of the
236 my ($self, $cond, @vals) = @_;
237 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
238 $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
239 return $self->search(\$cond, $attrs);
246 =item Arguments: @values | \%cols, \%attrs?
248 =item Return Value: $row_object
252 Finds a row based on its primary key or unique constraint. For example, to find
253 a row by its primary key:
255 my $cd = $schema->resultset('CD')->find(5);
257 You can also find a row by a specific unique constraint using the C<key>
258 attribute. For example:
260 my $cd = $schema->resultset('CD')->find('Massive Attack', 'Mezzanine', { key => 'artist_title' });
262 Additionally, you can specify the columns explicitly by name:
264 my $cd = $schema->resultset('CD')->find(
266 artist => 'Massive Attack',
267 title => 'Mezzanine',
269 { key => 'artist_title' }
272 If no C<key> is specified and you explicitly name columns, it searches on all
273 unique constraints defined on the source, including the primary key.
275 If the C<key> is specified as C<primary>, it searches only on the primary key.
277 See also L</find_or_create> and L</update_or_create>. For information on how to
278 declare unique constraints, see
279 L<DBIx::Class::ResultSource/add_unique_constraint>.
285 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
287 # Parse out a hash from input
288 my @cols = exists $attrs->{key}
289 ? $self->result_source->unique_constraint_columns($attrs->{key})
290 : $self->result_source->primary_columns;
293 if (ref $_[0] eq 'HASH') {
294 $hash = { %{$_[0]} };
296 elsif (@_ == @cols) {
298 @{$hash}{@cols} = @_;
301 # For backwards compatibility
305 $self->throw_exception(
306 "Arguments to find must be a hashref or match the number of columns in the "
307 . (exists $attrs->{key} ? "$attrs->{key} unique constraint" : "primary key")
311 # Check the hash we just parsed against our source's unique constraints
312 my @constraint_names = exists $attrs->{key}
314 : $self->result_source->unique_constraint_names;
315 $self->throw_exception(
316 "Can't find unless a primary key or unique constraint is defined"
317 ) unless @constraint_names;
320 foreach my $name (@constraint_names) {
321 my @unique_cols = $self->result_source->unique_constraint_columns($name);
322 my $unique_query = $self->_build_unique_query($hash, \@unique_cols);
324 # Add the ResultSet's alias
325 foreach my $key (grep { ! m/\./ } keys %$unique_query) {
326 my $alias = $self->{attrs}->{alias};
327 $unique_query->{"$alias.$key"} = delete $unique_query->{$key};
330 push @unique_queries, $unique_query if %$unique_query;
333 # Handle cases where the ResultSet already defines the query
334 my $query = @unique_queries ? \@unique_queries : undef;
339 my $rs = $self->search($query, $attrs);
341 return keys %{$rs->{_attrs}->{collapse}} ? $rs->next : $rs->single;
345 return (keys %{$self->{_attrs}->{collapse}})
346 ? $self->search($query)->next
347 : $self->single($query);
351 # _build_unique_query
353 # Constrain the specified query hash based on the specified column names.
355 sub _build_unique_query {
356 my ($self, $query, $unique_cols) = @_;
359 map { $_ => $query->{$_} }
360 grep { exists $query->{$_} }
363 return \%unique_query;
366 =head2 search_related
370 =item Arguments: $cond, \%attrs?
372 =item Return Value: $new_resultset
376 $new_rs = $cd_rs->search_related('artist', {
380 Searches the specified relationship, optionally specifying a condition and
381 attributes for matching records. See L</ATTRIBUTES> for more information.
386 return shift->related_resultset(shift)->search(@_);
393 =item Arguments: none
395 =item Return Value: $cursor
399 Returns a storage-driven cursor to the given resultset. See
400 L<DBIx::Class::Cursor> for more information.
408 my $attrs = { %{$self->{_attrs}} };
409 return $self->{cursor}
410 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
411 $attrs->{where},$attrs);
418 =item Arguments: $cond?
420 =item Return Value: $row_object?
424 my $cd = $schema->resultset('CD')->single({ year => 2001 });
426 Inflates the first result without creating a cursor if the resultset has
427 any records in it; if not returns nothing. Used by L</find> as an optimisation.
432 my ($self, $where) = @_;
434 my $attrs = { %{$self->{_attrs}} };
436 if (defined $attrs->{where}) {
439 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
440 $where, delete $attrs->{where} ]
443 $attrs->{where} = $where;
447 my @data = $self->result_source->storage->select_single(
448 $attrs->{from}, $attrs->{select},
449 $attrs->{where},$attrs);
450 return (@data ? $self->_construct_object(@data) : ());
457 =item Arguments: $cond?
459 =item Return Value: $resultsetcolumn
463 my $max_length = $rs->get_column('length')->max;
465 Returns a ResultSetColumn instance for $column based on $self
470 my ($self, $column) = @_;
472 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
480 =item Arguments: $cond, \%attrs?
482 =item Return Value: $resultset (scalar context), @row_objs (list context)
486 # WHERE title LIKE '%blue%'
487 $cd_rs = $rs->search_like({ title => '%blue%'});
489 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
490 that this is simply a convenience method. You most likely want to use
491 L</search> with specific operators.
493 For more information, see L<DBIx::Class::Manual::Cookbook>.
499 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
500 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
501 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
502 return $class->search($query, { %$attrs });
509 =item Arguments: $first, $last
511 =item Return Value: $resultset (scalar context), @row_objs (list context)
515 Returns a resultset or object list representing a subset of elements from the
516 resultset slice is called on. Indexes are from 0, i.e., to get the first
519 my ($one, $two, $three) = $rs->slice(0, 2);
524 my ($self, $min, $max) = @_;
525 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
526 $attrs->{offset} = $self->{attrs}{offset} || 0;
527 $attrs->{offset} += $min;
528 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
529 return $self->search(undef(), $attrs);
530 #my $slice = (ref $self)->new($self->result_source, $attrs);
531 #return (wantarray ? $slice->all : $slice);
538 =item Arguments: none
540 =item Return Value: $result?
544 Returns the next element in the resultset (C<undef> is there is none).
546 Can be used to efficiently iterate over records in the resultset:
548 my $rs = $schema->resultset('CD')->search;
549 while (my $cd = $rs->next) {
553 Note that you need to store the resultset object, and call C<next> on it.
554 Calling C<< resultset('Table')->next >> repeatedly will always return the
555 first record from the resultset.
561 if (my $cache = $self->get_cache) {
562 $self->{all_cache_position} ||= 0;
563 return $cache->[$self->{all_cache_position}++];
565 if ($self->{attrs}{cache}) {
566 $self->{all_cache_position} = 1;
567 return ($self->all)[0];
569 my @row = (exists $self->{stashed_row} ?
570 @{delete $self->{stashed_row}} :
573 return unless (@row);
574 return $self->_construct_object(@row);
577 # XXX - this is essentially just the old new(). rewrite / tidy up?
581 return if(exists $self->{_attrs}); #return if _resolve has already been called
583 my $attrs = $self->{attrs};
584 my $source = ($self->{_parent_rs}) ? $self->{_parent_rs} : $self->{result_source};
586 # XXX - this is a hack to prevent dclone dieing because of the code ref, get's put back in $attrs afterwards
587 my $record_filter = delete $attrs->{record_filter} if (defined $attrs->{record_filter});
588 $attrs = Storable::dclone($attrs || {}); # { %{ $attrs || {} } };
589 $attrs->{record_filter} = $record_filter if ($record_filter);
590 $self->{attrs}->{record_filter} = $record_filter if ($record_filter);
592 my $alias = $attrs->{alias};
594 $attrs->{columns} ||= delete $attrs->{cols} if $attrs->{cols};
595 delete $attrs->{as} if $attrs->{columns};
596 $attrs->{columns} ||= [ $self->{result_source}->columns ] unless $attrs->{select};
597 my $select_alias = ($self->{_parent_rs}) ? $self->{attrs}->{_live_join} : $alias;
599 map { m/\./ ? $_ : "${select_alias}.$_" } @{delete $attrs->{columns}}
600 ] if $attrs->{columns};
602 map { m/^\Q$alias.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}}
604 if (my $include = delete $attrs->{include_columns}) {
605 push(@{$attrs->{select}}, @$include);
606 push(@{$attrs->{as}}, map { m/([^.]+)$/; $1; } @$include);
609 $attrs->{from} ||= [ { $alias => $source->from } ];
610 $attrs->{seen_join} ||= {};
612 if (my $join = delete $attrs->{join}) {
613 foreach my $j (ref $join eq 'ARRAY' ? @$join : ($join)) {
614 if (ref $j eq 'HASH') {
615 $seen{$_} = 1 foreach keys %$j;
621 push(@{$attrs->{from}}, $source->resolve_join($join, $attrs->{alias}, $attrs->{seen_join}));
623 $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
624 $attrs->{order_by} = [ $attrs->{order_by} ] if
625 $attrs->{order_by} and !ref($attrs->{order_by});
626 $attrs->{order_by} ||= [];
628 my $collapse = $attrs->{collapse} || {};
629 if (my $prefetch = delete $attrs->{prefetch}) {
631 foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
632 if ( ref $p eq 'HASH' ) {
633 foreach my $key (keys %$p) {
634 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
638 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
641 my @prefetch = $source->resolve_prefetch(
642 $p, $attrs->{alias}, {}, \@pre_order, $collapse);
643 push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
644 push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
646 push(@{$attrs->{order_by}}, @pre_order);
648 $attrs->{collapse} = $collapse;
649 $self->{_attrs} = $attrs;
652 sub _construct_object {
653 my ($self, @row) = @_;
654 my @as = @{ $self->{_attrs}{as} };
656 my $info = $self->_collapse_result(\@as, \@row);
657 my $new = $self->result_class->inflate_result($self->result_source, @$info);
658 $new = $self->{_attrs}{record_filter}->($new)
659 if exists $self->{_attrs}{record_filter};
663 sub _collapse_result {
664 my ($self, $as, $row, $prefix) = @_;
666 my $live_join = $self->{attrs}->{_live_join} ||="";
670 foreach my $this_as (@$as) {
671 my $val = shift @copy;
672 if (defined $prefix) {
673 if ($this_as =~ m/^\Q${prefix}.\E(.+)$/) {
675 $remain =~ /^(?:(.*)\.)?([^.]+)$/;
676 $const{$1||''}{$2} = $val;
679 $this_as =~ /^(?:(.*)\.)?([^.]+)$/;
680 $const{$1||''}{$2} = $val;
684 my $info = [ {}, {} ];
685 foreach my $key (keys %const) {
686 if (length $key && $key ne $live_join) {
688 my @parts = split(/\./, $key);
689 foreach my $p (@parts) {
690 $target = $target->[1]->{$p} ||= [];
692 $target->[0] = $const{$key};
694 $info->[0] = $const{$key};
699 if (defined $prefix) {
701 m/^\Q${prefix}.\E(.+)$/ ? ($1) : ()
702 } keys %{$self->{_attrs}->{collapse}}
704 @collapse = keys %{$self->{_attrs}->{collapse}};
708 my ($c) = sort { length $a <=> length $b } @collapse;
710 foreach my $p (split(/\./, $c)) {
711 $target = $target->[1]->{$p} ||= [];
713 my $c_prefix = (defined($prefix) ? "${prefix}.${c}" : $c);
714 my @co_key = @{$self->{_attrs}->{collapse}{$c_prefix}};
715 my %co_check = map { ($_, $target->[0]->{$_}); } @co_key;
716 my $tree = $self->_collapse_result($as, $row, $c_prefix);
719 !defined($tree->[0]->{$_}) ||
720 $co_check{$_} ne $tree->[0]->{$_}
723 last unless (@raw = $self->cursor->next);
724 $row = $self->{stashed_row} = \@raw;
725 $tree = $self->_collapse_result($as, $row, $c_prefix);
727 @$target = (@final ? @final : [ {}, {} ]);
728 # single empty result to indicate an empty prefetched has_many
737 =item Arguments: $result_source?
739 =item Return Value: $result_source
743 An accessor for the primary ResultSource object from which this ResultSet
753 =item Arguments: $cond, \%attrs??
755 =item Return Value: $count
759 Performs an SQL C<COUNT> with the same query as the resultset was built
760 with to find the number of elements. If passed arguments, does a search
761 on the resultset and counts the results of that.
763 Note: When using C<count> with C<group_by>, L<DBIX::Class> emulates C<GROUP BY>
764 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
765 not support C<DISTINCT> with multiple columns. If you are using such a
766 database, you should only use columns from the main table in your C<group_by>
773 return $self->search(@_)->count if @_ and defined $_[0];
774 return scalar @{ $self->get_cache } if $self->get_cache;
776 my $count = $self->_count;
777 return 0 unless $count;
779 $count -= $self->{attrs}{offset} if $self->{attrs}{offset};
780 $count = $self->{attrs}{rows} if
781 $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
785 sub _count { # Separated out so pager can get the full count
787 my $select = { count => '*' };
790 my $attrs = { %{ $self->{_attrs} } };
791 if ($attrs->{distinct} && (my $group_by = $attrs->{group_by} || $attrs->{select})) {
792 delete $attrs->{having};
793 my @distinct = (ref $group_by ? @$group_by : ($group_by));
794 # todo: try CONCAT for multi-column pk
795 my @pk = $self->result_source->primary_columns;
797 foreach my $column (@distinct) {
798 if ($column =~ qr/^(?:\Q$attrs->{alias}.\E)?$pk[0]$/) {
799 @distinct = ($column);
805 $select = { count => { distinct => \@distinct } };
806 #use Data::Dumper; die Dumper $select;
809 $attrs->{select} = $select;
810 $attrs->{as} = [qw/count/];
812 # offset, order by and page are not needed to count. record_filter is cdbi
813 delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
814 my ($count) = (ref $self)->new($self->result_source, $attrs)->cursor->next;
822 =item Arguments: $sql_fragment, @bind_values
824 =item Return Value: $count
828 Counts the results in a literal query. Equivalent to calling L</search_literal>
829 with the passed arguments, then L</count>.
833 sub count_literal { shift->search_literal(@_)->count; }
839 =item Arguments: none
841 =item Return Value: @objects
845 Returns all elements in the resultset. Called implicitly if the resultset
846 is returned in list context.
852 return @{ $self->get_cache } if $self->get_cache;
856 # TODO: don't call resolve here
858 if (keys %{$self->{_attrs}->{collapse}}) {
859 # if ($self->{attrs}->{prefetch}) {
860 # Using $self->cursor->all is really just an optimisation.
861 # If we're collapsing has_many prefetches it probably makes
862 # very little difference, and this is cleaner than hacking
863 # _construct_object to survive the approach
864 my @row = $self->cursor->next;
866 push(@obj, $self->_construct_object(@row));
867 @row = (exists $self->{stashed_row}
868 ? @{delete $self->{stashed_row}}
869 : $self->cursor->next);
872 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
875 $self->set_cache(\@obj) if $self->{attrs}{cache};
883 =item Arguments: none
885 =item Return Value: $self
889 Resets the resultset's cursor, so you can iterate through the elements again.
895 delete $self->{_attrs} if (exists $self->{_attrs});
897 $self->{all_cache_position} = 0;
898 $self->cursor->reset;
906 =item Arguments: none
908 =item Return Value: $object?
912 Resets the resultset and returns an object for the first result (if the
913 resultset returns anything).
918 return $_[0]->reset->next;
921 # _cond_for_update_delete
923 # update/delete require the condition to be modified to handle
924 # the differing SQL syntax available. This transforms the $self->{cond}
925 # appropriately, returning the new condition.
927 sub _cond_for_update_delete {
931 if (!ref($self->{cond})) {
932 # No-op. No condition, we're updating/deleting everything
934 elsif (ref $self->{cond} eq 'ARRAY') {
938 foreach my $key (keys %{$_}) {
940 $hash{$1} = $_->{$key};
946 elsif (ref $self->{cond} eq 'HASH') {
947 if ((keys %{$self->{cond}})[0] eq '-and') {
950 my @cond = @{$self->{cond}{-and}};
951 for (my $i = 0; $i < @cond - 1; $i++) {
952 my $entry = $cond[$i];
955 if (ref $entry eq 'HASH') {
956 foreach my $key (keys %{$entry}) {
958 $hash{$1} = $entry->{$key};
962 $entry =~ /([^.]+)$/;
963 $hash{$entry} = $cond[++$i];
966 push @{$cond->{-and}}, \%hash;
970 foreach my $key (keys %{$self->{cond}}) {
972 $cond->{$1} = $self->{cond}{$key};
977 $self->throw_exception(
978 "Can't update/delete on resultset with condition unless hash or array"
990 =item Arguments: \%values
992 =item Return Value: $storage_rv
996 Sets the specified columns in the resultset to the supplied values in a
997 single query. Return value will be true if the update succeeded or false
998 if no records were updated; exact type of success value is storage-dependent.
1003 my ($self, $values) = @_;
1004 $self->throw_exception("Values for update must be a hash")
1005 unless ref $values eq 'HASH';
1007 my $cond = $self->_cond_for_update_delete;
1009 return $self->result_source->storage->update(
1010 $self->result_source->from, $values, $cond
1018 =item Arguments: \%values
1020 =item Return Value: 1
1024 Fetches all objects and updates them one at a time. Note that C<update_all>
1025 will run DBIC cascade triggers, while L</update> will not.
1030 my ($self, $values) = @_;
1031 $self->throw_exception("Values for update must be a hash")
1032 unless ref $values eq 'HASH';
1033 foreach my $obj ($self->all) {
1034 $obj->set_columns($values)->update;
1043 =item Arguments: none
1045 =item Return Value: 1
1049 Deletes the contents of the resultset from its result source. Note that this
1050 will not run DBIC cascade triggers. See L</delete_all> if you need triggers
1059 my $cond = $self->_cond_for_update_delete;
1061 $self->result_source->storage->delete($self->result_source->from, $cond);
1069 =item Arguments: none
1071 =item Return Value: 1
1075 Fetches all objects and deletes them one at a time. Note that C<delete_all>
1076 will run DBIC cascade triggers, while L</delete> will not.
1082 $_->delete for $self->all;
1090 =item Arguments: none
1092 =item Return Value: $pager
1096 Return Value a L<Data::Page> object for the current resultset. Only makes
1097 sense for queries with a C<page> attribute.
1103 my $attrs = $self->{attrs};
1104 $self->throw_exception("Can't create pager for non-paged rs")
1105 unless $self->{page};
1106 $attrs->{rows} ||= 10;
1107 return $self->{pager} ||= Data::Page->new(
1108 $self->_count, $attrs->{rows}, $self->{page});
1115 =item Arguments: $page_number
1117 =item Return Value: $rs
1121 Returns a resultset for the $page_number page of the resultset on which page
1122 is called, where each page contains a number of rows equal to the 'rows'
1123 attribute set on the resultset (10 by default).
1128 my ($self, $page) = @_;
1129 my $attrs = { %{$self->{attrs}} };
1130 $attrs->{page} = $page;
1131 return (ref $self)->new($self->result_source, $attrs);
1138 =item Arguments: \%vals
1140 =item Return Value: $object
1144 Creates an object in the resultset's result class and returns it.
1149 my ($self, $values) = @_;
1150 $self->throw_exception( "new_result needs a hash" )
1151 unless (ref $values eq 'HASH');
1152 $self->throw_exception(
1153 "Can't abstract implicit construct, condition not a hash"
1154 ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
1156 my $alias = $self->{attrs}{alias};
1157 foreach my $key (keys %{$self->{cond}||{}}) {
1158 $new{$1} = $self->{cond}{$key} if ($key =~ m/^(?:\Q${alias}.\E)?([^.]+)$/);
1160 my $obj = $self->result_class->new(\%new);
1161 $obj->result_source($self->result_source) if $obj->can('result_source');
1169 =item Arguments: \%vals, \%attrs?
1171 =item Return Value: $object
1175 Find an existing record from this resultset. If none exists, instantiate a new
1176 result object and return it. The object will not be saved into your storage
1177 until you call L<DBIx::Class::Row/insert> on it.
1179 If you want objects to be saved immediately, use L</find_or_create> instead.
1185 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1186 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1187 my $exists = $self->find($hash, $attrs);
1188 return defined $exists ? $exists : $self->new_result($hash);
1195 =item Arguments: \%vals
1197 =item Return Value: $object
1201 Inserts a record into the resultset and returns the object representing it.
1203 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
1208 my ($self, $attrs) = @_;
1209 $self->throw_exception( "create needs a hashref" )
1210 unless ref $attrs eq 'HASH';
1211 return $self->new_result($attrs)->insert;
1214 =head2 find_or_create
1218 =item Arguments: \%vals, \%attrs?
1220 =item Return Value: $object
1224 $class->find_or_create({ key => $val, ... });
1226 Searches for a record matching the search condition; if it doesn't find one,
1227 creates one and returns that instead.
1229 my $cd = $schema->resultset('CD')->find_or_create({
1231 artist => 'Massive Attack',
1232 title => 'Mezzanine',
1236 Also takes an optional C<key> attribute, to search by a specific key or unique
1237 constraint. For example:
1239 my $cd = $schema->resultset('CD')->find_or_create(
1241 artist => 'Massive Attack',
1242 title => 'Mezzanine',
1244 { key => 'artist_title' }
1247 See also L</find> and L</update_or_create>. For information on how to declare
1248 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1252 sub find_or_create {
1254 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1255 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1256 my $exists = $self->find($hash, $attrs);
1257 return defined $exists ? $exists : $self->create($hash);
1260 =head2 update_or_create
1264 =item Arguments: \%col_values, { key => $unique_constraint }?
1266 =item Return Value: $object
1270 $class->update_or_create({ col => $val, ... });
1272 First, searches for an existing row matching one of the unique constraints
1273 (including the primary key) on the source of this resultset. If a row is
1274 found, updates it with the other given column values. Otherwise, creates a new
1277 Takes an optional C<key> attribute to search on a specific unique constraint.
1280 # In your application
1281 my $cd = $schema->resultset('CD')->update_or_create(
1283 artist => 'Massive Attack',
1284 title => 'Mezzanine',
1287 { key => 'artist_title' }
1290 If no C<key> is specified, it searches on all unique constraints defined on the
1291 source, including the primary key.
1293 If the C<key> is specified as C<primary>, it searches only on the primary key.
1295 See also L</find> and L</find_or_create>. For information on how to declare
1296 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1300 sub update_or_create {
1302 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1303 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1305 my $row = $self->find($hash, $attrs);
1307 $row->update($hash);
1311 return $self->create($hash);
1318 =item Arguments: none
1320 =item Return Value: \@cache_objects?
1324 Gets the contents of the cache for the resultset, if the cache is set.
1336 =item Arguments: \@cache_objects
1338 =item Return Value: \@cache_objects
1342 Sets the contents of the cache for the resultset. Expects an arrayref
1343 of objects of the same class as those produced by the resultset. Note that
1344 if the cache is set the resultset will return the cached objects rather
1345 than re-querying the database even if the cache attr is not set.
1350 my ( $self, $data ) = @_;
1351 $self->throw_exception("set_cache requires an arrayref")
1352 if defined($data) && (ref $data ne 'ARRAY');
1353 $self->{all_cache} = $data;
1360 =item Arguments: none
1362 =item Return Value: []
1366 Clears the cache for the resultset.
1371 shift->set_cache(undef);
1374 =head2 related_resultset
1378 =item Arguments: $relationship_name
1380 =item Return Value: $resultset
1384 Returns a related resultset for the supplied relationship name.
1386 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1390 sub related_resultset {
1391 my ( $self, $rel ) = @_;
1393 $self->{related_resultsets} ||= {};
1394 return $self->{related_resultsets}{$rel} ||= do {
1395 #warn "fetching related resultset for rel '$rel' " . $self->result_source->{name};
1396 my $rel_obj = $self->result_source->relationship_info($rel);
1397 $self->throw_exception(
1398 "search_related: result source '" . $self->result_source->name .
1399 "' has no such relationship ${rel}")
1400 unless $rel_obj; #die Dumper $self->{attrs};
1402 my $rs = $self->result_source->schema->resultset($rel_obj->{class}
1404 { %{$self->{attrs}},
1408 _live_join => $rel }
1411 # keep reference of the original resultset
1412 $rs->{_parent_rs} = $self->result_source;
1417 =head2 throw_exception
1419 See L<DBIx::Class::Schema/throw_exception> for details.
1423 sub throw_exception {
1425 $self->result_source->schema->throw_exception(@_);
1428 # XXX: FIXME: Attributes docs need clearing up
1432 The resultset takes various attributes that modify its behavior. Here's an
1439 =item Value: ($order_by | \@order_by)
1443 Which column(s) to order the results by. This is currently passed
1444 through directly to SQL, so you can give e.g. C<year DESC> for a
1445 descending order on the column `year'.
1451 =item Value: \@columns
1455 Shortcut to request a particular set of columns to be retrieved. Adds
1456 C<me.> onto the start of any column without a C<.> in it and sets C<select>
1457 from that, then auto-populates C<as> from C<select> as normal. (You may also
1458 use the C<cols> attribute, as in earlier versions of DBIC.)
1460 =head2 include_columns
1464 =item Value: \@columns
1468 Shortcut to include additional columns in the returned results - for example
1470 $schema->resultset('CD')->search(undef, {
1471 include_columns => ['artist.name'],
1475 would return all CDs and include a 'name' column to the information
1476 passed to object inflation
1482 =item Value: \@select_columns
1486 Indicates which columns should be selected from the storage. You can use
1487 column names, or in the case of RDBMS back ends, function or stored procedure
1490 $rs = $schema->resultset('Employee')->search(undef, {
1493 { count => 'employeeid' },
1498 When you use function/stored procedure names and do not supply an C<as>
1499 attribute, the column names returned are storage-dependent. E.g. MySQL would
1500 return a column named C<count(employeeid)> in the above example.
1506 =item Value: \@inflation_names
1510 Indicates column names for object inflation. This is used in conjunction with
1511 C<select>, usually when C<select> contains one or more function or stored
1514 $rs = $schema->resultset('Employee')->search(undef, {
1517 { count => 'employeeid' }
1519 as => ['name', 'employee_count'],
1522 my $employee = $rs->first(); # get the first Employee
1524 If the object against which the search is performed already has an accessor
1525 matching a column name specified in C<as>, the value can be retrieved using
1526 the accessor as normal:
1528 my $name = $employee->name();
1530 If on the other hand an accessor does not exist in the object, you need to
1531 use C<get_column> instead:
1533 my $employee_count = $employee->get_column('employee_count');
1535 You can create your own accessors if required - see
1536 L<DBIx::Class::Manual::Cookbook> for details.
1542 =item Value: ($rel_name | \@rel_names | \%rel_names)
1546 Contains a list of relationships that should be joined for this query. For
1549 # Get CDs by Nine Inch Nails
1550 my $rs = $schema->resultset('CD')->search(
1551 { 'artist.name' => 'Nine Inch Nails' },
1552 { join => 'artist' }
1555 Can also contain a hash reference to refer to the other relation's relations.
1558 package MyApp::Schema::Track;
1559 use base qw/DBIx::Class/;
1560 __PACKAGE__->table('track');
1561 __PACKAGE__->add_columns(qw/trackid cd position title/);
1562 __PACKAGE__->set_primary_key('trackid');
1563 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
1566 # In your application
1567 my $rs = $schema->resultset('Artist')->search(
1568 { 'track.title' => 'Teardrop' },
1570 join => { cd => 'track' },
1571 order_by => 'artist.name',
1575 If the same join is supplied twice, it will be aliased to <rel>_2 (and
1576 similarly for a third time). For e.g.
1578 my $rs = $schema->resultset('Artist')->search({
1579 'cds.title' => 'Down to Earth',
1580 'cds_2.title' => 'Popular',
1582 join => [ qw/cds cds/ ],
1585 will return a set of all artists that have both a cd with title 'Down
1586 to Earth' and a cd with title 'Popular'.
1588 If you want to fetch related objects from other tables as well, see C<prefetch>
1595 =item Value: ($rel_name | \@rel_names | \%rel_names)
1599 Contains one or more relationships that should be fetched along with the main
1600 query (when they are accessed afterwards they will have already been
1601 "prefetched"). This is useful for when you know you will need the related
1602 objects, because it saves at least one query:
1604 my $rs = $schema->resultset('Tag')->search(
1613 The initial search results in SQL like the following:
1615 SELECT tag.*, cd.*, artist.* FROM tag
1616 JOIN cd ON tag.cd = cd.cdid
1617 JOIN artist ON cd.artist = artist.artistid
1619 L<DBIx::Class> has no need to go back to the database when we access the
1620 C<cd> or C<artist> relationships, which saves us two SQL statements in this
1623 Simple prefetches will be joined automatically, so there is no need
1624 for a C<join> attribute in the above search. If you're prefetching to
1625 depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
1626 specify the join as well.
1628 C<prefetch> can be used with the following relationship types: C<belongs_to>,
1629 C<has_one> (or if you're using C<add_relationship>, any relationship declared
1630 with an accessor type of 'single' or 'filter').
1636 =item Value: \@from_clause
1640 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
1641 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
1644 NOTE: Use this on your own risk. This allows you to shoot off your foot!
1645 C<join> will usually do what you need and it is strongly recommended that you
1646 avoid using C<from> unless you cannot achieve the desired result using C<join>.
1648 In simple terms, C<from> works as follows:
1651 { <alias> => <table>, -join_type => 'inner|left|right' }
1652 [] # nested JOIN (optional)
1653 { <table.column> => <foreign_table.foreign_key> }
1659 ON <table.column> = <foreign_table.foreign_key>
1661 An easy way to follow the examples below is to remember the following:
1663 Anything inside "[]" is a JOIN
1664 Anything inside "{}" is a condition for the enclosing JOIN
1666 The following examples utilize a "person" table in a family tree application.
1667 In order to express parent->child relationships, this table is self-joined:
1669 # Person->belongs_to('father' => 'Person');
1670 # Person->belongs_to('mother' => 'Person');
1672 C<from> can be used to nest joins. Here we return all children with a father,
1673 then search against all mothers of those children:
1675 $rs = $schema->resultset('Person')->search(
1678 alias => 'mother', # alias columns in accordance with "from"
1680 { mother => 'person' },
1683 { child => 'person' },
1685 { father => 'person' },
1686 { 'father.person_id' => 'child.father_id' }
1689 { 'mother.person_id' => 'child.mother_id' }
1696 # SELECT mother.* FROM person mother
1699 # JOIN person father
1700 # ON ( father.person_id = child.father_id )
1702 # ON ( mother.person_id = child.mother_id )
1704 The type of any join can be controlled manually. To search against only people
1705 with a father in the person table, we could explicitly use C<INNER JOIN>:
1707 $rs = $schema->resultset('Person')->search(
1710 alias => 'child', # alias columns in accordance with "from"
1712 { child => 'person' },
1714 { father => 'person', -join_type => 'inner' },
1715 { 'father.id' => 'child.father_id' }
1722 # SELECT child.* FROM person child
1723 # INNER JOIN person father ON child.father_id = father.id
1733 Makes the resultset paged and specifies the page to retrieve. Effectively
1734 identical to creating a non-pages resultset and then calling ->page($page)
1745 Specifes the maximum number of rows for direct retrieval or the number of
1746 rows per page if the page attribute or method is used.
1752 =item Value: \@columns
1756 A arrayref of columns to group by. Can include columns of joined tables.
1758 group_by => [qw/ column1 column2 ... /]
1764 =item Value: $condition
1768 HAVING is a select statement attribute that is applied between GROUP BY and
1769 ORDER BY. It is applied to the after the grouping calculations have been
1772 having => { 'count(employee)' => { '>=', 100 } }
1778 =item Value: (0 | 1)
1782 Set to 1 to group by all columns.
1786 Set to 1 to cache search results. This prevents extra SQL queries if you
1787 revisit rows in your ResultSet:
1789 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
1791 while( my $artist = $resultset->next ) {
1795 $rs->first; # without cache, this would issue a query
1797 By default, searches are not cached.
1799 For more examples of using these attributes, see
1800 L<DBIx::Class::Manual::Cookbook>.