1 package DBIx::Class::ResultSet;
11 use Scalar::Util qw/weaken/;
13 use DBIx::Class::ResultSetColumn;
14 use base qw/DBIx::Class/;
15 __PACKAGE__->load_components(qw/AccessorGroup/);
16 __PACKAGE__->mk_group_accessors('simple' => qw/result_source result_class/);
20 DBIx::Class::ResultSet - Responsible for fetching and creating resultset.
24 my $rs = $schema->resultset('User')->search(registered => 1);
25 my @rows = $schema->resultset('CD')->search(year => 2005);
29 The resultset is also known as an iterator. It is responsible for handling
30 queries that may return an arbitrary number of rows, e.g. via L</search>
31 or a C<has_many> relationship.
33 In the examples below, the following table classes are used:
35 package MyApp::Schema::Artist;
36 use base qw/DBIx::Class/;
37 __PACKAGE__->load_components(qw/Core/);
38 __PACKAGE__->table('artist');
39 __PACKAGE__->add_columns(qw/artistid name/);
40 __PACKAGE__->set_primary_key('artistid');
41 __PACKAGE__->has_many(cds => 'MyApp::Schema::CD');
44 package MyApp::Schema::CD;
45 use base qw/DBIx::Class/;
46 __PACKAGE__->load_components(qw/Core/);
47 __PACKAGE__->table('cd');
48 __PACKAGE__->add_columns(qw/cdid artist title year/);
49 __PACKAGE__->set_primary_key('cdid');
50 __PACKAGE__->belongs_to(artist => 'MyApp::Schema::Artist');
59 =item Arguments: $source, \%$attrs
61 =item Return Value: $rs
65 The resultset constructor. Takes a source object (usually a
66 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
67 L</ATTRIBUTES> below). Does not perform any queries -- these are
68 executed as needed by the other methods.
70 Generally you won't need to construct a resultset manually. You'll
71 automatically get one from e.g. a L</search> called in scalar context:
73 my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
75 IMPORTANT: If called on an object, proxies to new_result instead so
77 my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
79 will return a CD object, not a ResultSet.
85 return $class->new_result(@_) if ref $class;
87 my ($source, $attrs) = @_;
89 $attrs = Storable::dclone($attrs || {}); # { %{ $attrs || {} } };
90 #use Data::Dumper; warn Dumper($attrs);
91 my $alias = ($attrs->{alias} ||= 'me');
93 $attrs->{columns} ||= delete $attrs->{cols} if $attrs->{cols};
94 delete $attrs->{as} if $attrs->{columns};
95 $attrs->{columns} ||= [ $source->columns ] unless $attrs->{select};
97 map { m/\./ ? $_ : "${alias}.$_" } @{delete $attrs->{columns}}
98 ] if $attrs->{columns};
100 map { m/^\Q$alias.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}}
102 if (my $include = delete $attrs->{include_columns}) {
103 push(@{$attrs->{select}}, @$include);
104 push(@{$attrs->{as}}, map { m/([^.]+)$/; $1; } @$include);
106 #use Data::Dumper; warn Dumper(@{$attrs}{qw/select as/});
108 $attrs->{from} ||= [ { $alias => $source->from } ];
109 $attrs->{seen_join} ||= {};
111 if (my $join = delete $attrs->{join}) {
112 foreach my $j (ref $join eq 'ARRAY' ? @$join : ($join)) {
113 if (ref $j eq 'HASH') {
114 $seen{$_} = 1 foreach keys %$j;
119 push(@{$attrs->{from}}, $source->resolve_join(
120 $join, $attrs->{alias}, $attrs->{seen_join})
124 $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
125 $attrs->{order_by} = [ $attrs->{order_by} ] if
126 $attrs->{order_by} and !ref($attrs->{order_by});
127 $attrs->{order_by} ||= [];
129 my $collapse = $attrs->{collapse} || {};
130 if (my $prefetch = delete $attrs->{prefetch}) {
132 foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
133 if ( ref $p eq 'HASH' ) {
134 foreach my $key (keys %$p) {
135 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
139 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
142 my @prefetch = $source->resolve_prefetch(
143 $p, $attrs->{alias}, {}, \@pre_order, $collapse);
144 push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
145 push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
147 push(@{$attrs->{order_by}}, @pre_order);
149 $attrs->{collapse} = $collapse;
150 # use Data::Dumper; warn Dumper($collapse) if keys %{$collapse};
152 if ($attrs->{page}) {
153 $attrs->{rows} ||= 10;
154 $attrs->{offset} ||= 0;
155 $attrs->{offset} += ($attrs->{rows} * ($attrs->{page} - 1));
159 result_source => $source,
160 result_class => $attrs->{result_class} || $source->result_class,
161 cond => $attrs->{where},
162 from => $attrs->{from},
163 collapse => $collapse,
165 page => delete $attrs->{page},
175 =item Arguments: $cond, \%attrs?
177 =item Return Value: $resultset (scalar context), @row_objs (list context)
181 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
182 my $new_rs = $cd_rs->search({ year => 2005 });
184 my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
185 # year = 2005 OR year = 2004
187 If you need to pass in additional attributes but no additional condition,
188 call it as C<search(undef, \%attrs)>.
190 # "SELECT name, artistid FROM $artist_table"
191 my @all_artists = $schema->resultset('Artist')->search(undef, {
192 columns => [qw/name artistid/],
200 my $attrs = { %{$self->{attrs}} };
201 my $having = delete $attrs->{having};
202 $attrs = { %$attrs, %{ pop(@_) } } if @_ > 1 and ref $_[$#_] eq 'HASH';
205 ? ((@_ == 1 || ref $_[0] eq "HASH")
208 ? $self->throw_exception(
209 "Odd number of arguments to search")
212 if (defined $where) {
213 $attrs->{where} = (defined $attrs->{where}
215 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
216 $where, $attrs->{where} ] }
220 if (defined $having) {
221 $attrs->{having} = (defined $attrs->{having}
223 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
224 $having, $attrs->{having} ] }
228 my $rs = (ref $self)->new($self->result_source, $attrs);
230 my $rows = $self->get_cache;
232 $rs->set_cache($rows);
235 return (wantarray ? $rs->all : $rs);
238 =head2 search_literal
242 =item Arguments: $sql_fragment, @bind_values
244 =item Return Value: $resultset (scalar context), @row_objs (list context)
248 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
249 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
251 Pass a literal chunk of SQL to be added to the conditional part of the
257 my ($self, $cond, @vals) = @_;
258 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
259 $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
260 return $self->search(\$cond, $attrs);
267 =item Arguments: @values | \%cols, \%attrs?
269 =item Return Value: $row_object
273 Finds a row based on its primary key or unique constraint. For example, to find
274 a row by its primary key:
276 my $cd = $schema->resultset('CD')->find(5);
278 You can also find a row by a specific unique constraint using the C<key>
279 attribute. For example:
281 my $cd = $schema->resultset('CD')->find('Massive Attack', 'Mezzanine', { key => 'artist_title' });
283 Additionally, you can specify the columns explicitly by name:
285 my $cd = $schema->resultset('CD')->find(
287 artist => 'Massive Attack',
288 title => 'Mezzanine',
290 { key => 'artist_title' }
293 If no C<key> is specified and you explicitly name columns, it searches on all
294 unique constraints defined on the source, including the primary key.
296 If the C<key> is specified as C<primary>, it searches only on the primary key.
298 See also L</find_or_create> and L</update_or_create>. For information on how to
299 declare unique constraints, see
300 L<DBIx::Class::ResultSource/add_unique_constraint>.
306 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
308 # Parse out a hash from input
309 my @cols = exists $attrs->{key}
310 ? $self->result_source->unique_constraint_columns($attrs->{key})
311 : $self->result_source->primary_columns;
314 if (ref $_[0] eq 'HASH') {
315 $hash = { %{$_[0]} };
317 elsif (@_ == @cols) {
319 @{$hash}{@cols} = @_;
322 $self->throw_exception(
323 "Arguments to find must be a hashref or match the number of columns in the "
324 . exists $attrs->{key} ? "$attrs->{key} unique constraint" : "primary key"
328 # Check the hash we just parsed against our source's unique constraints
329 my @constraint_names = exists $attrs->{key}
331 : $self->result_source->unique_constraint_names;
332 $self->throw_exception(
333 "Can't find unless a primary key or unique constraint is defined"
334 ) unless @constraint_names;
337 foreach my $name (@constraint_names) {
338 my @unique_cols = $self->result_source->unique_constraint_columns($name);
339 my $unique_query = $self->_build_unique_query($hash, \@unique_cols);
341 # Add the ResultSet's alias
342 foreach my $key (grep { ! m/\./ } keys %$unique_query) {
343 $unique_query->{"$self->{attrs}{alias}.$key"} = delete $unique_query->{$key};
346 push @unique_queries, $unique_query if %$unique_query;
349 # Handle cases where the ResultSet already defines the query
350 my $query = @unique_queries ? \@unique_queries : undef;
354 my $rs = $self->search($query, $attrs);
355 return keys %{$rs->{collapse}} ? $rs->next : $rs->single;
358 return keys %{$self->{collapse}}
359 ? $self->search($query)->next
360 : $self->single($query);
364 # _build_unique_query
366 # Constrain the specified query hash based on the specified column names.
368 sub _build_unique_query {
369 my ($self, $query, $unique_cols) = @_;
372 map { $_ => $query->{$_} }
373 grep { exists $query->{$_} }
376 return \%unique_query;
379 =head2 search_related
383 =item Arguments: $cond, \%attrs?
385 =item Return Value: $new_resultset
389 $new_rs = $cd_rs->search_related('artist', {
393 Searches the specified relationship, optionally specifying a condition and
394 attributes for matching records. See L</ATTRIBUTES> for more information.
399 return shift->related_resultset(shift)->search(@_);
406 =item Arguments: none
408 =item Return Value: $cursor
412 Returns a storage-driven cursor to the given resultset. See
413 L<DBIx::Class::Cursor> for more information.
419 my $attrs = { %{$self->{attrs}} };
420 return $self->{cursor}
421 ||= $self->result_source->storage->select($self->{from}, $attrs->{select},
422 $attrs->{where},$attrs);
429 =item Arguments: $cond?
431 =item Return Value: $row_object?
435 my $cd = $schema->resultset('CD')->single({ year => 2001 });
437 Inflates the first result without creating a cursor if the resultset has
438 any records in it; if not returns nothing. Used by L</find> as an optimisation.
443 my ($self, $where) = @_;
444 my $attrs = { %{$self->{attrs}} };
446 if (defined $attrs->{where}) {
449 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
450 $where, delete $attrs->{where} ]
453 $attrs->{where} = $where;
456 my @data = $self->result_source->storage->select_single(
457 $self->{from}, $attrs->{select},
458 $attrs->{where},$attrs);
459 return (@data ? $self->_construct_object(@data) : ());
466 =item Arguments: $cond?
468 =item Return Value: $resultsetcolumn
472 my $max_length = $rs->get_column('length')->max;
474 Returns a ResultSetColumn instance for $column based on $self
479 my ($self, $column) = @_;
481 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
489 =item Arguments: $cond, \%attrs?
491 =item Return Value: $resultset (scalar context), @row_objs (list context)
495 # WHERE title LIKE '%blue%'
496 $cd_rs = $rs->search_like({ title => '%blue%'});
498 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
499 that this is simply a convenience method. You most likely want to use
500 L</search> with specific operators.
502 For more information, see L<DBIx::Class::Manual::Cookbook>.
508 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
509 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
510 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
511 return $class->search($query, { %$attrs });
518 =item Arguments: $first, $last
520 =item Return Value: $resultset (scalar context), @row_objs (list context)
524 Returns a resultset or object list representing a subset of elements from the
525 resultset slice is called on. Indexes are from 0, i.e., to get the first
528 my ($one, $two, $three) = $rs->slice(0, 2);
533 my ($self, $min, $max) = @_;
534 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
535 $attrs->{offset} = $self->{attrs}{offset} || 0;
536 $attrs->{offset} += $min;
537 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
538 return $self->search(undef(), $attrs);
539 #my $slice = (ref $self)->new($self->result_source, $attrs);
540 #return (wantarray ? $slice->all : $slice);
547 =item Arguments: none
549 =item Return Value: $result?
553 Returns the next element in the resultset (C<undef> is there is none).
555 Can be used to efficiently iterate over records in the resultset:
557 my $rs = $schema->resultset('CD')->search;
558 while (my $cd = $rs->next) {
562 Note that you need to store the resultset object, and call C<next> on it.
563 Calling C<< resultset('Table')->next >> repeatedly will always return the
564 first record from the resultset.
570 if (@{$self->{all_cache} || []}) {
571 $self->{all_cache_position} ||= 0;
572 return $self->{all_cache}->[$self->{all_cache_position}++];
574 if ($self->{attrs}{cache}) {
575 $self->{all_cache_position} = 1;
576 return ($self->all)[0];
578 my @row = (exists $self->{stashed_row} ?
579 @{delete $self->{stashed_row}} :
582 # warn Dumper(\@row); use Data::Dumper;
583 return unless (@row);
584 return $self->_construct_object(@row);
587 sub _construct_object {
588 my ($self, @row) = @_;
589 my @as = @{ $self->{attrs}{as} };
591 my $info = $self->_collapse_result(\@as, \@row);
593 my $new = $self->result_class->inflate_result($self->result_source, @$info);
595 $new = $self->{attrs}{record_filter}->($new)
596 if exists $self->{attrs}{record_filter};
600 sub _collapse_result {
601 my ($self, $as, $row, $prefix) = @_;
606 foreach my $this_as (@$as) {
607 my $val = shift @copy;
608 if (defined $prefix) {
609 if ($this_as =~ m/^\Q${prefix}.\E(.+)$/) {
611 $remain =~ /^(?:(.*)\.)?([^.]+)$/;
612 $const{$1||''}{$2} = $val;
615 $this_as =~ /^(?:(.*)\.)?([^.]+)$/;
616 $const{$1||''}{$2} = $val;
620 my $info = [ {}, {} ];
621 foreach my $key (keys %const) {
624 my @parts = split(/\./, $key);
625 foreach my $p (@parts) {
626 $target = $target->[1]->{$p} ||= [];
628 $target->[0] = $const{$key};
630 $info->[0] = $const{$key};
635 if (defined $prefix) {
637 m/^\Q${prefix}.\E(.+)$/ ? ($1) : ()
638 } keys %{$self->{collapse}}
640 @collapse = keys %{$self->{collapse}};
644 my ($c) = sort { length $a <=> length $b } @collapse;
646 foreach my $p (split(/\./, $c)) {
647 $target = $target->[1]->{$p} ||= [];
649 my $c_prefix = (defined($prefix) ? "${prefix}.${c}" : $c);
650 my @co_key = @{$self->{collapse}{$c_prefix}};
651 my %co_check = map { ($_, $target->[0]->{$_}); } @co_key;
652 my $tree = $self->_collapse_result($as, $row, $c_prefix);
655 !defined($tree->[0]->{$_}) ||
656 $co_check{$_} ne $tree->[0]->{$_}
659 last unless (@raw = $self->cursor->next);
660 $row = $self->{stashed_row} = \@raw;
661 $tree = $self->_collapse_result($as, $row, $c_prefix);
662 #warn Data::Dumper::Dumper($tree, $row);
674 =item Arguments: $result_source?
676 =item Return Value: $result_source
680 An accessor for the primary ResultSource object from which this ResultSet
690 =item Arguments: $cond, \%attrs??
692 =item Return Value: $count
696 Performs an SQL C<COUNT> with the same query as the resultset was built
697 with to find the number of elements. If passed arguments, does a search
698 on the resultset and counts the results of that.
700 Note: When using C<count> with C<group_by>, L<DBIX::Class> emulates C<GROUP BY>
701 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
702 not support C<DISTINCT> with multiple columns. If you are using such a
703 database, you should only use columns from the main table in your C<group_by>
710 return $self->search(@_)->count if @_ and defined $_[0];
711 return scalar @{ $self->get_cache } if @{ $self->get_cache };
713 my $count = $self->_count;
714 return 0 unless $count;
716 $count -= $self->{attrs}{offset} if $self->{attrs}{offset};
717 $count = $self->{attrs}{rows} if
718 $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
722 sub _count { # Separated out so pager can get the full count
724 my $select = { count => '*' };
725 my $attrs = { %{ $self->{attrs} } };
726 if (my $group_by = delete $attrs->{group_by}) {
727 delete $attrs->{having};
728 my @distinct = (ref $group_by ? @$group_by : ($group_by));
729 # todo: try CONCAT for multi-column pk
730 my @pk = $self->result_source->primary_columns;
732 foreach my $column (@distinct) {
733 if ($column =~ qr/^(?:\Q$attrs->{alias}.\E)?$pk[0]$/) {
734 @distinct = ($column);
740 $select = { count => { distinct => \@distinct } };
741 #use Data::Dumper; die Dumper $select;
744 $attrs->{select} = $select;
745 $attrs->{as} = [qw/count/];
747 # offset, order by and page are not needed to count. record_filter is cdbi
748 delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
750 my ($count) = (ref $self)->new($self->result_source, $attrs)->cursor->next;
758 =item Arguments: $sql_fragment, @bind_values
760 =item Return Value: $count
764 Counts the results in a literal query. Equivalent to calling L</search_literal>
765 with the passed arguments, then L</count>.
769 sub count_literal { shift->search_literal(@_)->count; }
775 =item Arguments: none
777 =item Return Value: @objects
781 Returns all elements in the resultset. Called implicitly if the resultset
782 is returned in list context.
788 return @{ $self->get_cache } if @{ $self->get_cache };
792 if (keys %{$self->{collapse}}) {
793 # Using $self->cursor->all is really just an optimisation.
794 # If we're collapsing has_many prefetches it probably makes
795 # very little difference, and this is cleaner than hacking
796 # _construct_object to survive the approach
797 $self->cursor->reset;
798 my @row = $self->cursor->next;
800 push(@obj, $self->_construct_object(@row));
801 @row = (exists $self->{stashed_row}
802 ? @{delete $self->{stashed_row}}
803 : $self->cursor->next);
806 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
809 $self->set_cache(\@obj) if $self->{attrs}{cache};
817 =item Arguments: none
819 =item Return Value: $self
823 Resets the resultset's cursor, so you can iterate through the elements again.
829 $self->{all_cache_position} = 0;
830 $self->cursor->reset;
838 =item Arguments: none
840 =item Return Value: $object?
844 Resets the resultset and returns an object for the first result (if the
845 resultset returns anything).
850 return $_[0]->reset->next;
853 # _cond_for_update_delete
855 # update/delete require the condition to be modified to handle
856 # the differing SQL syntax available. This transforms the $self->{cond}
857 # appropriately, returning the new condition.
859 sub _cond_for_update_delete {
863 if (!ref($self->{cond})) {
864 # No-op. No condition, we're updating/deleting everything
866 elsif (ref $self->{cond} eq 'ARRAY') {
870 foreach my $key (keys %{$_}) {
872 $hash{$1} = $_->{$key};
878 elsif (ref $self->{cond} eq 'HASH') {
879 if ((keys %{$self->{cond}})[0] eq '-and') {
882 my @cond = @{$self->{cond}{-and}};
883 for (my $i = 0; $i < @cond - 1; $i++) {
884 my $entry = $cond[$i];
887 if (ref $entry eq 'HASH') {
888 foreach my $key (keys %{$entry}) {
890 $hash{$1} = $entry->{$key};
894 $entry =~ /([^.]+)$/;
895 $hash{$entry} = $cond[++$i];
898 push @{$cond->{-and}}, \%hash;
902 foreach my $key (keys %{$self->{cond}}) {
904 $cond->{$1} = $self->{cond}{$key};
909 $self->throw_exception(
910 "Can't update/delete on resultset with condition unless hash or array"
922 =item Arguments: \%values
924 =item Return Value: $storage_rv
928 Sets the specified columns in the resultset to the supplied values in a
929 single query. Return value will be true if the update succeeded or false
930 if no records were updated; exact type of success value is storage-dependent.
935 my ($self, $values) = @_;
936 $self->throw_exception("Values for update must be a hash")
937 unless ref $values eq 'HASH';
939 my $cond = $self->_cond_for_update_delete;
941 return $self->result_source->storage->update(
942 $self->result_source->from, $values, $cond
950 =item Arguments: \%values
952 =item Return Value: 1
956 Fetches all objects and updates them one at a time. Note that C<update_all>
957 will run DBIC cascade triggers, while L</update> will not.
962 my ($self, $values) = @_;
963 $self->throw_exception("Values for update must be a hash")
964 unless ref $values eq 'HASH';
965 foreach my $obj ($self->all) {
966 $obj->set_columns($values)->update;
975 =item Arguments: none
977 =item Return Value: 1
981 Deletes the contents of the resultset from its result source. Note that this
982 will not run DBIC cascade triggers. See L</delete_all> if you need triggers
991 my $cond = $self->_cond_for_update_delete;
993 $self->result_source->storage->delete($self->result_source->from, $cond);
1001 =item Arguments: none
1003 =item Return Value: 1
1007 Fetches all objects and deletes them one at a time. Note that C<delete_all>
1008 will run DBIC cascade triggers, while L</delete> will not.
1014 $_->delete for $self->all;
1022 =item Arguments: none
1024 =item Return Value: $pager
1028 Return Value a L<Data::Page> object for the current resultset. Only makes
1029 sense for queries with a C<page> attribute.
1035 my $attrs = $self->{attrs};
1036 $self->throw_exception("Can't create pager for non-paged rs")
1037 unless $self->{page};
1038 $attrs->{rows} ||= 10;
1039 return $self->{pager} ||= Data::Page->new(
1040 $self->_count, $attrs->{rows}, $self->{page});
1047 =item Arguments: $page_number
1049 =item Return Value: $rs
1053 Returns a resultset for the $page_number page of the resultset on which page
1054 is called, where each page contains a number of rows equal to the 'rows'
1055 attribute set on the resultset (10 by default).
1060 my ($self, $page) = @_;
1061 my $attrs = { %{$self->{attrs}} };
1062 $attrs->{page} = $page;
1063 return (ref $self)->new($self->result_source, $attrs);
1070 =item Arguments: \%vals
1072 =item Return Value: $object
1076 Creates an object in the resultset's result class and returns it.
1081 my ($self, $values) = @_;
1082 $self->throw_exception( "new_result needs a hash" )
1083 unless (ref $values eq 'HASH');
1084 $self->throw_exception(
1085 "Can't abstract implicit construct, condition not a hash"
1086 ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
1088 my $alias = $self->{attrs}{alias};
1089 foreach my $key (keys %{$self->{cond}||{}}) {
1090 $new{$1} = $self->{cond}{$key} if ($key =~ m/^(?:\Q${alias}.\E)?([^.]+)$/);
1092 my $obj = $self->result_class->new(\%new);
1093 $obj->result_source($self->result_source) if $obj->can('result_source');
1101 =item Arguments: \%vals, \%attrs?
1103 =item Return Value: $object
1107 Find an existing record from this resultset. If none exists, instantiate a new
1108 result object and return it. The object will not be saved into your storage
1109 until you call L<DBIx::Class::Row/insert> on it.
1111 If you want objects to be saved immediately, use L</find_or_create> instead.
1117 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1118 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1119 my $exists = $self->find($hash, $attrs);
1120 return defined $exists ? $exists : $self->new_result($hash);
1127 =item Arguments: \%vals
1129 =item Return Value: $object
1133 Inserts a record into the resultset and returns the object representing it.
1135 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
1140 my ($self, $attrs) = @_;
1141 $self->throw_exception( "create needs a hashref" )
1142 unless ref $attrs eq 'HASH';
1143 return $self->new_result($attrs)->insert;
1146 =head2 find_or_create
1150 =item Arguments: \%vals, \%attrs?
1152 =item Return Value: $object
1156 $class->find_or_create({ key => $val, ... });
1158 Searches for a record matching the search condition; if it doesn't find one,
1159 creates one and returns that instead.
1161 my $cd = $schema->resultset('CD')->find_or_create({
1163 artist => 'Massive Attack',
1164 title => 'Mezzanine',
1168 Also takes an optional C<key> attribute, to search by a specific key or unique
1169 constraint. For example:
1171 my $cd = $schema->resultset('CD')->find_or_create(
1173 artist => 'Massive Attack',
1174 title => 'Mezzanine',
1176 { key => 'artist_title' }
1179 See also L</find> and L</update_or_create>. For information on how to declare
1180 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1184 sub find_or_create {
1186 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1187 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1188 my $exists = $self->find($hash, $attrs);
1189 return defined $exists ? $exists : $self->create($hash);
1192 =head2 update_or_create
1196 =item Arguments: \%col_values, { key => $unique_constraint }?
1198 =item Return Value: $object
1202 $class->update_or_create({ col => $val, ... });
1204 First, searches for an existing row matching one of the unique constraints
1205 (including the primary key) on the source of this resultset. If a row is
1206 found, updates it with the other given column values. Otherwise, creates a new
1209 Takes an optional C<key> attribute to search on a specific unique constraint.
1212 # In your application
1213 my $cd = $schema->resultset('CD')->update_or_create(
1215 artist => 'Massive Attack',
1216 title => 'Mezzanine',
1219 { key => 'artist_title' }
1222 If no C<key> is specified, it searches on all unique constraints defined on the
1223 source, including the primary key.
1225 If the C<key> is specified as C<primary>, it searches only on the primary key.
1227 See also L</find> and L</find_or_create>. For information on how to declare
1228 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1232 sub update_or_create {
1234 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1235 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1237 my $row = $self->find($hash, $attrs);
1239 $row->set_columns($hash);
1244 return $self->create($hash);
1251 =item Arguments: none
1253 =item Return Value: \@cache_objects?
1257 Gets the contents of the cache for the resultset, if the cache is set.
1262 shift->{all_cache} || [];
1269 =item Arguments: \@cache_objects
1271 =item Return Value: \@cache_objects
1275 Sets the contents of the cache for the resultset. Expects an arrayref
1276 of objects of the same class as those produced by the resultset. Note that
1277 if the cache is set the resultset will return the cached objects rather
1278 than re-querying the database even if the cache attr is not set.
1283 my ( $self, $data ) = @_;
1284 $self->throw_exception("set_cache requires an arrayref")
1285 if ref $data ne 'ARRAY';
1286 my $result_class = $self->result_class;
1288 $self->throw_exception(
1289 "cannot cache object of type '$_', expected '$result_class'"
1290 ) if ref $_ ne $result_class;
1292 $self->{all_cache} = $data;
1299 =item Arguments: none
1301 =item Return Value: []
1305 Clears the cache for the resultset.
1310 shift->set_cache([]);
1313 =head2 related_resultset
1317 =item Arguments: $relationship_name
1319 =item Return Value: $resultset
1323 Returns a related resultset for the supplied relationship name.
1325 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1329 sub related_resultset {
1330 my ( $self, $rel ) = @_;
1331 $self->{related_resultsets} ||= {};
1332 return $self->{related_resultsets}{$rel} ||= do {
1333 #warn "fetching related resultset for rel '$rel'";
1334 my $rel_obj = $self->result_source->relationship_info($rel);
1335 $self->throw_exception(
1336 "search_related: result source '" . $self->result_source->name .
1337 "' has no such relationship ${rel}")
1338 unless $rel_obj; #die Dumper $self->{attrs};
1340 my $rs = $self->search(undef, { join => $rel });
1341 my $alias = defined $rs->{attrs}{seen_join}{$rel}
1342 && $rs->{attrs}{seen_join}{$rel} > 1
1343 ? join('_', $rel, $rs->{attrs}{seen_join}{$rel})
1346 $self->result_source->schema->resultset($rel_obj->{class}
1356 =head2 throw_exception
1358 See L<DBIx::Class::Schema/throw_exception> for details.
1362 sub throw_exception {
1364 $self->result_source->schema->throw_exception(@_);
1367 # XXX: FIXME: Attributes docs need clearing up
1371 The resultset takes various attributes that modify its behavior. Here's an
1378 =item Value: ($order_by | \@order_by)
1382 Which column(s) to order the results by. This is currently passed
1383 through directly to SQL, so you can give e.g. C<year DESC> for a
1384 descending order on the column `year'.
1390 =item Value: \@columns
1394 Shortcut to request a particular set of columns to be retrieved. Adds
1395 C<me.> onto the start of any column without a C<.> in it and sets C<select>
1396 from that, then auto-populates C<as> from C<select> as normal. (You may also
1397 use the C<cols> attribute, as in earlier versions of DBIC.)
1399 =head2 include_columns
1403 =item Value: \@columns
1407 Shortcut to include additional columns in the returned results - for example
1409 $schema->resultset('CD')->search(undef, {
1410 include_columns => ['artist.name'],
1414 would return all CDs and include a 'name' column to the information
1415 passed to object inflation
1421 =item Value: \@select_columns
1425 Indicates which columns should be selected from the storage. You can use
1426 column names, or in the case of RDBMS back ends, function or stored procedure
1429 $rs = $schema->resultset('Employee')->search(undef, {
1432 { count => 'employeeid' },
1437 When you use function/stored procedure names and do not supply an C<as>
1438 attribute, the column names returned are storage-dependent. E.g. MySQL would
1439 return a column named C<count(employeeid)> in the above example.
1445 =item Value: \@inflation_names
1449 Indicates column names for object inflation. This is used in conjunction with
1450 C<select>, usually when C<select> contains one or more function or stored
1453 $rs = $schema->resultset('Employee')->search(undef, {
1456 { count => 'employeeid' }
1458 as => ['name', 'employee_count'],
1461 my $employee = $rs->first(); # get the first Employee
1463 If the object against which the search is performed already has an accessor
1464 matching a column name specified in C<as>, the value can be retrieved using
1465 the accessor as normal:
1467 my $name = $employee->name();
1469 If on the other hand an accessor does not exist in the object, you need to
1470 use C<get_column> instead:
1472 my $employee_count = $employee->get_column('employee_count');
1474 You can create your own accessors if required - see
1475 L<DBIx::Class::Manual::Cookbook> for details.
1481 =item Value: ($rel_name | \@rel_names | \%rel_names)
1485 Contains a list of relationships that should be joined for this query. For
1488 # Get CDs by Nine Inch Nails
1489 my $rs = $schema->resultset('CD')->search(
1490 { 'artist.name' => 'Nine Inch Nails' },
1491 { join => 'artist' }
1494 Can also contain a hash reference to refer to the other relation's relations.
1497 package MyApp::Schema::Track;
1498 use base qw/DBIx::Class/;
1499 __PACKAGE__->table('track');
1500 __PACKAGE__->add_columns(qw/trackid cd position title/);
1501 __PACKAGE__->set_primary_key('trackid');
1502 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
1505 # In your application
1506 my $rs = $schema->resultset('Artist')->search(
1507 { 'track.title' => 'Teardrop' },
1509 join => { cd => 'track' },
1510 order_by => 'artist.name',
1514 If the same join is supplied twice, it will be aliased to <rel>_2 (and
1515 similarly for a third time). For e.g.
1517 my $rs = $schema->resultset('Artist')->search({
1518 'cds.title' => 'Down to Earth',
1519 'cds_2.title' => 'Popular',
1521 join => [ qw/cds cds/ ],
1524 will return a set of all artists that have both a cd with title 'Down
1525 to Earth' and a cd with title 'Popular'.
1527 If you want to fetch related objects from other tables as well, see C<prefetch>
1534 =item Value: ($rel_name | \@rel_names | \%rel_names)
1538 Contains one or more relationships that should be fetched along with the main
1539 query (when they are accessed afterwards they will have already been
1540 "prefetched"). This is useful for when you know you will need the related
1541 objects, because it saves at least one query:
1543 my $rs = $schema->resultset('Tag')->search(
1552 The initial search results in SQL like the following:
1554 SELECT tag.*, cd.*, artist.* FROM tag
1555 JOIN cd ON tag.cd = cd.cdid
1556 JOIN artist ON cd.artist = artist.artistid
1558 L<DBIx::Class> has no need to go back to the database when we access the
1559 C<cd> or C<artist> relationships, which saves us two SQL statements in this
1562 Simple prefetches will be joined automatically, so there is no need
1563 for a C<join> attribute in the above search. If you're prefetching to
1564 depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
1565 specify the join as well.
1567 C<prefetch> can be used with the following relationship types: C<belongs_to>,
1568 C<has_one> (or if you're using C<add_relationship>, any relationship declared
1569 with an accessor type of 'single' or 'filter').
1575 =item Value: \@from_clause
1579 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
1580 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
1583 NOTE: Use this on your own risk. This allows you to shoot off your foot!
1584 C<join> will usually do what you need and it is strongly recommended that you
1585 avoid using C<from> unless you cannot achieve the desired result using C<join>.
1587 In simple terms, C<from> works as follows:
1590 { <alias> => <table>, -join_type => 'inner|left|right' }
1591 [] # nested JOIN (optional)
1592 { <table.column> => <foreign_table.foreign_key> }
1598 ON <table.column> = <foreign_table.foreign_key>
1600 An easy way to follow the examples below is to remember the following:
1602 Anything inside "[]" is a JOIN
1603 Anything inside "{}" is a condition for the enclosing JOIN
1605 The following examples utilize a "person" table in a family tree application.
1606 In order to express parent->child relationships, this table is self-joined:
1608 # Person->belongs_to('father' => 'Person');
1609 # Person->belongs_to('mother' => 'Person');
1611 C<from> can be used to nest joins. Here we return all children with a father,
1612 then search against all mothers of those children:
1614 $rs = $schema->resultset('Person')->search(
1617 alias => 'mother', # alias columns in accordance with "from"
1619 { mother => 'person' },
1622 { child => 'person' },
1624 { father => 'person' },
1625 { 'father.person_id' => 'child.father_id' }
1628 { 'mother.person_id' => 'child.mother_id' }
1635 # SELECT mother.* FROM person mother
1638 # JOIN person father
1639 # ON ( father.person_id = child.father_id )
1641 # ON ( mother.person_id = child.mother_id )
1643 The type of any join can be controlled manually. To search against only people
1644 with a father in the person table, we could explicitly use C<INNER JOIN>:
1646 $rs = $schema->resultset('Person')->search(
1649 alias => 'child', # alias columns in accordance with "from"
1651 { child => 'person' },
1653 { father => 'person', -join_type => 'inner' },
1654 { 'father.id' => 'child.father_id' }
1661 # SELECT child.* FROM person child
1662 # INNER JOIN person father ON child.father_id = father.id
1672 Makes the resultset paged and specifies the page to retrieve. Effectively
1673 identical to creating a non-pages resultset and then calling ->page($page)
1684 Specifes the maximum number of rows for direct retrieval or the number of
1685 rows per page if the page attribute or method is used.
1691 =item Value: \@columns
1695 A arrayref of columns to group by. Can include columns of joined tables.
1697 group_by => [qw/ column1 column2 ... /]
1703 =item Value: $condition
1707 HAVING is a select statement attribute that is applied between GROUP BY and
1708 ORDER BY. It is applied to the after the grouping calculations have been
1711 having => { 'count(employee)' => { '>=', 100 } }
1717 =item Value: (0 | 1)
1721 Set to 1 to group by all columns.
1725 Set to 1 to cache search results. This prevents extra SQL queries if you
1726 revisit rows in your ResultSet:
1728 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
1730 while( my $artist = $resultset->next ) {
1734 $rs->first; # without cache, this would issue a query
1736 By default, searches are not cached.
1738 For more examples of using these attributes, see
1739 L<DBIx::Class::Manual::Cookbook>.