1 package DBIx::Class::ResultSet;
11 use Scalar::Util qw/weaken/;
13 use DBIx::Class::ResultSetColumn;
14 use base qw/DBIx::Class/;
15 __PACKAGE__->load_components(qw/AccessorGroup/);
16 __PACKAGE__->mk_group_accessors('simple' => qw/result_source result_class/);
20 DBIx::Class::ResultSet - Responsible for fetching and creating resultset.
24 my $rs = $schema->resultset('User')->search(registered => 1);
25 my @rows = $schema->resultset('CD')->search(year => 2005);
29 The resultset is also known as an iterator. It is responsible for handling
30 queries that may return an arbitrary number of rows, e.g. via L</search>
31 or a C<has_many> relationship.
33 In the examples below, the following table classes are used:
35 package MyApp::Schema::Artist;
36 use base qw/DBIx::Class/;
37 __PACKAGE__->load_components(qw/Core/);
38 __PACKAGE__->table('artist');
39 __PACKAGE__->add_columns(qw/artistid name/);
40 __PACKAGE__->set_primary_key('artistid');
41 __PACKAGE__->has_many(cds => 'MyApp::Schema::CD');
44 package MyApp::Schema::CD;
45 use base qw/DBIx::Class/;
46 __PACKAGE__->load_components(qw/Core/);
47 __PACKAGE__->table('cd');
48 __PACKAGE__->add_columns(qw/cdid artist title year/);
49 __PACKAGE__->set_primary_key('cdid');
50 __PACKAGE__->belongs_to(artist => 'MyApp::Schema::Artist');
59 =item Arguments: $source, \%$attrs
61 =item Return Value: $rs
65 The resultset constructor. Takes a source object (usually a
66 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
67 L</ATTRIBUTES> below). Does not perform any queries -- these are
68 executed as needed by the other methods.
70 Generally you won't need to construct a resultset manually. You'll
71 automatically get one from e.g. a L</search> called in scalar context:
73 my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
75 IMPORTANT: If called on an object, proxies to new_result instead so
77 my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
79 will return a CD object, not a ResultSet.
85 return $class->new_result(@_) if ref $class;
87 my ($source, $attrs) = @_;
91 $attrs->{rows} ||= 10;
92 $attrs->{offset} ||= 0;
93 $attrs->{offset} += ($attrs->{rows} * ($attrs->{page} - 1));
96 $attrs->{alias} ||= 'me';
99 result_source => $source,
100 result_class => $attrs->{result_class} || $source->result_class,
101 cond => $attrs->{where},
102 # from => $attrs->{from},
103 # collapse => $collapse,
105 page => delete $attrs->{page},
115 =item Arguments: $cond, \%attrs?
117 =item Return Value: $resultset (scalar context), @row_objs (list context)
121 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
122 my $new_rs = $cd_rs->search({ year => 2005 });
124 my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
125 # year = 2005 OR year = 2004
127 If you need to pass in additional attributes but no additional condition,
128 call it as C<search(undef, \%attrs)>.
130 # "SELECT name, artistid FROM $artist_table"
131 my @all_artists = $schema->resultset('Artist')->search(undef, {
132 columns => [qw/name artistid/],
140 my $our_attrs = { %{$self->{attrs}} };
141 my $having = delete $our_attrs->{having};
143 $attrs = pop(@_) if @_ > 1 and ref $_[$#_] eq 'HASH';
145 # merge new attrs into old
146 foreach my $key (qw/join prefetch/) {
147 next unless (exists $attrs->{$key});
148 if (exists $our_attrs->{$key}) {
149 $our_attrs->{$key} = [$our_attrs->{$key}] if (ref $our_attrs->{$key} ne 'ARRAY');
150 push(@{$our_attrs->{$key}}, (ref $attrs->{$key} eq 'ARRAY') ? @{$attrs->{$key}} : $attrs->{$key});
152 $our_attrs->{$key} = $attrs->{$key};
154 delete $attrs->{$key};
156 $our_attrs = { %{$our_attrs}, %{$attrs} };
158 # merge new where and having into old
160 ? ((@_ == 1 || ref $_[0] eq "HASH")
163 ? $self->throw_exception(
164 "Odd number of arguments to search")
167 if (defined $where) {
168 $our_attrs->{where} = (defined $our_attrs->{where}
170 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
171 $where, $our_attrs->{where} ] }
175 if (defined $having) {
176 $our_attrs->{having} = (defined $our_attrs->{having}
178 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
179 $having, $our_attrs->{having} ] }
182 # use Data::Dumper; warn "attrs: " . Dumper($our_attrs);
184 my $rs = (ref $self)->new($self->result_source, $our_attrs);
185 $rs->{_parent_rs} = $self->{_parent_rs} if ($self->{_parent_rs}); #XXX - hack to pass through parent of related resultsets
187 unless (@_) { # no search, effectively just a clone
188 my $rows = $self->get_cache;
190 $rs->set_cache($rows);
194 return (wantarray ? $rs->all : $rs);
197 =head2 search_literal
201 =item Arguments: $sql_fragment, @bind_values
203 =item Return Value: $resultset (scalar context), @row_objs (list context)
207 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
208 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
210 Pass a literal chunk of SQL to be added to the conditional part of the
216 my ($self, $cond, @vals) = @_;
217 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
218 $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
219 return $self->search(\$cond, $attrs);
226 =item Arguments: @values | \%cols, \%attrs?
228 =item Return Value: $row_object
232 Finds a row based on its primary key or unique constraint. For example, to find
233 a row by its primary key:
235 my $cd = $schema->resultset('CD')->find(5);
237 You can also find a row by a specific unique constraint using the C<key>
238 attribute. For example:
240 my $cd = $schema->resultset('CD')->find('Massive Attack', 'Mezzanine', { key => 'artist_title' });
242 Additionally, you can specify the columns explicitly by name:
244 my $cd = $schema->resultset('CD')->find(
246 artist => 'Massive Attack',
247 title => 'Mezzanine',
249 { key => 'artist_title' }
252 If no C<key> is specified and you explicitly name columns, it searches on all
253 unique constraints defined on the source, including the primary key.
255 If the C<key> is specified as C<primary>, it searches only on the primary key.
257 See also L</find_or_create> and L</update_or_create>. For information on how to
258 declare unique constraints, see
259 L<DBIx::Class::ResultSource/add_unique_constraint>.
265 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
267 # Parse out a hash from input
268 my @cols = exists $attrs->{key}
269 ? $self->result_source->unique_constraint_columns($attrs->{key})
270 : $self->result_source->primary_columns;
273 if (ref $_[0] eq 'HASH') {
274 $hash = { %{$_[0]} };
276 elsif (@_ == @cols) {
278 @{$hash}{@cols} = @_;
281 $self->throw_exception(
282 "Arguments to find must be a hashref or match the number of columns in the "
283 . exists $attrs->{key} ? "$attrs->{key} unique constraint" : "primary key"
287 # Check the hash we just parsed against our source's unique constraints
288 my @constraint_names = exists $attrs->{key}
290 : $self->result_source->unique_constraint_names;
291 $self->throw_exception(
292 "Can't find unless a primary key or unique constraint is defined"
293 ) unless @constraint_names;
296 foreach my $name (@constraint_names) {
297 my @unique_cols = $self->result_source->unique_constraint_columns($name);
298 my $unique_query = $self->_build_unique_query($hash, \@unique_cols);
300 # Add the ResultSet's alias
301 foreach my $key (grep { ! m/\./ } keys %$unique_query) {
302 my $alias = $self->{attrs}->{alias};
303 $unique_query->{"$alias.$key"} = delete $unique_query->{$key};
306 push @unique_queries, $unique_query if %$unique_query;
309 # Handle cases where the ResultSet already defines the query
310 my $query = @unique_queries ? \@unique_queries : undef;
315 my $rs = $self->search($query, $attrs);
317 return keys %{$rs->{_attrs}->{collapse}} ? $rs->next : $rs->single;
321 return (keys %{$self->{_attrs}->{collapse}})
322 ? $self->search($query)->next
323 : $self->single($query);
327 # _build_unique_query
329 # Constrain the specified query hash based on the specified column names.
331 sub _build_unique_query {
332 my ($self, $query, $unique_cols) = @_;
335 map { $_ => $query->{$_} }
336 grep { exists $query->{$_} }
339 return \%unique_query;
342 =head2 search_related
346 =item Arguments: $cond, \%attrs?
348 =item Return Value: $new_resultset
352 $new_rs = $cd_rs->search_related('artist', {
356 Searches the specified relationship, optionally specifying a condition and
357 attributes for matching records. See L</ATTRIBUTES> for more information.
362 return shift->related_resultset(shift)->search(@_);
369 =item Arguments: none
371 =item Return Value: $cursor
375 Returns a storage-driven cursor to the given resultset. See
376 L<DBIx::Class::Cursor> for more information.
384 my $attrs = { %{$self->{_attrs}} };
385 return $self->{cursor}
386 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
387 $attrs->{where},$attrs);
394 =item Arguments: $cond?
396 =item Return Value: $row_object?
400 my $cd = $schema->resultset('CD')->single({ year => 2001 });
402 Inflates the first result without creating a cursor if the resultset has
403 any records in it; if not returns nothing. Used by L</find> as an optimisation.
408 my ($self, $where) = @_;
410 my $attrs = { %{$self->{_attrs}} };
412 if (defined $attrs->{where}) {
415 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
416 $where, delete $attrs->{where} ]
419 $attrs->{where} = $where;
423 my @data = $self->result_source->storage->select_single(
424 $attrs->{from}, $attrs->{select},
425 $attrs->{where},$attrs);
426 return (@data ? $self->_construct_object(@data) : ());
433 =item Arguments: $cond?
435 =item Return Value: $resultsetcolumn
439 my $max_length = $rs->get_column('length')->max;
441 Returns a ResultSetColumn instance for $column based on $self
446 my ($self, $column) = @_;
448 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
456 =item Arguments: $cond, \%attrs?
458 =item Return Value: $resultset (scalar context), @row_objs (list context)
462 # WHERE title LIKE '%blue%'
463 $cd_rs = $rs->search_like({ title => '%blue%'});
465 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
466 that this is simply a convenience method. You most likely want to use
467 L</search> with specific operators.
469 For more information, see L<DBIx::Class::Manual::Cookbook>.
475 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
476 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
477 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
478 return $class->search($query, { %$attrs });
485 =item Arguments: $first, $last
487 =item Return Value: $resultset (scalar context), @row_objs (list context)
491 Returns a resultset or object list representing a subset of elements from the
492 resultset slice is called on. Indexes are from 0, i.e., to get the first
495 my ($one, $two, $three) = $rs->slice(0, 2);
500 my ($self, $min, $max) = @_;
501 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
502 $attrs->{offset} = $self->{attrs}{offset} || 0;
503 $attrs->{offset} += $min;
504 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
505 return $self->search(undef(), $attrs);
506 #my $slice = (ref $self)->new($self->result_source, $attrs);
507 #return (wantarray ? $slice->all : $slice);
514 =item Arguments: none
516 =item Return Value: $result?
520 Returns the next element in the resultset (C<undef> is there is none).
522 Can be used to efficiently iterate over records in the resultset:
524 my $rs = $schema->resultset('CD')->search;
525 while (my $cd = $rs->next) {
529 Note that you need to store the resultset object, and call C<next> on it.
530 Calling C<< resultset('Table')->next >> repeatedly will always return the
531 first record from the resultset.
537 if (@{$self->{all_cache} || []}) {
538 $self->{all_cache_position} ||= 0;
539 return $self->{all_cache}->[$self->{all_cache_position}++];
541 if ($self->{attrs}{cache}) {
542 $self->{all_cache_position} = 1;
543 return ($self->all)[0];
545 my @row = (exists $self->{stashed_row} ?
546 @{delete $self->{stashed_row}} :
549 return unless (@row);
550 return $self->_construct_object(@row);
553 # XXX - this is essentially just the old new(). rewrite / tidy up?
557 return if(exists $self->{_attrs}); #return if _resolve has already been called
559 my $attrs = $self->{attrs};
560 my $source = ($self->{_parent_rs}) ? $self->{_parent_rs} : $self->{result_source};
562 # XXX - this is a hack to prevent dclone dieing because of the code ref, get's put back in $attrs afterwards
563 my $record_filter = delete $attrs->{record_filter} if (defined $attrs->{record_filter});
564 $attrs = Storable::dclone($attrs || {}); # { %{ $attrs || {} } };
565 $attrs->{record_filter} = $record_filter if ($record_filter);
566 $self->{attrs}->{record_filter} = $record_filter if ($record_filter);
568 my $alias = $attrs->{alias};
570 $attrs->{columns} ||= delete $attrs->{cols} if $attrs->{cols};
571 delete $attrs->{as} if $attrs->{columns};
572 $attrs->{columns} ||= [ $self->{result_source}->columns ] unless $attrs->{select};
573 my $select_alias = ($self->{_parent_rs}) ? $self->{attrs}->{_live_join} : $alias;
575 map { m/\./ ? $_ : "${select_alias}.$_" } @{delete $attrs->{columns}}
576 ] if $attrs->{columns};
578 map { m/^\Q$alias.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}}
580 if (my $include = delete $attrs->{include_columns}) {
581 push(@{$attrs->{select}}, @$include);
582 push(@{$attrs->{as}}, map { m/([^.]+)$/; $1; } @$include);
585 $attrs->{from} ||= [ { $alias => $source->from } ];
586 $attrs->{seen_join} ||= {};
588 if (my $join = delete $attrs->{join}) {
589 foreach my $j (ref $join eq 'ARRAY' ? @$join : ($join)) {
590 if (ref $j eq 'HASH') {
591 $seen{$_} = 1 foreach keys %$j;
597 push(@{$attrs->{from}}, $source->resolve_join($join, $attrs->{alias}, $attrs->{seen_join}));
599 $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
600 $attrs->{order_by} = [ $attrs->{order_by} ] if
601 $attrs->{order_by} and !ref($attrs->{order_by});
602 $attrs->{order_by} ||= [];
604 my $collapse = $attrs->{collapse} || {};
605 if (my $prefetch = delete $attrs->{prefetch}) {
607 foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
608 if ( ref $p eq 'HASH' ) {
609 foreach my $key (keys %$p) {
610 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
614 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
617 my @prefetch = $source->resolve_prefetch(
618 $p, $attrs->{alias}, {}, \@pre_order, $collapse);
619 push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
620 push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
622 push(@{$attrs->{order_by}}, @pre_order);
624 $attrs->{collapse} = $collapse;
625 $self->{_attrs} = $attrs;
628 sub _construct_object {
629 my ($self, @row) = @_;
630 my @as = @{ $self->{_attrs}{as} };
632 my $info = $self->_collapse_result(\@as, \@row);
633 my $new = $self->result_class->inflate_result($self->result_source, @$info);
634 $new = $self->{_attrs}{record_filter}->($new)
635 if exists $self->{_attrs}{record_filter};
639 sub _collapse_result {
640 my ($self, $as, $row, $prefix) = @_;
642 my $live_join = $self->{attrs}->{_live_join} ||="";
646 foreach my $this_as (@$as) {
647 my $val = shift @copy;
648 if (defined $prefix) {
649 if ($this_as =~ m/^\Q${prefix}.\E(.+)$/) {
651 $remain =~ /^(?:(.*)\.)?([^.]+)$/;
652 $const{$1||''}{$2} = $val;
655 $this_as =~ /^(?:(.*)\.)?([^.]+)$/;
656 $const{$1||''}{$2} = $val;
660 my $info = [ {}, {} ];
661 foreach my $key (keys %const) {
662 if (length $key && $key ne $live_join) {
664 my @parts = split(/\./, $key);
665 foreach my $p (@parts) {
666 $target = $target->[1]->{$p} ||= [];
668 $target->[0] = $const{$key};
670 $info->[0] = $const{$key};
675 if (defined $prefix) {
677 m/^\Q${prefix}.\E(.+)$/ ? ($1) : ()
678 } keys %{$self->{_attrs}->{collapse}}
680 @collapse = keys %{$self->{_attrs}->{collapse}};
684 my ($c) = sort { length $a <=> length $b } @collapse;
686 foreach my $p (split(/\./, $c)) {
687 $target = $target->[1]->{$p} ||= [];
689 my $c_prefix = (defined($prefix) ? "${prefix}.${c}" : $c);
690 my @co_key = @{$self->{_attrs}->{collapse}{$c_prefix}};
691 my %co_check = map { ($_, $target->[0]->{$_}); } @co_key;
692 my $tree = $self->_collapse_result($as, $row, $c_prefix);
695 !defined($tree->[0]->{$_}) ||
696 $co_check{$_} ne $tree->[0]->{$_}
699 last unless (@raw = $self->cursor->next);
700 $row = $self->{stashed_row} = \@raw;
701 $tree = $self->_collapse_result($as, $row, $c_prefix);
712 =item Arguments: $result_source?
714 =item Return Value: $result_source
718 An accessor for the primary ResultSource object from which this ResultSet
728 =item Arguments: $cond, \%attrs??
730 =item Return Value: $count
734 Performs an SQL C<COUNT> with the same query as the resultset was built
735 with to find the number of elements. If passed arguments, does a search
736 on the resultset and counts the results of that.
738 Note: When using C<count> with C<group_by>, L<DBIX::Class> emulates C<GROUP BY>
739 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
740 not support C<DISTINCT> with multiple columns. If you are using such a
741 database, you should only use columns from the main table in your C<group_by>
748 return $self->search(@_)->count if @_ and defined $_[0];
749 return scalar @{ $self->get_cache } if @{ $self->get_cache };
751 my $count = $self->_count;
752 return 0 unless $count;
754 $count -= $self->{attrs}{offset} if $self->{attrs}{offset};
755 $count = $self->{attrs}{rows} if
756 $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
760 sub _count { # Separated out so pager can get the full count
762 my $select = { count => '*' };
765 my $attrs = { %{ $self->{_attrs} } };
766 if ($attrs->{distinct} && (my $group_by = $attrs->{group_by} || $attrs->{select})) {
767 delete $attrs->{having};
768 my @distinct = (ref $group_by ? @$group_by : ($group_by));
769 # todo: try CONCAT for multi-column pk
770 my @pk = $self->result_source->primary_columns;
772 foreach my $column (@distinct) {
773 if ($column =~ qr/^(?:\Q$attrs->{alias}.\E)?$pk[0]$/) {
774 @distinct = ($column);
780 $select = { count => { distinct => \@distinct } };
781 #use Data::Dumper; die Dumper $select;
784 $attrs->{select} = $select;
785 $attrs->{as} = [qw/count/];
787 # offset, order by and page are not needed to count. record_filter is cdbi
788 delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
789 my ($count) = (ref $self)->new($self->result_source, $attrs)->cursor->next;
797 =item Arguments: $sql_fragment, @bind_values
799 =item Return Value: $count
803 Counts the results in a literal query. Equivalent to calling L</search_literal>
804 with the passed arguments, then L</count>.
808 sub count_literal { shift->search_literal(@_)->count; }
814 =item Arguments: none
816 =item Return Value: @objects
820 Returns all elements in the resultset. Called implicitly if the resultset
821 is returned in list context.
827 return @{ $self->get_cache } if @{ $self->get_cache };
831 # TODO: don't call resolve here
833 if (keys %{$self->{_attrs}->{collapse}}) {
834 # if ($self->{attrs}->{prefetch}) {
835 # Using $self->cursor->all is really just an optimisation.
836 # If we're collapsing has_many prefetches it probably makes
837 # very little difference, and this is cleaner than hacking
838 # _construct_object to survive the approach
839 my @row = $self->cursor->next;
841 push(@obj, $self->_construct_object(@row));
842 @row = (exists $self->{stashed_row}
843 ? @{delete $self->{stashed_row}}
844 : $self->cursor->next);
847 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
850 $self->set_cache(\@obj) if $self->{attrs}{cache};
858 =item Arguments: none
860 =item Return Value: $self
864 Resets the resultset's cursor, so you can iterate through the elements again.
870 delete $self->{_attrs} if (exists $self->{_attrs});
872 $self->{all_cache_position} = 0;
873 $self->cursor->reset;
881 =item Arguments: none
883 =item Return Value: $object?
887 Resets the resultset and returns an object for the first result (if the
888 resultset returns anything).
893 return $_[0]->reset->next;
896 # _cond_for_update_delete
898 # update/delete require the condition to be modified to handle
899 # the differing SQL syntax available. This transforms the $self->{cond}
900 # appropriately, returning the new condition.
902 sub _cond_for_update_delete {
906 if (!ref($self->{cond})) {
907 # No-op. No condition, we're updating/deleting everything
909 elsif (ref $self->{cond} eq 'ARRAY') {
913 foreach my $key (keys %{$_}) {
915 $hash{$1} = $_->{$key};
921 elsif (ref $self->{cond} eq 'HASH') {
922 if ((keys %{$self->{cond}})[0] eq '-and') {
925 my @cond = @{$self->{cond}{-and}};
926 for (my $i = 0; $i < @cond - 1; $i++) {
927 my $entry = $cond[$i];
930 if (ref $entry eq 'HASH') {
931 foreach my $key (keys %{$entry}) {
933 $hash{$1} = $entry->{$key};
937 $entry =~ /([^.]+)$/;
938 $hash{$entry} = $cond[++$i];
941 push @{$cond->{-and}}, \%hash;
945 foreach my $key (keys %{$self->{cond}}) {
947 $cond->{$1} = $self->{cond}{$key};
952 $self->throw_exception(
953 "Can't update/delete on resultset with condition unless hash or array"
965 =item Arguments: \%values
967 =item Return Value: $storage_rv
971 Sets the specified columns in the resultset to the supplied values in a
972 single query. Return value will be true if the update succeeded or false
973 if no records were updated; exact type of success value is storage-dependent.
978 my ($self, $values) = @_;
979 $self->throw_exception("Values for update must be a hash")
980 unless ref $values eq 'HASH';
982 my $cond = $self->_cond_for_update_delete;
984 return $self->result_source->storage->update(
985 $self->result_source->from, $values, $cond
993 =item Arguments: \%values
995 =item Return Value: 1
999 Fetches all objects and updates them one at a time. Note that C<update_all>
1000 will run DBIC cascade triggers, while L</update> will not.
1005 my ($self, $values) = @_;
1006 $self->throw_exception("Values for update must be a hash")
1007 unless ref $values eq 'HASH';
1008 foreach my $obj ($self->all) {
1009 $obj->set_columns($values)->update;
1018 =item Arguments: none
1020 =item Return Value: 1
1024 Deletes the contents of the resultset from its result source. Note that this
1025 will not run DBIC cascade triggers. See L</delete_all> if you need triggers
1034 my $cond = $self->_cond_for_update_delete;
1036 $self->result_source->storage->delete($self->result_source->from, $cond);
1044 =item Arguments: none
1046 =item Return Value: 1
1050 Fetches all objects and deletes them one at a time. Note that C<delete_all>
1051 will run DBIC cascade triggers, while L</delete> will not.
1057 $_->delete for $self->all;
1065 =item Arguments: none
1067 =item Return Value: $pager
1071 Return Value a L<Data::Page> object for the current resultset. Only makes
1072 sense for queries with a C<page> attribute.
1078 my $attrs = $self->{attrs};
1079 $self->throw_exception("Can't create pager for non-paged rs")
1080 unless $self->{page};
1081 $attrs->{rows} ||= 10;
1082 return $self->{pager} ||= Data::Page->new(
1083 $self->_count, $attrs->{rows}, $self->{page});
1090 =item Arguments: $page_number
1092 =item Return Value: $rs
1096 Returns a resultset for the $page_number page of the resultset on which page
1097 is called, where each page contains a number of rows equal to the 'rows'
1098 attribute set on the resultset (10 by default).
1103 my ($self, $page) = @_;
1104 my $attrs = { %{$self->{attrs}} };
1105 $attrs->{page} = $page;
1106 return (ref $self)->new($self->result_source, $attrs);
1113 =item Arguments: \%vals
1115 =item Return Value: $object
1119 Creates an object in the resultset's result class and returns it.
1124 my ($self, $values) = @_;
1125 $self->throw_exception( "new_result needs a hash" )
1126 unless (ref $values eq 'HASH');
1127 $self->throw_exception(
1128 "Can't abstract implicit construct, condition not a hash"
1129 ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
1131 my $alias = $self->{attrs}{alias};
1132 foreach my $key (keys %{$self->{cond}||{}}) {
1133 $new{$1} = $self->{cond}{$key} if ($key =~ m/^(?:\Q${alias}.\E)?([^.]+)$/);
1135 my $obj = $self->result_class->new(\%new);
1136 $obj->result_source($self->result_source) if $obj->can('result_source');
1144 =item Arguments: \%vals, \%attrs?
1146 =item Return Value: $object
1150 Find an existing record from this resultset. If none exists, instantiate a new
1151 result object and return it. The object will not be saved into your storage
1152 until you call L<DBIx::Class::Row/insert> on it.
1154 If you want objects to be saved immediately, use L</find_or_create> instead.
1160 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1161 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1162 my $exists = $self->find($hash, $attrs);
1163 return defined $exists ? $exists : $self->new_result($hash);
1170 =item Arguments: \%vals
1172 =item Return Value: $object
1176 Inserts a record into the resultset and returns the object representing it.
1178 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
1183 my ($self, $attrs) = @_;
1184 $self->throw_exception( "create needs a hashref" )
1185 unless ref $attrs eq 'HASH';
1186 return $self->new_result($attrs)->insert;
1189 =head2 find_or_create
1193 =item Arguments: \%vals, \%attrs?
1195 =item Return Value: $object
1199 $class->find_or_create({ key => $val, ... });
1201 Searches for a record matching the search condition; if it doesn't find one,
1202 creates one and returns that instead.
1204 my $cd = $schema->resultset('CD')->find_or_create({
1206 artist => 'Massive Attack',
1207 title => 'Mezzanine',
1211 Also takes an optional C<key> attribute, to search by a specific key or unique
1212 constraint. For example:
1214 my $cd = $schema->resultset('CD')->find_or_create(
1216 artist => 'Massive Attack',
1217 title => 'Mezzanine',
1219 { key => 'artist_title' }
1222 See also L</find> and L</update_or_create>. For information on how to declare
1223 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1227 sub find_or_create {
1229 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1230 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1231 my $exists = $self->find($hash, $attrs);
1232 return defined $exists ? $exists : $self->create($hash);
1235 =head2 update_or_create
1239 =item Arguments: \%col_values, { key => $unique_constraint }?
1241 =item Return Value: $object
1245 $class->update_or_create({ col => $val, ... });
1247 First, searches for an existing row matching one of the unique constraints
1248 (including the primary key) on the source of this resultset. If a row is
1249 found, updates it with the other given column values. Otherwise, creates a new
1252 Takes an optional C<key> attribute to search on a specific unique constraint.
1255 # In your application
1256 my $cd = $schema->resultset('CD')->update_or_create(
1258 artist => 'Massive Attack',
1259 title => 'Mezzanine',
1262 { key => 'artist_title' }
1265 If no C<key> is specified, it searches on all unique constraints defined on the
1266 source, including the primary key.
1268 If the C<key> is specified as C<primary>, it searches only on the primary key.
1270 See also L</find> and L</find_or_create>. For information on how to declare
1271 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1275 sub update_or_create {
1277 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1278 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1280 my $row = $self->find($hash, $attrs);
1282 $row->set_columns($hash);
1287 return $self->create($hash);
1294 =item Arguments: none
1296 =item Return Value: \@cache_objects?
1300 Gets the contents of the cache for the resultset, if the cache is set.
1305 shift->{all_cache} || [];
1312 =item Arguments: \@cache_objects
1314 =item Return Value: \@cache_objects
1318 Sets the contents of the cache for the resultset. Expects an arrayref
1319 of objects of the same class as those produced by the resultset. Note that
1320 if the cache is set the resultset will return the cached objects rather
1321 than re-querying the database even if the cache attr is not set.
1326 my ( $self, $data ) = @_;
1327 $self->throw_exception("set_cache requires an arrayref")
1328 if ref $data ne 'ARRAY';
1329 my $result_class = $self->result_class;
1331 $self->throw_exception(
1332 "cannot cache object of type '$_', expected '$result_class'"
1333 ) if ref $_ ne $result_class;
1335 $self->{all_cache} = $data;
1342 =item Arguments: none
1344 =item Return Value: []
1348 Clears the cache for the resultset.
1353 shift->set_cache([]);
1356 =head2 related_resultset
1360 =item Arguments: $relationship_name
1362 =item Return Value: $resultset
1366 Returns a related resultset for the supplied relationship name.
1368 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1372 sub related_resultset {
1373 my ( $self, $rel ) = @_;
1375 $self->{related_resultsets} ||= {};
1376 return $self->{related_resultsets}{$rel} ||= do {
1377 #warn "fetching related resultset for rel '$rel' " . $self->result_source->{name};
1378 my $rel_obj = $self->result_source->relationship_info($rel);
1379 $self->throw_exception(
1380 "search_related: result source '" . $self->result_source->name .
1381 "' has no such relationship ${rel}")
1382 unless $rel_obj; #die Dumper $self->{attrs};
1384 my $rs = $self->result_source->schema->resultset($rel_obj->{class}
1386 { %{$self->{attrs}},
1390 _live_join => $rel }
1393 # keep reference of the original resultset
1394 $rs->{_parent_rs} = $self->result_source;
1399 =head2 throw_exception
1401 See L<DBIx::Class::Schema/throw_exception> for details.
1405 sub throw_exception {
1407 $self->result_source->schema->throw_exception(@_);
1410 # XXX: FIXME: Attributes docs need clearing up
1414 The resultset takes various attributes that modify its behavior. Here's an
1421 =item Value: ($order_by | \@order_by)
1425 Which column(s) to order the results by. This is currently passed
1426 through directly to SQL, so you can give e.g. C<year DESC> for a
1427 descending order on the column `year'.
1433 =item Value: \@columns
1437 Shortcut to request a particular set of columns to be retrieved. Adds
1438 C<me.> onto the start of any column without a C<.> in it and sets C<select>
1439 from that, then auto-populates C<as> from C<select> as normal. (You may also
1440 use the C<cols> attribute, as in earlier versions of DBIC.)
1442 =head2 include_columns
1446 =item Value: \@columns
1450 Shortcut to include additional columns in the returned results - for example
1452 $schema->resultset('CD')->search(undef, {
1453 include_columns => ['artist.name'],
1457 would return all CDs and include a 'name' column to the information
1458 passed to object inflation
1464 =item Value: \@select_columns
1468 Indicates which columns should be selected from the storage. You can use
1469 column names, or in the case of RDBMS back ends, function or stored procedure
1472 $rs = $schema->resultset('Employee')->search(undef, {
1475 { count => 'employeeid' },
1480 When you use function/stored procedure names and do not supply an C<as>
1481 attribute, the column names returned are storage-dependent. E.g. MySQL would
1482 return a column named C<count(employeeid)> in the above example.
1488 =item Value: \@inflation_names
1492 Indicates column names for object inflation. This is used in conjunction with
1493 C<select>, usually when C<select> contains one or more function or stored
1496 $rs = $schema->resultset('Employee')->search(undef, {
1499 { count => 'employeeid' }
1501 as => ['name', 'employee_count'],
1504 my $employee = $rs->first(); # get the first Employee
1506 If the object against which the search is performed already has an accessor
1507 matching a column name specified in C<as>, the value can be retrieved using
1508 the accessor as normal:
1510 my $name = $employee->name();
1512 If on the other hand an accessor does not exist in the object, you need to
1513 use C<get_column> instead:
1515 my $employee_count = $employee->get_column('employee_count');
1517 You can create your own accessors if required - see
1518 L<DBIx::Class::Manual::Cookbook> for details.
1524 =item Value: ($rel_name | \@rel_names | \%rel_names)
1528 Contains a list of relationships that should be joined for this query. For
1531 # Get CDs by Nine Inch Nails
1532 my $rs = $schema->resultset('CD')->search(
1533 { 'artist.name' => 'Nine Inch Nails' },
1534 { join => 'artist' }
1537 Can also contain a hash reference to refer to the other relation's relations.
1540 package MyApp::Schema::Track;
1541 use base qw/DBIx::Class/;
1542 __PACKAGE__->table('track');
1543 __PACKAGE__->add_columns(qw/trackid cd position title/);
1544 __PACKAGE__->set_primary_key('trackid');
1545 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
1548 # In your application
1549 my $rs = $schema->resultset('Artist')->search(
1550 { 'track.title' => 'Teardrop' },
1552 join => { cd => 'track' },
1553 order_by => 'artist.name',
1557 If the same join is supplied twice, it will be aliased to <rel>_2 (and
1558 similarly for a third time). For e.g.
1560 my $rs = $schema->resultset('Artist')->search({
1561 'cds.title' => 'Down to Earth',
1562 'cds_2.title' => 'Popular',
1564 join => [ qw/cds cds/ ],
1567 will return a set of all artists that have both a cd with title 'Down
1568 to Earth' and a cd with title 'Popular'.
1570 If you want to fetch related objects from other tables as well, see C<prefetch>
1577 =item Value: ($rel_name | \@rel_names | \%rel_names)
1581 Contains one or more relationships that should be fetched along with the main
1582 query (when they are accessed afterwards they will have already been
1583 "prefetched"). This is useful for when you know you will need the related
1584 objects, because it saves at least one query:
1586 my $rs = $schema->resultset('Tag')->search(
1595 The initial search results in SQL like the following:
1597 SELECT tag.*, cd.*, artist.* FROM tag
1598 JOIN cd ON tag.cd = cd.cdid
1599 JOIN artist ON cd.artist = artist.artistid
1601 L<DBIx::Class> has no need to go back to the database when we access the
1602 C<cd> or C<artist> relationships, which saves us two SQL statements in this
1605 Simple prefetches will be joined automatically, so there is no need
1606 for a C<join> attribute in the above search. If you're prefetching to
1607 depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
1608 specify the join as well.
1610 C<prefetch> can be used with the following relationship types: C<belongs_to>,
1611 C<has_one> (or if you're using C<add_relationship>, any relationship declared
1612 with an accessor type of 'single' or 'filter').
1618 =item Value: \@from_clause
1622 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
1623 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
1626 NOTE: Use this on your own risk. This allows you to shoot off your foot!
1627 C<join> will usually do what you need and it is strongly recommended that you
1628 avoid using C<from> unless you cannot achieve the desired result using C<join>.
1630 In simple terms, C<from> works as follows:
1633 { <alias> => <table>, -join_type => 'inner|left|right' }
1634 [] # nested JOIN (optional)
1635 { <table.column> => <foreign_table.foreign_key> }
1641 ON <table.column> = <foreign_table.foreign_key>
1643 An easy way to follow the examples below is to remember the following:
1645 Anything inside "[]" is a JOIN
1646 Anything inside "{}" is a condition for the enclosing JOIN
1648 The following examples utilize a "person" table in a family tree application.
1649 In order to express parent->child relationships, this table is self-joined:
1651 # Person->belongs_to('father' => 'Person');
1652 # Person->belongs_to('mother' => 'Person');
1654 C<from> can be used to nest joins. Here we return all children with a father,
1655 then search against all mothers of those children:
1657 $rs = $schema->resultset('Person')->search(
1660 alias => 'mother', # alias columns in accordance with "from"
1662 { mother => 'person' },
1665 { child => 'person' },
1667 { father => 'person' },
1668 { 'father.person_id' => 'child.father_id' }
1671 { 'mother.person_id' => 'child.mother_id' }
1678 # SELECT mother.* FROM person mother
1681 # JOIN person father
1682 # ON ( father.person_id = child.father_id )
1684 # ON ( mother.person_id = child.mother_id )
1686 The type of any join can be controlled manually. To search against only people
1687 with a father in the person table, we could explicitly use C<INNER JOIN>:
1689 $rs = $schema->resultset('Person')->search(
1692 alias => 'child', # alias columns in accordance with "from"
1694 { child => 'person' },
1696 { father => 'person', -join_type => 'inner' },
1697 { 'father.id' => 'child.father_id' }
1704 # SELECT child.* FROM person child
1705 # INNER JOIN person father ON child.father_id = father.id
1715 Makes the resultset paged and specifies the page to retrieve. Effectively
1716 identical to creating a non-pages resultset and then calling ->page($page)
1727 Specifes the maximum number of rows for direct retrieval or the number of
1728 rows per page if the page attribute or method is used.
1734 =item Value: \@columns
1738 A arrayref of columns to group by. Can include columns of joined tables.
1740 group_by => [qw/ column1 column2 ... /]
1746 =item Value: $condition
1750 HAVING is a select statement attribute that is applied between GROUP BY and
1751 ORDER BY. It is applied to the after the grouping calculations have been
1754 having => { 'count(employee)' => { '>=', 100 } }
1760 =item Value: (0 | 1)
1764 Set to 1 to group by all columns.
1768 Set to 1 to cache search results. This prevents extra SQL queries if you
1769 revisit rows in your ResultSet:
1771 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
1773 while( my $artist = $resultset->next ) {
1777 $rs->first; # without cache, this would issue a query
1779 By default, searches are not cached.
1781 For more examples of using these attributes, see
1782 L<DBIx::Class::Manual::Cookbook>.