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
64 The resultset constructor. Takes a source object (usually a
65 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
66 L</ATTRIBUTES> below). Does not perform any queries -- these are
67 executed as needed by the other methods.
69 Generally you won't need to construct a resultset manually. You'll
70 automatically get one from e.g. a L</search> called in scalar context:
72 my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
74 IMPORTANT: If called on an object, proxies to new_result instead so
76 my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
78 will return a CD object, not a ResultSet.
84 return $class->new_result(@_) if ref $class;
86 my ($source, $attrs) = @_;
88 $attrs = Storable::dclone($attrs || {}); # { %{ $attrs || {} } };
89 #use Data::Dumper; warn Dumper($attrs);
90 my $alias = ($attrs->{alias} ||= 'me');
92 $attrs->{columns} ||= delete $attrs->{cols} if $attrs->{cols};
93 delete $attrs->{as} if $attrs->{columns};
94 $attrs->{columns} ||= [ $source->columns ] unless $attrs->{select};
96 map { m/\./ ? $_ : "${alias}.$_" } @{delete $attrs->{columns}}
97 ] if $attrs->{columns};
99 map { m/^\Q$alias.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}}
101 if (my $include = delete $attrs->{include_columns}) {
102 push(@{$attrs->{select}}, @$include);
103 push(@{$attrs->{as}}, map { m/([^.]+)$/; $1; } @$include);
105 #use Data::Dumper; warn Dumper(@{$attrs}{qw/select as/});
107 $attrs->{from} ||= [ { $alias => $source->from } ];
108 $attrs->{seen_join} ||= {};
110 if (my $join = delete $attrs->{join}) {
111 foreach my $j (ref $join eq 'ARRAY' ? @$join : ($join)) {
112 if (ref $j eq 'HASH') {
113 $seen{$_} = 1 foreach keys %$j;
118 push(@{$attrs->{from}}, $source->resolve_join(
119 $join, $attrs->{alias}, $attrs->{seen_join})
123 $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
124 $attrs->{order_by} = [ $attrs->{order_by} ] if
125 $attrs->{order_by} and !ref($attrs->{order_by});
126 $attrs->{order_by} ||= [];
128 my $collapse = $attrs->{collapse} || {};
129 if (my $prefetch = delete $attrs->{prefetch}) {
131 foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
132 if ( ref $p eq 'HASH' ) {
133 foreach my $key (keys %$p) {
134 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
138 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
141 my @prefetch = $source->resolve_prefetch(
142 $p, $attrs->{alias}, {}, \@pre_order, $collapse);
143 push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
144 push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
146 push(@{$attrs->{order_by}}, @pre_order);
148 $attrs->{collapse} = $collapse;
149 # use Data::Dumper; warn Dumper($collapse) if keys %{$collapse};
151 if ($attrs->{page}) {
152 $attrs->{rows} ||= 10;
153 $attrs->{offset} ||= 0;
154 $attrs->{offset} += ($attrs->{rows} * ($attrs->{page} - 1));
158 result_source => $source,
159 result_class => $attrs->{result_class} || $source->result_class,
160 cond => $attrs->{where},
161 from => $attrs->{from},
162 collapse => $collapse,
164 page => delete $attrs->{page},
174 =item Arguments: $cond, \%attrs?
176 =item Return Value: $resultset (scalar context), @row_objs (list context)
180 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
181 my $new_rs = $cd_rs->search({ year => 2005 });
183 my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
184 # year = 2005 OR year = 2004
186 If you need to pass in additional attributes but no additional condition,
187 call it as C<search(undef, \%attrs)>.
189 # "SELECT name, artistid FROM $artist_table"
190 my @all_artists = $schema->resultset('Artist')->search(undef, {
191 columns => [qw/name artistid/],
199 my $attrs = { %{$self->{attrs}} };
200 my $having = delete $attrs->{having};
201 $attrs = { %$attrs, %{ pop(@_) } } if @_ > 1 and ref $_[$#_] eq 'HASH';
204 ? ((@_ == 1 || ref $_[0] eq "HASH")
207 ? $self->throw_exception(
208 "Odd number of arguments to search")
211 if (defined $where) {
212 $attrs->{where} = (defined $attrs->{where}
214 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
215 $where, $attrs->{where} ] }
219 if (defined $having) {
220 $attrs->{having} = (defined $attrs->{having}
222 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
223 $having, $attrs->{having} ] }
227 my $rs = (ref $self)->new($self->result_source, $attrs);
229 unless (@_) { # no search, effectively just a clone
230 my $rows = $self->get_cache;
232 $rs->set_cache($rows);
236 return (wantarray ? $rs->all : $rs);
239 =head2 search_literal
243 =item Arguments: $sql_fragment, @bind_values
245 =item Return Value: $resultset (scalar context), @row_objs (list context)
249 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
250 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
252 Pass a literal chunk of SQL to be added to the conditional part of the
258 my ($self, $cond, @vals) = @_;
259 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
260 $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
261 return $self->search(\$cond, $attrs);
268 =item Arguments: @values | \%cols, \%attrs?
270 =item Return Value: $row_object
274 Finds a row based on its primary key or unique constraint. For example:
276 my $cd = $schema->resultset('CD')->find(5);
278 Also takes an optional C<key> attribute, to search by a specific key or unique
279 constraint. For example:
281 my $cd = $schema->resultset('CD')->find(
283 artist => 'Massive Attack',
284 title => 'Mezzanine',
286 { key => 'artist_title' }
289 See also L</find_or_create> and L</update_or_create>.
294 my ($self, @vals) = @_;
295 my $attrs = (@vals > 1 && ref $vals[$#vals] eq 'HASH' ? pop(@vals) : {});
297 my @cols = $self->result_source->primary_columns;
298 if (exists $attrs->{key}) {
299 my %uniq = $self->result_source->unique_constraints;
300 $self->throw_exception(
301 "Unknown key $attrs->{key} on '" . $self->result_source->name . "'"
302 ) unless exists $uniq{$attrs->{key}};
303 @cols = @{ $uniq{$attrs->{key}} };
305 #use Data::Dumper; warn Dumper($attrs, @vals, @cols);
306 $self->throw_exception(
307 "Can't find unless a primary key or unique constraint is defined"
311 if (ref $vals[0] eq 'HASH') {
312 $query = { %{$vals[0]} };
313 } elsif (@cols == @vals) {
315 @{$query}{@cols} = @vals;
319 foreach my $key (grep { ! m/\./ } keys %$query) {
320 $query->{"$self->{attrs}{alias}.$key"} = delete $query->{$key};
322 #warn Dumper($query);
325 my $rs = $self->search($query,$attrs);
326 return keys %{$rs->{collapse}} ? $rs->next : $rs->single;
328 return keys %{$self->{collapse}} ?
329 $self->search($query)->next :
330 $self->single($query);
334 =head2 search_related
338 =item Arguments: $cond, \%attrs?
340 =item Return Value: $new_resultset
344 $new_rs = $cd_rs->search_related('artist', {
348 Searches the specified relationship, optionally specifying a condition and
349 attributes for matching records. See L</ATTRIBUTES> for more information.
354 return shift->related_resultset(shift)->search(@_);
361 =item Arguments: none
363 =item Return Value: $cursor
367 Returns a storage-driven cursor to the given resultset. See
368 L<DBIx::Class::Cursor> for more information.
374 my $attrs = { %{$self->{attrs}} };
375 return $self->{cursor}
376 ||= $self->result_source->storage->select($self->{from}, $attrs->{select},
377 $attrs->{where},$attrs);
384 =item Arguments: $cond?
386 =item Return Value: $row_object?
390 my $cd = $schema->resultset('CD')->single({ year => 2001 });
392 Inflates the first result without creating a cursor if the resultset has
393 any records in it; if not returns nothing. Used by find() as an optimisation.
395 Can optionally take an additional condition *only* - this is a fast-code-path
396 method; if you need to add extra joins or similar call ->search and then
397 ->single without a condition on the $rs returned from that.
402 my ($self, $where) = @_;
403 my $attrs = { %{$self->{attrs}} };
405 if (defined $attrs->{where}) {
408 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
409 $where, delete $attrs->{where} ]
412 $attrs->{where} = $where;
415 my @data = $self->result_source->storage->select_single(
416 $self->{from}, $attrs->{select},
417 $attrs->{where},$attrs);
418 return (@data ? $self->_construct_object(@data) : ());
426 =item Arguments: $cond, \%attrs?
428 =item Return Value: $resultset (scalar context), @row_objs (list context)
432 # WHERE title LIKE '%blue%'
433 $cd_rs = $rs->search_like({ title => '%blue%'});
435 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
436 that this is simply a convenience method. You most likely want to use
437 L</search> with specific operators.
439 For more information, see L<DBIx::Class::Manual::Cookbook>.
445 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
446 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
447 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
448 return $class->search($query, { %$attrs });
455 =item Arguments: $first, $last
457 =item Return Value: $resultset (scalar context), @row_objs (list context)
461 Returns a resultset or object list representing a subset of elements from the
462 resultset slice is called on. Indexes are from 0, i.e., to get the first
465 my ($one, $two, $three) = $rs->slice(0, 2);
470 my ($self, $min, $max) = @_;
471 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
472 $attrs->{offset} = $self->{attrs}{offset} || 0;
473 $attrs->{offset} += $min;
474 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
475 return $self->search(undef(), $attrs);
476 #my $slice = (ref $self)->new($self->result_source, $attrs);
477 #return (wantarray ? $slice->all : $slice);
484 =item Arguments: none
486 =item Return Value: $result?
490 Returns the next element in the resultset (C<undef> is there is none).
492 Can be used to efficiently iterate over records in the resultset:
494 my $rs = $schema->resultset('CD')->search;
495 while (my $cd = $rs->next) {
499 Note that you need to store the resultset object, and call C<next> on it.
500 Calling C<< resultset('Table')->next >> repeatedly will always return the
501 first record from the resultset.
507 if (my $cache = $self->get_cache) {
508 $self->{all_cache_position} ||= 0;
509 return $cache->[$self->{all_cache_position}++];
511 if ($self->{attrs}{cache}) {
512 $self->{all_cache_position} = 1;
513 return ($self->all)[0];
515 my @row = (exists $self->{stashed_row} ?
516 @{delete $self->{stashed_row}} :
519 # warn Dumper(\@row); use Data::Dumper;
520 return unless (@row);
521 return $self->_construct_object(@row);
524 sub _construct_object {
525 my ($self, @row) = @_;
526 my @as = @{ $self->{attrs}{as} };
528 my $info = $self->_collapse_result(\@as, \@row);
530 my $new = $self->result_class->inflate_result($self->result_source, @$info);
532 $new = $self->{attrs}{record_filter}->($new)
533 if exists $self->{attrs}{record_filter};
537 sub _collapse_result {
538 my ($self, $as, $row, $prefix) = @_;
543 foreach my $this_as (@$as) {
544 my $val = shift @copy;
545 if (defined $prefix) {
546 if ($this_as =~ m/^\Q${prefix}.\E(.+)$/) {
548 $remain =~ /^(?:(.*)\.)?([^.]+)$/;
549 $const{$1||''}{$2} = $val;
552 $this_as =~ /^(?:(.*)\.)?([^.]+)$/;
553 $const{$1||''}{$2} = $val;
557 my $info = [ {}, {} ];
558 foreach my $key (keys %const) {
561 my @parts = split(/\./, $key);
562 foreach my $p (@parts) {
563 $target = $target->[1]->{$p} ||= [];
565 $target->[0] = $const{$key};
567 $info->[0] = $const{$key};
572 if (defined $prefix) {
574 m/^\Q${prefix}.\E(.+)$/ ? ($1) : ()
575 } keys %{$self->{collapse}}
577 @collapse = keys %{$self->{collapse}};
581 my ($c) = sort { length $a <=> length $b } @collapse;
583 foreach my $p (split(/\./, $c)) {
584 $target = $target->[1]->{$p} ||= [];
586 my $c_prefix = (defined($prefix) ? "${prefix}.${c}" : $c);
587 my @co_key = @{$self->{collapse}{$c_prefix}};
588 my %co_check = map { ($_, $target->[0]->{$_}); } @co_key;
589 my $tree = $self->_collapse_result($as, $row, $c_prefix);
592 !defined($tree->[0]->{$_}) ||
593 $co_check{$_} ne $tree->[0]->{$_}
596 last unless (@raw = $self->cursor->next);
597 $row = $self->{stashed_row} = \@raw;
598 $tree = $self->_collapse_result($as, $row, $c_prefix);
600 @$target = (@final ? @final : [ {}, {} ]);
601 # single empty result to indicate an empty prefetched has_many
611 =item Arguments: $result_source?
613 =item Return Value: $result_source
617 An accessor for the primary ResultSource object from which this ResultSet
627 =item Arguments: $cond, \%attrs??
629 =item Return Value: $count
633 Performs an SQL C<COUNT> with the same query as the resultset was built
634 with to find the number of elements. If passed arguments, does a search
635 on the resultset and counts the results of that.
637 Note: When using C<count> with C<group_by>, L<DBIX::Class> emulates C<GROUP BY>
638 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
639 not support C<DISTINCT> with multiple columns. If you are using such a
640 database, you should only use columns from the main table in your C<group_by>
647 return $self->search(@_)->count if @_ and defined $_[0];
648 return scalar @{ $self->get_cache } if $self->get_cache;
650 my $count = $self->_count;
651 return 0 unless $count;
653 $count -= $self->{attrs}{offset} if $self->{attrs}{offset};
654 $count = $self->{attrs}{rows} if
655 $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
659 sub _count { # Separated out so pager can get the full count
661 my $select = { count => '*' };
662 my $attrs = { %{ $self->{attrs} } };
663 if (my $group_by = delete $attrs->{group_by}) {
664 delete $attrs->{having};
665 my @distinct = (ref $group_by ? @$group_by : ($group_by));
666 # todo: try CONCAT for multi-column pk
667 my @pk = $self->result_source->primary_columns;
669 foreach my $column (@distinct) {
670 if ($column =~ qr/^(?:\Q$attrs->{alias}.\E)?$pk[0]$/) {
671 @distinct = ($column);
677 $select = { count => { distinct => \@distinct } };
678 #use Data::Dumper; die Dumper $select;
681 $attrs->{select} = $select;
682 $attrs->{as} = [qw/count/];
684 # offset, order by and page are not needed to count. record_filter is cdbi
685 delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
687 my ($count) = (ref $self)->new($self->result_source, $attrs)->cursor->next;
695 =item Arguments: $sql_fragment, @bind_values
697 =item Return Value: $count
701 Counts the results in a literal query. Equivalent to calling L</search_literal>
702 with the passed arguments, then L</count>.
706 sub count_literal { shift->search_literal(@_)->count; }
712 =item Arguments: none
714 =item Return Value: @objects
718 Returns all elements in the resultset. Called implicitly if the resultset
719 is returned in list context.
725 return @{ $self->get_cache } if $self->get_cache;
729 if (keys %{$self->{collapse}}) {
730 # Using $self->cursor->all is really just an optimisation.
731 # If we're collapsing has_many prefetches it probably makes
732 # very little difference, and this is cleaner than hacking
733 # _construct_object to survive the approach
734 $self->cursor->reset;
735 my @row = $self->cursor->next;
737 push(@obj, $self->_construct_object(@row));
738 @row = (exists $self->{stashed_row}
739 ? @{delete $self->{stashed_row}}
740 : $self->cursor->next);
743 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
746 $self->set_cache(\@obj) if $self->{attrs}{cache};
754 =item Arguments: none
756 =item Return Value: $self
760 Resets the resultset's cursor, so you can iterate through the elements again.
766 $self->{all_cache_position} = 0;
767 $self->cursor->reset;
775 =item Arguments: none
777 =item Return Value: $object?
781 Resets the resultset and returns an object for the first result (if the
782 resultset returns anything).
787 return $_[0]->reset->next;
790 # _cond_for_update_delete
792 # update/delete require the condition to be modified to handle
793 # the differing SQL syntax available. This transforms the $self->{cond}
794 # appropriately, returning the new condition.
796 sub _cond_for_update_delete {
800 if (!ref($self->{cond})) {
801 # No-op. No condition, we're updating/deleting everything
803 elsif (ref $self->{cond} eq 'ARRAY') {
807 foreach my $key (keys %{$_}) {
809 $hash{$1} = $_->{$key};
815 elsif (ref $self->{cond} eq 'HASH') {
816 if ((keys %{$self->{cond}})[0] eq '-and') {
819 my @cond = @{$self->{cond}{-and}};
820 for (my $i = 0; $i < @cond - 1; $i++) {
821 my $entry = $cond[$i];
824 if (ref $entry eq 'HASH') {
825 foreach my $key (keys %{$entry}) {
827 $hash{$1} = $entry->{$key};
831 $entry =~ /([^.]+)$/;
832 $hash{$entry} = $cond[++$i];
835 push @{$cond->{-and}}, \%hash;
839 foreach my $key (keys %{$self->{cond}}) {
841 $cond->{$1} = $self->{cond}{$key};
846 $self->throw_exception(
847 "Can't update/delete on resultset with condition unless hash or array"
859 =item Arguments: \%values
861 =item Return Value: $storage_rv
865 Sets the specified columns in the resultset to the supplied values in a
866 single query. Return value will be true if the update succeeded or false
867 if no records were updated; exact type of success value is storage-dependent.
872 my ($self, $values) = @_;
873 $self->throw_exception("Values for update must be a hash")
874 unless ref $values eq 'HASH';
876 my $cond = $self->_cond_for_update_delete;
878 return $self->result_source->storage->update(
879 $self->result_source->from, $values, $cond
887 =item Arguments: \%values
889 =item Return Value: 1
893 Fetches all objects and updates them one at a time. Note that C<update_all>
894 will run DBIC cascade triggers, while L</update> will not.
899 my ($self, $values) = @_;
900 $self->throw_exception("Values for update must be a hash")
901 unless ref $values eq 'HASH';
902 foreach my $obj ($self->all) {
903 $obj->set_columns($values)->update;
912 =item Arguments: none
914 =item Return Value: 1
918 Deletes the contents of the resultset from its result source. Note that this
919 will not run DBIC cascade triggers. See L</delete_all> if you need triggers
928 my $cond = $self->_cond_for_update_delete;
930 $self->result_source->storage->delete($self->result_source->from, $cond);
938 =item Arguments: none
940 =item Return Value: 1
944 Fetches all objects and deletes them one at a time. Note that C<delete_all>
945 will run DBIC cascade triggers, while L</delete> will not.
951 $_->delete for $self->all;
959 =item Arguments: none
961 =item Return Value: $pager
965 Return Value a L<Data::Page> object for the current resultset. Only makes
966 sense for queries with a C<page> attribute.
972 my $attrs = $self->{attrs};
973 $self->throw_exception("Can't create pager for non-paged rs")
974 unless $self->{page};
975 $attrs->{rows} ||= 10;
976 return $self->{pager} ||= Data::Page->new(
977 $self->_count, $attrs->{rows}, $self->{page});
984 =item Arguments: $page_number
986 =item Return Value: $rs
990 Returns a resultset for the $page_number page of the resultset on which page
991 is called, where each page contains a number of rows equal to the 'rows'
992 attribute set on the resultset (10 by default).
997 my ($self, $page) = @_;
998 my $attrs = { %{$self->{attrs}} };
999 $attrs->{page} = $page;
1000 return (ref $self)->new($self->result_source, $attrs);
1007 =item Arguments: \%vals
1009 =item Return Value: $object
1013 Creates an object in the resultset's result class and returns it.
1018 my ($self, $values) = @_;
1019 $self->throw_exception( "new_result needs a hash" )
1020 unless (ref $values eq 'HASH');
1021 $self->throw_exception(
1022 "Can't abstract implicit construct, condition not a hash"
1023 ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
1025 my $alias = $self->{attrs}{alias};
1026 foreach my $key (keys %{$self->{cond}||{}}) {
1027 $new{$1} = $self->{cond}{$key} if ($key =~ m/^(?:\Q${alias}.\E)?([^.]+)$/);
1029 my $obj = $self->result_class->new(\%new);
1030 $obj->result_source($self->result_source) if $obj->can('result_source');
1038 =item Arguments: \%vals
1040 =item Return Value: $object
1044 Inserts a record into the resultset and returns the object representing it.
1046 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
1051 my ($self, $attrs) = @_;
1052 $self->throw_exception( "create needs a hashref" )
1053 unless ref $attrs eq 'HASH';
1054 return $self->new_result($attrs)->insert;
1057 =head2 find_or_create
1061 =item Arguments: \%vals, \%attrs?
1063 =item Return Value: $object
1067 $class->find_or_create({ key => $val, ... });
1069 Searches for a record matching the search condition; if it doesn't find one,
1070 creates one and returns that instead.
1072 my $cd = $schema->resultset('CD')->find_or_create({
1074 artist => 'Massive Attack',
1075 title => 'Mezzanine',
1079 Also takes an optional C<key> attribute, to search by a specific key or unique
1080 constraint. For example:
1082 my $cd = $schema->resultset('CD')->find_or_create(
1084 artist => 'Massive Attack',
1085 title => 'Mezzanine',
1087 { key => 'artist_title' }
1090 See also L</find> and L</update_or_create>.
1094 sub find_or_create {
1096 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1097 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1098 my $exists = $self->find($hash, $attrs);
1099 return defined $exists ? $exists : $self->create($hash);
1102 =head2 update_or_create
1106 =item Arguments: \%col_values, { key => $unique_constraint }?
1108 =item Return Value: $object
1112 $class->update_or_create({ col => $val, ... });
1114 First, searches for an existing row matching one of the unique constraints
1115 (including the primary key) on the source of this resultset. If a row is
1116 found, updates it with the other given column values. Otherwise, creates a new
1119 Takes an optional C<key> attribute to search on a specific unique constraint.
1122 # In your application
1123 my $cd = $schema->resultset('CD')->update_or_create(
1125 artist => 'Massive Attack',
1126 title => 'Mezzanine',
1129 { key => 'artist_title' }
1132 If no C<key> is specified, it searches on all unique constraints defined on the
1133 source, including the primary key.
1135 If the C<key> is specified as C<primary>, it searches only on the primary key.
1137 See also L</find> and L</find_or_create>.
1141 sub update_or_create {
1143 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1144 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1146 my %unique_constraints = $self->result_source->unique_constraints;
1147 my @constraint_names = (exists $attrs->{key}
1149 : keys %unique_constraints);
1152 foreach my $name (@constraint_names) {
1153 my @unique_cols = @{ $unique_constraints{$name} };
1155 map { $_ => $hash->{$_} }
1156 grep { exists $hash->{$_} }
1159 push @unique_hashes, \%unique_hash
1160 if (scalar keys %unique_hash == scalar @unique_cols);
1163 if (@unique_hashes) {
1164 my $row = $self->single(\@unique_hashes);
1166 $row->update($hash);
1171 return $self->create($hash);
1178 =item Arguments: none
1180 =item Return Value: \@cache_objects?
1184 Gets the contents of the cache for the resultset, if the cache is set.
1196 =item Arguments: \@cache_objects
1198 =item Return Value: \@cache_objects
1202 Sets the contents of the cache for the resultset. Expects an arrayref
1203 of objects of the same class as those produced by the resultset. Note that
1204 if the cache is set the resultset will return the cached objects rather
1205 than re-querying the database even if the cache attr is not set.
1210 my ( $self, $data ) = @_;
1211 $self->throw_exception("set_cache requires an arrayref")
1212 if defined($data) && (ref $data ne 'ARRAY');
1213 $self->{all_cache} = $data;
1220 =item Arguments: none
1222 =item Return Value: []
1226 Clears the cache for the resultset.
1231 shift->set_cache(undef);
1234 =head2 related_resultset
1238 =item Arguments: $relationship_name
1240 =item Return Value: $resultset
1244 Returns a related resultset for the supplied relationship name.
1246 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1250 sub related_resultset {
1251 my ( $self, $rel ) = @_;
1252 $self->{related_resultsets} ||= {};
1253 return $self->{related_resultsets}{$rel} ||= do {
1254 #warn "fetching related resultset for rel '$rel'";
1255 my $rel_obj = $self->result_source->relationship_info($rel);
1256 $self->throw_exception(
1257 "search_related: result source '" . $self->result_source->name .
1258 "' has no such relationship ${rel}")
1259 unless $rel_obj; #die Dumper $self->{attrs};
1261 my $rs = $self->search(undef, { join => $rel });
1262 my $alias = defined $rs->{attrs}{seen_join}{$rel}
1263 && $rs->{attrs}{seen_join}{$rel} > 1
1264 ? join('_', $rel, $rs->{attrs}{seen_join}{$rel})
1267 $self->result_source->schema->resultset($rel_obj->{class}
1277 =head2 throw_exception
1279 See L<DBIx::Class::Schema/throw_exception> for details.
1283 sub throw_exception {
1285 $self->result_source->schema->throw_exception(@_);
1288 # XXX: FIXME: Attributes docs need clearing up
1292 The resultset takes various attributes that modify its behavior. Here's an
1299 =item Value: ($order_by | \@order_by)
1303 Which column(s) to order the results by. This is currently passed
1304 through directly to SQL, so you can give e.g. C<year DESC> for a
1305 descending order on the column `year'.
1311 =item Value: \@columns
1315 Shortcut to request a particular set of columns to be retrieved. Adds
1316 C<me.> onto the start of any column without a C<.> in it and sets C<select>
1317 from that, then auto-populates C<as> from C<select> as normal. (You may also
1318 use the C<cols> attribute, as in earlier versions of DBIC.)
1320 =head2 include_columns
1324 =item Value: \@columns
1328 Shortcut to include additional columns in the returned results - for example
1330 $schema->resultset('CD')->search(undef, {
1331 include_columns => ['artist.name'],
1335 would return all CDs and include a 'name' column to the information
1336 passed to object inflation
1342 =item Value: \@select_columns
1346 Indicates which columns should be selected from the storage. You can use
1347 column names, or in the case of RDBMS back ends, function or stored procedure
1350 $rs = $schema->resultset('Employee')->search(undef, {
1353 { count => 'employeeid' },
1358 When you use function/stored procedure names and do not supply an C<as>
1359 attribute, the column names returned are storage-dependent. E.g. MySQL would
1360 return a column named C<count(employeeid)> in the above example.
1366 =item Value: \@inflation_names
1370 Indicates column names for object inflation. This is used in conjunction with
1371 C<select>, usually when C<select> contains one or more function or stored
1374 $rs = $schema->resultset('Employee')->search(undef, {
1377 { count => 'employeeid' }
1379 as => ['name', 'employee_count'],
1382 my $employee = $rs->first(); # get the first Employee
1384 If the object against which the search is performed already has an accessor
1385 matching a column name specified in C<as>, the value can be retrieved using
1386 the accessor as normal:
1388 my $name = $employee->name();
1390 If on the other hand an accessor does not exist in the object, you need to
1391 use C<get_column> instead:
1393 my $employee_count = $employee->get_column('employee_count');
1395 You can create your own accessors if required - see
1396 L<DBIx::Class::Manual::Cookbook> for details.
1398 Please note: This will NOT insert an C<AS employee_count> into the SQL statement
1399 produced, it is used for internal access only. Thus attempting to use the accessor
1400 in an C<order_by> clause or similar will fail misrably.
1406 =item Value: ($rel_name | \@rel_names | \%rel_names)
1410 Contains a list of relationships that should be joined for this query. For
1413 # Get CDs by Nine Inch Nails
1414 my $rs = $schema->resultset('CD')->search(
1415 { 'artist.name' => 'Nine Inch Nails' },
1416 { join => 'artist' }
1419 Can also contain a hash reference to refer to the other relation's relations.
1422 package MyApp::Schema::Track;
1423 use base qw/DBIx::Class/;
1424 __PACKAGE__->table('track');
1425 __PACKAGE__->add_columns(qw/trackid cd position title/);
1426 __PACKAGE__->set_primary_key('trackid');
1427 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
1430 # In your application
1431 my $rs = $schema->resultset('Artist')->search(
1432 { 'track.title' => 'Teardrop' },
1434 join => { cd => 'track' },
1435 order_by => 'artist.name',
1439 If the same join is supplied twice, it will be aliased to <rel>_2 (and
1440 similarly for a third time). For e.g.
1442 my $rs = $schema->resultset('Artist')->search({
1443 'cds.title' => 'Down to Earth',
1444 'cds_2.title' => 'Popular',
1446 join => [ qw/cds cds/ ],
1449 will return a set of all artists that have both a cd with title 'Down
1450 to Earth' and a cd with title 'Popular'.
1452 If you want to fetch related objects from other tables as well, see C<prefetch>
1459 =item Value: ($rel_name | \@rel_names | \%rel_names)
1463 Contains one or more relationships that should be fetched along with the main
1464 query (when they are accessed afterwards they will have already been
1465 "prefetched"). This is useful for when you know you will need the related
1466 objects, because it saves at least one query:
1468 my $rs = $schema->resultset('Tag')->search(
1477 The initial search results in SQL like the following:
1479 SELECT tag.*, cd.*, artist.* FROM tag
1480 JOIN cd ON tag.cd = cd.cdid
1481 JOIN artist ON cd.artist = artist.artistid
1483 L<DBIx::Class> has no need to go back to the database when we access the
1484 C<cd> or C<artist> relationships, which saves us two SQL statements in this
1487 Simple prefetches will be joined automatically, so there is no need
1488 for a C<join> attribute in the above search. If you're prefetching to
1489 depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
1490 specify the join as well.
1492 C<prefetch> can be used with the following relationship types: C<belongs_to>,
1493 C<has_one> (or if you're using C<add_relationship>, any relationship declared
1494 with an accessor type of 'single' or 'filter').
1504 Makes the resultset paged and specifies the page to retrieve. Effectively
1505 identical to creating a non-pages resultset and then calling ->page($page)
1516 Specifes the maximum number of rows for direct retrieval or the number of
1517 rows per page if the page attribute or method is used.
1523 =item Value: \@columns
1527 A arrayref of columns to group by. Can include columns of joined tables.
1529 group_by => [qw/ column1 column2 ... /]
1535 =item Value: $condition
1539 HAVING is a select statement attribute that is applied between GROUP BY and
1540 ORDER BY. It is applied to the after the grouping calculations have been
1543 having => { 'count(employee)' => { '>=', 100 } }
1549 =item Value: (0 | 1)
1553 Set to 1 to group by all columns.
1557 Set to 1 to cache search results. This prevents extra SQL queries if you
1558 revisit rows in your ResultSet:
1560 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
1562 while( my $artist = $resultset->next ) {
1566 $rs->first; # without cache, this would issue a query
1568 By default, searches are not cached.
1570 For more examples of using these attributes, see
1571 L<DBIx::Class::Manual::Cookbook>.
1577 =item Value: \@from_clause
1581 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
1582 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
1585 NOTE: Use this on your own risk. This allows you to shoot off your foot!
1587 C<join> will usually do what you need and it is strongly recommended that you
1588 avoid using C<from> unless you cannot achieve the desired result using C<join>.
1589 And we really do mean "cannot", not just tried and failed. Attempting to use
1590 this because you're having problems with C<join> is like trying to use x86
1591 ASM because you've got a syntax error in your C. Trust us on this.
1593 Now, if you're still really, really sure you need to use this (and if you're
1594 not 100% sure, ask the mailing list first), here's an explanation of how this
1597 The syntax is as follows -
1600 { <alias1> => <table1> },
1602 { <alias2> => <table2>, -join_type => 'inner|left|right' },
1603 [], # nested JOIN (optional)
1604 { <table1.column1> => <table2.column2>, ... (more conditions) },
1606 # More of the above [ ] may follow for additional joins
1613 ON <table1.column1> = <table2.column2>
1614 <more joins may follow>
1616 An easy way to follow the examples below is to remember the following:
1618 Anything inside "[]" is a JOIN
1619 Anything inside "{}" is a condition for the enclosing JOIN
1621 The following examples utilize a "person" table in a family tree application.
1622 In order to express parent->child relationships, this table is self-joined:
1624 # Person->belongs_to('father' => 'Person');
1625 # Person->belongs_to('mother' => 'Person');
1627 C<from> can be used to nest joins. Here we return all children with a father,
1628 then search against all mothers of those children:
1630 $rs = $schema->resultset('Person')->search(
1633 alias => 'mother', # alias columns in accordance with "from"
1635 { mother => 'person' },
1638 { child => 'person' },
1640 { father => 'person' },
1641 { 'father.person_id' => 'child.father_id' }
1644 { 'mother.person_id' => 'child.mother_id' }
1651 # SELECT mother.* FROM person mother
1654 # JOIN person father
1655 # ON ( father.person_id = child.father_id )
1657 # ON ( mother.person_id = child.mother_id )
1659 The type of any join can be controlled manually. To search against only people
1660 with a father in the person table, we could explicitly use C<INNER JOIN>:
1662 $rs = $schema->resultset('Person')->search(
1665 alias => 'child', # alias columns in accordance with "from"
1667 { child => 'person' },
1669 { father => 'person', -join_type => 'inner' },
1670 { 'father.id' => 'child.father_id' }
1677 # SELECT child.* FROM person child
1678 # INNER JOIN person father ON child.father_id = father.id