1 package DBIx::Class::ResultSet;
9 use Carp::Clan qw/^DBIx::Class/;
12 use DBIx::Class::ResultSetColumn;
13 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 # Use a named hash here and bless afterwards to avoid a huge performance hit
100 # in perl 5.8.8-5+ FC5 and later, and possibly other distributions.
102 # See https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=196836 for more
105 result_source => $source,
106 result_class => $attrs->{result_class} || $source->result_class,
107 cond => $attrs->{where},
122 =item Arguments: $cond, \%attrs?
124 =item Return Value: $resultset (scalar context), @row_objs (list context)
128 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
129 my $new_rs = $cd_rs->search({ year => 2005 });
131 my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
132 # year = 2005 OR year = 2004
134 If you need to pass in additional attributes but no additional condition,
135 call it as C<search(undef, \%attrs)>.
137 # "SELECT name, artistid FROM $artist_table"
138 my @all_artists = $schema->resultset('Artist')->search(undef, {
139 columns => [qw/name artistid/],
142 For a list of attributes that can be passed to C<search>, see L</ATTRIBUTES>. For more examples of using this function, see L<Searching|DBIx::Class::Manual::Cookbook/Searching>.
148 my $rs = $self->search_rs( @_ );
149 return (wantarray ? $rs->all : $rs);
156 =item Arguments: $cond, \%attrs?
158 =item Return Value: $resultset
162 This method does the same exact thing as search() except it will
163 always return a resultset, even in list context.
172 unless (@_) { # no search, effectively just a clone
173 $rows = $self->get_cache;
177 $attrs = pop(@_) if @_ > 1 and ref $_[$#_] eq 'HASH';
178 my $our_attrs = { %{$self->{attrs}} };
179 my $having = delete $our_attrs->{having};
181 # merge new attrs into inherited
182 foreach my $key (qw/join prefetch/) {
183 next unless exists $attrs->{$key};
184 $our_attrs->{$key} = $self->_merge_attr($our_attrs->{$key}, delete $attrs->{$key});
187 my $new_attrs = { %{$our_attrs}, %{$attrs} };
190 (@_ == 1 || ref $_[0] eq "HASH")
194 ? $self->throw_exception("Odd number of arguments to search")
201 if (defined $where) {
202 $new_attrs->{where} = (
203 defined $new_attrs->{where}
206 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
207 } $where, $new_attrs->{where}
213 if (defined $having) {
214 $new_attrs->{having} = (
215 defined $new_attrs->{having}
218 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
219 } $having, $new_attrs->{having}
225 my $rs = (ref $self)->new($self->result_source, $new_attrs);
227 $rs->set_cache($rows);
232 =head2 search_literal
236 =item Arguments: $sql_fragment, @bind_values
238 =item Return Value: $resultset (scalar context), @row_objs (list context)
242 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
243 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
245 Pass a literal chunk of SQL to be added to the conditional part of the
251 my ($self, $cond, @vals) = @_;
252 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
253 $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
254 return $self->search(\$cond, $attrs);
261 =item Arguments: @values | \%cols, \%attrs?
263 =item Return Value: $row_object
267 Finds a row based on its primary key or unique constraint. For example, to find
268 a row by its primary key:
270 my $cd = $schema->resultset('CD')->find(5);
272 You can also find a row by a specific unique constraint using the C<key>
273 attribute. For example:
275 my $cd = $schema->resultset('CD')->find('Massive Attack', 'Mezzanine', {
276 key => 'cd_artist_title'
279 Additionally, you can specify the columns explicitly by name:
281 my $cd = $schema->resultset('CD')->find(
283 artist => 'Massive Attack',
284 title => 'Mezzanine',
286 { key => 'cd_artist_title' }
289 If the C<key> is specified as C<primary>, it searches only on the primary key.
291 If no C<key> is specified, it searches on all unique constraints defined on the
292 source, including the primary key.
294 See also L</find_or_create> and L</update_or_create>. For information on how to
295 declare unique constraints, see
296 L<DBIx::Class::ResultSource/add_unique_constraint>.
302 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
304 # Default to the primary key, but allow a specific key
305 my @cols = exists $attrs->{key}
306 ? $self->result_source->unique_constraint_columns($attrs->{key})
307 : $self->result_source->primary_columns;
308 $self->throw_exception(
309 "Can't find unless a primary key or unique constraint is defined"
312 # Parse out a hashref from input
314 if (ref $_[0] eq 'HASH') {
315 $input_query = { %{$_[0]} };
317 elsif (@_ == @cols) {
319 @{$input_query}{@cols} = @_;
322 # Compatibility: Allow e.g. find(id => $value)
323 carp "Find by key => value deprecated; please use a hashref instead";
327 my @unique_queries = $self->_unique_queries($input_query, $attrs);
329 # Handle cases where the ResultSet defines the query, or where the user is
331 my $query = @unique_queries ? \@unique_queries : $input_query;
335 my $rs = $self->search($query, $attrs);
336 return keys %{$rs->_resolved_attrs->{collapse}} ? $rs->next : $rs->single;
339 return keys %{$self->_resolved_attrs->{collapse}}
340 ? $self->search($query)->next
341 : $self->single($query);
347 # Build a list of queries which satisfy unique constraints.
349 sub _unique_queries {
350 my ($self, $query, $attrs) = @_;
352 my $alias = $self->{attrs}{alias};
353 my @constraint_names = exists $attrs->{key}
355 : $self->result_source->unique_constraint_names;
358 foreach my $name (@constraint_names) {
359 my @unique_cols = $self->result_source->unique_constraint_columns($name);
360 my $unique_query = $self->_build_unique_query($query, \@unique_cols);
362 my $num_query = scalar keys %$unique_query;
363 next unless $num_query;
365 # Add the ResultSet's alias
366 foreach my $col (grep { ! m/\./ } keys %$unique_query) {
367 $unique_query->{"$alias.$col"} = delete $unique_query->{$col};
370 # XXX: Assuming quite a bit about $self->{attrs}{where}
371 my $num_cols = scalar @unique_cols;
372 my $num_where = exists $self->{attrs}{where}
373 ? scalar keys %{ $self->{attrs}{where} }
375 push @unique_queries, $unique_query
376 if $num_query + $num_where == $num_cols;
379 return @unique_queries;
382 # _build_unique_query
384 # Constrain the specified query hash based on the specified column names.
386 sub _build_unique_query {
387 my ($self, $query, $unique_cols) = @_;
390 map { $_ => $query->{$_} }
391 grep { exists $query->{$_} }
396 =head2 search_related
400 =item Arguments: $rel, $cond, \%attrs?
402 =item Return Value: $new_resultset
406 $new_rs = $cd_rs->search_related('artist', {
410 Searches the specified relationship, optionally specifying a condition and
411 attributes for matching records. See L</ATTRIBUTES> for more information.
416 return shift->related_resultset(shift)->search(@_);
423 =item Arguments: none
425 =item Return Value: $cursor
429 Returns a storage-driven cursor to the given resultset. See
430 L<DBIx::Class::Cursor> for more information.
437 my $attrs = { %{$self->_resolved_attrs} };
438 return $self->{cursor}
439 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
440 $attrs->{where},$attrs);
447 =item Arguments: $cond?
449 =item Return Value: $row_object?
453 my $cd = $schema->resultset('CD')->single({ year => 2001 });
455 Inflates the first result without creating a cursor if the resultset has
456 any records in it; if not returns nothing. Used by L</find> as an optimisation.
458 Can optionally take an additional condition *only* - this is a fast-code-path
459 method; if you need to add extra joins or similar call ->search and then
460 ->single without a condition on the $rs returned from that.
465 my ($self, $where) = @_;
466 my $attrs = { %{$self->_resolved_attrs} };
468 if (defined $attrs->{where}) {
471 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
472 $where, delete $attrs->{where} ]
475 $attrs->{where} = $where;
479 # XXX: Disabled since it doesn't infer uniqueness in all cases
480 # unless ($self->_is_unique_query($attrs->{where})) {
481 # carp "Query not guaranteed to return a single row"
482 # . "; please declare your unique constraints or use search instead";
485 my @data = $self->result_source->storage->select_single(
486 $attrs->{from}, $attrs->{select},
487 $attrs->{where}, $attrs
490 return (@data ? $self->_construct_object(@data) : ());
495 # Try to determine if the specified query is guaranteed to be unique, based on
496 # the declared unique constraints.
498 sub _is_unique_query {
499 my ($self, $query) = @_;
501 my $collapsed = $self->_collapse_query($query);
502 my $alias = $self->{attrs}{alias};
504 foreach my $name ($self->result_source->unique_constraint_names) {
505 my @unique_cols = map {
507 } $self->result_source->unique_constraint_columns($name);
509 # Count the values for each unique column
510 my %seen = map { $_ => 0 } @unique_cols;
512 foreach my $key (keys %$collapsed) {
513 my $aliased = $key =~ /\./ ? $key : "$alias.$key";
514 next unless exists $seen{$aliased}; # Additional constraints are okay
515 $seen{$aliased} = scalar keys %{ $collapsed->{$key} };
518 # If we get 0 or more than 1 value for a column, it's not necessarily unique
519 return 1 unless grep { $_ != 1 } values %seen;
527 # Recursively collapse the query, accumulating values for each column.
529 sub _collapse_query {
530 my ($self, $query, $collapsed) = @_;
534 if (ref $query eq 'ARRAY') {
535 foreach my $subquery (@$query) {
536 next unless ref $subquery; # -or
537 # warn "ARRAY: " . Dumper $subquery;
538 $collapsed = $self->_collapse_query($subquery, $collapsed);
541 elsif (ref $query eq 'HASH') {
542 if (keys %$query and (keys %$query)[0] eq '-and') {
543 foreach my $subquery (@{$query->{-and}}) {
544 # warn "HASH: " . Dumper $subquery;
545 $collapsed = $self->_collapse_query($subquery, $collapsed);
549 # warn "LEAF: " . Dumper $query;
550 foreach my $col (keys %$query) {
551 my $value = $query->{$col};
552 $collapsed->{$col}{$value}++;
564 =item Arguments: $cond?
566 =item Return Value: $resultsetcolumn
570 my $max_length = $rs->get_column('length')->max;
572 Returns a ResultSetColumn instance for $column based on $self
577 my ($self, $column) = @_;
578 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
586 =item Arguments: $cond, \%attrs?
588 =item Return Value: $resultset (scalar context), @row_objs (list context)
592 # WHERE title LIKE '%blue%'
593 $cd_rs = $rs->search_like({ title => '%blue%'});
595 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
596 that this is simply a convenience method. You most likely want to use
597 L</search> with specific operators.
599 For more information, see L<DBIx::Class::Manual::Cookbook>.
605 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
606 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
607 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
608 return $class->search($query, { %$attrs });
615 =item Arguments: $first, $last
617 =item Return Value: $resultset (scalar context), @row_objs (list context)
621 Returns a resultset or object list representing a subset of elements from the
622 resultset slice is called on. Indexes are from 0, i.e., to get the first
625 my ($one, $two, $three) = $rs->slice(0, 2);
630 my ($self, $min, $max) = @_;
631 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
632 $attrs->{offset} = $self->{attrs}{offset} || 0;
633 $attrs->{offset} += $min;
634 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
635 return $self->search(undef(), $attrs);
636 #my $slice = (ref $self)->new($self->result_source, $attrs);
637 #return (wantarray ? $slice->all : $slice);
644 =item Arguments: none
646 =item Return Value: $result?
650 Returns the next element in the resultset (C<undef> is there is none).
652 Can be used to efficiently iterate over records in the resultset:
654 my $rs = $schema->resultset('CD')->search;
655 while (my $cd = $rs->next) {
659 Note that you need to store the resultset object, and call C<next> on it.
660 Calling C<< resultset('Table')->next >> repeatedly will always return the
661 first record from the resultset.
667 if (my $cache = $self->get_cache) {
668 $self->{all_cache_position} ||= 0;
669 return $cache->[$self->{all_cache_position}++];
671 if ($self->{attrs}{cache}) {
672 $self->{all_cache_position} = 1;
673 return ($self->all)[0];
676 exists $self->{stashed_row}
677 ? @{delete $self->{stashed_row}}
678 : $self->cursor->next
680 return unless (@row);
681 return $self->_construct_object(@row);
684 sub _construct_object {
685 my ($self, @row) = @_;
686 my $info = $self->_collapse_result($self->{_attrs}{as}, \@row);
687 my $new = $self->result_class->inflate_result($self->result_source, @$info);
688 $new = $self->{_attrs}{record_filter}->($new)
689 if exists $self->{_attrs}{record_filter};
693 sub _collapse_result {
694 my ($self, $as, $row, $prefix) = @_;
699 foreach my $this_as (@$as) {
700 my $val = shift @copy;
701 if (defined $prefix) {
702 if ($this_as =~ m/^\Q${prefix}.\E(.+)$/) {
704 $remain =~ /^(?:(.*)\.)?([^.]+)$/;
705 $const{$1||''}{$2} = $val;
708 $this_as =~ /^(?:(.*)\.)?([^.]+)$/;
709 $const{$1||''}{$2} = $val;
713 my $alias = $self->{attrs}{alias};
714 my $info = [ {}, {} ];
715 foreach my $key (keys %const) {
716 if (length $key && $key ne $alias) {
718 my @parts = split(/\./, $key);
719 foreach my $p (@parts) {
720 $target = $target->[1]->{$p} ||= [];
722 $target->[0] = $const{$key};
724 $info->[0] = $const{$key};
729 if (defined $prefix) {
731 m/^\Q${prefix}.\E(.+)$/ ? ($1) : ()
732 } keys %{$self->{_attrs}{collapse}}
734 @collapse = keys %{$self->{_attrs}{collapse}};
738 my ($c) = sort { length $a <=> length $b } @collapse;
740 foreach my $p (split(/\./, $c)) {
741 $target = $target->[1]->{$p} ||= [];
743 my $c_prefix = (defined($prefix) ? "${prefix}.${c}" : $c);
744 my @co_key = @{$self->{_attrs}{collapse}{$c_prefix}};
745 my $tree = $self->_collapse_result($as, $row, $c_prefix);
746 my %co_check = map { ($_, $tree->[0]->{$_}); } @co_key;
752 !defined($tree->[0]->{$_}) || $co_check{$_} ne $tree->[0]->{$_}
757 last unless (@raw = $self->cursor->next);
758 $row = $self->{stashed_row} = \@raw;
759 $tree = $self->_collapse_result($as, $row, $c_prefix);
761 @$target = (@final ? @final : [ {}, {} ]);
762 # single empty result to indicate an empty prefetched has_many
765 #print "final info: " . Dumper($info);
773 =item Arguments: $result_source?
775 =item Return Value: $result_source
779 An accessor for the primary ResultSource object from which this ResultSet
786 =item Arguments: $result_class?
788 =item Return Value: $result_class
792 An accessor for the class to use when creating row objects. Defaults to
793 C<< result_source->result_class >> - which in most cases is the name of the
794 L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class.
803 =item Arguments: $cond, \%attrs??
805 =item Return Value: $count
809 Performs an SQL C<COUNT> with the same query as the resultset was built
810 with to find the number of elements. If passed arguments, does a search
811 on the resultset and counts the results of that.
813 Note: When using C<count> with C<group_by>, L<DBIX::Class> emulates C<GROUP BY>
814 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
815 not support C<DISTINCT> with multiple columns. If you are using such a
816 database, you should only use columns from the main table in your C<group_by>
823 return $self->search(@_)->count if @_ and defined $_[0];
824 return scalar @{ $self->get_cache } if $self->get_cache;
825 my $count = $self->_count;
826 return 0 unless $count;
828 $count -= $self->{attrs}{offset} if $self->{attrs}{offset};
829 $count = $self->{attrs}{rows} if
830 $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
834 sub _count { # Separated out so pager can get the full count
836 my $select = { count => '*' };
838 my $attrs = { %{$self->_resolved_attrs} };
839 if (my $group_by = delete $attrs->{group_by}) {
840 delete $attrs->{having};
841 my @distinct = (ref $group_by ? @$group_by : ($group_by));
842 # todo: try CONCAT for multi-column pk
843 my @pk = $self->result_source->primary_columns;
845 my $alias = $attrs->{alias};
846 foreach my $column (@distinct) {
847 if ($column =~ qr/^(?:\Q${alias}.\E)?$pk[0]$/) {
848 @distinct = ($column);
854 $select = { count => { distinct => \@distinct } };
857 $attrs->{select} = $select;
858 $attrs->{as} = [qw/count/];
860 # offset, order by and page are not needed to count. record_filter is cdbi
861 delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
863 my $tmp_rs = (ref $self)->new($self->result_source, $attrs);
864 my ($count) = $tmp_rs->cursor->next;
872 =item Arguments: $sql_fragment, @bind_values
874 =item Return Value: $count
878 Counts the results in a literal query. Equivalent to calling L</search_literal>
879 with the passed arguments, then L</count>.
883 sub count_literal { shift->search_literal(@_)->count; }
889 =item Arguments: none
891 =item Return Value: @objects
895 Returns all elements in the resultset. Called implicitly if the resultset
896 is returned in list context.
902 return @{ $self->get_cache } if $self->get_cache;
906 # TODO: don't call resolve here
907 if (keys %{$self->_resolved_attrs->{collapse}}) {
908 # if ($self->{attrs}{prefetch}) {
909 # Using $self->cursor->all is really just an optimisation.
910 # If we're collapsing has_many prefetches it probably makes
911 # very little difference, and this is cleaner than hacking
912 # _construct_object to survive the approach
913 my @row = $self->cursor->next;
915 push(@obj, $self->_construct_object(@row));
916 @row = (exists $self->{stashed_row}
917 ? @{delete $self->{stashed_row}}
918 : $self->cursor->next);
921 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
924 $self->set_cache(\@obj) if $self->{attrs}{cache};
932 =item Arguments: none
934 =item Return Value: $self
938 Resets the resultset's cursor, so you can iterate through the elements again.
944 delete $self->{_attrs} if exists $self->{_attrs};
945 $self->{all_cache_position} = 0;
946 $self->cursor->reset;
954 =item Arguments: none
956 =item Return Value: $object?
960 Resets the resultset and returns an object for the first result (if the
961 resultset returns anything).
966 return $_[0]->reset->next;
969 # _cond_for_update_delete
971 # update/delete require the condition to be modified to handle
972 # the differing SQL syntax available. This transforms the $self->{cond}
973 # appropriately, returning the new condition.
975 sub _cond_for_update_delete {
979 # No-op. No condition, we're updating/deleting everything
980 return $cond unless ref $self->{cond};
982 if (ref $self->{cond} eq 'ARRAY') {
986 foreach my $key (keys %{$_}) {
988 $hash{$1} = $_->{$key};
994 elsif (ref $self->{cond} eq 'HASH') {
995 if ((keys %{$self->{cond}})[0] eq '-and') {
998 my @cond = @{$self->{cond}{-and}};
999 for (my $i = 0; $i < @cond; $i++) {
1000 my $entry = $cond[$i];
1003 if (ref $entry eq 'HASH') {
1004 foreach my $key (keys %{$entry}) {
1006 $hash{$1} = $entry->{$key};
1010 $entry =~ /([^.]+)$/;
1011 $hash{$1} = $cond[++$i];
1014 push @{$cond->{-and}}, \%hash;
1018 foreach my $key (keys %{$self->{cond}}) {
1020 $cond->{$1} = $self->{cond}{$key};
1025 $self->throw_exception(
1026 "Can't update/delete on resultset with condition unless hash or array"
1038 =item Arguments: \%values
1040 =item Return Value: $storage_rv
1044 Sets the specified columns in the resultset to the supplied values in a
1045 single query. Return value will be true if the update succeeded or false
1046 if no records were updated; exact type of success value is storage-dependent.
1051 my ($self, $values) = @_;
1052 $self->throw_exception("Values for update must be a hash")
1053 unless ref $values eq 'HASH';
1055 my $cond = $self->_cond_for_update_delete;
1057 return $self->result_source->storage->update(
1058 $self->result_source->from, $values, $cond
1066 =item Arguments: \%values
1068 =item Return Value: 1
1072 Fetches all objects and updates them one at a time. Note that C<update_all>
1073 will run DBIC cascade triggers, while L</update> will not.
1078 my ($self, $values) = @_;
1079 $self->throw_exception("Values for update must be a hash")
1080 unless ref $values eq 'HASH';
1081 foreach my $obj ($self->all) {
1082 $obj->set_columns($values)->update;
1091 =item Arguments: none
1093 =item Return Value: 1
1097 Deletes the contents of the resultset from its result source. Note that this
1098 will not run DBIC cascade triggers. See L</delete_all> if you need triggers
1106 my $cond = $self->_cond_for_update_delete;
1108 $self->result_source->storage->delete($self->result_source->from, $cond);
1116 =item Arguments: none
1118 =item Return Value: 1
1122 Fetches all objects and deletes them one at a time. Note that C<delete_all>
1123 will run DBIC cascade triggers, while L</delete> will not.
1129 $_->delete for $self->all;
1137 =item Arguments: none
1139 =item Return Value: $pager
1143 Return Value a L<Data::Page> object for the current resultset. Only makes
1144 sense for queries with a C<page> attribute.
1150 my $attrs = $self->{attrs};
1151 $self->throw_exception("Can't create pager for non-paged rs")
1152 unless $self->{attrs}{page};
1153 $attrs->{rows} ||= 10;
1154 return $self->{pager} ||= Data::Page->new(
1155 $self->_count, $attrs->{rows}, $self->{attrs}{page});
1162 =item Arguments: $page_number
1164 =item Return Value: $rs
1168 Returns a resultset for the $page_number page of the resultset on which page
1169 is called, where each page contains a number of rows equal to the 'rows'
1170 attribute set on the resultset (10 by default).
1175 my ($self, $page) = @_;
1176 return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
1183 =item Arguments: \%vals
1185 =item Return Value: $object
1189 Creates an object in the resultset's result class and returns it.
1194 my ($self, $values) = @_;
1195 $self->throw_exception( "new_result needs a hash" )
1196 unless (ref $values eq 'HASH');
1197 $self->throw_exception(
1198 "Can't abstract implicit construct, condition not a hash"
1199 ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
1201 my $alias = $self->{attrs}{alias};
1202 foreach my $key (keys %{$self->{cond}||{}}) {
1203 $new{$1} = $self->{cond}{$key} if ($key =~ m/^(?:\Q${alias}.\E)?([^.]+)$/);
1205 my $obj = $self->result_class->new(\%new);
1206 $obj->result_source($self->result_source) if $obj->can('result_source');
1214 =item Arguments: \%vals, \%attrs?
1216 =item Return Value: $object
1220 Find an existing record from this resultset. If none exists, instantiate a new
1221 result object and return it. The object will not be saved into your storage
1222 until you call L<DBIx::Class::Row/insert> on it.
1224 If you want objects to be saved immediately, use L</find_or_create> instead.
1230 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1231 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1232 my $exists = $self->find($hash, $attrs);
1233 return defined $exists ? $exists : $self->new_result($hash);
1240 =item Arguments: \%vals
1242 =item Return Value: $object
1246 Inserts a record into the resultset and returns the object representing it.
1248 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
1253 my ($self, $attrs) = @_;
1254 $self->throw_exception( "create needs a hashref" )
1255 unless ref $attrs eq 'HASH';
1256 return $self->new_result($attrs)->insert;
1259 =head2 find_or_create
1263 =item Arguments: \%vals, \%attrs?
1265 =item Return Value: $object
1269 $class->find_or_create({ key => $val, ... });
1271 Tries to find a record based on its primary key or unique constraint; if none
1272 is found, creates one and returns that instead.
1274 my $cd = $schema->resultset('CD')->find_or_create({
1276 artist => 'Massive Attack',
1277 title => 'Mezzanine',
1281 Also takes an optional C<key> attribute, to search by a specific key or unique
1282 constraint. For example:
1284 my $cd = $schema->resultset('CD')->find_or_create(
1286 artist => 'Massive Attack',
1287 title => 'Mezzanine',
1289 { key => 'cd_artist_title' }
1292 See also L</find> and L</update_or_create>. For information on how to declare
1293 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1297 sub find_or_create {
1299 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1300 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1301 my $exists = $self->find($hash, $attrs);
1302 return defined $exists ? $exists : $self->create($hash);
1305 =head2 update_or_create
1309 =item Arguments: \%col_values, { key => $unique_constraint }?
1311 =item Return Value: $object
1315 $class->update_or_create({ col => $val, ... });
1317 First, searches for an existing row matching one of the unique constraints
1318 (including the primary key) on the source of this resultset. If a row is
1319 found, updates it with the other given column values. Otherwise, creates a new
1322 Takes an optional C<key> attribute to search on a specific unique constraint.
1325 # In your application
1326 my $cd = $schema->resultset('CD')->update_or_create(
1328 artist => 'Massive Attack',
1329 title => 'Mezzanine',
1332 { key => 'cd_artist_title' }
1335 If no C<key> is specified, it searches on all unique constraints defined on the
1336 source, including the primary key.
1338 If the C<key> is specified as C<primary>, it searches only on the primary key.
1340 See also L</find> and L</find_or_create>. For information on how to declare
1341 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1345 sub update_or_create {
1347 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1348 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
1350 my $row = $self->find($cond);
1352 $row->update($cond);
1356 return $self->create($cond);
1363 =item Arguments: none
1365 =item Return Value: \@cache_objects?
1369 Gets the contents of the cache for the resultset, if the cache is set.
1381 =item Arguments: \@cache_objects
1383 =item Return Value: \@cache_objects
1387 Sets the contents of the cache for the resultset. Expects an arrayref
1388 of objects of the same class as those produced by the resultset. Note that
1389 if the cache is set the resultset will return the cached objects rather
1390 than re-querying the database even if the cache attr is not set.
1395 my ( $self, $data ) = @_;
1396 $self->throw_exception("set_cache requires an arrayref")
1397 if defined($data) && (ref $data ne 'ARRAY');
1398 $self->{all_cache} = $data;
1405 =item Arguments: none
1407 =item Return Value: []
1411 Clears the cache for the resultset.
1416 shift->set_cache(undef);
1419 =head2 related_resultset
1423 =item Arguments: $relationship_name
1425 =item Return Value: $resultset
1429 Returns a related resultset for the supplied relationship name.
1431 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1435 sub related_resultset {
1436 my ($self, $rel) = @_;
1438 $self->{related_resultsets} ||= {};
1439 return $self->{related_resultsets}{$rel} ||= do {
1440 my $rel_obj = $self->result_source->relationship_info($rel);
1442 $self->throw_exception(
1443 "search_related: result source '" . $self->result_source->name .
1444 "' has no such relationship $rel")
1447 my ($from,$seen) = $self->_resolve_from($rel);
1449 my $join_count = $seen->{$rel};
1450 my $alias = ($join_count > 1 ? join('_', $rel, $join_count) : $rel);
1452 $self->result_source->schema->resultset($rel_obj->{class})->search_rs(
1454 %{$self->{attrs}||{}},
1460 where => $self->{cond},
1468 my ($self, $extra_join) = @_;
1469 my $source = $self->result_source;
1470 my $attrs = $self->{attrs};
1472 my $from = $attrs->{from}
1473 || [ { $attrs->{alias} => $source->from } ];
1475 my $seen = { %{$attrs->{seen_join}||{}} };
1477 my $join = ($attrs->{join}
1478 ? [ $attrs->{join}, $extra_join ]
1482 ($join ? $source->resolve_join($join, $attrs->{alias}, $seen) : ()),
1485 return ($from,$seen);
1488 sub _resolved_attrs {
1490 return $self->{_attrs} if $self->{_attrs};
1492 my $attrs = { %{$self->{attrs}||{}} };
1493 my $source = $self->{result_source};
1494 my $alias = $attrs->{alias};
1496 $attrs->{columns} ||= delete $attrs->{cols} if exists $attrs->{cols};
1497 if ($attrs->{columns}) {
1498 delete $attrs->{as};
1499 } elsif (!$attrs->{select}) {
1500 $attrs->{columns} = [ $source->columns ];
1505 ? (ref $attrs->{select} eq 'ARRAY'
1506 ? [ @{$attrs->{select}} ]
1507 : [ $attrs->{select} ])
1508 : [ map { m/\./ ? $_ : "${alias}.$_" } @{delete $attrs->{columns}} ]
1512 ? (ref $attrs->{as} eq 'ARRAY'
1513 ? [ @{$attrs->{as}} ]
1515 : [ map { m/^\Q${alias}.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}} ]
1519 if ($adds = delete $attrs->{include_columns}) {
1520 $adds = [$adds] unless ref $adds eq 'ARRAY';
1521 push(@{$attrs->{select}}, @$adds);
1522 push(@{$attrs->{as}}, map { m/([^.]+)$/; $1 } @$adds);
1524 if ($adds = delete $attrs->{'+select'}) {
1525 $adds = [$adds] unless ref $adds eq 'ARRAY';
1526 push(@{$attrs->{select}},
1527 map { /\./ || ref $_ ? $_ : "${alias}.$_" } @$adds);
1529 if (my $adds = delete $attrs->{'+as'}) {
1530 $adds = [$adds] unless ref $adds eq 'ARRAY';
1531 push(@{$attrs->{as}}, @$adds);
1534 $attrs->{from} ||= [ { 'me' => $source->from } ];
1536 if (exists $attrs->{join} || exists $attrs->{prefetch}) {
1537 my $join = delete $attrs->{join} || {};
1539 if (defined $attrs->{prefetch}) {
1540 $join = $self->_merge_attr(
1541 $join, $attrs->{prefetch}
1545 $attrs->{from} = # have to copy here to avoid corrupting the original
1548 $source->resolve_join($join, $alias, { %{$attrs->{seen_join}||{}} })
1552 $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
1553 if ($attrs->{order_by}) {
1554 $attrs->{order_by} = (ref($attrs->{order_by}) eq 'ARRAY'
1555 ? [ @{$attrs->{order_by}} ]
1556 : [ $attrs->{order_by} ]);
1558 $attrs->{order_by} = [];
1561 my $collapse = $attrs->{collapse} || {};
1562 if (my $prefetch = delete $attrs->{prefetch}) {
1564 foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
1565 # bring joins back to level of current class
1566 my @prefetch = $source->resolve_prefetch(
1567 $p, $alias, { %{$attrs->{seen_join}||{}} }, \@pre_order, $collapse
1569 push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
1570 push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
1572 push(@{$attrs->{order_by}}, @pre_order);
1574 $attrs->{collapse} = $collapse;
1576 return $self->{_attrs} = $attrs;
1580 my ($self, $a, $b) = @_;
1581 return $b unless defined($a);
1582 return $a unless defined($b);
1584 if (ref $b eq 'HASH' && ref $a eq 'HASH') {
1585 foreach my $key (keys %{$b}) {
1586 if (exists $a->{$key}) {
1587 $a->{$key} = $self->_merge_attr($a->{$key}, $b->{$key});
1589 $a->{$key} = $b->{$key};
1594 $a = [$a] unless ref $a eq 'ARRAY';
1595 $b = [$b] unless ref $b eq 'ARRAY';
1599 foreach my $x ($a, $b) {
1600 foreach my $element (@{$x}) {
1601 if (ref $element eq 'HASH') {
1602 $hash = $self->_merge_attr($hash, $element);
1603 } elsif (ref $element eq 'ARRAY') {
1604 push(@array, @{$element});
1606 push(@array, $element) unless $b == $x
1607 && grep { $_ eq $element } @array;
1612 @array = grep { !exists $hash->{$_} } @array;
1614 return keys %{$hash}
1623 =head2 throw_exception
1625 See L<DBIx::Class::Schema/throw_exception> for details.
1629 sub throw_exception {
1631 $self->result_source->schema->throw_exception(@_);
1634 # XXX: FIXME: Attributes docs need clearing up
1638 The resultset takes various attributes that modify its behavior. Here's an
1645 =item Value: ($order_by | \@order_by)
1649 Which column(s) to order the results by. This is currently passed
1650 through directly to SQL, so you can give e.g. C<year DESC> for a
1651 descending order on the column `year'.
1653 Please note that if you have quoting enabled (see
1654 L<DBIx::Class::Storage/quote_char>) you will need to do C<\'year DESC' > to
1655 specify an order. (The scalar ref causes it to be passed as raw sql to the DB,
1656 so you will need to manually quote things as appropriate.)
1662 =item Value: \@columns
1666 Shortcut to request a particular set of columns to be retrieved. Adds
1667 C<me.> onto the start of any column without a C<.> in it and sets C<select>
1668 from that, then auto-populates C<as> from C<select> as normal. (You may also
1669 use the C<cols> attribute, as in earlier versions of DBIC.)
1671 =head2 include_columns
1675 =item Value: \@columns
1679 Shortcut to include additional columns in the returned results - for example
1681 $schema->resultset('CD')->search(undef, {
1682 include_columns => ['artist.name'],
1686 would return all CDs and include a 'name' column to the information
1687 passed to object inflation
1693 =item Value: \@select_columns
1697 Indicates which columns should be selected from the storage. You can use
1698 column names, or in the case of RDBMS back ends, function or stored procedure
1701 $rs = $schema->resultset('Employee')->search(undef, {
1704 { count => 'employeeid' },
1709 When you use function/stored procedure names and do not supply an C<as>
1710 attribute, the column names returned are storage-dependent. E.g. MySQL would
1711 return a column named C<count(employeeid)> in the above example.
1717 Indicates additional columns to be selected from storage. Works the same as
1718 L<select> but adds columns to the selection.
1726 Indicates additional column names for those added via L<+select>.
1734 =item Value: \@inflation_names
1738 Indicates column names for object inflation. This is used in conjunction with
1739 C<select>, usually when C<select> contains one or more function or stored
1742 $rs = $schema->resultset('Employee')->search(undef, {
1745 { count => 'employeeid' }
1747 as => ['name', 'employee_count'],
1750 my $employee = $rs->first(); # get the first Employee
1752 If the object against which the search is performed already has an accessor
1753 matching a column name specified in C<as>, the value can be retrieved using
1754 the accessor as normal:
1756 my $name = $employee->name();
1758 If on the other hand an accessor does not exist in the object, you need to
1759 use C<get_column> instead:
1761 my $employee_count = $employee->get_column('employee_count');
1763 You can create your own accessors if required - see
1764 L<DBIx::Class::Manual::Cookbook> for details.
1766 Please note: This will NOT insert an C<AS employee_count> into the SQL
1767 statement produced, it is used for internal access only. Thus
1768 attempting to use the accessor in an C<order_by> clause or similar
1769 will fail miserably.
1771 To get around this limitation, you can supply literal SQL to your
1772 C<select> attibute that contains the C<AS alias> text, eg:
1774 select => [\'myfield AS alias']
1780 =item Value: ($rel_name | \@rel_names | \%rel_names)
1784 Contains a list of relationships that should be joined for this query. For
1787 # Get CDs by Nine Inch Nails
1788 my $rs = $schema->resultset('CD')->search(
1789 { 'artist.name' => 'Nine Inch Nails' },
1790 { join => 'artist' }
1793 Can also contain a hash reference to refer to the other relation's relations.
1796 package MyApp::Schema::Track;
1797 use base qw/DBIx::Class/;
1798 __PACKAGE__->table('track');
1799 __PACKAGE__->add_columns(qw/trackid cd position title/);
1800 __PACKAGE__->set_primary_key('trackid');
1801 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
1804 # In your application
1805 my $rs = $schema->resultset('Artist')->search(
1806 { 'track.title' => 'Teardrop' },
1808 join => { cd => 'track' },
1809 order_by => 'artist.name',
1813 If the same join is supplied twice, it will be aliased to <rel>_2 (and
1814 similarly for a third time). For e.g.
1816 my $rs = $schema->resultset('Artist')->search({
1817 'cds.title' => 'Down to Earth',
1818 'cds_2.title' => 'Popular',
1820 join => [ qw/cds cds/ ],
1823 will return a set of all artists that have both a cd with title 'Down
1824 to Earth' and a cd with title 'Popular'.
1826 If you want to fetch related objects from other tables as well, see C<prefetch>
1833 =item Value: ($rel_name | \@rel_names | \%rel_names)
1837 Contains one or more relationships that should be fetched along with the main
1838 query (when they are accessed afterwards they will have already been
1839 "prefetched"). This is useful for when you know you will need the related
1840 objects, because it saves at least one query:
1842 my $rs = $schema->resultset('Tag')->search(
1851 The initial search results in SQL like the following:
1853 SELECT tag.*, cd.*, artist.* FROM tag
1854 JOIN cd ON tag.cd = cd.cdid
1855 JOIN artist ON cd.artist = artist.artistid
1857 L<DBIx::Class> has no need to go back to the database when we access the
1858 C<cd> or C<artist> relationships, which saves us two SQL statements in this
1861 Simple prefetches will be joined automatically, so there is no need
1862 for a C<join> attribute in the above search. If you're prefetching to
1863 depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
1864 specify the join as well.
1866 C<prefetch> can be used with the following relationship types: C<belongs_to>,
1867 C<has_one> (or if you're using C<add_relationship>, any relationship declared
1868 with an accessor type of 'single' or 'filter').
1878 Makes the resultset paged and specifies the page to retrieve. Effectively
1879 identical to creating a non-pages resultset and then calling ->page($page)
1882 If L<rows> attribute is not specified it defualts to 10 rows per page.
1892 Specifes the maximum number of rows for direct retrieval or the number of
1893 rows per page if the page attribute or method is used.
1899 =item Value: $offset
1903 Specifies the (zero-based) row number for the first row to be returned, or the
1904 of the first row of the first page if paging is used.
1910 =item Value: \@columns
1914 A arrayref of columns to group by. Can include columns of joined tables.
1916 group_by => [qw/ column1 column2 ... /]
1922 =item Value: $condition
1926 HAVING is a select statement attribute that is applied between GROUP BY and
1927 ORDER BY. It is applied to the after the grouping calculations have been
1930 having => { 'count(employee)' => { '>=', 100 } }
1936 =item Value: (0 | 1)
1940 Set to 1 to group by all columns.
1946 Adds to the WHERE clause.
1948 # only return rows WHERE deleted IS NULL for all searches
1949 __PACKAGE__->resultset_attributes({ where => { deleted => undef } }); )
1951 Can be overridden by passing C<{ where => undef }> as an attribute
1958 Set to 1 to cache search results. This prevents extra SQL queries if you
1959 revisit rows in your ResultSet:
1961 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
1963 while( my $artist = $resultset->next ) {
1967 $rs->first; # without cache, this would issue a query
1969 By default, searches are not cached.
1971 For more examples of using these attributes, see
1972 L<DBIx::Class::Manual::Cookbook>.
1978 =item Value: \@from_clause
1982 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
1983 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
1986 NOTE: Use this on your own risk. This allows you to shoot off your foot!
1988 C<join> will usually do what you need and it is strongly recommended that you
1989 avoid using C<from> unless you cannot achieve the desired result using C<join>.
1990 And we really do mean "cannot", not just tried and failed. Attempting to use
1991 this because you're having problems with C<join> is like trying to use x86
1992 ASM because you've got a syntax error in your C. Trust us on this.
1994 Now, if you're still really, really sure you need to use this (and if you're
1995 not 100% sure, ask the mailing list first), here's an explanation of how this
1998 The syntax is as follows -
2001 { <alias1> => <table1> },
2003 { <alias2> => <table2>, -join_type => 'inner|left|right' },
2004 [], # nested JOIN (optional)
2005 { <table1.column1> => <table2.column2>, ... (more conditions) },
2007 # More of the above [ ] may follow for additional joins
2014 ON <table1.column1> = <table2.column2>
2015 <more joins may follow>
2017 An easy way to follow the examples below is to remember the following:
2019 Anything inside "[]" is a JOIN
2020 Anything inside "{}" is a condition for the enclosing JOIN
2022 The following examples utilize a "person" table in a family tree application.
2023 In order to express parent->child relationships, this table is self-joined:
2025 # Person->belongs_to('father' => 'Person');
2026 # Person->belongs_to('mother' => 'Person');
2028 C<from> can be used to nest joins. Here we return all children with a father,
2029 then search against all mothers of those children:
2031 $rs = $schema->resultset('Person')->search(
2034 alias => 'mother', # alias columns in accordance with "from"
2036 { mother => 'person' },
2039 { child => 'person' },
2041 { father => 'person' },
2042 { 'father.person_id' => 'child.father_id' }
2045 { 'mother.person_id' => 'child.mother_id' }
2052 # SELECT mother.* FROM person mother
2055 # JOIN person father
2056 # ON ( father.person_id = child.father_id )
2058 # ON ( mother.person_id = child.mother_id )
2060 The type of any join can be controlled manually. To search against only people
2061 with a father in the person table, we could explicitly use C<INNER JOIN>:
2063 $rs = $schema->resultset('Person')->search(
2066 alias => 'child', # alias columns in accordance with "from"
2068 { child => 'person' },
2070 { father => 'person', -join_type => 'inner' },
2071 { 'father.id' => 'child.father_id' }
2078 # SELECT child.* FROM person child
2079 # INNER JOIN person father ON child.father_id = father.id