1 package DBIx::Class::ResultSet;
9 use Carp::Clan qw/^DBIx::Class/;
12 use DBIx::Class::ResultSetColumn;
13 use base qw/DBIx::Class/;
15 use Data::Dumper; $Data::Dumper::Indent = 1;
17 __PACKAGE__->load_components(qw/AccessorGroup/);
18 __PACKAGE__->mk_group_accessors('simple' => qw/result_source result_class/);
22 DBIx::Class::ResultSet - Responsible for fetching and creating resultset.
26 my $rs = $schema->resultset('User')->search(registered => 1);
27 my @rows = $schema->resultset('CD')->search(year => 2005);
31 The resultset is also known as an iterator. It is responsible for handling
32 queries that may return an arbitrary number of rows, e.g. via L</search>
33 or a C<has_many> relationship.
35 In the examples below, the following table classes are used:
37 package MyApp::Schema::Artist;
38 use base qw/DBIx::Class/;
39 __PACKAGE__->load_components(qw/Core/);
40 __PACKAGE__->table('artist');
41 __PACKAGE__->add_columns(qw/artistid name/);
42 __PACKAGE__->set_primary_key('artistid');
43 __PACKAGE__->has_many(cds => 'MyApp::Schema::CD');
46 package MyApp::Schema::CD;
47 use base qw/DBIx::Class/;
48 __PACKAGE__->load_components(qw/Core/);
49 __PACKAGE__->table('cd');
50 __PACKAGE__->add_columns(qw/cdid artist title year/);
51 __PACKAGE__->set_primary_key('cdid');
52 __PACKAGE__->belongs_to(artist => 'MyApp::Schema::Artist');
61 =item Arguments: $source, \%$attrs
63 =item Return Value: $rs
67 The resultset constructor. Takes a source object (usually a
68 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
69 L</ATTRIBUTES> below). Does not perform any queries -- these are
70 executed as needed by the other methods.
72 Generally you won't need to construct a resultset manually. You'll
73 automatically get one from e.g. a L</search> called in scalar context:
75 my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
77 IMPORTANT: If called on an object, proxies to new_result instead so
79 my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
81 will return a CD object, not a ResultSet.
87 return $class->new_result(@_) if ref $class;
89 my ($source, $attrs) = @_;
93 $attrs->{rows} ||= 10;
94 $attrs->{offset} ||= 0;
95 $attrs->{offset} += ($attrs->{rows} * ($attrs->{page} - 1));
98 $attrs->{alias} ||= 'me';
101 result_source => $source,
102 result_class => $attrs->{result_class} || $source->result_class,
103 cond => $attrs->{where},
104 # from => $attrs->{from},
105 # collapse => $collapse,
116 =item Arguments: $cond, \%attrs?
118 =item Return Value: $resultset (scalar context), @row_objs (list context)
122 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
123 my $new_rs = $cd_rs->search({ year => 2005 });
125 my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
126 # year = 2005 OR year = 2004
128 If you need to pass in additional attributes but no additional condition,
129 call it as C<search(undef, \%attrs)>.
131 # "SELECT name, artistid FROM $artist_table"
132 my @all_artists = $schema->resultset('Artist')->search(undef, {
133 columns => [qw/name artistid/],
140 my $rs = $self->search_rs( @_ );
141 return (wantarray ? $rs->all : $rs);
148 =item Arguments: $cond, \%attrs?
150 =item Return Value: $resultset
154 This method does the same exact thing as search() except it will
155 always return a resultset, even in list context.
164 unless (@_) { # no search, effectively just a clone
165 $rows = $self->get_cache;
169 $attrs = pop(@_) if @_ > 1 and ref $_[$#_] eq 'HASH';
170 my $our_attrs = { %{$self->{attrs}} };
171 my $having = delete $our_attrs->{having};
173 # merge new attrs into inherited
174 foreach my $key (qw/join prefetch/) {
175 next unless exists $attrs->{$key};
176 $our_attrs->{$key} = $self->_merge_attr($our_attrs->{$key}, delete $attrs->{$key});
179 my $new_attrs = { %{$our_attrs}, %{$attrs} };
182 (@_ == 1 || ref $_[0] eq "HASH")
186 ? $self->throw_exception("Odd number of arguments to search")
193 if (defined $where) {
194 $new_attrs->{where} = (
195 defined $new_attrs->{where}
198 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
199 } $where, $new_attrs->{where}
205 if (defined $having) {
206 $new_attrs->{having} = (
207 defined $new_attrs->{having}
210 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
211 } $having, $new_attrs->{having}
217 my $rs = (ref $self)->new($self->result_source, $new_attrs);
219 $rs->set_cache($rows);
224 =head2 search_literal
228 =item Arguments: $sql_fragment, @bind_values
230 =item Return Value: $resultset (scalar context), @row_objs (list context)
234 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
235 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
237 Pass a literal chunk of SQL to be added to the conditional part of the
243 my ($self, $cond, @vals) = @_;
244 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
245 $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
246 return $self->search(\$cond, $attrs);
253 =item Arguments: @values | \%cols, \%attrs?
255 =item Return Value: $row_object
259 Finds a row based on its primary key or unique constraint. For example, to find
260 a row by its primary key:
262 my $cd = $schema->resultset('CD')->find(5);
264 You can also find a row by a specific unique constraint using the C<key>
265 attribute. For example:
267 my $cd = $schema->resultset('CD')->find('Massive Attack', 'Mezzanine', {
268 key => 'cd_artist_title'
271 Additionally, you can specify the columns explicitly by name:
273 my $cd = $schema->resultset('CD')->find(
275 artist => 'Massive Attack',
276 title => 'Mezzanine',
278 { key => 'cd_artist_title' }
281 If the C<key> is specified as C<primary>, it searches only on the primary key.
283 If no C<key> is specified, it searches on all unique constraints defined on the
284 source, including the primary key.
286 See also L</find_or_create> and L</update_or_create>. For information on how to
287 declare unique constraints, see
288 L<DBIx::Class::ResultSource/add_unique_constraint>.
294 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
296 # Default to the primary key, but allow a specific key
297 my @cols = exists $attrs->{key}
298 ? $self->result_source->unique_constraint_columns($attrs->{key})
299 : $self->result_source->primary_columns;
300 $self->throw_exception(
301 "Can't find unless a primary key or unique constraint is defined"
304 # Parse out a hashref from input
306 if (ref $_[0] eq 'HASH') {
307 $input_query = { %{$_[0]} };
309 elsif (@_ == @cols) {
311 @{$input_query}{@cols} = @_;
314 # Compatibility: Allow e.g. find(id => $value)
315 carp "Find by key => value deprecated; please use a hashref instead";
319 my @unique_queries = $self->_unique_queries($input_query, $attrs);
321 # Handle cases where the ResultSet defines the query, or where the user is
323 my $query = @unique_queries ? \@unique_queries : $input_query;
327 my $rs = $self->search($query, $attrs);
328 return keys %{$rs->_resolved_attrs->{collapse}} ? $rs->next : $rs->single;
331 return keys %{$self->_resolved_attrs->{collapse}}
332 ? $self->search($query)->next
333 : $self->single($query);
339 # Build a list of queries which satisfy unique constraints.
341 sub _unique_queries {
342 my ($self, $query, $attrs) = @_;
344 my $alias = $self->{attrs}{alias};
345 my @constraint_names = exists $attrs->{key}
347 : $self->result_source->unique_constraint_names;
350 foreach my $name (@constraint_names) {
351 my @unique_cols = $self->result_source->unique_constraint_columns($name);
352 my $unique_query = $self->_build_unique_query($query, \@unique_cols);
354 my $num_query = scalar keys %$unique_query;
355 next unless $num_query;
357 # Add the ResultSet's alias
358 foreach my $col (grep { ! m/\./ } keys %$unique_query) {
359 $unique_query->{"$alias.$col"} = delete $unique_query->{$col};
362 # XXX: Assuming quite a bit about $self->{attrs}{where}
363 my $num_cols = scalar @unique_cols;
364 my $num_where = exists $self->{attrs}{where}
365 ? scalar keys %{ $self->{attrs}{where} }
367 push @unique_queries, $unique_query
368 if $num_query + $num_where == $num_cols;
371 return @unique_queries;
374 # _build_unique_query
376 # Constrain the specified query hash based on the specified column names.
378 sub _build_unique_query {
379 my ($self, $query, $unique_cols) = @_;
382 map { $_ => $query->{$_} }
383 grep { exists $query->{$_} }
388 =head2 search_related
392 =item Arguments: $rel, $cond, \%attrs?
394 =item Return Value: $new_resultset
398 $new_rs = $cd_rs->search_related('artist', {
402 Searches the specified relationship, optionally specifying a condition and
403 attributes for matching records. See L</ATTRIBUTES> for more information.
408 return shift->related_resultset(shift)->search(@_);
415 =item Arguments: none
417 =item Return Value: $cursor
421 Returns a storage-driven cursor to the given resultset. See
422 L<DBIx::Class::Cursor> for more information.
429 my $attrs = { %{$self->_resolved_attrs} };
430 return $self->{cursor}
431 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
432 $attrs->{where},$attrs);
439 =item Arguments: $cond?
441 =item Return Value: $row_object?
445 my $cd = $schema->resultset('CD')->single({ year => 2001 });
447 Inflates the first result without creating a cursor if the resultset has
448 any records in it; if not returns nothing. Used by L</find> as an optimisation.
450 Can optionally take an additional condition *only* - this is a fast-code-path
451 method; if you need to add extra joins or similar call ->search and then
452 ->single without a condition on the $rs returned from that.
457 my ($self, $where) = @_;
458 my $attrs = { %{$self->_resolved_attrs} };
460 if (defined $attrs->{where}) {
463 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
464 $where, delete $attrs->{where} ]
467 $attrs->{where} = $where;
471 unless ($self->_is_unique_query($attrs->{where})) {
472 carp "Query not guaranteed to return a single row"
473 . "; please declare your unique constraints or use search instead";
476 my @data = $self->result_source->storage->select_single(
477 $attrs->{from}, $attrs->{select},
478 $attrs->{where}, $attrs
481 return (@data ? $self->_construct_object(@data) : ());
486 # Try to determine if the specified query is guaranteed to be unique, based on
487 # the declared unique constraints.
489 sub _is_unique_query {
490 my ($self, $query) = @_;
492 my $collapsed = $self->_collapse_query($query);
493 my $alias = $self->{attrs}{alias};
495 foreach my $name ($self->result_source->unique_constraint_names) {
496 my @unique_cols = map {
498 } $self->result_source->unique_constraint_columns($name);
500 # Count the values for each unique column
501 my %seen = map { $_ => 0 } @unique_cols;
503 foreach my $key (keys %$collapsed) {
504 my $aliased = $key =~ /\./ ? $key : "$alias.$key";
505 next unless exists $seen{$aliased}; # Additional constraints are okay
506 $seen{$aliased} = scalar keys %{ $collapsed->{$key} };
509 # If we get 0 or more than 1 value for a column, it's not necessarily unique
510 return 1 unless grep { $_ != 1 } values %seen;
518 # Recursively collapse the query, accumulating values for each column.
520 sub _collapse_query {
521 my ($self, $query, $collapsed) = @_;
525 if (ref $query eq 'ARRAY') {
526 foreach my $subquery (@$query) {
527 next unless ref $subquery; # -or
528 # warn "ARRAY: " . Dumper $subquery;
529 $collapsed = $self->_collapse_query($subquery, $collapsed);
532 elsif (ref $query eq 'HASH') {
533 if (keys %$query and (keys %$query)[0] eq '-and') {
534 foreach my $subquery (@{$query->{-and}}) {
535 # warn "HASH: " . Dumper $subquery;
536 $collapsed = $self->_collapse_query($subquery, $collapsed);
540 # warn "LEAF: " . Dumper $query;
541 foreach my $col (keys %$query) {
542 my $value = $query->{$col};
543 $collapsed->{$col}{$value}++;
555 =item Arguments: $cond?
557 =item Return Value: $resultsetcolumn
561 my $max_length = $rs->get_column('length')->max;
563 Returns a ResultSetColumn instance for $column based on $self
568 my ($self, $column) = @_;
569 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
577 =item Arguments: $cond, \%attrs?
579 =item Return Value: $resultset (scalar context), @row_objs (list context)
583 # WHERE title LIKE '%blue%'
584 $cd_rs = $rs->search_like({ title => '%blue%'});
586 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
587 that this is simply a convenience method. You most likely want to use
588 L</search> with specific operators.
590 For more information, see L<DBIx::Class::Manual::Cookbook>.
596 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
597 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
598 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
599 return $class->search($query, { %$attrs });
606 =item Arguments: $first, $last
608 =item Return Value: $resultset (scalar context), @row_objs (list context)
612 Returns a resultset or object list representing a subset of elements from the
613 resultset slice is called on. Indexes are from 0, i.e., to get the first
616 my ($one, $two, $three) = $rs->slice(0, 2);
621 my ($self, $min, $max) = @_;
622 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
623 $attrs->{offset} = $self->{attrs}{offset} || 0;
624 $attrs->{offset} += $min;
625 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
626 return $self->search(undef(), $attrs);
627 #my $slice = (ref $self)->new($self->result_source, $attrs);
628 #return (wantarray ? $slice->all : $slice);
635 =item Arguments: none
637 =item Return Value: $result?
641 Returns the next element in the resultset (C<undef> is there is none).
643 Can be used to efficiently iterate over records in the resultset:
645 my $rs = $schema->resultset('CD')->search;
646 while (my $cd = $rs->next) {
650 Note that you need to store the resultset object, and call C<next> on it.
651 Calling C<< resultset('Table')->next >> repeatedly will always return the
652 first record from the resultset.
658 if (my $cache = $self->get_cache) {
659 $self->{all_cache_position} ||= 0;
660 return $cache->[$self->{all_cache_position}++];
662 if ($self->{attrs}{cache}) {
663 $self->{all_cache_position} = 1;
664 return ($self->all)[0];
667 exists $self->{stashed_row}
668 ? @{delete $self->{stashed_row}}
669 : $self->cursor->next
671 return unless (@row);
672 return $self->_construct_object(@row);
675 sub _construct_object {
676 my ($self, @row) = @_;
677 my $info = $self->_collapse_result($self->{_attrs}{as}, \@row);
678 my $new = $self->result_class->inflate_result($self->result_source, @$info);
679 $new = $self->{_attrs}{record_filter}->($new)
680 if exists $self->{_attrs}{record_filter};
684 sub _collapse_result {
685 my ($self, $as, $row, $prefix) = @_;
690 foreach my $this_as (@$as) {
691 my $val = shift @copy;
692 if (defined $prefix) {
693 if ($this_as =~ m/^\Q${prefix}.\E(.+)$/) {
695 $remain =~ /^(?:(.*)\.)?([^.]+)$/;
696 $const{$1||''}{$2} = $val;
699 $this_as =~ /^(?:(.*)\.)?([^.]+)$/;
700 $const{$1||''}{$2} = $val;
704 my $alias = $self->{attrs}{alias};
705 my $info = [ {}, {} ];
706 foreach my $key (keys %const) {
707 if (length $key && $key ne $alias) {
709 my @parts = split(/\./, $key);
710 foreach my $p (@parts) {
711 $target = $target->[1]->{$p} ||= [];
713 $target->[0] = $const{$key};
715 $info->[0] = $const{$key};
720 if (defined $prefix) {
722 m/^\Q${prefix}.\E(.+)$/ ? ($1) : ()
723 } keys %{$self->{_attrs}{collapse}}
725 @collapse = keys %{$self->{_attrs}{collapse}};
729 my ($c) = sort { length $a <=> length $b } @collapse;
731 foreach my $p (split(/\./, $c)) {
732 $target = $target->[1]->{$p} ||= [];
734 my $c_prefix = (defined($prefix) ? "${prefix}.${c}" : $c);
735 my @co_key = @{$self->{_attrs}{collapse}{$c_prefix}};
736 my $tree = $self->_collapse_result($as, $row, $c_prefix);
737 my %co_check = map { ($_, $tree->[0]->{$_}); } @co_key;
743 !defined($tree->[0]->{$_}) || $co_check{$_} ne $tree->[0]->{$_}
748 last unless (@raw = $self->cursor->next);
749 $row = $self->{stashed_row} = \@raw;
750 $tree = $self->_collapse_result($as, $row, $c_prefix);
752 @$target = (@final ? @final : [ {}, {} ]);
753 # single empty result to indicate an empty prefetched has_many
756 #print "final info: " . Dumper($info);
764 =item Arguments: $result_source?
766 =item Return Value: $result_source
770 An accessor for the primary ResultSource object from which this ResultSet
780 =item Arguments: $cond, \%attrs??
782 =item Return Value: $count
786 Performs an SQL C<COUNT> with the same query as the resultset was built
787 with to find the number of elements. If passed arguments, does a search
788 on the resultset and counts the results of that.
790 Note: When using C<count> with C<group_by>, L<DBIX::Class> emulates C<GROUP BY>
791 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
792 not support C<DISTINCT> with multiple columns. If you are using such a
793 database, you should only use columns from the main table in your C<group_by>
800 return $self->search(@_)->count if @_ and defined $_[0];
801 return scalar @{ $self->get_cache } if $self->get_cache;
802 my $count = $self->_count;
803 return 0 unless $count;
805 $count -= $self->{attrs}{offset} if $self->{attrs}{offset};
806 $count = $self->{attrs}{rows} if
807 $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
811 sub _count { # Separated out so pager can get the full count
813 my $select = { count => '*' };
815 my $attrs = { %{$self->_resolved_attrs} };
816 if (my $group_by = delete $attrs->{group_by}) {
817 delete $attrs->{having};
818 my @distinct = (ref $group_by ? @$group_by : ($group_by));
819 # todo: try CONCAT for multi-column pk
820 my @pk = $self->result_source->primary_columns;
822 my $alias = $attrs->{alias};
823 foreach my $column (@distinct) {
824 if ($column =~ qr/^(?:\Q${alias}.\E)?$pk[0]$/) {
825 @distinct = ($column);
831 $select = { count => { distinct => \@distinct } };
834 $attrs->{select} = $select;
835 $attrs->{as} = [qw/count/];
837 # offset, order by and page are not needed to count. record_filter is cdbi
838 delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
840 my $tmp_rs = (ref $self)->new($self->result_source, $attrs);
841 my ($count) = $tmp_rs->cursor->next;
849 =item Arguments: $sql_fragment, @bind_values
851 =item Return Value: $count
855 Counts the results in a literal query. Equivalent to calling L</search_literal>
856 with the passed arguments, then L</count>.
860 sub count_literal { shift->search_literal(@_)->count; }
866 =item Arguments: none
868 =item Return Value: @objects
872 Returns all elements in the resultset. Called implicitly if the resultset
873 is returned in list context.
879 return @{ $self->get_cache } if $self->get_cache;
883 # TODO: don't call resolve here
884 if (keys %{$self->_resolved_attrs->{collapse}}) {
885 # if ($self->{attrs}{prefetch}) {
886 # Using $self->cursor->all is really just an optimisation.
887 # If we're collapsing has_many prefetches it probably makes
888 # very little difference, and this is cleaner than hacking
889 # _construct_object to survive the approach
890 my @row = $self->cursor->next;
892 push(@obj, $self->_construct_object(@row));
893 @row = (exists $self->{stashed_row}
894 ? @{delete $self->{stashed_row}}
895 : $self->cursor->next);
898 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
901 $self->set_cache(\@obj) if $self->{attrs}{cache};
909 =item Arguments: none
911 =item Return Value: $self
915 Resets the resultset's cursor, so you can iterate through the elements again.
921 delete $self->{_attrs} if exists $self->{_attrs};
922 $self->{all_cache_position} = 0;
923 $self->cursor->reset;
931 =item Arguments: none
933 =item Return Value: $object?
937 Resets the resultset and returns an object for the first result (if the
938 resultset returns anything).
943 return $_[0]->reset->next;
946 # _cond_for_update_delete
948 # update/delete require the condition to be modified to handle
949 # the differing SQL syntax available. This transforms the $self->{cond}
950 # appropriately, returning the new condition.
952 sub _cond_for_update_delete {
956 # No-op. No condition, we're updating/deleting everything
957 return $cond unless ref $self->{cond};
959 if (ref $self->{cond} eq 'ARRAY') {
963 foreach my $key (keys %{$_}) {
965 $hash{$1} = $_->{$key};
971 elsif (ref $self->{cond} eq 'HASH') {
972 if ((keys %{$self->{cond}})[0] eq '-and') {
975 my @cond = @{$self->{cond}{-and}};
976 for (my $i = 0; $i < @cond; $i++) {
977 my $entry = $cond[$i];
980 if (ref $entry eq 'HASH') {
981 foreach my $key (keys %{$entry}) {
983 $hash{$1} = $entry->{$key};
987 $entry =~ /([^.]+)$/;
988 $hash{$1} = $cond[++$i];
991 push @{$cond->{-and}}, \%hash;
995 foreach my $key (keys %{$self->{cond}}) {
997 $cond->{$1} = $self->{cond}{$key};
1002 $self->throw_exception(
1003 "Can't update/delete on resultset with condition unless hash or array"
1015 =item Arguments: \%values
1017 =item Return Value: $storage_rv
1021 Sets the specified columns in the resultset to the supplied values in a
1022 single query. Return value will be true if the update succeeded or false
1023 if no records were updated; exact type of success value is storage-dependent.
1028 my ($self, $values) = @_;
1029 $self->throw_exception("Values for update must be a hash")
1030 unless ref $values eq 'HASH';
1032 my $cond = $self->_cond_for_update_delete;
1034 return $self->result_source->storage->update(
1035 $self->result_source->from, $values, $cond
1043 =item Arguments: \%values
1045 =item Return Value: 1
1049 Fetches all objects and updates them one at a time. Note that C<update_all>
1050 will run DBIC cascade triggers, while L</update> will not.
1055 my ($self, $values) = @_;
1056 $self->throw_exception("Values for update must be a hash")
1057 unless ref $values eq 'HASH';
1058 foreach my $obj ($self->all) {
1059 $obj->set_columns($values)->update;
1068 =item Arguments: none
1070 =item Return Value: 1
1074 Deletes the contents of the resultset from its result source. Note that this
1075 will not run DBIC cascade triggers. See L</delete_all> if you need triggers
1083 my $cond = $self->_cond_for_update_delete;
1085 $self->result_source->storage->delete($self->result_source->from, $cond);
1093 =item Arguments: none
1095 =item Return Value: 1
1099 Fetches all objects and deletes them one at a time. Note that C<delete_all>
1100 will run DBIC cascade triggers, while L</delete> will not.
1106 $_->delete for $self->all;
1114 =item Arguments: none
1116 =item Return Value: $pager
1120 Return Value a L<Data::Page> object for the current resultset. Only makes
1121 sense for queries with a C<page> attribute.
1127 my $attrs = $self->{attrs};
1128 $self->throw_exception("Can't create pager for non-paged rs")
1129 unless $self->{attrs}{page};
1130 $attrs->{rows} ||= 10;
1131 return $self->{pager} ||= Data::Page->new(
1132 $self->_count, $attrs->{rows}, $self->{attrs}{page});
1139 =item Arguments: $page_number
1141 =item Return Value: $rs
1145 Returns a resultset for the $page_number page of the resultset on which page
1146 is called, where each page contains a number of rows equal to the 'rows'
1147 attribute set on the resultset (10 by default).
1152 my ($self, $page) = @_;
1153 return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
1160 =item Arguments: \%vals
1162 =item Return Value: $object
1166 Creates an object in the resultset's result class and returns it.
1171 my ($self, $values) = @_;
1172 $self->throw_exception( "new_result needs a hash" )
1173 unless (ref $values eq 'HASH');
1174 $self->throw_exception(
1175 "Can't abstract implicit construct, condition not a hash"
1176 ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
1178 my $alias = $self->{attrs}{alias};
1179 foreach my $key (keys %{$self->{cond}||{}}) {
1180 $new{$1} = $self->{cond}{$key} if ($key =~ m/^(?:\Q${alias}.\E)?([^.]+)$/);
1182 my $obj = $self->result_class->new(\%new);
1183 $obj->result_source($self->result_source) if $obj->can('result_source');
1191 =item Arguments: \%vals, \%attrs?
1193 =item Return Value: $object
1197 Find an existing record from this resultset. If none exists, instantiate a new
1198 result object and return it. The object will not be saved into your storage
1199 until you call L<DBIx::Class::Row/insert> on it.
1201 If you want objects to be saved immediately, use L</find_or_create> instead.
1207 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1208 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1209 my $exists = $self->find($hash, $attrs);
1210 return defined $exists ? $exists : $self->new_result($hash);
1217 =item Arguments: \%vals
1219 =item Return Value: $object
1223 Inserts a record into the resultset and returns the object representing it.
1225 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
1230 my ($self, $attrs) = @_;
1231 $self->throw_exception( "create needs a hashref" )
1232 unless ref $attrs eq 'HASH';
1233 return $self->new_result($attrs)->insert;
1236 =head2 find_or_create
1240 =item Arguments: \%vals, \%attrs?
1242 =item Return Value: $object
1246 $class->find_or_create({ key => $val, ... });
1248 Tries to find a record based on its primary key or unique constraint; if none
1249 is found, creates one and returns that instead.
1251 my $cd = $schema->resultset('CD')->find_or_create({
1253 artist => 'Massive Attack',
1254 title => 'Mezzanine',
1258 Also takes an optional C<key> attribute, to search by a specific key or unique
1259 constraint. For example:
1261 my $cd = $schema->resultset('CD')->find_or_create(
1263 artist => 'Massive Attack',
1264 title => 'Mezzanine',
1266 { key => 'cd_artist_title' }
1269 See also L</find> and L</update_or_create>. For information on how to declare
1270 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1274 sub find_or_create {
1276 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1277 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1278 my $exists = $self->find($hash, $attrs);
1279 return defined $exists ? $exists : $self->create($hash);
1282 =head2 update_or_create
1286 =item Arguments: \%col_values, { key => $unique_constraint }?
1288 =item Return Value: $object
1292 $class->update_or_create({ col => $val, ... });
1294 First, searches for an existing row matching one of the unique constraints
1295 (including the primary key) on the source of this resultset. If a row is
1296 found, updates it with the other given column values. Otherwise, creates a new
1299 Takes an optional C<key> attribute to search on a specific unique constraint.
1302 # In your application
1303 my $cd = $schema->resultset('CD')->update_or_create(
1305 artist => 'Massive Attack',
1306 title => 'Mezzanine',
1309 { key => 'cd_artist_title' }
1312 If no C<key> is specified, it searches on all unique constraints defined on the
1313 source, including the primary key.
1315 If the C<key> is specified as C<primary>, it searches only on the primary key.
1317 See also L</find> and L</find_or_create>. For information on how to declare
1318 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1322 sub update_or_create {
1324 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1325 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
1327 my $row = $self->find($cond);
1329 $row->update($cond);
1333 return $self->create($cond);
1340 =item Arguments: none
1342 =item Return Value: \@cache_objects?
1346 Gets the contents of the cache for the resultset, if the cache is set.
1358 =item Arguments: \@cache_objects
1360 =item Return Value: \@cache_objects
1364 Sets the contents of the cache for the resultset. Expects an arrayref
1365 of objects of the same class as those produced by the resultset. Note that
1366 if the cache is set the resultset will return the cached objects rather
1367 than re-querying the database even if the cache attr is not set.
1372 my ( $self, $data ) = @_;
1373 $self->throw_exception("set_cache requires an arrayref")
1374 if defined($data) && (ref $data ne 'ARRAY');
1375 $self->{all_cache} = $data;
1382 =item Arguments: none
1384 =item Return Value: []
1388 Clears the cache for the resultset.
1393 shift->set_cache(undef);
1396 =head2 related_resultset
1400 =item Arguments: $relationship_name
1402 =item Return Value: $resultset
1406 Returns a related resultset for the supplied relationship name.
1408 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1412 sub related_resultset {
1413 my ($self, $rel) = @_;
1415 $self->{related_resultsets} ||= {};
1416 return $self->{related_resultsets}{$rel} ||= do {
1417 my $rel_obj = $self->result_source->relationship_info($rel);
1419 $self->throw_exception(
1420 "search_related: result source '" . $self->result_source->name .
1421 "' has no such relationship $rel")
1424 my $rs = $self->search(undef, { join => $rel });
1425 my ($from,$seen) = $rs->_resolve_from;
1427 my $join_count = $self->{attrs}{seen_join}{$rel};
1428 my $alias = $join_count ? join('_', $rel, $join_count+1) : $rel;
1430 $self->result_source->schema->resultset($rel_obj->{class})->search_rs(
1435 where => $self->{cond},
1436 _parent_from => $from,
1444 my $source = $self->result_source;
1445 my $attrs = $self->{attrs};
1447 my $from = $attrs->{_parent_from}
1448 || [ { $attrs->{alias} => $source->from } ];
1449 # ? [ @{$attrs->{_parent_from}} ]
1452 my $seen = { %{$attrs->{seen_join}||{}} };
1454 if ($attrs->{join}) {
1456 $source->resolve_join($attrs->{join}, $attrs->{alias}, $seen)
1460 return ($from,$seen);
1463 sub _resolved_attrs {
1465 return $self->{_attrs} if $self->{_attrs};
1467 my $attrs = { %{$self->{attrs}||{}} };
1468 my $source = $self->{result_source};
1469 my $alias = $attrs->{alias};
1471 # XXX - lose storable dclone
1472 my $record_filter = delete $attrs->{record_filter};
1473 #$attrs = Storable::dclone($attrs || {}); # { %{ $attrs || {} } };
1475 $attrs->{record_filter} = $record_filter if $record_filter;
1477 $attrs->{columns} ||= delete $attrs->{cols} if exists $attrs->{cols};
1478 if ($attrs->{columns}) {
1479 delete $attrs->{as};
1480 } elsif (!$attrs->{select}) {
1481 $attrs->{columns} = [ $self->{result_source}->columns ];
1484 $attrs->{select} ||= [
1485 map { m/\./ ? $_ : "${alias}.$_" } @{delete $attrs->{columns}}
1488 map { m/^\Q${alias}.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}}
1492 if ($adds = delete $attrs->{include_columns}) {
1493 $adds = [$adds] unless ref $adds eq 'ARRAY';
1494 push(@{$attrs->{select}}, @$adds);
1495 push(@{$attrs->{as}}, map { m/([^.]+)$/; $1 } @$adds);
1497 if ($adds = delete $attrs->{'+select'}) {
1498 $adds = [$adds] unless ref $adds eq 'ARRAY';
1499 push(@{$attrs->{select}}, map { /\./ || ref $_ ? $_ : "${alias}.$_" } @$adds);
1501 if (my $adds = delete $attrs->{'+as'}) {
1502 $adds = [$adds] unless ref $adds eq 'ARRAY';
1503 push(@{$attrs->{as}}, @$adds);
1506 $attrs->{from} ||= delete $attrs->{_parent_from}
1507 || [ { 'me' => $source->from } ];
1509 if (exists $attrs->{join} || exists $attrs->{prefetch}) {
1511 my $join = delete $attrs->{join} || {};
1513 if (defined $attrs->{prefetch}) {
1514 $join = $self->_merge_attr(
1515 $join, $attrs->{prefetch}
1519 push(@{$attrs->{from}},
1520 $source->resolve_join($join, $alias, { %{$attrs->{seen_join}||{}} })
1524 $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
1525 if ($attrs->{order_by}) {
1526 $attrs->{order_by} = [ $attrs->{order_by} ] unless ref $attrs->{order_by};
1528 $attrs->{order_by} ||= [];
1531 my $collapse = $attrs->{collapse} || {};
1532 if (my $prefetch = delete $attrs->{prefetch}) {
1534 foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
1535 # bring joins back to level of current class
1536 my @prefetch = $source->resolve_prefetch(
1537 $p, $alias, { %{$attrs->{seen_join}||{}} }, \@pre_order, $collapse
1539 push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
1540 push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
1542 push(@{$attrs->{order_by}}, @pre_order);
1544 $attrs->{collapse} = $collapse;
1546 return $self->{_attrs} = $attrs;
1550 my ($self, $a, $b) = @_;
1551 return $b unless $a;
1553 if (ref $b eq 'HASH' && ref $a eq 'HASH') {
1554 foreach my $key (keys %{$b}) {
1555 if (exists $a->{$key}) {
1556 $a->{$key} = $self->_merge_attr($a->{$key}, $b->{$key});
1558 $a->{$key} = $b->{$key};
1563 $a = [$a] unless ref $a eq 'ARRAY';
1564 $b = [$b] unless ref $b eq 'ARRAY';
1568 foreach my $x ($a, $b) {
1569 foreach my $element (@{$x}) {
1570 if (ref $element eq 'HASH') {
1571 $hash = $self->_merge_attr($hash, $element);
1572 } elsif (ref $element eq 'ARRAY') {
1573 push(@array, @{$element});
1575 push(@array, $element) unless $b == $x
1576 && grep { $_ eq $element } @array;
1581 @array = grep { !exists $hash->{$_} } @array;
1583 return keys %{$hash}
1592 =head2 throw_exception
1594 See L<DBIx::Class::Schema/throw_exception> for details.
1598 sub throw_exception {
1600 $self->result_source->schema->throw_exception(@_);
1603 # XXX: FIXME: Attributes docs need clearing up
1607 The resultset takes various attributes that modify its behavior. Here's an
1614 =item Value: ($order_by | \@order_by)
1618 Which column(s) to order the results by. This is currently passed
1619 through directly to SQL, so you can give e.g. C<year DESC> for a
1620 descending order on the column `year'.
1622 Please note that if you have quoting enabled (see
1623 L<DBIx::Class::Storage/quote_char>) you will need to do C<\'year DESC' > to
1624 specify an order. (The scalar ref causes it to be passed as raw sql to the DB,
1625 so you will need to manually quote things as appropriate.)
1631 =item Value: \@columns
1635 Shortcut to request a particular set of columns to be retrieved. Adds
1636 C<me.> onto the start of any column without a C<.> in it and sets C<select>
1637 from that, then auto-populates C<as> from C<select> as normal. (You may also
1638 use the C<cols> attribute, as in earlier versions of DBIC.)
1640 =head2 include_columns
1644 =item Value: \@columns
1648 Shortcut to include additional columns in the returned results - for example
1650 $schema->resultset('CD')->search(undef, {
1651 include_columns => ['artist.name'],
1655 would return all CDs and include a 'name' column to the information
1656 passed to object inflation
1662 =item Value: \@select_columns
1666 Indicates which columns should be selected from the storage. You can use
1667 column names, or in the case of RDBMS back ends, function or stored procedure
1670 $rs = $schema->resultset('Employee')->search(undef, {
1673 { count => 'employeeid' },
1678 When you use function/stored procedure names and do not supply an C<as>
1679 attribute, the column names returned are storage-dependent. E.g. MySQL would
1680 return a column named C<count(employeeid)> in the above example.
1686 Indicates additional columns to be selected from storage. Works the same as
1687 L<select> but adds columns to the selection.
1695 Indicates additional column names for those added via L<+select>.
1703 =item Value: \@inflation_names
1707 Indicates column names for object inflation. This is used in conjunction with
1708 C<select>, usually when C<select> contains one or more function or stored
1711 $rs = $schema->resultset('Employee')->search(undef, {
1714 { count => 'employeeid' }
1716 as => ['name', 'employee_count'],
1719 my $employee = $rs->first(); # get the first Employee
1721 If the object against which the search is performed already has an accessor
1722 matching a column name specified in C<as>, the value can be retrieved using
1723 the accessor as normal:
1725 my $name = $employee->name();
1727 If on the other hand an accessor does not exist in the object, you need to
1728 use C<get_column> instead:
1730 my $employee_count = $employee->get_column('employee_count');
1732 You can create your own accessors if required - see
1733 L<DBIx::Class::Manual::Cookbook> for details.
1735 Please note: This will NOT insert an C<AS employee_count> into the SQL statement
1736 produced, it is used for internal access only. Thus attempting to use the accessor
1737 in an C<order_by> clause or similar will fail misrably.
1743 =item Value: ($rel_name | \@rel_names | \%rel_names)
1747 Contains a list of relationships that should be joined for this query. For
1750 # Get CDs by Nine Inch Nails
1751 my $rs = $schema->resultset('CD')->search(
1752 { 'artist.name' => 'Nine Inch Nails' },
1753 { join => 'artist' }
1756 Can also contain a hash reference to refer to the other relation's relations.
1759 package MyApp::Schema::Track;
1760 use base qw/DBIx::Class/;
1761 __PACKAGE__->table('track');
1762 __PACKAGE__->add_columns(qw/trackid cd position title/);
1763 __PACKAGE__->set_primary_key('trackid');
1764 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
1767 # In your application
1768 my $rs = $schema->resultset('Artist')->search(
1769 { 'track.title' => 'Teardrop' },
1771 join => { cd => 'track' },
1772 order_by => 'artist.name',
1776 If the same join is supplied twice, it will be aliased to <rel>_2 (and
1777 similarly for a third time). For e.g.
1779 my $rs = $schema->resultset('Artist')->search({
1780 'cds.title' => 'Down to Earth',
1781 'cds_2.title' => 'Popular',
1783 join => [ qw/cds cds/ ],
1786 will return a set of all artists that have both a cd with title 'Down
1787 to Earth' and a cd with title 'Popular'.
1789 If you want to fetch related objects from other tables as well, see C<prefetch>
1796 =item Value: ($rel_name | \@rel_names | \%rel_names)
1800 Contains one or more relationships that should be fetched along with the main
1801 query (when they are accessed afterwards they will have already been
1802 "prefetched"). This is useful for when you know you will need the related
1803 objects, because it saves at least one query:
1805 my $rs = $schema->resultset('Tag')->search(
1814 The initial search results in SQL like the following:
1816 SELECT tag.*, cd.*, artist.* FROM tag
1817 JOIN cd ON tag.cd = cd.cdid
1818 JOIN artist ON cd.artist = artist.artistid
1820 L<DBIx::Class> has no need to go back to the database when we access the
1821 C<cd> or C<artist> relationships, which saves us two SQL statements in this
1824 Simple prefetches will be joined automatically, so there is no need
1825 for a C<join> attribute in the above search. If you're prefetching to
1826 depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
1827 specify the join as well.
1829 C<prefetch> can be used with the following relationship types: C<belongs_to>,
1830 C<has_one> (or if you're using C<add_relationship>, any relationship declared
1831 with an accessor type of 'single' or 'filter').
1841 Makes the resultset paged and specifies the page to retrieve. Effectively
1842 identical to creating a non-pages resultset and then calling ->page($page)
1845 If L<rows> attribute is not specified it defualts to 10 rows per page.
1855 Specifes the maximum number of rows for direct retrieval or the number of
1856 rows per page if the page attribute or method is used.
1862 =item Value: $offset
1866 Specifies the (zero-based) row number for the first row to be returned, or the
1867 of the first row of the first page if paging is used.
1873 =item Value: \@columns
1877 A arrayref of columns to group by. Can include columns of joined tables.
1879 group_by => [qw/ column1 column2 ... /]
1885 =item Value: $condition
1889 HAVING is a select statement attribute that is applied between GROUP BY and
1890 ORDER BY. It is applied to the after the grouping calculations have been
1893 having => { 'count(employee)' => { '>=', 100 } }
1899 =item Value: (0 | 1)
1903 Set to 1 to group by all columns.
1909 Adds to the WHERE clause.
1911 # only return rows WHERE deleted IS NULL for all searches
1912 __PACKAGE__->resultset_attributes({ where => { deleted => undef } }); )
1914 Can be overridden by passing C<{ where => undef }> as an attribute
1921 Set to 1 to cache search results. This prevents extra SQL queries if you
1922 revisit rows in your ResultSet:
1924 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
1926 while( my $artist = $resultset->next ) {
1930 $rs->first; # without cache, this would issue a query
1932 By default, searches are not cached.
1934 For more examples of using these attributes, see
1935 L<DBIx::Class::Manual::Cookbook>.
1941 =item Value: \@from_clause
1945 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
1946 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
1949 NOTE: Use this on your own risk. This allows you to shoot off your foot!
1951 C<join> will usually do what you need and it is strongly recommended that you
1952 avoid using C<from> unless you cannot achieve the desired result using C<join>.
1953 And we really do mean "cannot", not just tried and failed. Attempting to use
1954 this because you're having problems with C<join> is like trying to use x86
1955 ASM because you've got a syntax error in your C. Trust us on this.
1957 Now, if you're still really, really sure you need to use this (and if you're
1958 not 100% sure, ask the mailing list first), here's an explanation of how this
1961 The syntax is as follows -
1964 { <alias1> => <table1> },
1966 { <alias2> => <table2>, -join_type => 'inner|left|right' },
1967 [], # nested JOIN (optional)
1968 { <table1.column1> => <table2.column2>, ... (more conditions) },
1970 # More of the above [ ] may follow for additional joins
1977 ON <table1.column1> = <table2.column2>
1978 <more joins may follow>
1980 An easy way to follow the examples below is to remember the following:
1982 Anything inside "[]" is a JOIN
1983 Anything inside "{}" is a condition for the enclosing JOIN
1985 The following examples utilize a "person" table in a family tree application.
1986 In order to express parent->child relationships, this table is self-joined:
1988 # Person->belongs_to('father' => 'Person');
1989 # Person->belongs_to('mother' => 'Person');
1991 C<from> can be used to nest joins. Here we return all children with a father,
1992 then search against all mothers of those children:
1994 $rs = $schema->resultset('Person')->search(
1997 alias => 'mother', # alias columns in accordance with "from"
1999 { mother => 'person' },
2002 { child => 'person' },
2004 { father => 'person' },
2005 { 'father.person_id' => 'child.father_id' }
2008 { 'mother.person_id' => 'child.mother_id' }
2015 # SELECT mother.* FROM person mother
2018 # JOIN person father
2019 # ON ( father.person_id = child.father_id )
2021 # ON ( mother.person_id = child.mother_id )
2023 The type of any join can be controlled manually. To search against only people
2024 with a father in the person table, we could explicitly use C<INNER JOIN>:
2026 $rs = $schema->resultset('Person')->search(
2029 alias => 'child', # alias columns in accordance with "from"
2031 { child => 'person' },
2033 { father => 'person', -join_type => 'inner' },
2034 { 'father.id' => 'child.father_id' }
2041 # SELECT child.* FROM person child
2042 # INNER JOIN person father ON child.father_id = father.id