1 package DBIx::Class::ResultSet;
11 use Scalar::Util qw/weaken/;
13 use base qw/DBIx::Class/;
14 __PACKAGE__->load_components(qw/AccessorGroup/);
15 __PACKAGE__->mk_group_accessors('simple' => qw/result_source result_class/);
19 DBIx::Class::ResultSet - Responsible for fetching and creating resultset.
23 my $rs = $schema->resultset('User')->search(registered => 1);
24 my @rows = $schema->resultset('CD')->search(year => 2005);
28 The resultset is also known as an iterator. It is responsible for handling
29 queries that may return an arbitrary number of rows, e.g. via L</search>
30 or a C<has_many> relationship.
32 In the examples below, the following table classes are used:
34 package MyApp::Schema::Artist;
35 use base qw/DBIx::Class/;
36 __PACKAGE__->load_components(qw/Core/);
37 __PACKAGE__->table('artist');
38 __PACKAGE__->add_columns(qw/artistid name/);
39 __PACKAGE__->set_primary_key('artistid');
40 __PACKAGE__->has_many(cds => 'MyApp::Schema::CD');
43 package MyApp::Schema::CD;
44 use base qw/DBIx::Class/;
45 __PACKAGE__->load_components(qw/Core/);
46 __PACKAGE__->table('cd');
47 __PACKAGE__->add_columns(qw/cdid artist title year/);
48 __PACKAGE__->set_primary_key('cdid');
49 __PACKAGE__->belongs_to(artist => 'MyApp::Schema::Artist');
58 =item Arguments: $source, \%$attrs
60 =item Return Value: $rs
66 The resultset constructor. Takes a source object (usually a
67 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
68 L</ATTRIBUTES> below). Does not perform any queries -- these are
69 executed as needed by the other methods.
71 Generally you won't need to construct a resultset manually. You'll
72 automatically get one from e.g. a L</search> called in scalar context:
74 my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
76 IMPORTANT: If called on an object, proxies to new_result instead so
78 my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
80 will return a CD object, not a ResultSet.
86 return $class->new_result(@_) if ref $class;
88 my ($source, $attrs) = @_;
90 $attrs = Storable::dclone($attrs || {}); # { %{ $attrs || {} } };
91 #use Data::Dumper; warn Dumper($attrs);
92 my $alias = ($attrs->{alias} ||= 'me');
94 $attrs->{columns} ||= delete $attrs->{cols} if $attrs->{cols};
95 delete $attrs->{as} if $attrs->{columns};
96 $attrs->{columns} ||= [ $source->columns ] unless $attrs->{select};
98 map { m/\./ ? $_ : "${alias}.$_" } @{delete $attrs->{columns}}
99 ] if $attrs->{columns};
101 map { m/^\Q$alias.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}}
103 if (my $include = delete $attrs->{include_columns}) {
104 push(@{$attrs->{select}}, @$include);
105 push(@{$attrs->{as}}, map { m/([^.]+)$/; $1; } @$include);
107 #use Data::Dumper; warn Dumper(@{$attrs}{qw/select as/});
109 $attrs->{from} ||= [ { $alias => $source->from } ];
110 $attrs->{seen_join} ||= {};
112 if (my $join = delete $attrs->{join}) {
113 foreach my $j (ref $join eq 'ARRAY' ? @$join : ($join)) {
114 if (ref $j eq 'HASH') {
115 $seen{$_} = 1 foreach keys %$j;
120 push(@{$attrs->{from}}, $source->resolve_join(
121 $join, $attrs->{alias}, $attrs->{seen_join})
125 $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
126 $attrs->{order_by} = [ $attrs->{order_by} ] if
127 $attrs->{order_by} and !ref($attrs->{order_by});
128 $attrs->{order_by} ||= [];
130 my $collapse = $attrs->{collapse} || {};
131 if (my $prefetch = delete $attrs->{prefetch}) {
133 foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
134 if ( ref $p eq 'HASH' ) {
135 foreach my $key (keys %$p) {
136 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
140 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
143 my @prefetch = $source->resolve_prefetch(
144 $p, $attrs->{alias}, {}, \@pre_order, $collapse);
145 push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
146 push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
148 push(@{$attrs->{order_by}}, @pre_order);
150 $attrs->{collapse} = $collapse;
151 # use Data::Dumper; warn Dumper($collapse) if keys %{$collapse};
153 if ($attrs->{page}) {
154 $attrs->{rows} ||= 10;
155 $attrs->{offset} ||= 0;
156 $attrs->{offset} += ($attrs->{rows} * ($attrs->{page} - 1));
160 result_source => $source,
161 result_class => $attrs->{result_class} || $source->result_class,
162 cond => $attrs->{where},
163 from => $attrs->{from},
164 collapse => $collapse,
166 page => delete $attrs->{page},
176 =item Arguments: $cond, \%attrs?
178 =item Return Value: $resultset (scalar context), @row_objs (list context)
182 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
183 my $new_rs = $cd_rs->search({ year => 2005 });
185 my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
186 # year = 2005 OR year = 2004
188 If you need to pass in additional attributes but no additional condition,
189 call it as C<search(undef, \%attrs);>.
191 # "SELECT name, artistid FROM $artist_table"
192 my @all_artists = $schema->resultset('Artist')->search(undef, {
193 columns => [qw/name artistid/],
204 my $attrs = { %{$self->{attrs}} };
205 my $having = delete $attrs->{having};
206 $attrs = { %$attrs, %{ pop(@_) } } if @_ > 1 and ref $_[$#_] eq 'HASH';
209 ? ((@_ == 1 || ref $_[0] eq "HASH")
212 ? $self->throw_exception(
213 "Odd number of arguments to search")
216 if (defined $where) {
217 $attrs->{where} = (defined $attrs->{where}
219 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
220 $where, $attrs->{where} ] }
224 if (defined $having) {
225 $attrs->{having} = (defined $attrs->{having}
227 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
228 $having, $attrs->{having} ] }
232 $rs = (ref $self)->new($self->result_source, $attrs);
238 return (wantarray ? $rs->all : $rs);
241 =head2 search_literal
245 =item Arguments: $sql_fragment, @bind_values
247 =item Return Value: $resultset (scalar context), @row_objs (list context)
251 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
252 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
254 Pass a literal chunk of SQL to be added to the conditional part of the
260 my ($self, $cond, @vals) = @_;
261 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
262 $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
263 return $self->search(\$cond, $attrs);
270 =item Arguments: (@values | \%cols), \%attrs?
272 =item Return Value: $row_object
276 Finds a row based on its primary key or unique constraint. For example:
278 my $cd = $schema->resultset('CD')->find(5);
280 Also takes an optional C<key> attribute, to search by a specific key or unique
281 constraint. For example:
283 my $cd = $schema->resultset('CD')->find(
285 artist => 'Massive Attack',
286 title => 'Mezzanine',
288 { key => 'artist_title' }
291 See also L</find_or_create> and L</update_or_create>.
296 my ($self, @vals) = @_;
297 my $attrs = (@vals > 1 && ref $vals[$#vals] eq 'HASH' ? pop(@vals) : {});
299 my @cols = $self->result_source->primary_columns;
300 if (exists $attrs->{key}) {
301 my %uniq = $self->result_source->unique_constraints;
302 $self->throw_exception(
303 "Unknown key $attrs->{key} on '" . $self->result_source->name . "'"
304 ) unless exists $uniq{$attrs->{key}};
305 @cols = @{ $uniq{$attrs->{key}} };
307 #use Data::Dumper; warn Dumper($attrs, @vals, @cols);
308 $self->throw_exception(
309 "Can't find unless a primary key or unique constraint is defined"
313 if (ref $vals[0] eq 'HASH') {
314 $query = { %{$vals[0]} };
315 } elsif (@cols == @vals) {
317 @{$query}{@cols} = @vals;
321 foreach my $key (grep { ! m/\./ } keys %$query) {
322 $query->{"$self->{attrs}{alias}.$key"} = delete $query->{$key};
324 #warn Dumper($query);
327 my $rs = $self->search($query,$attrs);
328 return keys %{$rs->{collapse}} ? $rs->next : $rs->single;
330 return keys %{$self->{collapse}} ?
331 $self->search($query)->next :
332 $self->single($query);
336 =head2 search_related
340 =item Arguments: $cond, \%attrs?
342 =item Return Value: $new_resultset
346 $new_rs = $cd_rs->search_related('artist', {
350 Search the specified relationship, optionally specify a condition and
351 attributes for matching records. See L</ATTRIBUTES> for more information.
356 return shift->related_resultset(shift)->search(@_);
363 =item Arguments: none
365 =item Return Value: $cursor
369 Returns a storage-driven cursor to the given resultset. See
370 L<DBIx::Class::Cursor> for more information.
376 my $attrs = { %{$self->{attrs}} };
377 return $self->{cursor}
378 ||= $self->result_source->storage->select($self->{from}, $attrs->{select},
379 $attrs->{where},$attrs);
386 =item Arguments: $cond?
388 =item Return Value: $row_object?
392 my $cd = $schema->resultset('CD')->single({ year => 2001 });
394 Inflates the first result without creating a cursor if the resultset has
395 any records in it; if not returns nothing. Used by find() as an optimisation.
400 my ($self, $where) = @_;
401 my $attrs = { %{$self->{attrs}} };
403 if (defined $attrs->{where}) {
406 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
407 $where, delete $attrs->{where} ]
410 $attrs->{where} = $where;
413 my @data = $self->result_source->storage->select_single(
414 $self->{from}, $attrs->{select},
415 $attrs->{where},$attrs);
416 return (@data ? $self->_construct_object(@data) : ());
424 =item Arguments: $cond, \%attrs?
426 =item Return Value: $resultset (scalar context), @row_objs (list context)
430 # WHERE title LIKE '%blue%'
431 $cd_rs = $rs->search_like({ title => '%blue%'});
433 Perform a search, but use C<LIKE> instead of C<=> as the condition. Note
434 that this is simply a convenience method. You most likely want to use
435 L</search> with specific operators.
437 For more information, see L<DBIx::Class::Manual::Cookbook>.
443 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
444 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
445 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
446 return $class->search($query, { %$attrs });
453 =item Arguments: $first, $last
455 =item Return Value: $resultset (scalar context), @row_objs (list context)
459 Returns a resultset or object list representing a subset of elements from the
460 resultset slice is called on. Indexes are from 0 - i.e. to get the first
463 my ($one, $two, $three) = $rs->slice(0, 2);
468 my ($self, $min, $max) = @_;
469 my $attrs = { %{ $self->{attrs} || {} } };
470 $attrs->{offset} ||= 0;
471 $attrs->{offset} += $min;
472 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
473 my $slice = (ref $self)->new($self->result_source, $attrs);
474 return (wantarray ? $slice->all : $slice);
481 =item Arguments: none
483 =item Return Value: $result?
487 Returns the next element in the resultset (C<undef> is there is none).
489 Can be used to efficiently iterate over records in the resultset:
491 my $rs = $schema->resultset('CD')->search;
492 while (my $cd = $rs->next) {
500 if (@{$self->{all_cache} || []}) {
501 $self->{all_cache_position} ||= 0;
502 return $self->{all_cache}->[$self->{all_cache_position}++];
504 if ($self->{attrs}{cache}) {
505 $self->{all_cache_position} = 1;
506 return ($self->all)[0];
508 my @row = (exists $self->{stashed_row} ?
509 @{delete $self->{stashed_row}} :
512 # warn Dumper(\@row); use Data::Dumper;
513 return unless (@row);
514 return $self->_construct_object(@row);
517 sub _construct_object {
518 my ($self, @row) = @_;
519 my @as = @{ $self->{attrs}{as} };
521 my $info = $self->_collapse_result(\@as, \@row);
523 my $new = $self->result_class->inflate_result($self->result_source, @$info);
525 $new = $self->{attrs}{record_filter}->($new)
526 if exists $self->{attrs}{record_filter};
530 sub _collapse_result {
531 my ($self, $as, $row, $prefix) = @_;
536 foreach my $this_as (@$as) {
537 my $val = shift @copy;
538 if (defined $prefix) {
539 if ($this_as =~ m/^\Q${prefix}.\E(.+)$/) {
541 $remain =~ /^(?:(.*)\.)?([^.]+)$/;
542 $const{$1||''}{$2} = $val;
545 $this_as =~ /^(?:(.*)\.)?([^.]+)$/;
546 $const{$1||''}{$2} = $val;
550 my $info = [ {}, {} ];
551 foreach my $key (keys %const) {
554 my @parts = split(/\./, $key);
555 foreach my $p (@parts) {
556 $target = $target->[1]->{$p} ||= [];
558 $target->[0] = $const{$key};
560 $info->[0] = $const{$key};
565 if (defined $prefix) {
567 m/^\Q${prefix}.\E(.+)$/ ? ($1) : ()
568 } keys %{$self->{collapse}}
570 @collapse = keys %{$self->{collapse}};
574 my ($c) = sort { length $a <=> length $b } @collapse;
576 foreach my $p (split(/\./, $c)) {
577 $target = $target->[1]->{$p} ||= [];
579 my $c_prefix = (defined($prefix) ? "${prefix}.${c}" : $c);
580 my @co_key = @{$self->{collapse}{$c_prefix}};
581 my %co_check = map { ($_, $target->[0]->{$_}); } @co_key;
582 my $tree = $self->_collapse_result($as, $row, $c_prefix);
585 !defined($tree->[0]->{$_}) ||
586 $co_check{$_} ne $tree->[0]->{$_}
589 last unless (@raw = $self->cursor->next);
590 $row = $self->{stashed_row} = \@raw;
591 $tree = $self->_collapse_result($as, $row, $c_prefix);
592 #warn Data::Dumper::Dumper($tree, $row);
604 =item Arguments: $result_source?
606 =item Return Value: $result_source
610 An accessor for the primary ResultSource object from which this ResultSet
620 =item Arguments: ($cond, \%attrs?)?
622 =item Return Value: $count
626 Performs an SQL C<COUNT> with the same query as the resultset was built
627 with to find the number of elements. If passed arguments, does a search
628 on the resultset and counts the results of that.
630 Note: When using C<count> with C<group_by>, L<DBIX::Class> emulates C<GROUP BY>
631 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
632 not support C<DISTINCT> with multiple columns. If you are using such a
633 database, you should only use columns from the main table in your C<group_by>
640 return $self->search(@_)->count if @_ and defined $_[0];
641 return scalar @{ $self->get_cache } if @{ $self->get_cache };
643 my $count = $self->_count;
644 return 0 unless $count;
646 $count -= $self->{attrs}{offset} if $self->{attrs}{offset};
647 $count = $self->{attrs}{rows} if
648 $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
652 sub _count { # Separated out so pager can get the full count
654 my $select = { count => '*' };
655 my $attrs = { %{ $self->{attrs} } };
656 if (my $group_by = delete $attrs->{group_by}) {
657 delete $attrs->{having};
658 my @distinct = (ref $group_by ? @$group_by : ($group_by));
659 # todo: try CONCAT for multi-column pk
660 my @pk = $self->result_source->primary_columns;
662 foreach my $column (@distinct) {
663 if ($column =~ qr/^(?:\Q$attrs->{alias}.\E)?$pk[0]$/) {
664 @distinct = ($column);
670 $select = { count => { distinct => \@distinct } };
671 #use Data::Dumper; die Dumper $select;
674 $attrs->{select} = $select;
675 $attrs->{as} = [qw/count/];
677 # offset, order by and page are not needed to count. record_filter is cdbi
678 delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
680 my ($count) = (ref $self)->new($self->result_source, $attrs)->cursor->next;
688 =item Arguments: $sql_fragment, @bind_values
690 =item Return Value: $count
694 Counts the results in a literal query. Equivalent to calling L</search_literal>
695 with the passed arguments, then L</count>.
699 sub count_literal { shift->search_literal(@_)->count; }
705 =item Arguments: none
707 =item Return Value: @objects
711 Returns all elements in the resultset. Called implicitly if the resultset
712 is returned in list context.
718 return @{ $self->get_cache } if @{ $self->get_cache };
722 if (keys %{$self->{collapse}}) {
723 # Using $self->cursor->all is really just an optimisation.
724 # If we're collapsing has_many prefetches it probably makes
725 # very little difference, and this is cleaner than hacking
726 # _construct_object to survive the approach
727 $self->cursor->reset;
728 my @row = $self->cursor->next;
730 push(@obj, $self->_construct_object(@row));
731 @row = (exists $self->{stashed_row}
732 ? @{delete $self->{stashed_row}}
733 : $self->cursor->next);
736 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
739 $self->set_cache(\@obj) if $self->{attrs}{cache};
747 =item Arguments: none
749 =item Return Value: $self
753 Resets the resultset's cursor, so you can iterate through the elements again.
759 $self->{all_cache_position} = 0;
760 $self->cursor->reset;
768 =item Arguments: none
770 =item Return Value: $object?
774 Resets the resultset and returns an object for the first result (if the
775 resultset contains anything).
780 return $_[0]->reset->next;
787 =item Arguments: \%values
789 =item Return Value: $storage_rv
793 Sets the specified columns in the resultset to the supplied values in a
794 single query. Return value will be true if the update succeeded or false
795 if no records were updated; exact type of success value is storage-dependent.
800 my ($self, $values) = @_;
801 $self->throw_exception("Values for update must be a hash")
802 unless ref $values eq 'HASH';
803 return $self->result_source->storage->update(
804 $self->result_source->from, $values, $self->{cond}
812 =item Arguments: \%values
814 =item Return Value: 1
818 Fetches all objects and updates them one at a time. Note that C<update_all>
819 will run cascade triggers while L</update> will not.
824 my ($self, $values) = @_;
825 $self->throw_exception("Values for update must be a hash")
826 unless ref $values eq 'HASH';
827 foreach my $obj ($self->all) {
828 $obj->set_columns($values)->update;
837 =item Arguments: none
839 =item Return Value: 1
843 Deletes the contents of the resultset from its result source. Note that this
844 will not run cascade triggers. See L</delete_all> if you need triggers to run.
852 if (!ref($self->{cond})) {
854 # No-op. No condition, we're deleting everything
856 } elsif (ref $self->{cond} eq 'ARRAY') {
858 $del = [ map { my %hash;
859 foreach my $key (keys %{$_}) {
861 $hash{$1} = $_->{$key};
862 }; \%hash; } @{$self->{cond}} ];
864 } elsif (ref $self->{cond} eq 'HASH') {
866 if ((keys %{$self->{cond}})[0] eq '-and') {
868 $del->{-and} = [ map { my %hash;
869 foreach my $key (keys %{$_}) {
871 $hash{$1} = $_->{$key};
872 }; \%hash; } @{$self->{cond}{-and}} ];
876 foreach my $key (keys %{$self->{cond}}) {
878 $del->{$1} = $self->{cond}{$key};
883 $self->throw_exception(
884 "Can't delete on resultset with condition unless hash or array"
888 $self->result_source->storage->delete($self->result_source->from, $del);
896 =item Arguments: none
898 =item Return Value: 1
902 Fetches all objects and deletes them one at a time. Note that C<delete_all>
903 will run cascade triggers while L</delete> will not.
909 $_->delete for $self->all;
917 =item Arguments: none
919 =item Return Value: $pager
923 Return Value a L<Data::Page> object for the current resultset. Only makes
924 sense for queries with a C<page> attribute.
930 my $attrs = $self->{attrs};
931 $self->throw_exception("Can't create pager for non-paged rs")
932 unless $self->{page};
933 $attrs->{rows} ||= 10;
934 return $self->{pager} ||= Data::Page->new(
935 $self->_count, $attrs->{rows}, $self->{page});
942 =item Arguments: $page_number
944 =item Return Value: $rs
948 Returns a resultset for the $page_number page of the resultset on which page
949 is called, where each page contains a number of rows equal to the 'rows'
950 attribute set on the resultset, or 10 by default
955 my ($self, $page) = @_;
956 my $attrs = { %{$self->{attrs}} };
957 $attrs->{page} = $page;
958 return (ref $self)->new($self->result_source, $attrs);
965 =item Arguments: \%vals
967 =item Return Value: $object
971 Creates an object in the resultset's result class and returns it.
976 my ($self, $values) = @_;
977 $self->throw_exception( "new_result needs a hash" )
978 unless (ref $values eq 'HASH');
979 $self->throw_exception(
980 "Can't abstract implicit construct, condition not a hash"
981 ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
983 my $alias = $self->{attrs}{alias};
984 foreach my $key (keys %{$self->{cond}||{}}) {
985 $new{$1} = $self->{cond}{$key} if ($key =~ m/^(?:\Q${alias}.\E)?([^.]+)$/);
987 my $obj = $self->result_class->new(\%new);
988 $obj->result_source($self->result_source) if $obj->can('result_source');
996 =item Arguments: \%vals
998 =item Return Value: $object
1002 Inserts a record into the resultset and returns the object representing it.
1004 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
1009 my ($self, $attrs) = @_;
1010 $self->throw_exception( "create needs a hashref" )
1011 unless ref $attrs eq 'HASH';
1012 return $self->new_result($attrs)->insert;
1015 =head2 find_or_create
1019 =item Arguments: \%vals, \%attrs?
1021 =item Return Value: $object
1025 $class->find_or_create({ key => $val, ... });
1027 Searches for a record matching the search condition; if it doesn't find one,
1028 creates one and returns that instead.
1030 my $cd = $schema->resultset('CD')->find_or_create({
1032 artist => 'Massive Attack',
1033 title => 'Mezzanine',
1037 Also takes an optional C<key> attribute, to search by a specific key or unique
1038 constraint. For example:
1040 my $cd = $schema->resultset('CD')->find_or_create(
1042 artist => 'Massive Attack',
1043 title => 'Mezzanine',
1045 { key => 'artist_title' }
1048 See also L</find> and L</update_or_create>.
1052 sub find_or_create {
1054 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1055 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1056 my $exists = $self->find($hash, $attrs);
1057 return defined $exists ? $exists : $self->create($hash);
1060 =head2 update_or_create
1064 =item Arguments: \%col_values, { key => $unique_constraint }?
1066 =item Return Value: $object
1070 $class->update_or_create({ col => $val, ... });
1072 First, search for an existing row matching one of the unique constraints
1073 (including the primary key) on the source of this resultset. If a row is
1074 found, update it with the other given column values. Otherwise, create a new
1077 Takes an optional C<key> attribute to search on a specific unique constraint.
1080 # In your application
1081 my $cd = $schema->resultset('CD')->update_or_create(
1083 artist => 'Massive Attack',
1084 title => 'Mezzanine',
1087 { key => 'artist_title' }
1090 If no C<key> is specified, it searches on all unique constraints defined on the
1091 source, including the primary key.
1093 If the C<key> is specified as C<primary>, search only on the primary key.
1095 See also L</find> and L</find_or_create>.
1099 sub update_or_create {
1101 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1102 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1104 my %unique_constraints = $self->result_source->unique_constraints;
1105 my @constraint_names = (exists $attrs->{key}
1107 : keys %unique_constraints);
1110 foreach my $name (@constraint_names) {
1111 my @unique_cols = @{ $unique_constraints{$name} };
1113 map { $_ => $hash->{$_} }
1114 grep { exists $hash->{$_} }
1117 push @unique_hashes, \%unique_hash
1118 if (scalar keys %unique_hash == scalar @unique_cols);
1121 if (@unique_hashes) {
1122 my $row = $self->single(\@unique_hashes);
1124 $row->set_columns($hash);
1130 return $self->create($hash);
1137 =item Arguments: none
1139 =item Return Value: \@cache_objects?
1143 Gets the contents of the cache for the resultset if the cache is set
1148 shift->{all_cache} || [];
1155 =item Arguments: \@cache_objects
1157 =item Return Value: \@cache_objects
1161 Sets the contents of the cache for the resultset. Expects an arrayref
1162 of objects of the same class as those produced by the resultset. Note that
1163 if the cache is set the resultset will return the cached objects rather
1164 than re-querying the database even if the cache attr is not set.
1169 my ( $self, $data ) = @_;
1170 $self->throw_exception("set_cache requires an arrayref")
1171 if ref $data ne 'ARRAY';
1172 my $result_class = $self->result_class;
1174 $self->throw_exception(
1175 "cannot cache object of type '$_', expected '$result_class'"
1176 ) if ref $_ ne $result_class;
1178 $self->{all_cache} = $data;
1185 =item Arguments: none
1187 =item Return Value: []
1191 Clears the cache for the resultset.
1196 shift->set_cache([]);
1199 =head2 related_resultset
1203 =item Arguments: $relationship_name
1205 =item Return Value: $resultset
1209 Returns a related resultset for the supplied relationship name.
1211 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1215 sub related_resultset {
1216 my ( $self, $rel ) = @_;
1217 $self->{related_resultsets} ||= {};
1218 return $self->{related_resultsets}{$rel} ||= do {
1219 #warn "fetching related resultset for rel '$rel'";
1220 my $rel_obj = $self->result_source->relationship_info($rel);
1221 $self->throw_exception(
1222 "search_related: result source '" . $self->result_source->name .
1223 "' has no such relationship ${rel}")
1224 unless $rel_obj; #die Dumper $self->{attrs};
1226 my $rs = $self->search(undef, { join => $rel });
1227 my $alias = defined $rs->{attrs}{seen_join}{$rel}
1228 && $rs->{attrs}{seen_join}{$rel} > 1
1229 ? join('_', $rel, $rs->{attrs}{seen_join}{$rel})
1232 $self->result_source->schema->resultset($rel_obj->{class}
1242 =head2 throw_exception
1244 See L<DBIx::Class::Schema/throw_exception> for details.
1248 sub throw_exception {
1250 $self->result_source->schema->throw_exception(@_);
1253 # XXX: FIXME: Attributes docs need clearing up
1257 The resultset takes various attributes that modify its behavior. Here's an
1264 =item Value: ($order_by | \@order_by)
1266 Which column(s) to order the results by. This is currently passed
1267 through directly to SQL, so you can give e.g. C<year DESC> for a
1268 descending order on the column `year'.
1274 =item Value: \@columns
1278 Shortcut to request a particular set of columns to be retrieved. Adds
1279 C<me.> onto the start of any column without a C<.> in it and sets C<select>
1280 from that, then auto-populates C<as> from C<select> as normal. (You may also
1281 use the C<cols> attribute, as in earlier versions of DBIC.)
1283 =head2 include_columns
1287 =item Value: \@columns
1291 Shortcut to include additional columns in the returned results - for example
1293 $schema->resultset('CD')->search(undef, {
1294 include_columns => ['artist.name'],
1298 would return all CDs and include a 'name' column to the information
1299 passed to object inflation
1305 =item Value: \@select_columns
1309 Indicates which columns should be selected from the storage. You can use
1310 column names, or in the case of RDBMS back ends, function or stored procedure
1313 $rs = $schema->resultset('Employee')->search(undef, {
1316 { count => 'employeeid' },
1321 When you use function/stored procedure names and do not supply an C<as>
1322 attribute, the column names returned are storage-dependent. E.g. MySQL would
1323 return a column named C<count(employeeid)> in the above example.
1329 =item Value: \@inflation_names
1333 Indicates column names for object inflation. This is used in conjunction with
1334 C<select>, usually when C<select> contains one or more function or stored
1337 $rs = $schema->resultset('Employee')->search(undef, {
1340 { count => 'employeeid' }
1342 as => ['name', 'employee_count'],
1345 my $employee = $rs->first(); # get the first Employee
1347 If the object against which the search is performed already has an accessor
1348 matching a column name specified in C<as>, the value can be retrieved using
1349 the accessor as normal:
1351 my $name = $employee->name();
1353 If on the other hand an accessor does not exist in the object, you need to
1354 use C<get_column> instead:
1356 my $employee_count = $employee->get_column('employee_count');
1358 You can create your own accessors if required - see
1359 L<DBIx::Class::Manual::Cookbook> for details.
1365 =item Value: ($rel_name | \@rel_names | \%rel_names)
1369 Contains a list of relationships that should be joined for this query. For
1372 # Get CDs by Nine Inch Nails
1373 my $rs = $schema->resultset('CD')->search(
1374 { 'artist.name' => 'Nine Inch Nails' },
1375 { join => 'artist' }
1378 Can also contain a hash reference to refer to the other relation's relations.
1381 package MyApp::Schema::Track;
1382 use base qw/DBIx::Class/;
1383 __PACKAGE__->table('track');
1384 __PACKAGE__->add_columns(qw/trackid cd position title/);
1385 __PACKAGE__->set_primary_key('trackid');
1386 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
1389 # In your application
1390 my $rs = $schema->resultset('Artist')->search(
1391 { 'track.title' => 'Teardrop' },
1393 join => { cd => 'track' },
1394 order_by => 'artist.name',
1398 If the same join is supplied twice, it will be aliased to <rel>_2 (and
1399 similarly for a third time). For e.g.
1401 my $rs = $schema->resultset('Artist')->search({
1402 'cds.title' => 'Down to Earth',
1403 'cds_2.title' => 'Popular',
1405 join => [ qw/cds cds/ ],
1408 will return a set of all artists that have both a cd with title 'Down
1409 to Earth' and a cd with title 'Popular'.
1411 If you want to fetch related objects from other tables as well, see C<prefetch>
1418 =item Value: ($rel_name | \@rel_names | \%rel_names)
1422 Contains one or more relationships that should be fetched along with the main
1423 query (when they are accessed afterwards they will have already been
1424 "prefetched"). This is useful for when you know you will need the related
1425 objects, because it saves at least one query:
1427 my $rs = $schema->resultset('Tag')->search(
1436 The initial search results in SQL like the following:
1438 SELECT tag.*, cd.*, artist.* FROM tag
1439 JOIN cd ON tag.cd = cd.cdid
1440 JOIN artist ON cd.artist = artist.artistid
1442 L<DBIx::Class> has no need to go back to the database when we access the
1443 C<cd> or C<artist> relationships, which saves us two SQL statements in this
1446 Simple prefetches will be joined automatically, so there is no need
1447 for a C<join> attribute in the above search. If you're prefetching to
1448 depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
1449 specify the join as well.
1451 C<prefetch> can be used with the following relationship types: C<belongs_to>,
1452 C<has_one> (or if you're using C<add_relationship>, any relationship declared
1453 with an accessor type of 'single' or 'filter').
1459 =item Value: \@from_clause
1463 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
1464 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
1467 NOTE: Use this on your own risk. This allows you to shoot off your foot!
1468 C<join> will usually do what you need and it is strongly recommended that you
1469 avoid using C<from> unless you cannot achieve the desired result using C<join>.
1471 In simple terms, C<from> works as follows:
1474 { <alias> => <table>, -join-type => 'inner|left|right' }
1475 [] # nested JOIN (optional)
1476 { <table.column> => <foreign_table.foreign_key> }
1482 ON <table.column> = <foreign_table.foreign_key>
1484 An easy way to follow the examples below is to remember the following:
1486 Anything inside "[]" is a JOIN
1487 Anything inside "{}" is a condition for the enclosing JOIN
1489 The following examples utilize a "person" table in a family tree application.
1490 In order to express parent->child relationships, this table is self-joined:
1492 # Person->belongs_to('father' => 'Person');
1493 # Person->belongs_to('mother' => 'Person');
1495 C<from> can be used to nest joins. Here we return all children with a father,
1496 then search against all mothers of those children:
1498 $rs = $schema->resultset('Person')->search(
1501 alias => 'mother', # alias columns in accordance with "from"
1503 { mother => 'person' },
1506 { child => 'person' },
1508 { father => 'person' },
1509 { 'father.person_id' => 'child.father_id' }
1512 { 'mother.person_id' => 'child.mother_id' }
1519 # SELECT mother.* FROM person mother
1522 # JOIN person father
1523 # ON ( father.person_id = child.father_id )
1525 # ON ( mother.person_id = child.mother_id )
1527 The type of any join can be controlled manually. To search against only people
1528 with a father in the person table, we could explicitly use C<INNER JOIN>:
1530 $rs = $schema->resultset('Person')->search(
1533 alias => 'child', # alias columns in accordance with "from"
1535 { child => 'person' },
1537 { father => 'person', -join-type => 'inner' },
1538 { 'father.id' => 'child.father_id' }
1545 # SELECT child.* FROM person child
1546 # INNER JOIN person father ON child.father_id = father.id
1556 Makes the resultset paged and specifies the page to retrieve. Effectively
1557 identical to creating a non-pages resultset and then calling ->page($page)
1568 Specifes the maximum number of rows for direct retrieval or the number of
1569 rows per page if the page attribute or method is used.
1575 =item Value: \@columns
1579 A arrayref of columns to group by. Can include columns of joined tables.
1581 group_by => [qw/ column1 column2 ... /]
1587 =item Value: (0 | 1)
1591 Set to 1 to group by all columns.
1595 Set to 1 to cache search results. This prevents extra SQL queries if you
1596 revisit rows in your ResultSet:
1598 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
1600 while( my $artist = $resultset->next ) {
1604 $rs->first; # without cache, this would issue a query
1606 By default, searches are not cached.
1608 For more examples of using these attributes, see
1609 L<DBIx::Class::Manual::Cookbook>.