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 result_source => $source,
100 result_class => $attrs->{result_class} || $source->result_class,
101 cond => $attrs->{where},
112 =item Arguments: $cond, \%attrs?
114 =item Return Value: $resultset (scalar context), @row_objs (list context)
118 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
119 my $new_rs = $cd_rs->search({ year => 2005 });
121 my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
122 # year = 2005 OR year = 2004
124 If you need to pass in additional attributes but no additional condition,
125 call it as C<search(undef, \%attrs)>.
127 # "SELECT name, artistid FROM $artist_table"
128 my @all_artists = $schema->resultset('Artist')->search(undef, {
129 columns => [qw/name artistid/],
136 my $rs = $self->search_rs( @_ );
137 return (wantarray ? $rs->all : $rs);
144 =item Arguments: $cond, \%attrs?
146 =item Return Value: $resultset
150 This method does the same exact thing as search() except it will
151 always return a resultset, even in list context.
160 unless (@_) { # no search, effectively just a clone
161 $rows = $self->get_cache;
165 $attrs = pop(@_) if @_ > 1 and ref $_[$#_] eq 'HASH';
166 my $our_attrs = { %{$self->{attrs}} };
167 my $having = delete $our_attrs->{having};
169 # merge new attrs into inherited
170 foreach my $key (qw/join prefetch/) {
171 next unless exists $attrs->{$key};
172 $our_attrs->{$key} = $self->_merge_attr($our_attrs->{$key}, delete $attrs->{$key});
175 my $new_attrs = { %{$our_attrs}, %{$attrs} };
178 (@_ == 1 || ref $_[0] eq "HASH")
182 ? $self->throw_exception("Odd number of arguments to search")
189 if (defined $where) {
190 $new_attrs->{where} = (
191 defined $new_attrs->{where}
194 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
195 } $where, $new_attrs->{where}
201 if (defined $having) {
202 $new_attrs->{having} = (
203 defined $new_attrs->{having}
206 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
207 } $having, $new_attrs->{having}
213 my $rs = (ref $self)->new($self->result_source, $new_attrs);
215 $rs->set_cache($rows);
220 =head2 search_literal
224 =item Arguments: $sql_fragment, @bind_values
226 =item Return Value: $resultset (scalar context), @row_objs (list context)
230 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
231 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
233 Pass a literal chunk of SQL to be added to the conditional part of the
239 my ($self, $cond, @vals) = @_;
240 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
241 $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
242 return $self->search(\$cond, $attrs);
249 =item Arguments: @values | \%cols, \%attrs?
251 =item Return Value: $row_object
255 Finds a row based on its primary key or unique constraint. For example, to find
256 a row by its primary key:
258 my $cd = $schema->resultset('CD')->find(5);
260 You can also find a row by a specific unique constraint using the C<key>
261 attribute. For example:
263 my $cd = $schema->resultset('CD')->find('Massive Attack', 'Mezzanine', {
264 key => 'cd_artist_title'
267 Additionally, you can specify the columns explicitly by name:
269 my $cd = $schema->resultset('CD')->find(
271 artist => 'Massive Attack',
272 title => 'Mezzanine',
274 { key => 'cd_artist_title' }
277 If the C<key> is specified as C<primary>, it searches only on the primary key.
279 If no C<key> is specified, it searches on all unique constraints defined on the
280 source, including the primary key.
282 See also L</find_or_create> and L</update_or_create>. For information on how to
283 declare unique constraints, see
284 L<DBIx::Class::ResultSource/add_unique_constraint>.
290 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
292 # Default to the primary key, but allow a specific key
293 my @cols = exists $attrs->{key}
294 ? $self->result_source->unique_constraint_columns($attrs->{key})
295 : $self->result_source->primary_columns;
296 $self->throw_exception(
297 "Can't find unless a primary key or unique constraint is defined"
300 # Parse out a hashref from input
302 if (ref $_[0] eq 'HASH') {
303 $input_query = { %{$_[0]} };
305 elsif (@_ == @cols) {
307 @{$input_query}{@cols} = @_;
310 # Compatibility: Allow e.g. find(id => $value)
311 carp "Find by key => value deprecated; please use a hashref instead";
315 my @unique_queries = $self->_unique_queries($input_query, $attrs);
317 # Handle cases where the ResultSet defines the query, or where the user is
319 my $query = @unique_queries ? \@unique_queries : $input_query;
323 my $rs = $self->search($query, $attrs);
324 return keys %{$rs->_resolved_attrs->{collapse}} ? $rs->next : $rs->single;
327 return keys %{$self->_resolved_attrs->{collapse}}
328 ? $self->search($query)->next
329 : $self->single($query);
335 # Build a list of queries which satisfy unique constraints.
337 sub _unique_queries {
338 my ($self, $query, $attrs) = @_;
340 my $alias = $self->{attrs}{alias};
341 my @constraint_names = exists $attrs->{key}
343 : $self->result_source->unique_constraint_names;
346 foreach my $name (@constraint_names) {
347 my @unique_cols = $self->result_source->unique_constraint_columns($name);
348 my $unique_query = $self->_build_unique_query($query, \@unique_cols);
350 my $num_query = scalar keys %$unique_query;
351 next unless $num_query;
353 # Add the ResultSet's alias
354 foreach my $col (grep { ! m/\./ } keys %$unique_query) {
355 $unique_query->{"$alias.$col"} = delete $unique_query->{$col};
358 # XXX: Assuming quite a bit about $self->{attrs}{where}
359 my $num_cols = scalar @unique_cols;
360 my $num_where = exists $self->{attrs}{where}
361 ? scalar keys %{ $self->{attrs}{where} }
363 push @unique_queries, $unique_query
364 if $num_query + $num_where == $num_cols;
367 return @unique_queries;
370 # _build_unique_query
372 # Constrain the specified query hash based on the specified column names.
374 sub _build_unique_query {
375 my ($self, $query, $unique_cols) = @_;
378 map { $_ => $query->{$_} }
379 grep { exists $query->{$_} }
384 =head2 search_related
388 =item Arguments: $rel, $cond, \%attrs?
390 =item Return Value: $new_resultset
394 $new_rs = $cd_rs->search_related('artist', {
398 Searches the specified relationship, optionally specifying a condition and
399 attributes for matching records. See L</ATTRIBUTES> for more information.
404 return shift->related_resultset(shift)->search(@_);
411 =item Arguments: none
413 =item Return Value: $cursor
417 Returns a storage-driven cursor to the given resultset. See
418 L<DBIx::Class::Cursor> for more information.
425 my $attrs = { %{$self->_resolved_attrs} };
426 return $self->{cursor}
427 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
428 $attrs->{where},$attrs);
435 =item Arguments: $cond?
437 =item Return Value: $row_object?
441 my $cd = $schema->resultset('CD')->single({ year => 2001 });
443 Inflates the first result without creating a cursor if the resultset has
444 any records in it; if not returns nothing. Used by L</find> as an optimisation.
446 Can optionally take an additional condition *only* - this is a fast-code-path
447 method; if you need to add extra joins or similar call ->search and then
448 ->single without a condition on the $rs returned from that.
453 my ($self, $where) = @_;
454 my $attrs = { %{$self->_resolved_attrs} };
456 if (defined $attrs->{where}) {
459 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
460 $where, delete $attrs->{where} ]
463 $attrs->{where} = $where;
467 unless ($self->_is_unique_query($attrs->{where})) {
468 carp "Query not guaranteed to return a single row"
469 . "; please declare your unique constraints or use search instead";
472 my @data = $self->result_source->storage->select_single(
473 $attrs->{from}, $attrs->{select},
474 $attrs->{where}, $attrs
477 return (@data ? $self->_construct_object(@data) : ());
482 # Try to determine if the specified query is guaranteed to be unique, based on
483 # the declared unique constraints.
485 sub _is_unique_query {
486 my ($self, $query) = @_;
488 my $collapsed = $self->_collapse_query($query);
489 my $alias = $self->{attrs}{alias};
491 foreach my $name ($self->result_source->unique_constraint_names) {
492 my @unique_cols = map {
494 } $self->result_source->unique_constraint_columns($name);
496 # Count the values for each unique column
497 my %seen = map { $_ => 0 } @unique_cols;
499 foreach my $key (keys %$collapsed) {
500 my $aliased = $key =~ /\./ ? $key : "$alias.$key";
501 next unless exists $seen{$aliased}; # Additional constraints are okay
502 $seen{$aliased} = scalar keys %{ $collapsed->{$key} };
505 # If we get 0 or more than 1 value for a column, it's not necessarily unique
506 return 1 unless grep { $_ != 1 } values %seen;
514 # Recursively collapse the query, accumulating values for each column.
516 sub _collapse_query {
517 my ($self, $query, $collapsed) = @_;
521 if (ref $query eq 'ARRAY') {
522 foreach my $subquery (@$query) {
523 next unless ref $subquery; # -or
524 # warn "ARRAY: " . Dumper $subquery;
525 $collapsed = $self->_collapse_query($subquery, $collapsed);
528 elsif (ref $query eq 'HASH') {
529 if (keys %$query and (keys %$query)[0] eq '-and') {
530 foreach my $subquery (@{$query->{-and}}) {
531 # warn "HASH: " . Dumper $subquery;
532 $collapsed = $self->_collapse_query($subquery, $collapsed);
536 # warn "LEAF: " . Dumper $query;
537 foreach my $col (keys %$query) {
538 my $value = $query->{$col};
539 $collapsed->{$col}{$value}++;
551 =item Arguments: $cond?
553 =item Return Value: $resultsetcolumn
557 my $max_length = $rs->get_column('length')->max;
559 Returns a ResultSetColumn instance for $column based on $self
564 my ($self, $column) = @_;
565 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
573 =item Arguments: $cond, \%attrs?
575 =item Return Value: $resultset (scalar context), @row_objs (list context)
579 # WHERE title LIKE '%blue%'
580 $cd_rs = $rs->search_like({ title => '%blue%'});
582 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
583 that this is simply a convenience method. You most likely want to use
584 L</search> with specific operators.
586 For more information, see L<DBIx::Class::Manual::Cookbook>.
592 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
593 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
594 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
595 return $class->search($query, { %$attrs });
602 =item Arguments: $first, $last
604 =item Return Value: $resultset (scalar context), @row_objs (list context)
608 Returns a resultset or object list representing a subset of elements from the
609 resultset slice is called on. Indexes are from 0, i.e., to get the first
612 my ($one, $two, $three) = $rs->slice(0, 2);
617 my ($self, $min, $max) = @_;
618 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
619 $attrs->{offset} = $self->{attrs}{offset} || 0;
620 $attrs->{offset} += $min;
621 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
622 return $self->search(undef(), $attrs);
623 #my $slice = (ref $self)->new($self->result_source, $attrs);
624 #return (wantarray ? $slice->all : $slice);
631 =item Arguments: none
633 =item Return Value: $result?
637 Returns the next element in the resultset (C<undef> is there is none).
639 Can be used to efficiently iterate over records in the resultset:
641 my $rs = $schema->resultset('CD')->search;
642 while (my $cd = $rs->next) {
646 Note that you need to store the resultset object, and call C<next> on it.
647 Calling C<< resultset('Table')->next >> repeatedly will always return the
648 first record from the resultset.
654 if (my $cache = $self->get_cache) {
655 $self->{all_cache_position} ||= 0;
656 return $cache->[$self->{all_cache_position}++];
658 if ($self->{attrs}{cache}) {
659 $self->{all_cache_position} = 1;
660 return ($self->all)[0];
663 exists $self->{stashed_row}
664 ? @{delete $self->{stashed_row}}
665 : $self->cursor->next
667 return unless (@row);
668 return $self->_construct_object(@row);
671 sub _construct_object {
672 my ($self, @row) = @_;
673 my $info = $self->_collapse_result($self->{_attrs}{as}, \@row);
674 my $new = $self->result_class->inflate_result($self->result_source, @$info);
675 $new = $self->{_attrs}{record_filter}->($new)
676 if exists $self->{_attrs}{record_filter};
680 sub _collapse_result {
681 my ($self, $as, $row, $prefix) = @_;
686 foreach my $this_as (@$as) {
687 my $val = shift @copy;
688 if (defined $prefix) {
689 if ($this_as =~ m/^\Q${prefix}.\E(.+)$/) {
691 $remain =~ /^(?:(.*)\.)?([^.]+)$/;
692 $const{$1||''}{$2} = $val;
695 $this_as =~ /^(?:(.*)\.)?([^.]+)$/;
696 $const{$1||''}{$2} = $val;
700 my $alias = $self->{attrs}{alias};
701 my $info = [ {}, {} ];
702 foreach my $key (keys %const) {
703 if (length $key && $key ne $alias) {
705 my @parts = split(/\./, $key);
706 foreach my $p (@parts) {
707 $target = $target->[1]->{$p} ||= [];
709 $target->[0] = $const{$key};
711 $info->[0] = $const{$key};
716 if (defined $prefix) {
718 m/^\Q${prefix}.\E(.+)$/ ? ($1) : ()
719 } keys %{$self->{_attrs}{collapse}}
721 @collapse = keys %{$self->{_attrs}{collapse}};
725 my ($c) = sort { length $a <=> length $b } @collapse;
727 foreach my $p (split(/\./, $c)) {
728 $target = $target->[1]->{$p} ||= [];
730 my $c_prefix = (defined($prefix) ? "${prefix}.${c}" : $c);
731 my @co_key = @{$self->{_attrs}{collapse}{$c_prefix}};
732 my $tree = $self->_collapse_result($as, $row, $c_prefix);
733 my %co_check = map { ($_, $tree->[0]->{$_}); } @co_key;
739 !defined($tree->[0]->{$_}) || $co_check{$_} ne $tree->[0]->{$_}
744 last unless (@raw = $self->cursor->next);
745 $row = $self->{stashed_row} = \@raw;
746 $tree = $self->_collapse_result($as, $row, $c_prefix);
748 @$target = (@final ? @final : [ {}, {} ]);
749 # single empty result to indicate an empty prefetched has_many
752 #print "final info: " . Dumper($info);
760 =item Arguments: $result_source?
762 =item Return Value: $result_source
766 An accessor for the primary ResultSource object from which this ResultSet
773 =item Arguments: $result_class?
775 =item Return Value: $result_class
779 An accessor for the class to use when creating row objects. Defaults to
780 C<< result_source->result_class >> - which in most cases is the name of the
781 L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class.
790 =item Arguments: $cond, \%attrs??
792 =item Return Value: $count
796 Performs an SQL C<COUNT> with the same query as the resultset was built
797 with to find the number of elements. If passed arguments, does a search
798 on the resultset and counts the results of that.
800 Note: When using C<count> with C<group_by>, L<DBIX::Class> emulates C<GROUP BY>
801 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
802 not support C<DISTINCT> with multiple columns. If you are using such a
803 database, you should only use columns from the main table in your C<group_by>
810 return $self->search(@_)->count if @_ and defined $_[0];
811 return scalar @{ $self->get_cache } if $self->get_cache;
812 my $count = $self->_count;
813 return 0 unless $count;
815 $count -= $self->{attrs}{offset} if $self->{attrs}{offset};
816 $count = $self->{attrs}{rows} if
817 $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
821 sub _count { # Separated out so pager can get the full count
823 my $select = { count => '*' };
825 my $attrs = { %{$self->_resolved_attrs} };
826 if (my $group_by = delete $attrs->{group_by}) {
827 delete $attrs->{having};
828 my @distinct = (ref $group_by ? @$group_by : ($group_by));
829 # todo: try CONCAT for multi-column pk
830 my @pk = $self->result_source->primary_columns;
832 my $alias = $attrs->{alias};
833 foreach my $column (@distinct) {
834 if ($column =~ qr/^(?:\Q${alias}.\E)?$pk[0]$/) {
835 @distinct = ($column);
841 $select = { count => { distinct => \@distinct } };
844 $attrs->{select} = $select;
845 $attrs->{as} = [qw/count/];
847 # offset, order by and page are not needed to count. record_filter is cdbi
848 delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
850 my $tmp_rs = (ref $self)->new($self->result_source, $attrs);
851 my ($count) = $tmp_rs->cursor->next;
859 =item Arguments: $sql_fragment, @bind_values
861 =item Return Value: $count
865 Counts the results in a literal query. Equivalent to calling L</search_literal>
866 with the passed arguments, then L</count>.
870 sub count_literal { shift->search_literal(@_)->count; }
876 =item Arguments: none
878 =item Return Value: @objects
882 Returns all elements in the resultset. Called implicitly if the resultset
883 is returned in list context.
889 return @{ $self->get_cache } if $self->get_cache;
893 # TODO: don't call resolve here
894 if (keys %{$self->_resolved_attrs->{collapse}}) {
895 # if ($self->{attrs}{prefetch}) {
896 # Using $self->cursor->all is really just an optimisation.
897 # If we're collapsing has_many prefetches it probably makes
898 # very little difference, and this is cleaner than hacking
899 # _construct_object to survive the approach
900 my @row = $self->cursor->next;
902 push(@obj, $self->_construct_object(@row));
903 @row = (exists $self->{stashed_row}
904 ? @{delete $self->{stashed_row}}
905 : $self->cursor->next);
908 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
911 $self->set_cache(\@obj) if $self->{attrs}{cache};
919 =item Arguments: none
921 =item Return Value: $self
925 Resets the resultset's cursor, so you can iterate through the elements again.
931 delete $self->{_attrs} if exists $self->{_attrs};
932 $self->{all_cache_position} = 0;
933 $self->cursor->reset;
941 =item Arguments: none
943 =item Return Value: $object?
947 Resets the resultset and returns an object for the first result (if the
948 resultset returns anything).
953 return $_[0]->reset->next;
956 # _cond_for_update_delete
958 # update/delete require the condition to be modified to handle
959 # the differing SQL syntax available. This transforms the $self->{cond}
960 # appropriately, returning the new condition.
962 sub _cond_for_update_delete {
966 # No-op. No condition, we're updating/deleting everything
967 return $cond unless ref $self->{cond};
969 if (ref $self->{cond} eq 'ARRAY') {
973 foreach my $key (keys %{$_}) {
975 $hash{$1} = $_->{$key};
981 elsif (ref $self->{cond} eq 'HASH') {
982 if ((keys %{$self->{cond}})[0] eq '-and') {
985 my @cond = @{$self->{cond}{-and}};
986 for (my $i = 0; $i < @cond; $i++) {
987 my $entry = $cond[$i];
990 if (ref $entry eq 'HASH') {
991 foreach my $key (keys %{$entry}) {
993 $hash{$1} = $entry->{$key};
997 $entry =~ /([^.]+)$/;
998 $hash{$1} = $cond[++$i];
1001 push @{$cond->{-and}}, \%hash;
1005 foreach my $key (keys %{$self->{cond}}) {
1007 $cond->{$1} = $self->{cond}{$key};
1012 $self->throw_exception(
1013 "Can't update/delete on resultset with condition unless hash or array"
1025 =item Arguments: \%values
1027 =item Return Value: $storage_rv
1031 Sets the specified columns in the resultset to the supplied values in a
1032 single query. Return value will be true if the update succeeded or false
1033 if no records were updated; exact type of success value is storage-dependent.
1038 my ($self, $values) = @_;
1039 $self->throw_exception("Values for update must be a hash")
1040 unless ref $values eq 'HASH';
1042 my $cond = $self->_cond_for_update_delete;
1044 return $self->result_source->storage->update(
1045 $self->result_source->from, $values, $cond
1053 =item Arguments: \%values
1055 =item Return Value: 1
1059 Fetches all objects and updates them one at a time. Note that C<update_all>
1060 will run DBIC cascade triggers, while L</update> will not.
1065 my ($self, $values) = @_;
1066 $self->throw_exception("Values for update must be a hash")
1067 unless ref $values eq 'HASH';
1068 foreach my $obj ($self->all) {
1069 $obj->set_columns($values)->update;
1078 =item Arguments: none
1080 =item Return Value: 1
1084 Deletes the contents of the resultset from its result source. Note that this
1085 will not run DBIC cascade triggers. See L</delete_all> if you need triggers
1093 my $cond = $self->_cond_for_update_delete;
1095 $self->result_source->storage->delete($self->result_source->from, $cond);
1103 =item Arguments: none
1105 =item Return Value: 1
1109 Fetches all objects and deletes them one at a time. Note that C<delete_all>
1110 will run DBIC cascade triggers, while L</delete> will not.
1116 $_->delete for $self->all;
1124 =item Arguments: none
1126 =item Return Value: $pager
1130 Return Value a L<Data::Page> object for the current resultset. Only makes
1131 sense for queries with a C<page> attribute.
1137 my $attrs = $self->{attrs};
1138 $self->throw_exception("Can't create pager for non-paged rs")
1139 unless $self->{attrs}{page};
1140 $attrs->{rows} ||= 10;
1141 return $self->{pager} ||= Data::Page->new(
1142 $self->_count, $attrs->{rows}, $self->{attrs}{page});
1149 =item Arguments: $page_number
1151 =item Return Value: $rs
1155 Returns a resultset for the $page_number page of the resultset on which page
1156 is called, where each page contains a number of rows equal to the 'rows'
1157 attribute set on the resultset (10 by default).
1162 my ($self, $page) = @_;
1163 return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
1170 =item Arguments: \%vals
1172 =item Return Value: $object
1176 Creates an object in the resultset's result class and returns it.
1181 my ($self, $values) = @_;
1182 $self->throw_exception( "new_result needs a hash" )
1183 unless (ref $values eq 'HASH');
1184 $self->throw_exception(
1185 "Can't abstract implicit construct, condition not a hash"
1186 ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
1188 my $alias = $self->{attrs}{alias};
1189 foreach my $key (keys %{$self->{cond}||{}}) {
1190 $new{$1} = $self->{cond}{$key} if ($key =~ m/^(?:\Q${alias}.\E)?([^.]+)$/);
1192 my $obj = $self->result_class->new(\%new);
1193 $obj->result_source($self->result_source) if $obj->can('result_source');
1201 =item Arguments: \%vals, \%attrs?
1203 =item Return Value: $object
1207 Find an existing record from this resultset. If none exists, instantiate a new
1208 result object and return it. The object will not be saved into your storage
1209 until you call L<DBIx::Class::Row/insert> on it.
1211 If you want objects to be saved immediately, use L</find_or_create> instead.
1217 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1218 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1219 my $exists = $self->find($hash, $attrs);
1220 return defined $exists ? $exists : $self->new_result($hash);
1227 =item Arguments: \%vals
1229 =item Return Value: $object
1233 Inserts a record into the resultset and returns the object representing it.
1235 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
1240 my ($self, $attrs) = @_;
1241 $self->throw_exception( "create needs a hashref" )
1242 unless ref $attrs eq 'HASH';
1243 return $self->new_result($attrs)->insert;
1246 =head2 find_or_create
1250 =item Arguments: \%vals, \%attrs?
1252 =item Return Value: $object
1256 $class->find_or_create({ key => $val, ... });
1258 Tries to find a record based on its primary key or unique constraint; if none
1259 is found, creates one and returns that instead.
1261 my $cd = $schema->resultset('CD')->find_or_create({
1263 artist => 'Massive Attack',
1264 title => 'Mezzanine',
1268 Also takes an optional C<key> attribute, to search by a specific key or unique
1269 constraint. For example:
1271 my $cd = $schema->resultset('CD')->find_or_create(
1273 artist => 'Massive Attack',
1274 title => 'Mezzanine',
1276 { key => 'cd_artist_title' }
1279 See also L</find> and L</update_or_create>. For information on how to declare
1280 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1284 sub find_or_create {
1286 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1287 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1288 my $exists = $self->find($hash, $attrs);
1289 return defined $exists ? $exists : $self->create($hash);
1292 =head2 update_or_create
1296 =item Arguments: \%col_values, { key => $unique_constraint }?
1298 =item Return Value: $object
1302 $class->update_or_create({ col => $val, ... });
1304 First, searches for an existing row matching one of the unique constraints
1305 (including the primary key) on the source of this resultset. If a row is
1306 found, updates it with the other given column values. Otherwise, creates a new
1309 Takes an optional C<key> attribute to search on a specific unique constraint.
1312 # In your application
1313 my $cd = $schema->resultset('CD')->update_or_create(
1315 artist => 'Massive Attack',
1316 title => 'Mezzanine',
1319 { key => 'cd_artist_title' }
1322 If no C<key> is specified, it searches on all unique constraints defined on the
1323 source, including the primary key.
1325 If the C<key> is specified as C<primary>, it searches only on the primary key.
1327 See also L</find> and L</find_or_create>. For information on how to declare
1328 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1332 sub update_or_create {
1334 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1335 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
1337 my $row = $self->find($cond);
1339 $row->update($cond);
1343 return $self->create($cond);
1350 =item Arguments: none
1352 =item Return Value: \@cache_objects?
1356 Gets the contents of the cache for the resultset, if the cache is set.
1368 =item Arguments: \@cache_objects
1370 =item Return Value: \@cache_objects
1374 Sets the contents of the cache for the resultset. Expects an arrayref
1375 of objects of the same class as those produced by the resultset. Note that
1376 if the cache is set the resultset will return the cached objects rather
1377 than re-querying the database even if the cache attr is not set.
1382 my ( $self, $data ) = @_;
1383 $self->throw_exception("set_cache requires an arrayref")
1384 if defined($data) && (ref $data ne 'ARRAY');
1385 $self->{all_cache} = $data;
1392 =item Arguments: none
1394 =item Return Value: []
1398 Clears the cache for the resultset.
1403 shift->set_cache(undef);
1406 =head2 related_resultset
1410 =item Arguments: $relationship_name
1412 =item Return Value: $resultset
1416 Returns a related resultset for the supplied relationship name.
1418 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1422 sub related_resultset {
1423 my ($self, $rel) = @_;
1425 $self->{related_resultsets} ||= {};
1426 return $self->{related_resultsets}{$rel} ||= do {
1427 my $rel_obj = $self->result_source->relationship_info($rel);
1429 $self->throw_exception(
1430 "search_related: result source '" . $self->result_source->name .
1431 "' has no such relationship $rel")
1434 my ($from,$seen) = $self->_resolve_from($rel);
1436 my $join_count = $seen->{$rel};
1437 my $alias = ($join_count > 1 ? join('_', $rel, $join_count) : $rel);
1439 $self->result_source->schema->resultset($rel_obj->{class})->search_rs(
1441 %{$self->{attrs}||{}},
1447 where => $self->{cond},
1455 my ($self, $extra_join) = @_;
1456 my $source = $self->result_source;
1457 my $attrs = $self->{attrs};
1459 my $from = $attrs->{from}
1460 || [ { $attrs->{alias} => $source->from } ];
1462 my $seen = { %{$attrs->{seen_join}||{}} };
1464 my $join = ($attrs->{join}
1465 ? [ $attrs->{join}, $extra_join ]
1469 ($join ? $source->resolve_join($join, $attrs->{alias}, $seen) : ()),
1472 return ($from,$seen);
1475 sub _resolved_attrs {
1477 return $self->{_attrs} if $self->{_attrs};
1479 my $attrs = { %{$self->{attrs}||{}} };
1480 my $source = $self->{result_source};
1481 my $alias = $attrs->{alias};
1483 $attrs->{columns} ||= delete $attrs->{cols} if exists $attrs->{cols};
1484 if ($attrs->{columns}) {
1485 delete $attrs->{as};
1486 } elsif (!$attrs->{select}) {
1487 $attrs->{columns} = [ $source->columns ];
1492 ? (ref $attrs->{select} eq 'ARRAY'
1493 ? [ @{$attrs->{select}} ]
1494 : [ $attrs->{select} ])
1495 : [ map { m/\./ ? $_ : "${alias}.$_" } @{delete $attrs->{columns}} ]
1499 ? (ref $attrs->{as} eq 'ARRAY'
1500 ? [ @{$attrs->{as}} ]
1502 : [ map { m/^\Q${alias}.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}} ]
1506 if ($adds = delete $attrs->{include_columns}) {
1507 $adds = [$adds] unless ref $adds eq 'ARRAY';
1508 push(@{$attrs->{select}}, @$adds);
1509 push(@{$attrs->{as}}, map { m/([^.]+)$/; $1 } @$adds);
1511 if ($adds = delete $attrs->{'+select'}) {
1512 $adds = [$adds] unless ref $adds eq 'ARRAY';
1513 push(@{$attrs->{select}},
1514 map { /\./ || ref $_ ? $_ : "${alias}.$_" } @$adds);
1516 if (my $adds = delete $attrs->{'+as'}) {
1517 $adds = [$adds] unless ref $adds eq 'ARRAY';
1518 push(@{$attrs->{as}}, @$adds);
1521 $attrs->{from} ||= [ { 'me' => $source->from } ];
1523 if (exists $attrs->{join} || exists $attrs->{prefetch}) {
1524 my $join = delete $attrs->{join} || {};
1526 if (defined $attrs->{prefetch}) {
1527 $join = $self->_merge_attr(
1528 $join, $attrs->{prefetch}
1532 $attrs->{from} = # have to copy here to avoid corrupting the original
1535 $source->resolve_join($join, $alias, { %{$attrs->{seen_join}||{}} })
1539 $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
1540 if ($attrs->{order_by}) {
1541 $attrs->{order_by} = (ref($attrs->{order_by}) eq 'ARRAY'
1542 ? [ @{$attrs->{order_by}} ]
1543 : [ $attrs->{order_by} ]);
1545 $attrs->{order_by} = [];
1548 my $collapse = $attrs->{collapse} || {};
1549 if (my $prefetch = delete $attrs->{prefetch}) {
1551 foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
1552 # bring joins back to level of current class
1553 my @prefetch = $source->resolve_prefetch(
1554 $p, $alias, { %{$attrs->{seen_join}||{}} }, \@pre_order, $collapse
1556 push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
1557 push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
1559 push(@{$attrs->{order_by}}, @pre_order);
1561 $attrs->{collapse} = $collapse;
1563 return $self->{_attrs} = $attrs;
1567 my ($self, $a, $b) = @_;
1568 return $b unless $a;
1570 if (ref $b eq 'HASH' && ref $a eq 'HASH') {
1571 foreach my $key (keys %{$b}) {
1572 if (exists $a->{$key}) {
1573 $a->{$key} = $self->_merge_attr($a->{$key}, $b->{$key});
1575 $a->{$key} = $b->{$key};
1580 $a = [$a] unless ref $a eq 'ARRAY';
1581 $b = [$b] unless ref $b eq 'ARRAY';
1585 foreach my $x ($a, $b) {
1586 foreach my $element (@{$x}) {
1587 if (ref $element eq 'HASH') {
1588 $hash = $self->_merge_attr($hash, $element);
1589 } elsif (ref $element eq 'ARRAY') {
1590 push(@array, @{$element});
1592 push(@array, $element) unless $b == $x
1593 && grep { $_ eq $element } @array;
1598 @array = grep { !exists $hash->{$_} } @array;
1600 return keys %{$hash}
1609 =head2 throw_exception
1611 See L<DBIx::Class::Schema/throw_exception> for details.
1615 sub throw_exception {
1617 $self->result_source->schema->throw_exception(@_);
1620 # XXX: FIXME: Attributes docs need clearing up
1624 The resultset takes various attributes that modify its behavior. Here's an
1631 =item Value: ($order_by | \@order_by)
1635 Which column(s) to order the results by. This is currently passed
1636 through directly to SQL, so you can give e.g. C<year DESC> for a
1637 descending order on the column `year'.
1639 Please note that if you have quoting enabled (see
1640 L<DBIx::Class::Storage/quote_char>) you will need to do C<\'year DESC' > to
1641 specify an order. (The scalar ref causes it to be passed as raw sql to the DB,
1642 so you will need to manually quote things as appropriate.)
1648 =item Value: \@columns
1652 Shortcut to request a particular set of columns to be retrieved. Adds
1653 C<me.> onto the start of any column without a C<.> in it and sets C<select>
1654 from that, then auto-populates C<as> from C<select> as normal. (You may also
1655 use the C<cols> attribute, as in earlier versions of DBIC.)
1657 =head2 include_columns
1661 =item Value: \@columns
1665 Shortcut to include additional columns in the returned results - for example
1667 $schema->resultset('CD')->search(undef, {
1668 include_columns => ['artist.name'],
1672 would return all CDs and include a 'name' column to the information
1673 passed to object inflation
1679 =item Value: \@select_columns
1683 Indicates which columns should be selected from the storage. You can use
1684 column names, or in the case of RDBMS back ends, function or stored procedure
1687 $rs = $schema->resultset('Employee')->search(undef, {
1690 { count => 'employeeid' },
1695 When you use function/stored procedure names and do not supply an C<as>
1696 attribute, the column names returned are storage-dependent. E.g. MySQL would
1697 return a column named C<count(employeeid)> in the above example.
1703 Indicates additional columns to be selected from storage. Works the same as
1704 L<select> but adds columns to the selection.
1712 Indicates additional column names for those added via L<+select>.
1720 =item Value: \@inflation_names
1724 Indicates column names for object inflation. This is used in conjunction with
1725 C<select>, usually when C<select> contains one or more function or stored
1728 $rs = $schema->resultset('Employee')->search(undef, {
1731 { count => 'employeeid' }
1733 as => ['name', 'employee_count'],
1736 my $employee = $rs->first(); # get the first Employee
1738 If the object against which the search is performed already has an accessor
1739 matching a column name specified in C<as>, the value can be retrieved using
1740 the accessor as normal:
1742 my $name = $employee->name();
1744 If on the other hand an accessor does not exist in the object, you need to
1745 use C<get_column> instead:
1747 my $employee_count = $employee->get_column('employee_count');
1749 You can create your own accessors if required - see
1750 L<DBIx::Class::Manual::Cookbook> for details.
1752 Please note: This will NOT insert an C<AS employee_count> into the SQL statement
1753 produced, it is used for internal access only. Thus attempting to use the accessor
1754 in an C<order_by> clause or similar will fail misrably.
1760 =item Value: ($rel_name | \@rel_names | \%rel_names)
1764 Contains a list of relationships that should be joined for this query. For
1767 # Get CDs by Nine Inch Nails
1768 my $rs = $schema->resultset('CD')->search(
1769 { 'artist.name' => 'Nine Inch Nails' },
1770 { join => 'artist' }
1773 Can also contain a hash reference to refer to the other relation's relations.
1776 package MyApp::Schema::Track;
1777 use base qw/DBIx::Class/;
1778 __PACKAGE__->table('track');
1779 __PACKAGE__->add_columns(qw/trackid cd position title/);
1780 __PACKAGE__->set_primary_key('trackid');
1781 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
1784 # In your application
1785 my $rs = $schema->resultset('Artist')->search(
1786 { 'track.title' => 'Teardrop' },
1788 join => { cd => 'track' },
1789 order_by => 'artist.name',
1793 If the same join is supplied twice, it will be aliased to <rel>_2 (and
1794 similarly for a third time). For e.g.
1796 my $rs = $schema->resultset('Artist')->search({
1797 'cds.title' => 'Down to Earth',
1798 'cds_2.title' => 'Popular',
1800 join => [ qw/cds cds/ ],
1803 will return a set of all artists that have both a cd with title 'Down
1804 to Earth' and a cd with title 'Popular'.
1806 If you want to fetch related objects from other tables as well, see C<prefetch>
1813 =item Value: ($rel_name | \@rel_names | \%rel_names)
1817 Contains one or more relationships that should be fetched along with the main
1818 query (when they are accessed afterwards they will have already been
1819 "prefetched"). This is useful for when you know you will need the related
1820 objects, because it saves at least one query:
1822 my $rs = $schema->resultset('Tag')->search(
1831 The initial search results in SQL like the following:
1833 SELECT tag.*, cd.*, artist.* FROM tag
1834 JOIN cd ON tag.cd = cd.cdid
1835 JOIN artist ON cd.artist = artist.artistid
1837 L<DBIx::Class> has no need to go back to the database when we access the
1838 C<cd> or C<artist> relationships, which saves us two SQL statements in this
1841 Simple prefetches will be joined automatically, so there is no need
1842 for a C<join> attribute in the above search. If you're prefetching to
1843 depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
1844 specify the join as well.
1846 C<prefetch> can be used with the following relationship types: C<belongs_to>,
1847 C<has_one> (or if you're using C<add_relationship>, any relationship declared
1848 with an accessor type of 'single' or 'filter').
1858 Makes the resultset paged and specifies the page to retrieve. Effectively
1859 identical to creating a non-pages resultset and then calling ->page($page)
1862 If L<rows> attribute is not specified it defualts to 10 rows per page.
1872 Specifes the maximum number of rows for direct retrieval or the number of
1873 rows per page if the page attribute or method is used.
1879 =item Value: $offset
1883 Specifies the (zero-based) row number for the first row to be returned, or the
1884 of the first row of the first page if paging is used.
1890 =item Value: \@columns
1894 A arrayref of columns to group by. Can include columns of joined tables.
1896 group_by => [qw/ column1 column2 ... /]
1902 =item Value: $condition
1906 HAVING is a select statement attribute that is applied between GROUP BY and
1907 ORDER BY. It is applied to the after the grouping calculations have been
1910 having => { 'count(employee)' => { '>=', 100 } }
1916 =item Value: (0 | 1)
1920 Set to 1 to group by all columns.
1926 Adds to the WHERE clause.
1928 # only return rows WHERE deleted IS NULL for all searches
1929 __PACKAGE__->resultset_attributes({ where => { deleted => undef } }); )
1931 Can be overridden by passing C<{ where => undef }> as an attribute
1938 Set to 1 to cache search results. This prevents extra SQL queries if you
1939 revisit rows in your ResultSet:
1941 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
1943 while( my $artist = $resultset->next ) {
1947 $rs->first; # without cache, this would issue a query
1949 By default, searches are not cached.
1951 For more examples of using these attributes, see
1952 L<DBIx::Class::Manual::Cookbook>.
1958 =item Value: \@from_clause
1962 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
1963 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
1966 NOTE: Use this on your own risk. This allows you to shoot off your foot!
1968 C<join> will usually do what you need and it is strongly recommended that you
1969 avoid using C<from> unless you cannot achieve the desired result using C<join>.
1970 And we really do mean "cannot", not just tried and failed. Attempting to use
1971 this because you're having problems with C<join> is like trying to use x86
1972 ASM because you've got a syntax error in your C. Trust us on this.
1974 Now, if you're still really, really sure you need to use this (and if you're
1975 not 100% sure, ask the mailing list first), here's an explanation of how this
1978 The syntax is as follows -
1981 { <alias1> => <table1> },
1983 { <alias2> => <table2>, -join_type => 'inner|left|right' },
1984 [], # nested JOIN (optional)
1985 { <table1.column1> => <table2.column2>, ... (more conditions) },
1987 # More of the above [ ] may follow for additional joins
1994 ON <table1.column1> = <table2.column2>
1995 <more joins may follow>
1997 An easy way to follow the examples below is to remember the following:
1999 Anything inside "[]" is a JOIN
2000 Anything inside "{}" is a condition for the enclosing JOIN
2002 The following examples utilize a "person" table in a family tree application.
2003 In order to express parent->child relationships, this table is self-joined:
2005 # Person->belongs_to('father' => 'Person');
2006 # Person->belongs_to('mother' => 'Person');
2008 C<from> can be used to nest joins. Here we return all children with a father,
2009 then search against all mothers of those children:
2011 $rs = $schema->resultset('Person')->search(
2014 alias => 'mother', # alias columns in accordance with "from"
2016 { mother => 'person' },
2019 { child => 'person' },
2021 { father => 'person' },
2022 { 'father.person_id' => 'child.father_id' }
2025 { 'mother.person_id' => 'child.mother_id' }
2032 # SELECT mother.* FROM person mother
2035 # JOIN person father
2036 # ON ( father.person_id = child.father_id )
2038 # ON ( mother.person_id = child.mother_id )
2040 The type of any join can be controlled manually. To search against only people
2041 with a father in the person table, we could explicitly use C<INNER JOIN>:
2043 $rs = $schema->resultset('Person')->search(
2046 alias => 'child', # alias columns in accordance with "from"
2048 { child => 'person' },
2050 { father => 'person', -join_type => 'inner' },
2051 { 'father.id' => 'child.father_id' }
2058 # SELECT child.* FROM person child
2059 # INNER JOIN person father ON child.father_id = father.id