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.
163 my $our_attrs = { %{$self->{attrs}} };
164 my $having = delete $our_attrs->{having};
166 $attrs = pop(@_) if @_ > 1 and ref $_[$#_] eq 'HASH';
168 # merge new attrs into old
169 foreach my $key (qw/join prefetch/) {
170 next unless (exists $attrs->{$key});
171 if (exists $our_attrs->{$key}) {
172 $our_attrs->{$key} = $self->_merge_attr($our_attrs->{$key}, $attrs->{$key});
174 $our_attrs->{$key} = $attrs->{$key};
176 delete $attrs->{$key};
179 if (exists $our_attrs->{prefetch}) {
180 $our_attrs->{join} = $self->_merge_attr($our_attrs->{join}, $our_attrs->{prefetch}, 1);
183 my $new_attrs = { %{$our_attrs}, %{$attrs} };
185 # merge new where and having into old
187 ? ((@_ == 1 || ref $_[0] eq "HASH")
190 ? $self->throw_exception(
191 "Odd number of arguments to search")
194 if (defined $where) {
195 $new_attrs->{where} = (defined $new_attrs->{where}
197 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
198 $where, $new_attrs->{where} ] }
202 if (defined $having) {
203 $new_attrs->{having} = (defined $new_attrs->{having}
205 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
206 $having, $new_attrs->{having} ] }
210 my $rs = (ref $self)->new($self->result_source, $new_attrs);
211 $rs->{_parent_rs} = $self->{_parent_rs} if ($self->{_parent_rs}); #XXX - hack to pass through parent of related resultsets
213 unless (@_) { # no search, effectively just a clone
214 my $rows = $self->get_cache;
216 $rs->set_cache($rows);
223 =head2 search_literal
227 =item Arguments: $sql_fragment, @bind_values
229 =item Return Value: $resultset (scalar context), @row_objs (list context)
233 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
234 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
236 Pass a literal chunk of SQL to be added to the conditional part of the
242 my ($self, $cond, @vals) = @_;
243 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
244 $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
245 return $self->search(\$cond, $attrs);
252 =item Arguments: @values | \%cols, \%attrs?
254 =item Return Value: $row_object
258 Finds a row based on its primary key or unique constraint. For example, to find
259 a row by its primary key:
261 my $cd = $schema->resultset('CD')->find(5);
263 You can also find a row by a specific unique constraint using the C<key>
264 attribute. For example:
266 my $cd = $schema->resultset('CD')->find('Massive Attack', 'Mezzanine', { key => 'artist_title' });
268 Additionally, you can specify the columns explicitly by name:
270 my $cd = $schema->resultset('CD')->find(
272 artist => 'Massive Attack',
273 title => 'Mezzanine',
275 { key => 'artist_title' }
278 If the C<key> is specified as C<primary>, it searches only on the primary key.
280 See also L</find_or_create> and L</update_or_create>. For information on how to
281 declare unique constraints, see
282 L<DBIx::Class::ResultSource/add_unique_constraint>.
288 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
290 # Default to the primary key, but allow a specific key
291 my @cols = exists $attrs->{key}
292 ? $self->result_source->unique_constraint_columns($attrs->{key})
293 : $self->result_source->primary_columns;
294 $self->throw_exception(
295 "Can't find unless a primary key or unique constraint is defined"
298 # Parse out a hashref from input
300 if (ref $_[0] eq 'HASH') {
301 $query = { %{$_[0]} };
303 elsif (@_ == @cols) {
305 @{$query}{@cols} = @_;
308 # Compatibility: Allow e.g. find(id => $value)
309 carp "find by key => value deprecated; please use a hashref instead";
313 if (exists $attrs->{key}) {
314 my @unique_cols = $self->result_source->unique_constraint_columns($attrs->{key});
315 $query = $self->_build_unique_query($query, \@unique_cols);
318 # Add the ResultSet's alias
319 foreach my $key (grep { ! m/\./ } keys %$query) {
320 $query->{"$self->{attrs}{alias}.$key"} = delete $query->{$key};
325 my $rs = $self->search($query, $attrs);
327 return keys %{$rs->{_attrs}->{collapse}} ? $rs->next : $rs->single;
331 return (keys %{$self->{_attrs}->{collapse}})
332 ? $self->search($query)->next
333 : $self->single($query);
337 # _build_unique_query
339 # Constrain the specified query hash based on the specified column names.
341 sub _build_unique_query {
342 my ($self, $query, $unique_cols) = @_;
345 map { $_ => $query->{$_} }
346 grep { exists $query->{$_} }
349 return \%unique_query;
352 =head2 search_related
356 =item Arguments: $cond, \%attrs?
358 =item Return Value: $new_resultset
362 $new_rs = $cd_rs->search_related('artist', {
366 Searches the specified relationship, optionally specifying a condition and
367 attributes for matching records. See L</ATTRIBUTES> for more information.
372 return shift->related_resultset(shift)->search(@_);
379 =item Arguments: none
381 =item Return Value: $cursor
385 Returns a storage-driven cursor to the given resultset. See
386 L<DBIx::Class::Cursor> for more information.
394 my $attrs = { %{$self->{_attrs}} };
395 return $self->{cursor}
396 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
397 $attrs->{where},$attrs);
404 =item Arguments: $cond?
406 =item Return Value: $row_object?
410 my $cd = $schema->resultset('CD')->single({ year => 2001 });
412 Inflates the first result without creating a cursor if the resultset has
413 any records in it; if not returns nothing. Used by L</find> as an optimisation.
415 Can optionally take an additional condition *only* - this is a fast-code-path
416 method; if you need to add extra joins or similar call ->search and then
417 ->single without a condition on the $rs returned from that.
422 my ($self, $where) = @_;
424 my $attrs = { %{$self->{_attrs}} };
426 if (defined $attrs->{where}) {
429 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
430 $where, delete $attrs->{where} ]
433 $attrs->{where} = $where;
437 my @data = $self->result_source->storage->select_single(
438 $attrs->{from}, $attrs->{select},
439 $attrs->{where},$attrs);
440 return (@data ? $self->_construct_object(@data) : ());
447 =item Arguments: $cond?
449 =item Return Value: $resultsetcolumn
453 my $max_length = $rs->get_column('length')->max;
455 Returns a ResultSetColumn instance for $column based on $self
460 my ($self, $column) = @_;
462 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
470 =item Arguments: $cond, \%attrs?
472 =item Return Value: $resultset (scalar context), @row_objs (list context)
476 # WHERE title LIKE '%blue%'
477 $cd_rs = $rs->search_like({ title => '%blue%'});
479 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
480 that this is simply a convenience method. You most likely want to use
481 L</search> with specific operators.
483 For more information, see L<DBIx::Class::Manual::Cookbook>.
489 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
490 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
491 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
492 return $class->search($query, { %$attrs });
499 =item Arguments: $first, $last
501 =item Return Value: $resultset (scalar context), @row_objs (list context)
505 Returns a resultset or object list representing a subset of elements from the
506 resultset slice is called on. Indexes are from 0, i.e., to get the first
509 my ($one, $two, $three) = $rs->slice(0, 2);
514 my ($self, $min, $max) = @_;
515 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
516 $attrs->{offset} = $self->{attrs}{offset} || 0;
517 $attrs->{offset} += $min;
518 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
519 return $self->search(undef(), $attrs);
520 #my $slice = (ref $self)->new($self->result_source, $attrs);
521 #return (wantarray ? $slice->all : $slice);
528 =item Arguments: none
530 =item Return Value: $result?
534 Returns the next element in the resultset (C<undef> is there is none).
536 Can be used to efficiently iterate over records in the resultset:
538 my $rs = $schema->resultset('CD')->search;
539 while (my $cd = $rs->next) {
543 Note that you need to store the resultset object, and call C<next> on it.
544 Calling C<< resultset('Table')->next >> repeatedly will always return the
545 first record from the resultset.
551 if (my $cache = $self->get_cache) {
552 $self->{all_cache_position} ||= 0;
553 return $cache->[$self->{all_cache_position}++];
555 if ($self->{attrs}{cache}) {
556 $self->{all_cache_position} = 1;
557 return ($self->all)[0];
559 my @row = (exists $self->{stashed_row} ?
560 @{delete $self->{stashed_row}} :
563 return unless (@row);
564 return $self->_construct_object(@row);
570 return if(exists $self->{_attrs}); #return if _resolve has already been called
572 my $attrs = $self->{attrs};
573 my $source = ($self->{_parent_rs}) ? $self->{_parent_rs} : $self->{result_source};
575 # XXX - lose storable dclone
576 my $record_filter = delete $attrs->{record_filter} if (defined $attrs->{record_filter});
577 $attrs = Storable::dclone($attrs || {}); # { %{ $attrs || {} } };
578 $attrs->{record_filter} = $record_filter if ($record_filter);
579 $self->{attrs}->{record_filter} = $record_filter if ($record_filter);
581 my $alias = $attrs->{alias};
583 $attrs->{columns} ||= delete $attrs->{cols} if $attrs->{cols};
584 delete $attrs->{as} if $attrs->{columns};
585 $attrs->{columns} ||= [ $self->{result_source}->columns ] unless $attrs->{select};
586 my $select_alias = ($self->{_parent_rs}) ? $self->{attrs}->{_live_join} : $alias;
588 map { m/\./ ? $_ : "${select_alias}.$_" } @{delete $attrs->{columns}}
589 ] if $attrs->{columns};
591 map { m/^\Q$alias.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}}
593 if (my $include = delete $attrs->{include_columns}) {
594 push(@{$attrs->{select}}, @$include);
595 push(@{$attrs->{as}}, map { m/([^.]+)$/; $1; } @$include);
598 $attrs->{from} ||= [ { $alias => $source->from } ];
599 $attrs->{seen_join} ||= {};
601 if (my $join = delete $attrs->{join}) {
602 foreach my $j (ref $join eq 'ARRAY' ? @$join : ($join)) {
603 if (ref $j eq 'HASH') {
604 $seen{$_} = 1 foreach keys %$j;
610 push(@{$attrs->{from}}, $source->resolve_join($join, $attrs->{alias}, $attrs->{seen_join}));
612 $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
613 $attrs->{order_by} = [ $attrs->{order_by} ] if
614 $attrs->{order_by} and !ref($attrs->{order_by});
615 $attrs->{order_by} ||= [];
617 if(my $seladds = delete($attrs->{'+select'})) {
618 my @seladds = (ref($seladds) eq 'ARRAY' ? @$seladds : ($seladds));
620 @{ $attrs->{select} },
621 map { (m/\./ || ref($_)) ? $_ : "${alias}.$_" } $seladds
624 if(my $asadds = delete($attrs->{'+as'})) {
625 my @asadds = (ref($asadds) eq 'ARRAY' ? @$asadds : ($asadds));
626 $attrs->{as} = [ @{ $attrs->{as} }, @asadds ];
629 my $collapse = $attrs->{collapse} || {};
630 if (my $prefetch = delete $attrs->{prefetch}) {
632 foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
633 if ( ref $p eq 'HASH' ) {
634 foreach my $key (keys %$p) {
635 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
639 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
642 my @prefetch = $source->resolve_prefetch(
643 $p, $attrs->{alias}, {}, \@pre_order, $collapse);
644 push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
645 push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
647 push(@{$attrs->{order_by}}, @pre_order);
649 $attrs->{collapse} = $collapse;
650 $self->{_attrs} = $attrs;
654 my ($self, $a, $b, $is_prefetch) = @_;
657 if (ref $b eq 'HASH' && ref $a eq 'HASH') {
658 foreach my $key (keys %{$b}) {
659 if (exists $a->{$key}) {
660 $a->{$key} = $self->_merge_attr($a->{$key}, $b->{$key}, $is_prefetch);
662 $a->{$key} = delete $b->{$key};
667 $a = [$a] unless (ref $a eq 'ARRAY');
668 $b = [$b] unless (ref $b eq 'ARRAY');
673 foreach my $element (@{$_}) {
674 if (ref $element eq 'HASH') {
675 $hash = $self->_merge_attr($hash, $element, $is_prefetch);
676 } elsif (ref $element eq 'ARRAY') {
677 $array = [@{$array}, @{$element}];
679 if (($b == $_) && $is_prefetch) {
680 $self->_merge_array($array, $element, $is_prefetch);
682 push(@{$array}, $element);
688 if ((keys %{$hash}) && (scalar(@{$array} > 0))) {
689 return [$hash, @{$array}];
691 return (keys %{$hash}) ? $hash : $array;
697 my ($self, $a, $b) = @_;
699 $b = [$b] unless (ref $b eq 'ARRAY');
700 # add elements from @{$b} to @{$a} which aren't already in @{$a}
701 foreach my $b_element (@{$b}) {
702 push(@{$a}, $b_element) unless grep {$b_element eq $_} @{$a};
706 sub _construct_object {
707 my ($self, @row) = @_;
708 my @as = @{ $self->{_attrs}{as} };
710 my $info = $self->_collapse_result(\@as, \@row);
711 my $new = $self->result_class->inflate_result($self->result_source, @$info);
712 $new = $self->{_attrs}{record_filter}->($new)
713 if exists $self->{_attrs}{record_filter};
717 sub _collapse_result {
718 my ($self, $as, $row, $prefix) = @_;
720 my $live_join = $self->{attrs}->{_live_join} ||="";
724 foreach my $this_as (@$as) {
725 my $val = shift @copy;
726 if (defined $prefix) {
727 if ($this_as =~ m/^\Q${prefix}.\E(.+)$/) {
729 $remain =~ /^(?:(.*)\.)?([^.]+)$/;
730 $const{$1||''}{$2} = $val;
733 $this_as =~ /^(?:(.*)\.)?([^.]+)$/;
734 $const{$1||''}{$2} = $val;
738 my $info = [ {}, {} ];
739 foreach my $key (keys %const) {
740 if (length $key && $key ne $live_join) {
742 my @parts = split(/\./, $key);
743 foreach my $p (@parts) {
744 $target = $target->[1]->{$p} ||= [];
746 $target->[0] = $const{$key};
748 $info->[0] = $const{$key};
753 if (defined $prefix) {
755 m/^\Q${prefix}.\E(.+)$/ ? ($1) : ()
756 } keys %{$self->{_attrs}->{collapse}}
758 @collapse = keys %{$self->{_attrs}->{collapse}};
762 my ($c) = sort { length $a <=> length $b } @collapse;
764 foreach my $p (split(/\./, $c)) {
765 $target = $target->[1]->{$p} ||= [];
767 my $c_prefix = (defined($prefix) ? "${prefix}.${c}" : $c);
768 my @co_key = @{$self->{_attrs}->{collapse}{$c_prefix}};
769 my %co_check = map { ($_, $target->[0]->{$_}); } @co_key;
770 my $tree = $self->_collapse_result($as, $row, $c_prefix);
773 !defined($tree->[0]->{$_}) ||
774 $co_check{$_} ne $tree->[0]->{$_}
777 last unless (@raw = $self->cursor->next);
778 $row = $self->{stashed_row} = \@raw;
779 $tree = $self->_collapse_result($as, $row, $c_prefix);
781 @$target = (@final ? @final : [ {}, {} ]);
782 # single empty result to indicate an empty prefetched has_many
791 =item Arguments: $result_source?
793 =item Return Value: $result_source
797 An accessor for the primary ResultSource object from which this ResultSet
807 =item Arguments: $cond, \%attrs??
809 =item Return Value: $count
813 Performs an SQL C<COUNT> with the same query as the resultset was built
814 with to find the number of elements. If passed arguments, does a search
815 on the resultset and counts the results of that.
817 Note: When using C<count> with C<group_by>, L<DBIX::Class> emulates C<GROUP BY>
818 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
819 not support C<DISTINCT> with multiple columns. If you are using such a
820 database, you should only use columns from the main table in your C<group_by>
827 return $self->search(@_)->count if @_ and defined $_[0];
828 return scalar @{ $self->get_cache } if $self->get_cache;
830 my $count = $self->_count;
831 return 0 unless $count;
833 $count -= $self->{attrs}{offset} if $self->{attrs}{offset};
834 $count = $self->{attrs}{rows} if
835 $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
839 sub _count { # Separated out so pager can get the full count
841 my $select = { count => '*' };
844 my $attrs = { %{ $self->{_attrs} } };
845 if (my $group_by = delete $attrs->{group_by}) {
846 delete $attrs->{having};
847 my @distinct = (ref $group_by ? @$group_by : ($group_by));
848 # todo: try CONCAT for multi-column pk
849 my @pk = $self->result_source->primary_columns;
851 foreach my $column (@distinct) {
852 if ($column =~ qr/^(?:\Q$attrs->{alias}.\E)?$pk[0]$/) {
853 @distinct = ($column);
859 $select = { count => { distinct => \@distinct } };
862 $attrs->{select} = $select;
863 $attrs->{as} = [qw/count/];
865 # offset, order by and page are not needed to count. record_filter is cdbi
866 delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
867 my ($count) = (ref $self)->new($self->result_source, $attrs)->cursor->next;
875 =item Arguments: $sql_fragment, @bind_values
877 =item Return Value: $count
881 Counts the results in a literal query. Equivalent to calling L</search_literal>
882 with the passed arguments, then L</count>.
886 sub count_literal { shift->search_literal(@_)->count; }
892 =item Arguments: none
894 =item Return Value: @objects
898 Returns all elements in the resultset. Called implicitly if the resultset
899 is returned in list context.
905 return @{ $self->get_cache } if $self->get_cache;
909 # TODO: don't call resolve here
911 if (keys %{$self->{_attrs}->{collapse}}) {
912 # if ($self->{attrs}->{prefetch}) {
913 # Using $self->cursor->all is really just an optimisation.
914 # If we're collapsing has_many prefetches it probably makes
915 # very little difference, and this is cleaner than hacking
916 # _construct_object to survive the approach
917 my @row = $self->cursor->next;
919 push(@obj, $self->_construct_object(@row));
920 @row = (exists $self->{stashed_row}
921 ? @{delete $self->{stashed_row}}
922 : $self->cursor->next);
925 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
928 $self->set_cache(\@obj) if $self->{attrs}{cache};
936 =item Arguments: none
938 =item Return Value: $self
942 Resets the resultset's cursor, so you can iterate through the elements again.
948 delete $self->{_attrs} if (exists $self->{_attrs});
950 $self->{all_cache_position} = 0;
951 $self->cursor->reset;
959 =item Arguments: none
961 =item Return Value: $object?
965 Resets the resultset and returns an object for the first result (if the
966 resultset returns anything).
971 return $_[0]->reset->next;
974 # _cond_for_update_delete
976 # update/delete require the condition to be modified to handle
977 # the differing SQL syntax available. This transforms the $self->{cond}
978 # appropriately, returning the new condition.
980 sub _cond_for_update_delete {
984 if (!ref($self->{cond})) {
985 # No-op. No condition, we're updating/deleting everything
987 elsif (ref $self->{cond} eq 'ARRAY') {
991 foreach my $key (keys %{$_}) {
993 $hash{$1} = $_->{$key};
999 elsif (ref $self->{cond} eq 'HASH') {
1000 if ((keys %{$self->{cond}})[0] eq '-and') {
1003 my @cond = @{$self->{cond}{-and}};
1004 for (my $i = 0; $i <= @cond - 1; $i++) {
1005 my $entry = $cond[$i];
1008 if (ref $entry eq 'HASH') {
1009 foreach my $key (keys %{$entry}) {
1011 $hash{$1} = $entry->{$key};
1015 $entry =~ /([^.]+)$/;
1016 $hash{$1} = $cond[++$i];
1019 push @{$cond->{-and}}, \%hash;
1023 foreach my $key (keys %{$self->{cond}}) {
1025 $cond->{$1} = $self->{cond}{$key};
1030 $self->throw_exception(
1031 "Can't update/delete on resultset with condition unless hash or array"
1043 =item Arguments: \%values
1045 =item Return Value: $storage_rv
1049 Sets the specified columns in the resultset to the supplied values in a
1050 single query. Return value will be true if the update succeeded or false
1051 if no records were updated; exact type of success value is storage-dependent.
1056 my ($self, $values) = @_;
1057 $self->throw_exception("Values for update must be a hash")
1058 unless ref $values eq 'HASH';
1060 my $cond = $self->_cond_for_update_delete;
1062 return $self->result_source->storage->update(
1063 $self->result_source->from, $values, $cond
1071 =item Arguments: \%values
1073 =item Return Value: 1
1077 Fetches all objects and updates them one at a time. Note that C<update_all>
1078 will run DBIC cascade triggers, while L</update> will not.
1083 my ($self, $values) = @_;
1084 $self->throw_exception("Values for update must be a hash")
1085 unless ref $values eq 'HASH';
1086 foreach my $obj ($self->all) {
1087 $obj->set_columns($values)->update;
1096 =item Arguments: none
1098 =item Return Value: 1
1102 Deletes the contents of the resultset from its result source. Note that this
1103 will not run DBIC cascade triggers. See L</delete_all> if you need triggers
1112 my $cond = $self->_cond_for_update_delete;
1114 $self->result_source->storage->delete($self->result_source->from, $cond);
1122 =item Arguments: none
1124 =item Return Value: 1
1128 Fetches all objects and deletes them one at a time. Note that C<delete_all>
1129 will run DBIC cascade triggers, while L</delete> will not.
1135 $_->delete for $self->all;
1143 =item Arguments: none
1145 =item Return Value: $pager
1149 Return Value a L<Data::Page> object for the current resultset. Only makes
1150 sense for queries with a C<page> attribute.
1156 my $attrs = $self->{attrs};
1157 $self->throw_exception("Can't create pager for non-paged rs")
1158 unless $self->{page};
1159 $attrs->{rows} ||= 10;
1160 return $self->{pager} ||= Data::Page->new(
1161 $self->_count, $attrs->{rows}, $self->{page});
1168 =item Arguments: $page_number
1170 =item Return Value: $rs
1174 Returns a resultset for the $page_number page of the resultset on which page
1175 is called, where each page contains a number of rows equal to the 'rows'
1176 attribute set on the resultset (10 by default).
1181 my ($self, $page) = @_;
1182 my $attrs = { %{$self->{attrs}} };
1183 $attrs->{page} = $page;
1184 return (ref $self)->new($self->result_source, $attrs);
1191 =item Arguments: \%vals
1193 =item Return Value: $object
1197 Creates an object in the resultset's result class and returns it.
1202 my ($self, $values) = @_;
1203 $self->throw_exception( "new_result needs a hash" )
1204 unless (ref $values eq 'HASH');
1205 $self->throw_exception(
1206 "Can't abstract implicit construct, condition not a hash"
1207 ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
1209 my $alias = $self->{attrs}{alias};
1210 foreach my $key (keys %{$self->{cond}||{}}) {
1211 $new{$1} = $self->{cond}{$key} if ($key =~ m/^(?:\Q${alias}.\E)?([^.]+)$/);
1213 my $obj = $self->result_class->new(\%new);
1214 $obj->result_source($self->result_source) if $obj->can('result_source');
1222 =item Arguments: \%vals, \%attrs?
1224 =item Return Value: $object
1228 Find an existing record from this resultset. If none exists, instantiate a new
1229 result object and return it. The object will not be saved into your storage
1230 until you call L<DBIx::Class::Row/insert> on it.
1232 If you want objects to be saved immediately, use L</find_or_create> instead.
1238 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1239 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1240 my $exists = $self->find($hash, $attrs);
1241 return defined $exists ? $exists : $self->new_result($hash);
1248 =item Arguments: \%vals
1250 =item Return Value: $object
1254 Inserts a record into the resultset and returns the object representing it.
1256 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
1261 my ($self, $attrs) = @_;
1262 $self->throw_exception( "create needs a hashref" )
1263 unless ref $attrs eq 'HASH';
1264 return $self->new_result($attrs)->insert;
1267 =head2 find_or_create
1271 =item Arguments: \%vals, \%attrs?
1273 =item Return Value: $object
1277 $class->find_or_create({ key => $val, ... });
1279 Searches for a record matching the search condition; if it doesn't find one,
1280 creates one and returns that instead.
1282 my $cd = $schema->resultset('CD')->find_or_create({
1284 artist => 'Massive Attack',
1285 title => 'Mezzanine',
1289 Also takes an optional C<key> attribute, to search by a specific key or unique
1290 constraint. For example:
1292 my $cd = $schema->resultset('CD')->find_or_create(
1294 artist => 'Massive Attack',
1295 title => 'Mezzanine',
1297 { key => 'artist_title' }
1300 See also L</find> and L</update_or_create>. For information on how to declare
1301 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1305 sub find_or_create {
1307 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1308 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1309 my $exists = $self->find($hash, $attrs);
1310 return defined $exists ? $exists : $self->create($hash);
1313 =head2 update_or_create
1317 =item Arguments: \%col_values, { key => $unique_constraint }?
1319 =item Return Value: $object
1323 $class->update_or_create({ col => $val, ... });
1325 First, searches for an existing row matching one of the unique constraints
1326 (including the primary key) on the source of this resultset. If a row is
1327 found, updates it with the other given column values. Otherwise, creates a new
1330 Takes an optional C<key> attribute to search on a specific unique constraint.
1333 # In your application
1334 my $cd = $schema->resultset('CD')->update_or_create(
1336 artist => 'Massive Attack',
1337 title => 'Mezzanine',
1340 { key => 'artist_title' }
1343 If no C<key> is specified, it searches on all unique constraints defined on the
1344 source, including the primary key.
1346 If the C<key> is specified as C<primary>, it searches only on the primary key.
1348 See also L</find> and L</find_or_create>. For information on how to declare
1349 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1353 sub update_or_create {
1355 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1356 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1358 my @constraint_names = exists $attrs->{key}
1360 : $self->result_source->unique_constraint_names;
1361 $self->throw_exception(
1362 "update_or_create requires a primary key or unique constraint; none is defined on "
1363 . $self->result_source->name
1364 ) unless @constraint_names;
1367 foreach my $name (@constraint_names) {
1368 my @unique_cols = $self->result_source->unique_constraint_columns($name);
1369 my $unique_query = $self->_build_unique_query($hash, \@unique_cols);
1371 push @unique_queries, $unique_query
1372 if keys %$unique_query == @unique_cols;
1375 if (@unique_queries) {
1376 my $row = $self->single(\@unique_queries);
1378 $row->update($hash);
1383 return $self->create($hash);
1390 =item Arguments: none
1392 =item Return Value: \@cache_objects?
1396 Gets the contents of the cache for the resultset, if the cache is set.
1408 =item Arguments: \@cache_objects
1410 =item Return Value: \@cache_objects
1414 Sets the contents of the cache for the resultset. Expects an arrayref
1415 of objects of the same class as those produced by the resultset. Note that
1416 if the cache is set the resultset will return the cached objects rather
1417 than re-querying the database even if the cache attr is not set.
1422 my ( $self, $data ) = @_;
1423 $self->throw_exception("set_cache requires an arrayref")
1424 if defined($data) && (ref $data ne 'ARRAY');
1425 $self->{all_cache} = $data;
1432 =item Arguments: none
1434 =item Return Value: []
1438 Clears the cache for the resultset.
1443 shift->set_cache(undef);
1446 =head2 related_resultset
1450 =item Arguments: $relationship_name
1452 =item Return Value: $resultset
1456 Returns a related resultset for the supplied relationship name.
1458 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1462 sub related_resultset {
1463 my ( $self, $rel ) = @_;
1465 $self->{related_resultsets} ||= {};
1466 return $self->{related_resultsets}{$rel} ||= do {
1467 #warn "fetching related resultset for rel '$rel' " . $self->result_source->{name};
1468 my $rel_obj = $self->result_source->relationship_info($rel);
1469 $self->throw_exception(
1470 "search_related: result source '" . $self->result_source->name .
1471 "' has no such relationship ${rel}")
1472 unless $rel_obj; #die Dumper $self->{attrs};
1474 my $rs = $self->result_source->schema->resultset($rel_obj->{class}
1476 { %{$self->{attrs}},
1480 _live_join => $rel }
1483 # keep reference of the original resultset
1484 $rs->{_parent_rs} = $self->result_source;
1489 =head2 throw_exception
1491 See L<DBIx::Class::Schema/throw_exception> for details.
1495 sub throw_exception {
1497 $self->result_source->schema->throw_exception(@_);
1500 # XXX: FIXME: Attributes docs need clearing up
1504 The resultset takes various attributes that modify its behavior. Here's an
1511 =item Value: ($order_by | \@order_by)
1515 Which column(s) to order the results by. This is currently passed
1516 through directly to SQL, so you can give e.g. C<year DESC> for a
1517 descending order on the column `year'.
1519 Please note that if you have quoting enabled (see
1520 L<DBIx::Class::Storage/quote_char>) you will need to do C<\'year DESC' > to
1521 specify an order. (The scalar ref causes it to be passed as raw sql to the DB,
1522 so you will need to manually quote things as appropriate.)
1528 =item Value: \@columns
1532 Shortcut to request a particular set of columns to be retrieved. Adds
1533 C<me.> onto the start of any column without a C<.> in it and sets C<select>
1534 from that, then auto-populates C<as> from C<select> as normal. (You may also
1535 use the C<cols> attribute, as in earlier versions of DBIC.)
1537 =head2 include_columns
1541 =item Value: \@columns
1545 Shortcut to include additional columns in the returned results - for example
1547 $schema->resultset('CD')->search(undef, {
1548 include_columns => ['artist.name'],
1552 would return all CDs and include a 'name' column to the information
1553 passed to object inflation
1559 =item Value: \@select_columns
1563 Indicates which columns should be selected from the storage. You can use
1564 column names, or in the case of RDBMS back ends, function or stored procedure
1567 $rs = $schema->resultset('Employee')->search(undef, {
1570 { count => 'employeeid' },
1575 When you use function/stored procedure names and do not supply an C<as>
1576 attribute, the column names returned are storage-dependent. E.g. MySQL would
1577 return a column named C<count(employeeid)> in the above example.
1583 Indicates additional columns to be selected from storage. Works the same as
1584 L<select> but adds columns to the selection.
1592 Indicates additional column names for those added via L<+select>.
1600 =item Value: \@inflation_names
1604 Indicates column names for object inflation. This is used in conjunction with
1605 C<select>, usually when C<select> contains one or more function or stored
1608 $rs = $schema->resultset('Employee')->search(undef, {
1611 { count => 'employeeid' }
1613 as => ['name', 'employee_count'],
1616 my $employee = $rs->first(); # get the first Employee
1618 If the object against which the search is performed already has an accessor
1619 matching a column name specified in C<as>, the value can be retrieved using
1620 the accessor as normal:
1622 my $name = $employee->name();
1624 If on the other hand an accessor does not exist in the object, you need to
1625 use C<get_column> instead:
1627 my $employee_count = $employee->get_column('employee_count');
1629 You can create your own accessors if required - see
1630 L<DBIx::Class::Manual::Cookbook> for details.
1632 Please note: This will NOT insert an C<AS employee_count> into the SQL statement
1633 produced, it is used for internal access only. Thus attempting to use the accessor
1634 in an C<order_by> clause or similar will fail misrably.
1640 =item Value: ($rel_name | \@rel_names | \%rel_names)
1644 Contains a list of relationships that should be joined for this query. For
1647 # Get CDs by Nine Inch Nails
1648 my $rs = $schema->resultset('CD')->search(
1649 { 'artist.name' => 'Nine Inch Nails' },
1650 { join => 'artist' }
1653 Can also contain a hash reference to refer to the other relation's relations.
1656 package MyApp::Schema::Track;
1657 use base qw/DBIx::Class/;
1658 __PACKAGE__->table('track');
1659 __PACKAGE__->add_columns(qw/trackid cd position title/);
1660 __PACKAGE__->set_primary_key('trackid');
1661 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
1664 # In your application
1665 my $rs = $schema->resultset('Artist')->search(
1666 { 'track.title' => 'Teardrop' },
1668 join => { cd => 'track' },
1669 order_by => 'artist.name',
1673 If the same join is supplied twice, it will be aliased to <rel>_2 (and
1674 similarly for a third time). For e.g.
1676 my $rs = $schema->resultset('Artist')->search({
1677 'cds.title' => 'Down to Earth',
1678 'cds_2.title' => 'Popular',
1680 join => [ qw/cds cds/ ],
1683 will return a set of all artists that have both a cd with title 'Down
1684 to Earth' and a cd with title 'Popular'.
1686 If you want to fetch related objects from other tables as well, see C<prefetch>
1693 =item Value: ($rel_name | \@rel_names | \%rel_names)
1697 Contains one or more relationships that should be fetched along with the main
1698 query (when they are accessed afterwards they will have already been
1699 "prefetched"). This is useful for when you know you will need the related
1700 objects, because it saves at least one query:
1702 my $rs = $schema->resultset('Tag')->search(
1711 The initial search results in SQL like the following:
1713 SELECT tag.*, cd.*, artist.* FROM tag
1714 JOIN cd ON tag.cd = cd.cdid
1715 JOIN artist ON cd.artist = artist.artistid
1717 L<DBIx::Class> has no need to go back to the database when we access the
1718 C<cd> or C<artist> relationships, which saves us two SQL statements in this
1721 Simple prefetches will be joined automatically, so there is no need
1722 for a C<join> attribute in the above search. If you're prefetching to
1723 depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
1724 specify the join as well.
1726 C<prefetch> can be used with the following relationship types: C<belongs_to>,
1727 C<has_one> (or if you're using C<add_relationship>, any relationship declared
1728 with an accessor type of 'single' or 'filter').
1738 Makes the resultset paged and specifies the page to retrieve. Effectively
1739 identical to creating a non-pages resultset and then calling ->page($page)
1742 If L<rows> attribute is not specified it defualts to 10 rows per page.
1752 Specifes the maximum number of rows for direct retrieval or the number of
1753 rows per page if the page attribute or method is used.
1759 =item Value: $offset
1763 Specifies the (zero-based) row number for the first row to be returned, or the
1764 of the first row of the first page if paging is used.
1770 =item Value: \@columns
1774 A arrayref of columns to group by. Can include columns of joined tables.
1776 group_by => [qw/ column1 column2 ... /]
1782 =item Value: $condition
1786 HAVING is a select statement attribute that is applied between GROUP BY and
1787 ORDER BY. It is applied to the after the grouping calculations have been
1790 having => { 'count(employee)' => { '>=', 100 } }
1796 =item Value: (0 | 1)
1800 Set to 1 to group by all columns.
1804 Set to 1 to cache search results. This prevents extra SQL queries if you
1805 revisit rows in your ResultSet:
1807 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
1809 while( my $artist = $resultset->next ) {
1813 $rs->first; # without cache, this would issue a query
1815 By default, searches are not cached.
1817 For more examples of using these attributes, see
1818 L<DBIx::Class::Manual::Cookbook>.
1824 =item Value: \@from_clause
1828 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
1829 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
1832 NOTE: Use this on your own risk. This allows you to shoot off your foot!
1834 C<join> will usually do what you need and it is strongly recommended that you
1835 avoid using C<from> unless you cannot achieve the desired result using C<join>.
1836 And we really do mean "cannot", not just tried and failed. Attempting to use
1837 this because you're having problems with C<join> is like trying to use x86
1838 ASM because you've got a syntax error in your C. Trust us on this.
1840 Now, if you're still really, really sure you need to use this (and if you're
1841 not 100% sure, ask the mailing list first), here's an explanation of how this
1844 The syntax is as follows -
1847 { <alias1> => <table1> },
1849 { <alias2> => <table2>, -join_type => 'inner|left|right' },
1850 [], # nested JOIN (optional)
1851 { <table1.column1> => <table2.column2>, ... (more conditions) },
1853 # More of the above [ ] may follow for additional joins
1860 ON <table1.column1> = <table2.column2>
1861 <more joins may follow>
1863 An easy way to follow the examples below is to remember the following:
1865 Anything inside "[]" is a JOIN
1866 Anything inside "{}" is a condition for the enclosing JOIN
1868 The following examples utilize a "person" table in a family tree application.
1869 In order to express parent->child relationships, this table is self-joined:
1871 # Person->belongs_to('father' => 'Person');
1872 # Person->belongs_to('mother' => 'Person');
1874 C<from> can be used to nest joins. Here we return all children with a father,
1875 then search against all mothers of those children:
1877 $rs = $schema->resultset('Person')->search(
1880 alias => 'mother', # alias columns in accordance with "from"
1882 { mother => 'person' },
1885 { child => 'person' },
1887 { father => 'person' },
1888 { 'father.person_id' => 'child.father_id' }
1891 { 'mother.person_id' => 'child.mother_id' }
1898 # SELECT mother.* FROM person mother
1901 # JOIN person father
1902 # ON ( father.person_id = child.father_id )
1904 # ON ( mother.person_id = child.mother_id )
1906 The type of any join can be controlled manually. To search against only people
1907 with a father in the person table, we could explicitly use C<INNER JOIN>:
1909 $rs = $schema->resultset('Person')->search(
1912 alias => 'child', # alias columns in accordance with "from"
1914 { child => 'person' },
1916 { father => 'person', -join_type => 'inner' },
1917 { 'father.id' => 'child.father_id' }
1924 # SELECT child.* FROM person child
1925 # INNER JOIN person father ON child.father_id = father.id