1 package DBIx::Class::ResultSet;
5 use base qw/DBIx::Class/;
6 use Carp::Clan qw/^DBIx::Class/;
7 use DBIx::Class::Exception;
10 use DBIx::Class::ResultSetColumn;
11 use DBIx::Class::ResultSourceHandle;
13 use Scalar::Util qw/blessed weaken/;
15 use Storable qw/nfreeze thaw/;
23 __PACKAGE__->mk_group_accessors('simple' => qw/_result_class _source_handle/);
27 DBIx::Class::ResultSet - Represents a query used for fetching a set of results.
31 my $users_rs = $schema->resultset('User');
32 while( $user = $users_rs->next) {
33 print $user->username;
36 my $registered_users_rs = $schema->resultset('User')->search({ registered => 1 });
37 my @cds_in_2005 = $schema->resultset('CD')->search({ year => 2005 })->all();
41 A ResultSet is an object which stores a set of conditions representing
42 a query. It is the backbone of DBIx::Class (i.e. the really
43 important/useful bit).
45 No SQL is executed on the database when a ResultSet is created, it
46 just stores all the conditions needed to create the query.
48 A basic ResultSet representing the data of an entire table is returned
49 by calling C<resultset> on a L<DBIx::Class::Schema> and passing in a
50 L<Source|DBIx::Class::Manual::Glossary/Source> name.
52 my $users_rs = $schema->resultset('User');
54 A new ResultSet is returned from calling L</search> on an existing
55 ResultSet. The new one will contain all the conditions of the
56 original, plus any new conditions added in the C<search> call.
58 A ResultSet also incorporates an implicit iterator. L</next> and L</reset>
59 can be used to walk through all the L<DBIx::Class::Row>s the ResultSet
62 The query that the ResultSet represents is B<only> executed against
63 the database when these methods are called:
64 L</find>, L</next>, L</all>, L</first>, L</single>, L</count>.
66 If a resultset is used in a numeric context it returns the L</count>.
67 However, if it is used in a boolean context it is B<always> true. So if
68 you want to check if a resultset has any results, you must use C<if $rs
73 =head2 Chaining resultsets
75 Let's say you've got a query that needs to be run to return some data
76 to the user. But, you have an authorization system in place that
77 prevents certain users from seeing certain information. So, you want
78 to construct the basic query in one method, but add constraints to it in
83 my $request = $self->get_request; # Get a request object somehow.
84 my $schema = $self->get_schema; # Get the DBIC schema object somehow.
86 my $cd_rs = $schema->resultset('CD')->search({
87 title => $request->param('title'),
88 year => $request->param('year'),
91 $self->apply_security_policy( $cd_rs );
96 sub apply_security_policy {
105 =head3 Resolving conditions and attributes
107 When a resultset is chained from another resultset, conditions and
108 attributes with the same keys need resolving.
110 L</join>, L</prefetch>, L</+select>, L</+as> attributes are merged
111 into the existing ones from the original resultset.
113 The L</where> and L</having> attributes, and any search conditions, are
114 merged with an SQL C<AND> to the existing condition from the original
117 All other attributes are overridden by any new ones supplied in the
120 =head2 Multiple queries
122 Since a resultset just defines a query, you can do all sorts of
123 things with it with the same object.
125 # Don't hit the DB yet.
126 my $cd_rs = $schema->resultset('CD')->search({
127 title => 'something',
131 # Each of these hits the DB individually.
132 my $count = $cd_rs->count;
133 my $most_recent = $cd_rs->get_column('date_released')->max();
134 my @records = $cd_rs->all;
136 And it's not just limited to SELECT statements.
142 $cd_rs->create({ artist => 'Fred' });
144 Which is the same as:
146 $schema->resultset('CD')->create({
147 title => 'something',
152 See: L</search>, L</count>, L</get_column>, L</all>, L</create>.
160 =item Arguments: $source, \%$attrs
162 =item Return Value: $rs
166 The resultset constructor. Takes a source object (usually a
167 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
168 L</ATTRIBUTES> below). Does not perform any queries -- these are
169 executed as needed by the other methods.
171 Generally you won't need to construct a resultset manually. You'll
172 automatically get one from e.g. a L</search> called in scalar context:
174 my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
176 IMPORTANT: If called on an object, proxies to new_result instead so
178 my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
180 will return a CD object, not a ResultSet.
186 return $class->new_result(@_) if ref $class;
188 my ($source, $attrs) = @_;
189 $source = $source->handle
190 unless $source->isa('DBIx::Class::ResultSourceHandle');
191 $attrs = { %{$attrs||{}} };
193 if ($attrs->{page}) {
194 $attrs->{rows} ||= 10;
197 $attrs->{alias} ||= 'me';
199 # Creation of {} and bless separated to mitigate RH perl bug
200 # see https://bugzilla.redhat.com/show_bug.cgi?id=196836
202 _source_handle => $source,
203 cond => $attrs->{where},
211 $attrs->{result_class} || $source->resolve->result_class
221 =item Arguments: $cond, \%attrs?
223 =item Return Value: $resultset (scalar context), @row_objs (list context)
227 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
228 my $new_rs = $cd_rs->search({ year => 2005 });
230 my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
231 # year = 2005 OR year = 2004
233 If you need to pass in additional attributes but no additional condition,
234 call it as C<search(undef, \%attrs)>.
236 # "SELECT name, artistid FROM $artist_table"
237 my @all_artists = $schema->resultset('Artist')->search(undef, {
238 columns => [qw/name artistid/],
241 For a list of attributes that can be passed to C<search>, see
242 L</ATTRIBUTES>. For more examples of using this function, see
243 L<Searching|DBIx::Class::Manual::Cookbook/Searching>. For a complete
244 documentation for the first argument, see L<SQL::Abstract>.
246 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
252 my $rs = $self->search_rs( @_ );
254 my $want = wantarray;
258 elsif (defined $want) {
262 $self->throw_exception ('->search is *not* a mutator, calling it in void context makes no sense');
270 =item Arguments: $cond, \%attrs?
272 =item Return Value: $resultset
276 This method does the same exact thing as search() except it will
277 always return a resultset, even in list context.
284 # Special-case handling for (undef, undef).
285 if ( @_ == 2 && !defined $_[1] && !defined $_[0] ) {
290 $call_attrs = pop(@_) if (
291 @_ > 1 and ( ! defined $_[-1] or ref $_[-1] eq 'HASH' )
294 # see if we can keep the cache (no $rs changes)
296 my %safe = (alias => 1, cache => 1);
297 if ( ! List::Util::first { !$safe{$_} } keys %$call_attrs and (
300 ref $_[0] eq 'HASH' && ! keys %{$_[0]}
302 ref $_[0] eq 'ARRAY' && ! @{$_[0]}
304 $cache = $self->get_cache;
307 my $old_attrs = { %{$self->{attrs}} };
308 my $old_having = delete $old_attrs->{having};
309 my $old_where = delete $old_attrs->{where};
311 # reset the selector list
312 if (List::Util::first { exists $call_attrs->{$_} } qw{columns select as}) {
313 delete @{$old_attrs}{qw{select as columns +select +as +columns include_columns}};
316 my $new_attrs = { %{$old_attrs}, %{$call_attrs} };
318 # merge new attrs into inherited
319 foreach my $key (qw/join prefetch +select +as +columns include_columns bind/) {
320 next unless exists $call_attrs->{$key};
321 $new_attrs->{$key} = $self->_merge_attr($old_attrs->{$key}, $call_attrs->{$key});
324 # rip apart the rest of @_, parse a condition
327 if (ref $_[0] eq 'HASH') {
328 (keys %{$_[0]}) ? $_[0] : undef
334 $self->throw_exception('Odd number of arguments to search')
342 carp 'search( %condition ) is deprecated, use search( \%condition ) instead'
343 if (@_ > 1 and ! $self->result_source->result_class->isa('DBIx::Class::CDBICompat') );
345 for ($old_where, $call_cond) {
347 $new_attrs->{where} = $self->_stack_cond (
348 $_, $new_attrs->{where}
353 if (defined $old_having) {
354 $new_attrs->{having} = $self->_stack_cond (
355 $old_having, $new_attrs->{having}
359 my $rs = (ref $self)->new($self->result_source, $new_attrs);
361 $rs->set_cache($cache) if ($cache);
367 my ($self, $left, $right) = @_;
368 if (defined $left xor defined $right) {
369 return defined $left ? $left : $right;
371 elsif (defined $left) {
372 return { -and => [ map
373 { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
381 =head2 search_literal
385 =item Arguments: $sql_fragment, @bind_values
387 =item Return Value: $resultset (scalar context), @row_objs (list context)
391 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
392 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
394 Pass a literal chunk of SQL to be added to the conditional part of the
397 CAVEAT: C<search_literal> is provided for Class::DBI compatibility and should
398 only be used in that context. C<search_literal> is a convenience method.
399 It is equivalent to calling $schema->search(\[]), but if you want to ensure
400 columns are bound correctly, use C<search>.
402 Example of how to use C<search> instead of C<search_literal>
404 my @cds = $cd_rs->search_literal('cdid = ? AND (artist = ? OR artist = ?)', (2, 1, 2));
405 my @cds = $cd_rs->search(\[ 'cdid = ? AND (artist = ? OR artist = ?)', [ 'cdid', 2 ], [ 'artist', 1 ], [ 'artist', 2 ] ]);
408 See L<DBIx::Class::Manual::Cookbook/Searching> and
409 L<DBIx::Class::Manual::FAQ/Searching> for searching techniques that do not
410 require C<search_literal>.
415 my ($self, $sql, @bind) = @_;
417 if ( @bind && ref($bind[-1]) eq 'HASH' ) {
420 return $self->search(\[ $sql, map [ __DUMMY__ => $_ ], @bind ], ($attr || () ));
427 =item Arguments: \%columns_values | @pk_values, \%attrs?
429 =item Return Value: $row_object | undef
433 Finds and returns a single row based on supplied criteria. Takes either a
434 hashref with the same format as L</create> (including inference of foreign
435 keys from related objects), or a list of primary key values in the same
436 order as the L<primary columns|DBIx::Class::ResultSource/primary_columns>
437 declaration on the L</result_source>.
439 In either case an attempt is made to combine conditions already existing on
440 the resultset with the condition passed to this method.
442 To aid with preparing the correct query for the storage you may supply the
443 C<key> attribute, which is the name of a
444 L<unique constraint|DBIx::Class::ResultSource/add_unique_constraint> (the
445 unique constraint corresponding to the
446 L<primary columns|DBIx::Class::ResultSource/primary_columns> is always named
447 C<primary>). If the C<key> attribute has been supplied, and DBIC is unable
448 to construct a query that satisfies the named unique constraint fully (
449 non-NULL values for each column member of the constraint) an exception is
452 If no C<key> is specified, the search is carried over all unique constraints
453 which are fully defined by the available condition.
455 If no such constraint is found, C<find> currently defaults to a simple
456 C<< search->(\%column_values) >> which may or may not do what you expect.
457 Note that this fallback behavior may be deprecated in further versions. If
458 you need to search with arbitrary conditions - use L</search>. If the query
459 resulting from this fallback produces more than one row, a warning to the
460 effect is issued, though only the first row is constructed and returned as
463 In addition to C<key>, L</find> recognizes and applies standard
464 L<resultset attributes|/ATTRIBUTES> in the same way as L</search> does.
466 Note that if you have extra concerns about the correctness of the resulting
467 query you need to specify the C<key> attribute and supply the entire condition
468 as an argument to find (since it is not always possible to perform the
469 combination of the resultset condition with the supplied one, especially if
470 the resultset condition contains literal sql).
472 For example, to find a row by its primary key:
474 my $cd = $schema->resultset('CD')->find(5);
476 You can also find a row by a specific unique constraint:
478 my $cd = $schema->resultset('CD')->find(
480 artist => 'Massive Attack',
481 title => 'Mezzanine',
483 { key => 'cd_artist_title' }
486 See also L</find_or_create> and L</update_or_create>.
492 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
494 my $rsrc = $self->result_source;
496 # Parse out the condition from input
498 if (ref $_[0] eq 'HASH') {
499 $call_cond = { %{$_[0]} };
502 my $constraint = exists $attrs->{key} ? $attrs->{key} : 'primary';
503 my @c_cols = $rsrc->unique_constraint_columns($constraint);
505 $self->throw_exception(
506 "No constraint columns, maybe a malformed '$constraint' constraint?"
509 $self->throw_exception (
510 'find() expects either a column/value hashref, or a list of values '
511 . "corresponding to the columns of the specified unique constraint '$constraint'"
512 ) unless @c_cols == @_;
515 @{$call_cond}{@c_cols} = @_;
519 for my $key (keys %$call_cond) {
521 my $keyref = ref($call_cond->{$key})
523 my $relinfo = $rsrc->relationship_info($key)
525 my $val = delete $call_cond->{$key};
527 next if $keyref eq 'ARRAY'; # has_many for multi_create
529 my $rel_q = $rsrc->_resolve_condition(
530 $relinfo->{cond}, $val, $key
532 die "Can't handle complex relationship conditions in find" if ref($rel_q) ne 'HASH';
533 @related{keys %$rel_q} = values %$rel_q;
537 # relationship conditions take precedence (?)
538 @{$call_cond}{keys %related} = values %related;
540 my $alias = exists $attrs->{alias} ? $attrs->{alias} : $self->{attrs}{alias};
542 if (exists $attrs->{key}) {
543 $final_cond = $self->_qualify_cond_columns (
545 $self->_build_unique_cond (
553 elsif ($self->{attrs}{accessor} and $self->{attrs}{accessor} eq 'single') {
554 # This means that we got here after a merger of relationship conditions
555 # in ::Relationship::Base::search_related (the row method), and furthermore
556 # the relationship is of the 'single' type. This means that the condition
557 # provided by the relationship (already attached to $self) is sufficient,
558 # as there can be only one row in the database that would satisfy the
562 # no key was specified - fall down to heuristics mode:
563 # run through all unique queries registered on the resultset, and
564 # 'OR' all qualifying queries together
565 my (@unique_queries, %seen_column_combinations);
566 for my $c_name ($rsrc->unique_constraint_names) {
567 next if $seen_column_combinations{
568 join "\x00", sort $rsrc->unique_constraint_columns($c_name)
571 push @unique_queries, try {
572 $self->_build_unique_cond ($c_name, $call_cond)
576 $final_cond = @unique_queries
577 ? [ map { $self->_qualify_cond_columns($_, $alias) } @unique_queries ]
578 : $self->_non_unique_find_fallback ($call_cond, $attrs)
582 # Run the query, passing the result_class since it should propagate for find
583 my $rs = $self->search ($final_cond, {result_class => $self->result_class, %$attrs});
584 if (keys %{$rs->_resolved_attrs->{collapse}}) {
586 carp "Query returned more than one row" if $rs->next;
594 # This is a stop-gap method as agreed during the discussion on find() cleanup:
595 # http://lists.scsys.co.uk/pipermail/dbix-class/2010-October/009535.html
597 # It is invoked when find() is called in legacy-mode with insufficiently-unique
598 # condition. It is provided for overrides until a saner way forward is devised
600 # *NOTE* This is not a public method, and it's *GUARANTEED* to disappear down
601 # the road. Please adjust your tests accordingly to catch this situation early
602 # DBIx::Class::ResultSet->can('_non_unique_find_fallback') is reasonable
604 # The method will not be removed without an adequately complete replacement
605 # for strict-mode enforcement
606 sub _non_unique_find_fallback {
607 my ($self, $cond, $attrs) = @_;
609 return $self->_qualify_cond_columns(
611 exists $attrs->{alias}
613 : $self->{attrs}{alias}
618 sub _qualify_cond_columns {
619 my ($self, $cond, $alias) = @_;
621 my %aliased = %$cond;
622 for (keys %aliased) {
623 $aliased{"$alias.$_"} = delete $aliased{$_}
630 sub _build_unique_cond {
631 my ($self, $constraint_name, $extra_cond) = @_;
633 my @c_cols = $self->result_source->unique_constraint_columns($constraint_name);
635 # combination may fail if $self->{cond} is non-trivial
636 my ($final_cond) = try {
637 $self->_merge_with_rscond ($extra_cond)
642 # trim out everything not in $columns
643 $final_cond = { map { $_ => $final_cond->{$_} } @c_cols };
645 if (my @missing = grep { ! defined $final_cond->{$_} } (@c_cols) ) {
646 $self->throw_exception( sprintf ( "Unable to satisfy requested constraint '%s', no values for column(s): %s",
648 join (', ', map { "'$_'" } @missing),
655 =head2 search_related
659 =item Arguments: $rel, $cond, \%attrs?
661 =item Return Value: $new_resultset
665 $new_rs = $cd_rs->search_related('artist', {
669 Searches the specified relationship, optionally specifying a condition and
670 attributes for matching records. See L</ATTRIBUTES> for more information.
675 return shift->related_resultset(shift)->search(@_);
678 =head2 search_related_rs
680 This method works exactly the same as search_related, except that
681 it guarantees a resultset, even in list context.
685 sub search_related_rs {
686 return shift->related_resultset(shift)->search_rs(@_);
693 =item Arguments: none
695 =item Return Value: $cursor
699 Returns a storage-driven cursor to the given resultset. See
700 L<DBIx::Class::Cursor> for more information.
707 my $attrs = $self->_resolved_attrs_copy;
709 return $self->{cursor}
710 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
711 $attrs->{where},$attrs);
718 =item Arguments: $cond?
720 =item Return Value: $row_object | undef
724 my $cd = $schema->resultset('CD')->single({ year => 2001 });
726 Inflates the first result without creating a cursor if the resultset has
727 any records in it; if not returns C<undef>. Used by L</find> as a lean version
730 While this method can take an optional search condition (just like L</search>)
731 being a fast-code-path it does not recognize search attributes. If you need to
732 add extra joins or similar, call L</search> and then chain-call L</single> on the
733 L<DBIx::Class::ResultSet> returned.
739 As of 0.08100, this method enforces the assumption that the preceding
740 query returns only one row. If more than one row is returned, you will receive
743 Query returned more than one row
745 In this case, you should be using L</next> or L</find> instead, or if you really
746 know what you are doing, use the L</rows> attribute to explicitly limit the size
749 This method will also throw an exception if it is called on a resultset prefetching
750 has_many, as such a prefetch implies fetching multiple rows from the database in
751 order to assemble the resulting object.
758 my ($self, $where) = @_;
760 $self->throw_exception('single() only takes search conditions, no attributes. You want ->search( $cond, $attrs )->single()');
763 my $attrs = $self->_resolved_attrs_copy;
765 if (keys %{$attrs->{collapse}}) {
766 $self->throw_exception(
767 'single() can not be used on resultsets prefetching has_many. Use find( \%cond ) or next() instead'
772 if (defined $attrs->{where}) {
775 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
776 $where, delete $attrs->{where} ]
779 $attrs->{where} = $where;
783 my @data = $self->result_source->storage->select_single(
784 $attrs->{from}, $attrs->{select},
785 $attrs->{where}, $attrs
788 return (@data ? ($self->_construct_object(@data))[0] : undef);
794 # Recursively collapse the query, accumulating values for each column.
796 sub _collapse_query {
797 my ($self, $query, $collapsed) = @_;
801 if (ref $query eq 'ARRAY') {
802 foreach my $subquery (@$query) {
803 next unless ref $subquery; # -or
804 $collapsed = $self->_collapse_query($subquery, $collapsed);
807 elsif (ref $query eq 'HASH') {
808 if (keys %$query and (keys %$query)[0] eq '-and') {
809 foreach my $subquery (@{$query->{-and}}) {
810 $collapsed = $self->_collapse_query($subquery, $collapsed);
814 foreach my $col (keys %$query) {
815 my $value = $query->{$col};
816 $collapsed->{$col}{$value}++;
828 =item Arguments: $cond?
830 =item Return Value: $resultsetcolumn
834 my $max_length = $rs->get_column('length')->max;
836 Returns a L<DBIx::Class::ResultSetColumn> instance for a column of the ResultSet.
841 my ($self, $column) = @_;
842 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
850 =item Arguments: $cond, \%attrs?
852 =item Return Value: $resultset (scalar context), @row_objs (list context)
856 # WHERE title LIKE '%blue%'
857 $cd_rs = $rs->search_like({ title => '%blue%'});
859 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
860 that this is simply a convenience method retained for ex Class::DBI users.
861 You most likely want to use L</search> with specific operators.
863 For more information, see L<DBIx::Class::Manual::Cookbook>.
865 This method is deprecated and will be removed in 0.09. Use L</search()>
866 instead. An example conversion is:
868 ->search_like({ foo => 'bar' });
872 ->search({ foo => { like => 'bar' } });
879 'search_like() is deprecated and will be removed in DBIC version 0.09.'
880 .' Instead use ->search({ x => { -like => "y%" } })'
881 .' (note the outer pair of {}s - they are important!)'
883 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
884 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
885 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
886 return $class->search($query, { %$attrs });
893 =item Arguments: $first, $last
895 =item Return Value: $resultset (scalar context), @row_objs (list context)
899 Returns a resultset or object list representing a subset of elements from the
900 resultset slice is called on. Indexes are from 0, i.e., to get the first
903 my ($one, $two, $three) = $rs->slice(0, 2);
908 my ($self, $min, $max) = @_;
909 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
910 $attrs->{offset} = $self->{attrs}{offset} || 0;
911 $attrs->{offset} += $min;
912 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
913 return $self->search(undef, $attrs);
914 #my $slice = (ref $self)->new($self->result_source, $attrs);
915 #return (wantarray ? $slice->all : $slice);
922 =item Arguments: none
924 =item Return Value: $result | undef
928 Returns the next element in the resultset (C<undef> is there is none).
930 Can be used to efficiently iterate over records in the resultset:
932 my $rs = $schema->resultset('CD')->search;
933 while (my $cd = $rs->next) {
937 Note that you need to store the resultset object, and call C<next> on it.
938 Calling C<< resultset('Table')->next >> repeatedly will always return the
939 first record from the resultset.
945 if (my $cache = $self->get_cache) {
946 $self->{all_cache_position} ||= 0;
947 return $cache->[$self->{all_cache_position}++];
949 if ($self->{attrs}{cache}) {
950 delete $self->{pager};
951 $self->{all_cache_position} = 1;
952 return ($self->all)[0];
954 if ($self->{stashed_objects}) {
955 my $obj = shift(@{$self->{stashed_objects}});
956 delete $self->{stashed_objects} unless @{$self->{stashed_objects}};
960 exists $self->{stashed_row}
961 ? @{delete $self->{stashed_row}}
962 : $self->cursor->next
964 return undef unless (@row);
965 my ($row, @more) = $self->_construct_object(@row);
966 $self->{stashed_objects} = \@more if @more;
970 sub _construct_object {
971 my ($self, @row) = @_;
973 my $info = $self->_collapse_result($self->{_attrs}{as}, \@row)
975 my @new = $self->result_class->inflate_result($self->result_source, @$info);
976 @new = $self->{_attrs}{record_filter}->(@new)
977 if exists $self->{_attrs}{record_filter};
981 sub _collapse_result {
982 my ($self, $as_proto, $row) = @_;
986 # 'foo' => [ undef, 'foo' ]
987 # 'foo.bar' => [ 'foo', 'bar' ]
988 # 'foo.bar.baz' => [ 'foo.bar', 'baz' ]
990 my @construct_as = map { [ (/^(?:(.*)\.)?([^.]+)$/) ] } @$as_proto;
992 my %collapse = %{$self->{_attrs}{collapse}||{}};
996 # if we're doing collapsing (has_many prefetch) we need to grab records
997 # until the PK changes, so fill @pri_index. if not, we leave it empty so
998 # we know we don't have to bother.
1000 # the reason for not using the collapse stuff directly is because if you
1001 # had for e.g. two artists in a row with no cds, the collapse info for
1002 # both would be NULL (undef) so you'd lose the second artist
1004 # store just the index so we can check the array positions from the row
1005 # without having to contruct the full hash
1007 if (keys %collapse) {
1008 my %pri = map { ($_ => 1) } $self->result_source->_pri_cols;
1009 foreach my $i (0 .. $#construct_as) {
1010 next if defined($construct_as[$i][0]); # only self table
1011 if (delete $pri{$construct_as[$i][1]}) {
1012 push(@pri_index, $i);
1014 last unless keys %pri; # short circuit (Johnny Five Is Alive!)
1018 # no need to do an if, it'll be empty if @pri_index is empty anyway
1020 my %pri_vals = map { ($_ => $copy[$_]) } @pri_index;
1024 do { # no need to check anything at the front, we always want the first row
1028 foreach my $this_as (@construct_as) {
1029 $const{$this_as->[0]||''}{$this_as->[1]} = shift(@copy);
1032 push(@const_rows, \%const);
1034 } until ( # no pri_index => no collapse => drop straight out
1037 do { # get another row, stash it, drop out if different PK
1039 @copy = $self->cursor->next;
1040 $self->{stashed_row} = \@copy;
1042 # last thing in do block, counts as true if anything doesn't match
1044 # check xor defined first for NULL vs. NOT NULL then if one is
1045 # defined the other must be so check string equality
1048 (defined $pri_vals{$_} ^ defined $copy[$_])
1049 || (defined $pri_vals{$_} && ($pri_vals{$_} ne $copy[$_]))
1054 my $alias = $self->{attrs}{alias};
1061 foreach my $const (@const_rows) {
1062 scalar @const_keys or do {
1063 @const_keys = sort { length($a) <=> length($b) } keys %$const;
1065 foreach my $key (@const_keys) {
1068 my @parts = split(/\./, $key);
1070 my $data = $const->{$key};
1071 foreach my $p (@parts) {
1072 $target = $target->[1]->{$p} ||= [];
1074 if ($cur eq ".${key}" && (my @ckey = @{$collapse{$cur}||[]})) {
1075 # collapsing at this point and on final part
1076 my $pos = $collapse_pos{$cur};
1077 CK: foreach my $ck (@ckey) {
1078 if (!defined $pos->{$ck} || $pos->{$ck} ne $data->{$ck}) {
1079 $collapse_pos{$cur} = $data;
1080 delete @collapse_pos{ # clear all positioning for sub-entries
1081 grep { m/^\Q${cur}.\E/ } keys %collapse_pos
1088 if (exists $collapse{$cur}) {
1089 $target = $target->[-1];
1092 $target->[0] = $data;
1094 $info->[0] = $const->{$key};
1102 =head2 result_source
1106 =item Arguments: $result_source?
1108 =item Return Value: $result_source
1112 An accessor for the primary ResultSource object from which this ResultSet
1119 =item Arguments: $result_class?
1121 =item Return Value: $result_class
1125 An accessor for the class to use when creating row objects. Defaults to
1126 C<< result_source->result_class >> - which in most cases is the name of the
1127 L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class.
1129 Note that changing the result_class will also remove any components
1130 that were originally loaded in the source class via
1131 L<DBIx::Class::ResultSource/load_components>. Any overloaded methods
1132 in the original source class will not run.
1137 my ($self, $result_class) = @_;
1138 if ($result_class) {
1139 unless (ref $result_class) { # don't fire this for an object
1140 $self->ensure_class_loaded($result_class);
1142 $self->_result_class($result_class);
1143 # THIS LINE WOULD BE A BUG - this accessor specifically exists to
1144 # permit the user to set result class on one result set only; it only
1145 # chains if provided to search()
1146 #$self->{attrs}{result_class} = $result_class if ref $self;
1148 $self->_result_class;
1155 =item Arguments: $cond, \%attrs??
1157 =item Return Value: $count
1161 Performs an SQL C<COUNT> with the same query as the resultset was built
1162 with to find the number of elements. Passing arguments is equivalent to
1163 C<< $rs->search ($cond, \%attrs)->count >>
1169 return $self->search(@_)->count if @_ and defined $_[0];
1170 return scalar @{ $self->get_cache } if $self->get_cache;
1172 my $attrs = $self->_resolved_attrs_copy;
1174 # this is a little optimization - it is faster to do the limit
1175 # adjustments in software, instead of a subquery
1176 my $rows = delete $attrs->{rows};
1177 my $offset = delete $attrs->{offset};
1180 if ($self->_has_resolved_attr (qw/collapse group_by/)) {
1181 $crs = $self->_count_subq_rs ($attrs);
1184 $crs = $self->_count_rs ($attrs);
1186 my $count = $crs->next;
1188 $count -= $offset if $offset;
1189 $count = $rows if $rows and $rows < $count;
1190 $count = 0 if ($count < 0);
1199 =item Arguments: $cond, \%attrs??
1201 =item Return Value: $count_rs
1205 Same as L</count> but returns a L<DBIx::Class::ResultSetColumn> object.
1206 This can be very handy for subqueries:
1208 ->search( { amount => $some_rs->count_rs->as_query } )
1210 As with regular resultsets the SQL query will be executed only after
1211 the resultset is accessed via L</next> or L</all>. That would return
1212 the same single value obtainable via L</count>.
1218 return $self->search(@_)->count_rs if @_;
1220 # this may look like a lack of abstraction (count() does about the same)
1221 # but in fact an _rs *must* use a subquery for the limits, as the
1222 # software based limiting can not be ported if this $rs is to be used
1223 # in a subquery itself (i.e. ->as_query)
1224 if ($self->_has_resolved_attr (qw/collapse group_by offset rows/)) {
1225 return $self->_count_subq_rs;
1228 return $self->_count_rs;
1233 # returns a ResultSetColumn object tied to the count query
1236 my ($self, $attrs) = @_;
1238 my $rsrc = $self->result_source;
1239 $attrs ||= $self->_resolved_attrs;
1241 my $tmp_attrs = { %$attrs };
1242 # take off any limits, record_filter is cdbi, and no point of ordering nor locking a count
1243 delete @{$tmp_attrs}{qw/rows offset order_by record_filter for/};
1245 # overwrite the selector (supplied by the storage)
1246 $tmp_attrs->{select} = $rsrc->storage->_count_select ($rsrc, $attrs);
1247 $tmp_attrs->{as} = 'count';
1249 my $tmp_rs = $rsrc->resultset_class->new($rsrc, $tmp_attrs)->get_column ('count');
1255 # same as above but uses a subquery
1257 sub _count_subq_rs {
1258 my ($self, $attrs) = @_;
1260 my $rsrc = $self->result_source;
1261 $attrs ||= $self->_resolved_attrs;
1263 my $sub_attrs = { %$attrs };
1264 # extra selectors do not go in the subquery and there is no point of ordering it, nor locking it
1265 delete @{$sub_attrs}{qw/collapse select _prefetch_select as order_by for/};
1267 # if we multi-prefetch we group_by primary keys only as this is what we would
1268 # get out of the rs via ->next/->all. We *DO WANT* to clobber old group_by regardless
1269 if ( keys %{$attrs->{collapse}} ) {
1270 $sub_attrs->{group_by} = [ map { "$attrs->{alias}.$_" } ($rsrc->_pri_cols) ]
1273 # Calculate subquery selector
1274 if (my $g = $sub_attrs->{group_by}) {
1276 my $sql_maker = $rsrc->storage->sql_maker;
1278 # necessary as the group_by may refer to aliased functions
1280 for my $sel (@{$attrs->{select}}) {
1281 $sel_index->{$sel->{-as}} = $sel
1282 if (ref $sel eq 'HASH' and $sel->{-as});
1285 for my $g_part (@$g) {
1286 my $colpiece = $sel_index->{$g_part} || $g_part;
1288 # disqualify join-based group_by's. Arcane but possible query
1289 # also horrible horrible hack to alias a column (not a func.)
1290 # (probably need to introduce SQLA syntax)
1291 if ($colpiece =~ /\./ && $colpiece !~ /^$attrs->{alias}\./) {
1294 $colpiece = \ sprintf ('%s AS %s', map { $sql_maker->_quote ($_) } ($colpiece, $as) );
1296 push @{$sub_attrs->{select}}, $colpiece;
1300 my @pcols = map { "$attrs->{alias}.$_" } ($rsrc->primary_columns);
1301 $sub_attrs->{select} = @pcols ? \@pcols : [ 1 ];
1304 return $rsrc->resultset_class
1305 ->new ($rsrc, $sub_attrs)
1307 ->search ({}, { columns => { count => $rsrc->storage->_count_select ($rsrc, $attrs) } })
1308 ->get_column ('count');
1315 =head2 count_literal
1319 =item Arguments: $sql_fragment, @bind_values
1321 =item Return Value: $count
1325 Counts the results in a literal query. Equivalent to calling L</search_literal>
1326 with the passed arguments, then L</count>.
1330 sub count_literal { shift->search_literal(@_)->count; }
1336 =item Arguments: none
1338 =item Return Value: @objects
1342 Returns all elements in the resultset. Called implicitly if the resultset
1343 is returned in list context.
1350 $self->throw_exception("all() doesn't take any arguments, you probably wanted ->search(...)->all()");
1353 return @{ $self->get_cache } if $self->get_cache;
1357 if (keys %{$self->_resolved_attrs->{collapse}}) {
1358 # Using $self->cursor->all is really just an optimisation.
1359 # If we're collapsing has_many prefetches it probably makes
1360 # very little difference, and this is cleaner than hacking
1361 # _construct_object to survive the approach
1362 $self->cursor->reset;
1363 my @row = $self->cursor->next;
1365 push(@obj, $self->_construct_object(@row));
1366 @row = (exists $self->{stashed_row}
1367 ? @{delete $self->{stashed_row}}
1368 : $self->cursor->next);
1371 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
1374 $self->set_cache(\@obj) if $self->{attrs}{cache};
1383 =item Arguments: none
1385 =item Return Value: $self
1389 Resets the resultset's cursor, so you can iterate through the elements again.
1390 Implicitly resets the storage cursor, so a subsequent L</next> will trigger
1397 delete $self->{_attrs} if exists $self->{_attrs};
1398 $self->{all_cache_position} = 0;
1399 $self->cursor->reset;
1407 =item Arguments: none
1409 =item Return Value: $object | undef
1413 Resets the resultset and returns an object for the first result (or C<undef>
1414 if the resultset is empty).
1419 return $_[0]->reset->next;
1425 # Determines whether and what type of subquery is required for the $rs operation.
1426 # If grouping is necessary either supplies its own, or verifies the current one
1427 # After all is done delegates to the proper storage method.
1429 sub _rs_update_delete {
1430 my ($self, $op, $values) = @_;
1432 my $rsrc = $self->result_source;
1434 # if a condition exists we need to strip all table qualifiers
1435 # if this is not possible we'll force a subquery below
1436 my $cond = $rsrc->schema->storage->_strip_cond_qualifiers ($self->{cond});
1438 my $needs_group_by_subq = $self->_has_resolved_attr (qw/collapse group_by -join/);
1439 my $needs_subq = $needs_group_by_subq || (not defined $cond) || $self->_has_resolved_attr(qw/rows offset/);
1441 if ($needs_group_by_subq or $needs_subq) {
1443 # make a new $rs selecting only the PKs (that's all we really need)
1444 my $attrs = $self->_resolved_attrs_copy;
1447 delete $attrs->{$_} for qw/collapse _collapse_order_by select _prefetch_select as/;
1448 $attrs->{columns} = [ map { "$attrs->{alias}.$_" } ($self->result_source->_pri_cols) ];
1450 if ($needs_group_by_subq) {
1451 # make sure no group_by was supplied, or if there is one - make sure it matches
1452 # the columns compiled above perfectly. Anything else can not be sanely executed
1453 # on most databases so croak right then and there
1455 if (my $g = $attrs->{group_by}) {
1456 my @current_group_by = map
1457 { $_ =~ /\./ ? $_ : "$attrs->{alias}.$_" }
1462 join ("\x00", sort @current_group_by)
1464 join ("\x00", sort @{$attrs->{columns}} )
1466 $self->throw_exception (
1467 "You have just attempted a $op operation on a resultset which does group_by"
1468 . ' on columns other than the primary keys, while DBIC internally needs to retrieve'
1469 . ' the primary keys in a subselect. All sane RDBMS engines do not support this'
1470 . ' kind of queries. Please retry the operation with a modified group_by or'
1471 . ' without using one at all.'
1476 $attrs->{group_by} = $attrs->{columns};
1480 my $subrs = (ref $self)->new($rsrc, $attrs);
1481 return $self->result_source->storage->_subq_update_delete($subrs, $op, $values);
1484 return $rsrc->storage->$op(
1486 $op eq 'update' ? $values : (),
1496 =item Arguments: \%values
1498 =item Return Value: $storage_rv
1502 Sets the specified columns in the resultset to the supplied values in a
1503 single query. Note that this will not run any accessor/set_column/update
1504 triggers, nor will it update any row object instances derived from this
1505 resultset (this includes the contents of the L<resultset cache|/set_cache>
1506 if any). See L</update_all> if you need to execute any on-update
1507 triggers or cascades defined either by you or a
1508 L<result component|DBIx::Class::Manual::Component/WHAT_IS_A_COMPONENT>.
1510 The return value is a pass through of what the underlying
1511 storage backend returned, and may vary. See L<DBI/execute> for the most
1517 my ($self, $values) = @_;
1518 $self->throw_exception('Values for update must be a hash')
1519 unless ref $values eq 'HASH';
1521 return $self->_rs_update_delete ('update', $values);
1528 =item Arguments: \%values
1530 =item Return Value: 1
1534 Fetches all objects and updates them one at a time via
1535 L<DBIx::Class::Row/update>. Note that C<update_all> will run DBIC defined
1536 triggers, while L</update> will not.
1541 my ($self, $values) = @_;
1542 $self->throw_exception('Values for update_all must be a hash')
1543 unless ref $values eq 'HASH';
1545 my $guard = $self->result_source->schema->txn_scope_guard;
1546 $_->update($values) for $self->all;
1555 =item Arguments: none
1557 =item Return Value: $storage_rv
1561 Deletes the rows matching this resultset in a single query. Note that this
1562 will not run any delete triggers, nor will it alter the
1563 L<in_storage|DBIx::Class::Row/in_storage> status of any row object instances
1564 derived from this resultset (this includes the contents of the
1565 L<resultset cache|/set_cache> if any). See L</delete_all> if you need to
1566 execute any on-delete triggers or cascades defined either by you or a
1567 L<result component|DBIx::Class::Manual::Component/WHAT_IS_A_COMPONENT>.
1569 The return value is a pass through of what the underlying storage backend
1570 returned, and may vary. See L<DBI/execute> for the most common case.
1576 $self->throw_exception('delete does not accept any arguments')
1579 return $self->_rs_update_delete ('delete');
1586 =item Arguments: none
1588 =item Return Value: 1
1592 Fetches all objects and deletes them one at a time via
1593 L<DBIx::Class::Row/delete>. Note that C<delete_all> will run DBIC defined
1594 triggers, while L</delete> will not.
1600 $self->throw_exception('delete_all does not accept any arguments')
1603 my $guard = $self->result_source->schema->txn_scope_guard;
1604 $_->delete for $self->all;
1613 =item Arguments: \@data;
1617 Accepts either an arrayref of hashrefs or alternatively an arrayref of arrayrefs.
1618 For the arrayref of hashrefs style each hashref should be a structure suitable
1619 forsubmitting to a $resultset->create(...) method.
1621 In void context, C<insert_bulk> in L<DBIx::Class::Storage::DBI> is used
1622 to insert the data, as this is a faster method.
1624 Otherwise, each set of data is inserted into the database using
1625 L<DBIx::Class::ResultSet/create>, and the resulting objects are
1626 accumulated into an array. The array itself, or an array reference
1627 is returned depending on scalar or list context.
1629 Example: Assuming an Artist Class that has many CDs Classes relating:
1631 my $Artist_rs = $schema->resultset("Artist");
1633 ## Void Context Example
1634 $Artist_rs->populate([
1635 { artistid => 4, name => 'Manufactured Crap', cds => [
1636 { title => 'My First CD', year => 2006 },
1637 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
1640 { artistid => 5, name => 'Angsty-Whiny Girl', cds => [
1641 { title => 'My parents sold me to a record company', year => 2005 },
1642 { title => 'Why Am I So Ugly?', year => 2006 },
1643 { title => 'I Got Surgery and am now Popular', year => 2007 }
1648 ## Array Context Example
1649 my ($ArtistOne, $ArtistTwo, $ArtistThree) = $Artist_rs->populate([
1650 { name => "Artist One"},
1651 { name => "Artist Two"},
1652 { name => "Artist Three", cds=> [
1653 { title => "First CD", year => 2007},
1654 { title => "Second CD", year => 2008},
1658 print $ArtistOne->name; ## response is 'Artist One'
1659 print $ArtistThree->cds->count ## reponse is '2'
1661 For the arrayref of arrayrefs style, the first element should be a list of the
1662 fieldsnames to which the remaining elements are rows being inserted. For
1665 $Arstist_rs->populate([
1666 [qw/artistid name/],
1667 [100, 'A Formally Unknown Singer'],
1668 [101, 'A singer that jumped the shark two albums ago'],
1669 [102, 'An actually cool singer'],
1672 Please note an important effect on your data when choosing between void and
1673 wantarray context. Since void context goes straight to C<insert_bulk> in
1674 L<DBIx::Class::Storage::DBI> this will skip any component that is overriding
1675 C<insert>. So if you are using something like L<DBIx-Class-UUIDColumns> to
1676 create primary keys for you, you will find that your PKs are empty. In this
1677 case you will have to use the wantarray context in order to create those
1685 # cruft placed in standalone method
1686 my $data = $self->_normalize_populate_args(@_);
1688 if(defined wantarray) {
1690 foreach my $item (@$data) {
1691 push(@created, $self->create($item));
1693 return wantarray ? @created : \@created;
1695 my $first = $data->[0];
1697 # if a column is a registered relationship, and is a non-blessed hash/array, consider
1698 # it relationship data
1699 my (@rels, @columns);
1700 for (keys %$first) {
1701 my $ref = ref $first->{$_};
1702 $self->result_source->has_relationship($_) && ($ref eq 'ARRAY' or $ref eq 'HASH')
1708 my @pks = $self->result_source->primary_columns;
1710 ## do the belongs_to relationships
1711 foreach my $index (0..$#$data) {
1713 # delegate to create() for any dataset without primary keys with specified relationships
1714 if (grep { !defined $data->[$index]->{$_} } @pks ) {
1716 if (grep { ref $data->[$index]{$r} eq $_ } qw/HASH ARRAY/) { # a related set must be a HASH or AoH
1717 my @ret = $self->populate($data);
1723 foreach my $rel (@rels) {
1724 next unless ref $data->[$index]->{$rel} eq "HASH";
1725 my $result = $self->related_resultset($rel)->create($data->[$index]->{$rel});
1726 my ($reverse) = keys %{$self->result_source->reverse_relationship_info($rel)};
1727 my $related = $result->result_source->_resolve_condition(
1728 $result->result_source->relationship_info($reverse)->{cond},
1733 delete $data->[$index]->{$rel};
1734 $data->[$index] = {%{$data->[$index]}, %$related};
1736 push @columns, keys %$related if $index == 0;
1740 ## inherit the data locked in the conditions of the resultset
1741 my ($rs_data) = $self->_merge_with_rscond({});
1742 delete @{$rs_data}{@columns};
1743 my @inherit_cols = keys %$rs_data;
1744 my @inherit_data = values %$rs_data;
1746 ## do bulk insert on current row
1747 $self->result_source->storage->insert_bulk(
1748 $self->result_source,
1749 [@columns, @inherit_cols],
1750 [ map { [ @$_{@columns}, @inherit_data ] } @$data ],
1753 ## do the has_many relationships
1754 foreach my $item (@$data) {
1756 foreach my $rel (@rels) {
1757 next unless $item->{$rel} && ref $item->{$rel} eq "ARRAY";
1759 my $parent = $self->find({map { $_ => $item->{$_} } @pks})
1760 || $self->throw_exception('Cannot find the relating object.');
1762 my $child = $parent->$rel;
1764 my $related = $child->result_source->_resolve_condition(
1765 $parent->result_source->relationship_info($rel)->{cond},
1770 my @rows_to_add = ref $item->{$rel} eq 'ARRAY' ? @{$item->{$rel}} : ($item->{$rel});
1771 my @populate = map { {%$_, %$related} } @rows_to_add;
1773 $child->populate( \@populate );
1780 # populate() argumnets went over several incarnations
1781 # What we ultimately support is AoH
1782 sub _normalize_populate_args {
1783 my ($self, $arg) = @_;
1785 if (ref $arg eq 'ARRAY') {
1786 if (ref $arg->[0] eq 'HASH') {
1789 elsif (ref $arg->[0] eq 'ARRAY') {
1791 my @colnames = @{$arg->[0]};
1792 foreach my $values (@{$arg}[1 .. $#$arg]) {
1793 push @ret, { map { $colnames[$_] => $values->[$_] } (0 .. $#colnames) };
1799 $self->throw_exception('Populate expects an arrayref of hashrefs or arrayref of arrayrefs');
1806 =item Arguments: none
1808 =item Return Value: $pager
1812 Return Value a L<Data::Page> object for the current resultset. Only makes
1813 sense for queries with a C<page> attribute.
1815 To get the full count of entries for a paged resultset, call
1816 C<total_entries> on the L<Data::Page> object.
1820 # make a wizard good for both a scalar and a hashref
1821 my $mk_lazy_count_wizard = sub {
1822 require Variable::Magic;
1824 my $stash = { total_rs => shift };
1825 my $slot = shift; # only used by the hashref magic
1827 my $magic = Variable::Magic::wizard (
1828 data => sub { $stash },
1834 # set value lazily, and dispell for good
1835 ${$_[0]} = $_[1]{total_rs}->count;
1836 Variable::Magic::dispell (${$_[0]}, $_[1]{magic_selfref});
1840 # an explicit set implies dispell as well
1841 # the unless() is to work around "fun and giggles" below
1842 Variable::Magic::dispell (${$_[0]}, $_[1]{magic_selfref})
1843 unless (caller(2))[3] eq 'DBIx::Class::ResultSet::pager';
1850 if ($_[2] eq $slot and !$_[1]{inactive}) {
1851 my $cnt = $_[1]{total_rs}->count;
1852 $_[0]->{$slot} = $cnt;
1854 # attempting to dispell in a fetch handle (works in store), seems
1855 # to invariable segfault on 5.10, 5.12, 5.13 :(
1856 # so use an inactivator instead
1857 #Variable::Magic::dispell (%{$_[0]}, $_[1]{magic_selfref});
1863 if (! $_[1]{inactive} and $_[2] eq $slot) {
1864 #Variable::Magic::dispell (%{$_[0]}, $_[1]{magic_selfref});
1866 unless (caller(2))[3] eq 'DBIx::Class::ResultSet::pager';
1873 $stash->{magic_selfref} = $magic;
1874 weaken ($stash->{magic_selfref}); # this fails on 5.8.1
1879 # the tie class for 5.8.1
1881 package # hide from pause
1882 DBIx::Class::__DBIC_LAZY_RS_COUNT__;
1883 use base qw/Tie::Hash/;
1885 sub FIRSTKEY { my $dummy = scalar keys %{$_[0]{data}}; each %{$_[0]{data}} }
1886 sub NEXTKEY { each %{$_[0]{data}} }
1887 sub EXISTS { exists $_[0]{data}{$_[1]} }
1888 sub DELETE { delete $_[0]{data}{$_[1]} }
1889 sub CLEAR { %{$_[0]{data}} = () }
1890 sub SCALAR { scalar %{$_[0]{data}} }
1893 $_[1]{data} = {%{$_[1]{selfref}}};
1894 %{$_[1]{selfref}} = ();
1895 Scalar::Util::weaken ($_[1]{selfref});
1896 return bless ($_[1], $_[0]);
1900 if ($_[1] eq $_[0]{slot}) {
1901 my $cnt = $_[0]{data}{$_[1]} = $_[0]{total_rs}->count;
1902 untie %{$_[0]{selfref}};
1903 %{$_[0]{selfref}} = %{$_[0]{data}};
1912 $_[0]{data}{$_[1]} = $_[2];
1913 if ($_[1] eq $_[0]{slot}) {
1914 untie %{$_[0]{selfref}};
1915 %{$_[0]{selfref}} = %{$_[0]{data}};
1924 return $self->{pager} if $self->{pager};
1926 if ($self->get_cache) {
1927 $self->throw_exception ('Pagers on cached resultsets are not supported');
1930 my $attrs = $self->{attrs};
1931 $self->throw_exception("Can't create pager for non-paged rs")
1932 unless $self->{attrs}{page};
1933 $attrs->{rows} ||= 10;
1935 # throw away the paging flags and re-run the count (possibly
1936 # with a subselect) to get the real total count
1937 my $count_attrs = { %$attrs };
1938 delete $count_attrs->{$_} for qw/rows offset page pager/;
1939 my $total_rs = (ref $self)->new($self->result_source, $count_attrs);
1942 ### the following may seem awkward and dirty, but it's a thought-experiment
1943 ### necessary for future development of DBIx::DS. Do *NOT* change this code
1944 ### before talking to ribasushi/mst
1946 my $pager = Data::Page->new(
1947 0, #start with an empty set
1949 $self->{attrs}{page},
1952 my $data_slot = 'total_entries';
1954 # Since we are interested in a cached value (once it's set - it's set), every
1955 # technique will detach from the magic-host once the time comes to fire the
1956 # ->count (or in the segfaulting case of >= 5.10 it will deactivate itself)
1958 if ($] < 5.008003) {
1959 # 5.8.1 throws 'Modification of a read-only value attempted' when one tries
1960 # to weakref the magic container :(
1962 tie (%$pager, 'DBIx::Class::__DBIC_LAZY_RS_COUNT__',
1963 { slot => $data_slot, total_rs => $total_rs, selfref => $pager }
1966 elsif ($] < 5.010) {
1967 # We can use magic on the hash value slot. It's interesting that the magic is
1968 # attached to the hash-slot, and does *not* stop working once I do the dummy
1969 # assignments after the cast()
1970 # tested on 5.8.3 and 5.8.9
1971 my $magic = $mk_lazy_count_wizard->($total_rs);
1972 Variable::Magic::cast ( $pager->{$data_slot}, $magic );
1974 # this is for fun and giggles
1975 $pager->{$data_slot} = -1;
1976 $pager->{$data_slot} = 0;
1978 # this does not work for scalars, but works with
1980 #my %vals = %$pager;
1985 # And the uvar magic
1986 # works on 5.10.1, 5.12.1 and 5.13.4 in its current form,
1987 # however see the wizard maker for more notes
1988 my $magic = $mk_lazy_count_wizard->($total_rs, $data_slot);
1989 Variable::Magic::cast ( %$pager, $magic );
1992 $pager->{$data_slot} = -1;
1993 $pager->{$data_slot} = 0;
2001 return $self->{pager} = $pager;
2008 =item Arguments: $page_number
2010 =item Return Value: $rs
2014 Returns a resultset for the $page_number page of the resultset on which page
2015 is called, where each page contains a number of rows equal to the 'rows'
2016 attribute set on the resultset (10 by default).
2021 my ($self, $page) = @_;
2022 return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
2029 =item Arguments: \%vals
2031 =item Return Value: $rowobject
2035 Creates a new row object in the resultset's result class and returns
2036 it. The row is not inserted into the database at this point, call
2037 L<DBIx::Class::Row/insert> to do that. Calling L<DBIx::Class::Row/in_storage>
2038 will tell you whether the row object has been inserted or not.
2040 Passes the hashref of input on to L<DBIx::Class::Row/new>.
2045 my ($self, $values) = @_;
2046 $self->throw_exception( "new_result needs a hash" )
2047 unless (ref $values eq 'HASH');
2049 my ($merged_cond, $cols_from_relations) = $self->_merge_with_rscond($values);
2053 @$cols_from_relations
2054 ? (-cols_from_relations => $cols_from_relations)
2056 -source_handle => $self->_source_handle,
2057 -result_source => $self->result_source, # DO NOT REMOVE THIS, REQUIRED
2060 return $self->result_class->new(\%new);
2063 # _merge_with_rscond
2065 # Takes a simple hash of K/V data and returns its copy merged with the
2066 # condition already present on the resultset. Additionally returns an
2067 # arrayref of value/condition names, which were inferred from related
2068 # objects (this is needed for in-memory related objects)
2069 sub _merge_with_rscond {
2070 my ($self, $data) = @_;
2072 my (%new_data, @cols_from_relations);
2074 my $alias = $self->{attrs}{alias};
2076 if (! defined $self->{cond}) {
2077 # just massage $data below
2079 elsif ($self->{cond} eq $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION) {
2080 %new_data = %{ $self->{attrs}{related_objects} || {} }; # nothing might have been inserted yet
2081 @cols_from_relations = keys %new_data;
2083 elsif (ref $self->{cond} ne 'HASH') {
2084 $self->throw_exception(
2085 "Can't abstract implicit construct, resultset condition not a hash"
2089 # precendence must be given to passed values over values inherited from
2090 # the cond, so the order here is important.
2091 my $collapsed_cond = $self->_collapse_cond($self->{cond});
2092 my %implied = %{$self->_remove_alias($collapsed_cond, $alias)};
2094 while ( my($col, $value) = each %implied ) {
2095 my $vref = ref $value;
2096 if ($vref eq 'HASH' && keys(%$value) && (keys %$value)[0] eq '=') {
2097 $new_data{$col} = $value->{'='};
2099 elsif( !$vref or $vref eq 'SCALAR' or blessed($value) ) {
2100 $new_data{$col} = $value;
2107 %{ $self->_remove_alias($data, $alias) },
2110 return (\%new_data, \@cols_from_relations);
2113 # _has_resolved_attr
2115 # determines if the resultset defines at least one
2116 # of the attributes supplied
2118 # used to determine if a subquery is neccessary
2120 # supports some virtual attributes:
2122 # This will scan for any joins being present on the resultset.
2123 # It is not a mere key-search but a deep inspection of {from}
2126 sub _has_resolved_attr {
2127 my ($self, @attr_names) = @_;
2129 my $attrs = $self->_resolved_attrs;
2133 for my $n (@attr_names) {
2134 if (grep { $n eq $_ } (qw/-join/) ) {
2135 $extra_checks{$n}++;
2139 my $attr = $attrs->{$n};
2141 next if not defined $attr;
2143 if (ref $attr eq 'HASH') {
2144 return 1 if keys %$attr;
2146 elsif (ref $attr eq 'ARRAY') {
2154 # a resolved join is expressed as a multi-level from
2156 $extra_checks{-join}
2158 ref $attrs->{from} eq 'ARRAY'
2160 @{$attrs->{from}} > 1
2168 # Recursively collapse the condition.
2170 sub _collapse_cond {
2171 my ($self, $cond, $collapsed) = @_;
2175 if (ref $cond eq 'ARRAY') {
2176 foreach my $subcond (@$cond) {
2177 next unless ref $subcond; # -or
2178 $collapsed = $self->_collapse_cond($subcond, $collapsed);
2181 elsif (ref $cond eq 'HASH') {
2182 if (keys %$cond and (keys %$cond)[0] eq '-and') {
2183 foreach my $subcond (@{$cond->{-and}}) {
2184 $collapsed = $self->_collapse_cond($subcond, $collapsed);
2188 foreach my $col (keys %$cond) {
2189 my $value = $cond->{$col};
2190 $collapsed->{$col} = $value;
2200 # Remove the specified alias from the specified query hash. A copy is made so
2201 # the original query is not modified.
2204 my ($self, $query, $alias) = @_;
2206 my %orig = %{ $query || {} };
2209 foreach my $key (keys %orig) {
2211 $unaliased{$key} = $orig{$key};
2214 $unaliased{$1} = $orig{$key}
2215 if $key =~ m/^(?:\Q$alias\E\.)?([^.]+)$/;
2225 =item Arguments: none
2227 =item Return Value: \[ $sql, @bind ]
2231 Returns the SQL query and bind vars associated with the invocant.
2233 This is generally used as the RHS for a subquery.
2240 my $attrs = $self->_resolved_attrs_copy;
2245 # my ($sql, \@bind, \%dbi_bind_attrs) = _select_args_to_query (...)
2246 # $sql also has no wrapping parenthesis in list ctx
2248 my $sqlbind = $self->result_source->storage
2249 ->_select_args_to_query ($attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs);
2258 =item Arguments: \%vals, \%attrs?
2260 =item Return Value: $rowobject
2264 my $artist = $schema->resultset('Artist')->find_or_new(
2265 { artist => 'fred' }, { key => 'artists' });
2267 $cd->cd_to_producer->find_or_new({ producer => $producer },
2268 { key => 'primary });
2270 Find an existing record from this resultset using L</find>. if none exists,
2271 instantiate a new result object and return it. The object will not be saved
2272 into your storage until you call L<DBIx::Class::Row/insert> on it.
2274 You most likely want this method when looking for existing rows using a unique
2275 constraint that is not the primary key, or looking for related rows.
2277 If you want objects to be saved immediately, use L</find_or_create> instead.
2279 B<Note>: Make sure to read the documentation of L</find> and understand the
2280 significance of the C<key> attribute, as its lack may skew your search, and
2281 subsequently result in spurious new objects.
2283 B<Note>: Take care when using C<find_or_new> with a table having
2284 columns with default values that you intend to be automatically
2285 supplied by the database (e.g. an auto_increment primary key column).
2286 In normal usage, the value of such columns should NOT be included at
2287 all in the call to C<find_or_new>, even when set to C<undef>.
2293 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2294 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
2295 if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2298 return $self->new_result($hash);
2305 =item Arguments: \%vals
2307 =item Return Value: a L<DBIx::Class::Row> $object
2311 Attempt to create a single new row or a row with multiple related rows
2312 in the table represented by the resultset (and related tables). This
2313 will not check for duplicate rows before inserting, use
2314 L</find_or_create> to do that.
2316 To create one row for this resultset, pass a hashref of key/value
2317 pairs representing the columns of the table and the values you wish to
2318 store. If the appropriate relationships are set up, foreign key fields
2319 can also be passed an object representing the foreign row, and the
2320 value will be set to its primary key.
2322 To create related objects, pass a hashref of related-object column values
2323 B<keyed on the relationship name>. If the relationship is of type C<multi>
2324 (L<DBIx::Class::Relationship/has_many>) - pass an arrayref of hashrefs.
2325 The process will correctly identify columns holding foreign keys, and will
2326 transparently populate them from the keys of the corresponding relation.
2327 This can be applied recursively, and will work correctly for a structure
2328 with an arbitrary depth and width, as long as the relationships actually
2329 exists and the correct column data has been supplied.
2332 Instead of hashrefs of plain related data (key/value pairs), you may
2333 also pass new or inserted objects. New objects (not inserted yet, see
2334 L</new>), will be inserted into their appropriate tables.
2336 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
2338 Example of creating a new row.
2340 $person_rs->create({
2341 name=>"Some Person",
2342 email=>"somebody@someplace.com"
2345 Example of creating a new row and also creating rows in a related C<has_many>
2346 or C<has_one> resultset. Note Arrayref.
2349 { artistid => 4, name => 'Manufactured Crap', cds => [
2350 { title => 'My First CD', year => 2006 },
2351 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
2356 Example of creating a new row and also creating a row in a related
2357 C<belongs_to> resultset. Note Hashref.
2360 title=>"Music for Silly Walks",
2363 name=>"Silly Musician",
2371 When subclassing ResultSet never attempt to override this method. Since
2372 it is a simple shortcut for C<< $self->new_result($attrs)->insert >>, a
2373 lot of the internals simply never call it, so your override will be
2374 bypassed more often than not. Override either L<new|DBIx::Class::Row/new>
2375 or L<insert|DBIx::Class::Row/insert> depending on how early in the
2376 L</create> process you need to intervene.
2383 my ($self, $attrs) = @_;
2384 $self->throw_exception( "create needs a hashref" )
2385 unless ref $attrs eq 'HASH';
2386 return $self->new_result($attrs)->insert;
2389 =head2 find_or_create
2393 =item Arguments: \%vals, \%attrs?
2395 =item Return Value: $rowobject
2399 $cd->cd_to_producer->find_or_create({ producer => $producer },
2400 { key => 'primary' });
2402 Tries to find a record based on its primary key or unique constraints; if none
2403 is found, creates one and returns that instead.
2405 my $cd = $schema->resultset('CD')->find_or_create({
2407 artist => 'Massive Attack',
2408 title => 'Mezzanine',
2412 Also takes an optional C<key> attribute, to search by a specific key or unique
2413 constraint. For example:
2415 my $cd = $schema->resultset('CD')->find_or_create(
2417 artist => 'Massive Attack',
2418 title => 'Mezzanine',
2420 { key => 'cd_artist_title' }
2423 B<Note>: Make sure to read the documentation of L</find> and understand the
2424 significance of the C<key> attribute, as its lack may skew your search, and
2425 subsequently result in spurious row creation.
2427 B<Note>: Because find_or_create() reads from the database and then
2428 possibly inserts based on the result, this method is subject to a race
2429 condition. Another process could create a record in the table after
2430 the find has completed and before the create has started. To avoid
2431 this problem, use find_or_create() inside a transaction.
2433 B<Note>: Take care when using C<find_or_create> with a table having
2434 columns with default values that you intend to be automatically
2435 supplied by the database (e.g. an auto_increment primary key column).
2436 In normal usage, the value of such columns should NOT be included at
2437 all in the call to C<find_or_create>, even when set to C<undef>.
2439 See also L</find> and L</update_or_create>. For information on how to declare
2440 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2444 sub find_or_create {
2446 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2447 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
2448 if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2451 return $self->create($hash);
2454 =head2 update_or_create
2458 =item Arguments: \%col_values, { key => $unique_constraint }?
2460 =item Return Value: $row_object
2464 $resultset->update_or_create({ col => $val, ... });
2466 Like L</find_or_create>, but if a row is found it is immediately updated via
2467 C<< $found_row->update (\%col_values) >>.
2470 Takes an optional C<key> attribute to search on a specific unique constraint.
2473 # In your application
2474 my $cd = $schema->resultset('CD')->update_or_create(
2476 artist => 'Massive Attack',
2477 title => 'Mezzanine',
2480 { key => 'cd_artist_title' }
2483 $cd->cd_to_producer->update_or_create({
2484 producer => $producer,
2490 B<Note>: Make sure to read the documentation of L</find> and understand the
2491 significance of the C<key> attribute, as its lack may skew your search, and
2492 subsequently result in spurious row creation.
2494 B<Note>: Take care when using C<update_or_create> with a table having
2495 columns with default values that you intend to be automatically
2496 supplied by the database (e.g. an auto_increment primary key column).
2497 In normal usage, the value of such columns should NOT be included at
2498 all in the call to C<update_or_create>, even when set to C<undef>.
2500 See also L</find> and L</find_or_create>. For information on how to declare
2501 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2505 sub update_or_create {
2507 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2508 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
2510 my $row = $self->find($cond, $attrs);
2512 $row->update($cond);
2516 return $self->create($cond);
2519 =head2 update_or_new
2523 =item Arguments: \%col_values, { key => $unique_constraint }?
2525 =item Return Value: $rowobject
2529 $resultset->update_or_new({ col => $val, ... });
2531 Like L</find_or_new> but if a row is found it is immediately updated via
2532 C<< $found_row->update (\%col_values) >>.
2536 # In your application
2537 my $cd = $schema->resultset('CD')->update_or_new(
2539 artist => 'Massive Attack',
2540 title => 'Mezzanine',
2543 { key => 'cd_artist_title' }
2546 if ($cd->in_storage) {
2547 # the cd was updated
2550 # the cd is not yet in the database, let's insert it
2554 B<Note>: Make sure to read the documentation of L</find> and understand the
2555 significance of the C<key> attribute, as its lack may skew your search, and
2556 subsequently result in spurious new objects.
2558 B<Note>: Take care when using C<update_or_new> with a table having
2559 columns with default values that you intend to be automatically
2560 supplied by the database (e.g. an auto_increment primary key column).
2561 In normal usage, the value of such columns should NOT be included at
2562 all in the call to C<update_or_new>, even when set to C<undef>.
2564 See also L</find>, L</find_or_create> and L</find_or_new>.
2570 my $attrs = ( @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {} );
2571 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
2573 my $row = $self->find( $cond, $attrs );
2574 if ( defined $row ) {
2575 $row->update($cond);
2579 return $self->new_result($cond);
2586 =item Arguments: none
2588 =item Return Value: \@cache_objects | undef
2592 Gets the contents of the cache for the resultset, if the cache is set.
2594 The cache is populated either by using the L</prefetch> attribute to
2595 L</search> or by calling L</set_cache>.
2607 =item Arguments: \@cache_objects
2609 =item Return Value: \@cache_objects
2613 Sets the contents of the cache for the resultset. Expects an arrayref
2614 of objects of the same class as those produced by the resultset. Note that
2615 if the cache is set the resultset will return the cached objects rather
2616 than re-querying the database even if the cache attr is not set.
2618 The contents of the cache can also be populated by using the
2619 L</prefetch> attribute to L</search>.
2624 my ( $self, $data ) = @_;
2625 $self->throw_exception("set_cache requires an arrayref")
2626 if defined($data) && (ref $data ne 'ARRAY');
2627 $self->{all_cache} = $data;
2634 =item Arguments: none
2636 =item Return Value: undef
2640 Clears the cache for the resultset.
2645 shift->set_cache(undef);
2652 =item Arguments: none
2654 =item Return Value: true, if the resultset has been paginated
2662 return !!$self->{attrs}{page};
2669 =item Arguments: none
2671 =item Return Value: true, if the resultset has been ordered with C<order_by>.
2679 return scalar $self->result_source->storage->_extract_order_columns($self->{attrs}{order_by});
2682 =head2 related_resultset
2686 =item Arguments: $relationship_name
2688 =item Return Value: $resultset
2692 Returns a related resultset for the supplied relationship name.
2694 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
2698 sub related_resultset {
2699 my ($self, $rel) = @_;
2701 $self->{related_resultsets} ||= {};
2702 return $self->{related_resultsets}{$rel} ||= do {
2703 my $rsrc = $self->result_source;
2704 my $rel_info = $rsrc->relationship_info($rel);
2706 $self->throw_exception(
2707 "search_related: result source '" . $rsrc->source_name .
2708 "' has no such relationship $rel")
2711 my $attrs = $self->_chain_relationship($rel);
2713 my $join_count = $attrs->{seen_join}{$rel};
2715 my $alias = $self->result_source->storage
2716 ->relname_to_table_alias($rel, $join_count);
2718 # since this is search_related, and we already slid the select window inwards
2719 # (the select/as attrs were deleted in the beginning), we need to flip all
2720 # left joins to inner, so we get the expected results
2721 # read the comment on top of the actual function to see what this does
2722 $attrs->{from} = $rsrc->schema->storage->_inner_join_to_node ($attrs->{from}, $alias);
2725 #XXX - temp fix for result_class bug. There likely is a more elegant fix -groditi
2726 delete @{$attrs}{qw(result_class alias)};
2730 if (my $cache = $self->get_cache) {
2731 if ($cache->[0] && $cache->[0]->related_resultset($rel)->get_cache) {
2732 $new_cache = [ map { @{$_->related_resultset($rel)->get_cache} }
2737 my $rel_source = $rsrc->related_source($rel);
2741 # The reason we do this now instead of passing the alias to the
2742 # search_rs below is that if you wrap/overload resultset on the
2743 # source you need to know what alias it's -going- to have for things
2744 # to work sanely (e.g. RestrictWithObject wants to be able to add
2745 # extra query restrictions, and these may need to be $alias.)
2747 my $rel_attrs = $rel_source->resultset_attributes;
2748 local $rel_attrs->{alias} = $alias;
2750 $rel_source->resultset
2754 where => $attrs->{where},
2757 $new->set_cache($new_cache) if $new_cache;
2762 =head2 current_source_alias
2766 =item Arguments: none
2768 =item Return Value: $source_alias
2772 Returns the current table alias for the result source this resultset is built
2773 on, that will be used in the SQL query. Usually it is C<me>.
2775 Currently the source alias that refers to the result set returned by a
2776 L</search>/L</find> family method depends on how you got to the resultset: it's
2777 C<me> by default, but eg. L</search_related> aliases it to the related result
2778 source name (and keeps C<me> referring to the original result set). The long
2779 term goal is to make L<DBIx::Class> always alias the current resultset as C<me>
2780 (and make this method unnecessary).
2782 Thus it's currently necessary to use this method in predefined queries (see
2783 L<DBIx::Class::Manual::Cookbook/Predefined searches>) when referring to the
2784 source alias of the current result set:
2786 # in a result set class
2788 my ($self, $user) = @_;
2790 my $me = $self->current_source_alias;
2792 return $self->search(
2793 "$me.modified" => $user->id,
2799 sub current_source_alias {
2802 return ($self->{attrs} || {})->{alias} || 'me';
2805 =head2 as_subselect_rs
2809 =item Arguments: none
2811 =item Return Value: $resultset
2815 Act as a barrier to SQL symbols. The resultset provided will be made into a
2816 "virtual view" by including it as a subquery within the from clause. From this
2817 point on, any joined tables are inaccessible to ->search on the resultset (as if
2818 it were simply where-filtered without joins). For example:
2820 my $rs = $schema->resultset('Bar')->search({'x.name' => 'abc'},{ join => 'x' });
2822 # 'x' now pollutes the query namespace
2824 # So the following works as expected
2825 my $ok_rs = $rs->search({'x.other' => 1});
2827 # But this doesn't: instead of finding a 'Bar' related to two x rows (abc and
2828 # def) we look for one row with contradictory terms and join in another table
2829 # (aliased 'x_2') which we never use
2830 my $broken_rs = $rs->search({'x.name' => 'def'});
2832 my $rs2 = $rs->as_subselect_rs;
2834 # doesn't work - 'x' is no longer accessible in $rs2, having been sealed away
2835 my $not_joined_rs = $rs2->search({'x.other' => 1});
2837 # works as expected: finds a 'table' row related to two x rows (abc and def)
2838 my $correctly_joined_rs = $rs2->search({'x.name' => 'def'});
2840 Another example of when one might use this would be to select a subset of
2841 columns in a group by clause:
2843 my $rs = $schema->resultset('Bar')->search(undef, {
2844 group_by => [qw{ id foo_id baz_id }],
2845 })->as_subselect_rs->search(undef, {
2846 columns => [qw{ id foo_id }]
2849 In the above example normally columns would have to be equal to the group by,
2850 but because we isolated the group by into a subselect the above works.
2854 sub as_subselect_rs {
2857 my $attrs = $self->_resolved_attrs;
2859 my $fresh_rs = (ref $self)->new (
2860 $self->result_source
2863 # these pieces will be locked in the subquery
2864 delete $fresh_rs->{cond};
2865 delete @{$fresh_rs->{attrs}}{qw/where bind/};
2867 return $fresh_rs->search( {}, {
2869 $attrs->{alias} => $self->as_query,
2870 -alias => $attrs->{alias},
2871 -source_handle => $self->result_source->handle,
2873 alias => $attrs->{alias},
2877 # This code is called by search_related, and makes sure there
2878 # is clear separation between the joins before, during, and
2879 # after the relationship. This information is needed later
2880 # in order to properly resolve prefetch aliases (any alias
2881 # with a relation_chain_depth less than the depth of the
2882 # current prefetch is not considered)
2884 # The increments happen twice per join. An even number means a
2885 # relationship specified via a search_related, whereas an odd
2886 # number indicates a join/prefetch added via attributes
2888 # Also this code will wrap the current resultset (the one we
2889 # chain to) in a subselect IFF it contains limiting attributes
2890 sub _chain_relationship {
2891 my ($self, $rel) = @_;
2892 my $source = $self->result_source;
2893 my $attrs = { %{$self->{attrs}||{}} };
2895 # we need to take the prefetch the attrs into account before we
2896 # ->_resolve_join as otherwise they get lost - captainL
2897 my $join = $self->_merge_attr( $attrs->{join}, $attrs->{prefetch} );
2899 delete @{$attrs}{qw/join prefetch collapse group_by distinct select as columns +select +as +columns/};
2901 my $seen = { %{ (delete $attrs->{seen_join}) || {} } };
2904 my @force_subq_attrs = qw/offset rows group_by having/;
2907 ($attrs->{from} && ref $attrs->{from} ne 'ARRAY')
2909 $self->_has_resolved_attr (@force_subq_attrs)
2911 # Nuke the prefetch (if any) before the new $rs attrs
2912 # are resolved (prefetch is useless - we are wrapping
2913 # a subquery anyway).
2914 my $rs_copy = $self->search;
2915 $rs_copy->{attrs}{join} = $self->_merge_attr (
2916 $rs_copy->{attrs}{join},
2917 delete $rs_copy->{attrs}{prefetch},
2921 -source_handle => $source->handle,
2922 -alias => $attrs->{alias},
2923 $attrs->{alias} => $rs_copy->as_query,
2925 delete @{$attrs}{@force_subq_attrs, qw/where bind/};
2926 $seen->{-relation_chain_depth} = 0;
2928 elsif ($attrs->{from}) { #shallow copy suffices
2929 $from = [ @{$attrs->{from}} ];
2933 -source_handle => $source->handle,
2934 -alias => $attrs->{alias},
2935 $attrs->{alias} => $source->from,
2939 my $jpath = ($seen->{-relation_chain_depth})
2940 ? $from->[-1][0]{-join_path}
2943 my @requested_joins = $source->_resolve_join(
2950 push @$from, @requested_joins;
2952 $seen->{-relation_chain_depth}++;
2954 # if $self already had a join/prefetch specified on it, the requested
2955 # $rel might very well be already included. What we do in this case
2956 # is effectively a no-op (except that we bump up the chain_depth on
2957 # the join in question so we could tell it *is* the search_related)
2960 # we consider the last one thus reverse
2961 for my $j (reverse @requested_joins) {
2962 my ($last_j) = keys %{$j->[0]{-join_path}[-1]};
2963 if ($rel eq $last_j) {
2964 $j->[0]{-relation_chain_depth}++;
2970 unless ($already_joined) {
2971 push @$from, $source->_resolve_join(
2979 $seen->{-relation_chain_depth}++;
2981 return {%$attrs, from => $from, seen_join => $seen};
2984 # too many times we have to do $attrs = { %{$self->_resolved_attrs} }
2985 sub _resolved_attrs_copy {
2987 return { %{$self->_resolved_attrs (@_)} };
2990 sub _resolved_attrs {
2992 return $self->{_attrs} if $self->{_attrs};
2994 my $attrs = { %{ $self->{attrs} || {} } };
2995 my $source = $self->result_source;
2996 my $alias = $attrs->{alias};
2998 $attrs->{columns} ||= delete $attrs->{cols} if exists $attrs->{cols};
3001 # build columns (as long as select isn't set) into a set of as/select hashes
3002 unless ( $attrs->{select} ) {
3005 if ( ref $attrs->{columns} eq 'ARRAY' ) {
3006 @cols = @{ delete $attrs->{columns}}
3007 } elsif ( defined $attrs->{columns} ) {
3008 @cols = delete $attrs->{columns}
3010 @cols = $source->columns
3014 if ( ref $_ eq 'HASH' ) {
3017 my $key = /^\Q${alias}.\E(.+)$/
3023 push @colbits, { $key => $value };
3028 # add the additional columns on
3029 foreach (qw{include_columns +columns}) {
3030 if ( $attrs->{$_} ) {
3031 my @list = ( ref($attrs->{$_}) eq 'ARRAY' )
3032 ? @{ delete $attrs->{$_} }
3033 : delete $attrs->{$_};
3035 if ( ref($_) eq 'HASH' ) {
3038 my $key = ( split /\./, $_ )[-1];
3039 my $value = ( /\./ ? $_ : "$alias.$_" );
3040 push @colbits, { $key => $value };
3046 # start with initial select items
3047 if ( $attrs->{select} ) {
3049 ( ref $attrs->{select} eq 'ARRAY' )
3050 ? [ @{ $attrs->{select} } ]
3051 : [ $attrs->{select} ];
3053 if ( $attrs->{as} ) {
3056 ref $attrs->{as} eq 'ARRAY'
3057 ? [ @{ $attrs->{as} } ]
3061 $attrs->{as} = [ map {
3062 m/^\Q${alias}.\E(.+)$/
3065 } @{ $attrs->{select} }
3071 # otherwise we intialise select & as to empty
3072 $attrs->{select} = [];
3076 # now add colbits to select/as
3077 push @{ $attrs->{select} }, map values %{$_}, @colbits;
3078 push @{ $attrs->{as} }, map keys %{$_}, @colbits;
3080 if ( my $adds = delete $attrs->{'+select'} ) {
3081 $adds = [$adds] unless ref $adds eq 'ARRAY';
3082 push @{ $attrs->{select} },
3083 map { /\./ || ref $_ ? $_ : "$alias.$_" } @$adds;
3085 if ( my $adds = delete $attrs->{'+as'} ) {
3086 $adds = [$adds] unless ref $adds eq 'ARRAY';
3087 push @{ $attrs->{as} }, @$adds;
3090 $attrs->{from} ||= [{
3091 -source_handle => $source->handle,
3092 -alias => $self->{attrs}{alias},
3093 $self->{attrs}{alias} => $source->from,
3096 if ( $attrs->{join} || $attrs->{prefetch} ) {
3098 $self->throw_exception ('join/prefetch can not be used with a custom {from}')
3099 if ref $attrs->{from} ne 'ARRAY';
3101 my $join = delete $attrs->{join} || {};
3103 if ( defined $attrs->{prefetch} ) {
3104 $join = $self->_merge_attr( $join, $attrs->{prefetch} );
3107 $attrs->{from} = # have to copy here to avoid corrupting the original
3109 @{ $attrs->{from} },
3110 $source->_resolve_join(
3113 { %{ $attrs->{seen_join} || {} } },
3114 ( $attrs->{seen_join} && keys %{$attrs->{seen_join}})
3115 ? $attrs->{from}[-1][0]{-join_path}
3122 if ( defined $attrs->{order_by} ) {
3123 $attrs->{order_by} = (
3124 ref( $attrs->{order_by} ) eq 'ARRAY'
3125 ? [ @{ $attrs->{order_by} } ]
3126 : [ $attrs->{order_by} || () ]
3130 if ($attrs->{group_by} and ref $attrs->{group_by} ne 'ARRAY') {
3131 $attrs->{group_by} = [ $attrs->{group_by} ];
3134 # generate the distinct induced group_by early, as prefetch will be carried via a
3135 # subquery (since a group_by is present)
3136 if (delete $attrs->{distinct}) {
3137 if ($attrs->{group_by}) {
3138 carp ("Useless use of distinct on a grouped resultset ('distinct' is ignored when a 'group_by' is present)");
3141 $attrs->{group_by} = $source->storage->_group_over_selection (
3142 @{$attrs}{qw/from select order_by/}
3147 $attrs->{collapse} ||= {};
3148 if ( my $prefetch = delete $attrs->{prefetch} ) {
3149 $prefetch = $self->_merge_attr( {}, $prefetch );
3151 my $prefetch_ordering = [];
3153 # this is a separate structure (we don't look in {from} directly)
3154 # as the resolver needs to shift things off the lists to work
3155 # properly (identical-prefetches on different branches)
3157 if (ref $attrs->{from} eq 'ARRAY') {
3159 my $start_depth = $attrs->{seen_join}{-relation_chain_depth} || 0;
3161 for my $j ( @{$attrs->{from}}[1 .. $#{$attrs->{from}} ] ) {
3162 next unless $j->[0]{-alias};
3163 next unless $j->[0]{-join_path};
3164 next if ($j->[0]{-relation_chain_depth} || 0) < $start_depth;
3166 my @jpath = map { keys %$_ } @{$j->[0]{-join_path}};
3169 $p = $p->{$_} ||= {} for @jpath[ ($start_depth/2) .. $#jpath]; #only even depths are actual jpath boundaries
3170 push @{$p->{-join_aliases} }, $j->[0]{-alias};
3175 $source->_resolve_prefetch( $prefetch, $alias, $join_map, $prefetch_ordering, $attrs->{collapse} );
3177 # we need to somehow mark which columns came from prefetch
3178 $attrs->{_prefetch_select} = [ map { $_->[0] } @prefetch ];
3180 push @{ $attrs->{select} }, @{$attrs->{_prefetch_select}};
3181 push @{ $attrs->{as} }, (map { $_->[1] } @prefetch);
3183 push( @{$attrs->{order_by}}, @$prefetch_ordering );
3184 $attrs->{_collapse_order_by} = \@$prefetch_ordering;
3187 # if both page and offset are specified, produce a combined offset
3188 # even though it doesn't make much sense, this is what pre 081xx has
3190 if (my $page = delete $attrs->{page}) {
3192 ($attrs->{rows} * ($page - 1))
3194 ($attrs->{offset} || 0)
3198 return $self->{_attrs} = $attrs;
3202 my ($self, $attr) = @_;
3204 if (ref $attr eq 'HASH') {
3205 return $self->_rollout_hash($attr);
3206 } elsif (ref $attr eq 'ARRAY') {
3207 return $self->_rollout_array($attr);
3213 sub _rollout_array {
3214 my ($self, $attr) = @_;
3217 foreach my $element (@{$attr}) {
3218 if (ref $element eq 'HASH') {
3219 push( @rolled_array, @{ $self->_rollout_hash( $element ) } );
3220 } elsif (ref $element eq 'ARRAY') {
3221 # XXX - should probably recurse here
3222 push( @rolled_array, @{$self->_rollout_array($element)} );
3224 push( @rolled_array, $element );
3227 return \@rolled_array;
3231 my ($self, $attr) = @_;
3234 foreach my $key (keys %{$attr}) {
3235 push( @rolled_array, { $key => $attr->{$key} } );
3237 return \@rolled_array;
3240 sub _calculate_score {
3241 my ($self, $a, $b) = @_;
3243 if (defined $a xor defined $b) {
3246 elsif (not defined $a) {
3250 if (ref $b eq 'HASH') {
3251 my ($b_key) = keys %{$b};
3252 if (ref $a eq 'HASH') {
3253 my ($a_key) = keys %{$a};
3254 if ($a_key eq $b_key) {
3255 return (1 + $self->_calculate_score( $a->{$a_key}, $b->{$b_key} ));
3260 return ($a eq $b_key) ? 1 : 0;
3263 if (ref $a eq 'HASH') {
3264 my ($a_key) = keys %{$a};
3265 return ($b eq $a_key) ? 1 : 0;
3267 return ($b eq $a) ? 1 : 0;
3273 my ($self, $orig, $import) = @_;
3275 return $import unless defined($orig);
3276 return $orig unless defined($import);
3278 $orig = $self->_rollout_attr($orig);
3279 $import = $self->_rollout_attr($import);
3282 foreach my $import_element ( @{$import} ) {
3283 # find best candidate from $orig to merge $b_element into
3284 my $best_candidate = { position => undef, score => 0 }; my $position = 0;
3285 foreach my $orig_element ( @{$orig} ) {
3286 my $score = $self->_calculate_score( $orig_element, $import_element );
3287 if ($score > $best_candidate->{score}) {
3288 $best_candidate->{position} = $position;
3289 $best_candidate->{score} = $score;
3293 my ($import_key) = ( ref $import_element eq 'HASH' ) ? keys %{$import_element} : ($import_element);
3295 if ($best_candidate->{score} == 0 || exists $seen_keys->{$import_key}) {
3296 push( @{$orig}, $import_element );
3298 my $orig_best = $orig->[$best_candidate->{position}];
3299 # merge orig_best and b_element together and replace original with merged
3300 if (ref $orig_best ne 'HASH') {
3301 $orig->[$best_candidate->{position}] = $import_element;
3302 } elsif (ref $import_element eq 'HASH') {
3303 my ($key) = keys %{$orig_best};
3304 $orig->[$best_candidate->{position}] = { $key => $self->_merge_attr($orig_best->{$key}, $import_element->{$key}) };
3307 $seen_keys->{$import_key} = 1; # don't merge the same key twice
3318 $self->_source_handle($_[0]->handle);
3320 $self->_source_handle->resolve;
3325 sub STORABLE_freeze {
3326 my ($self, $cloning) = @_;
3327 my $to_serialize = { %$self };
3329 # A cursor in progress can't be serialized (and would make little sense anyway)
3330 delete $to_serialize->{cursor};
3332 return nfreeze($to_serialize);
3335 # need this hook for symmetry
3337 my ($self, $cloning, $serialized) = @_;
3339 %$self = %{ thaw($serialized) };
3345 =head2 throw_exception
3347 See L<DBIx::Class::Schema/throw_exception> for details.
3351 sub throw_exception {
3354 if (ref $self && $self->_source_handle->schema) {
3355 $self->_source_handle->schema->throw_exception(@_)
3358 DBIx::Class::Exception->throw(@_);
3362 # XXX: FIXME: Attributes docs need clearing up
3366 Attributes are used to refine a ResultSet in various ways when
3367 searching for data. They can be passed to any method which takes an
3368 C<\%attrs> argument. See L</search>, L</search_rs>, L</find>,
3371 These are in no particular order:
3377 =item Value: ( $order_by | \@order_by | \%order_by )
3381 Which column(s) to order the results by.
3383 [The full list of suitable values is documented in
3384 L<SQL::Abstract/"ORDER BY CLAUSES">; the following is a summary of
3387 If a single column name, or an arrayref of names is supplied, the
3388 argument is passed through directly to SQL. The hashref syntax allows
3389 for connection-agnostic specification of ordering direction:
3391 For descending order:
3393 order_by => { -desc => [qw/col1 col2 col3/] }
3395 For explicit ascending order:
3397 order_by => { -asc => 'col' }
3399 The old scalarref syntax (i.e. order_by => \'year DESC') is still
3400 supported, although you are strongly encouraged to use the hashref
3401 syntax as outlined above.
3407 =item Value: \@columns
3411 Shortcut to request a particular set of columns to be retrieved. Each
3412 column spec may be a string (a table column name), or a hash (in which
3413 case the key is the C<as> value, and the value is used as the C<select>
3414 expression). Adds C<me.> onto the start of any column without a C<.> in
3415 it and sets C<select> from that, then auto-populates C<as> from
3416 C<select> as normal. (You may also use the C<cols> attribute, as in
3417 earlier versions of DBIC.)
3419 Essentially C<columns> does the same as L</select> and L</as>.
3421 columns => [ 'foo', { bar => 'baz' } ]
3425 select => [qw/foo baz/],
3432 =item Value: \@columns
3436 Indicates additional columns to be selected from storage. Works the same
3437 as L</columns> but adds columns to the selection. (You may also use the
3438 C<include_columns> attribute, as in earlier versions of DBIC). For
3441 $schema->resultset('CD')->search(undef, {
3442 '+columns' => ['artist.name'],
3446 would return all CDs and include a 'name' column to the information
3447 passed to object inflation. Note that the 'artist' is the name of the
3448 column (or relationship) accessor, and 'name' is the name of the column
3449 accessor in the related table.
3451 =head2 include_columns
3455 =item Value: \@columns
3459 Deprecated. Acts as a synonym for L</+columns> for backward compatibility.
3465 =item Value: \@select_columns
3469 Indicates which columns should be selected from the storage. You can use
3470 column names, or in the case of RDBMS back ends, function or stored procedure
3473 $rs = $schema->resultset('Employee')->search(undef, {
3476 { count => 'employeeid' },
3477 { max => { length => 'name' }, -as => 'longest_name' }
3482 SELECT name, COUNT( employeeid ), MAX( LENGTH( name ) ) AS longest_name FROM employee
3484 B<NOTE:> You will almost always need a corresponding L</as> attribute when you
3485 use L</select>, to instruct DBIx::Class how to store the result of the column.
3486 Also note that the L</as> attribute has nothing to do with the SQL-side 'AS'
3487 identifier aliasing. You can however alias a function, so you can use it in
3488 e.g. an C<ORDER BY> clause. This is done via the C<-as> B<select function
3489 attribute> supplied as shown in the example above.
3495 Indicates additional columns to be selected from storage. Works the same as
3496 L</select> but adds columns to the default selection, instead of specifying
3505 Indicates additional column names for those added via L</+select>. See L</as>.
3513 =item Value: \@inflation_names
3517 Indicates column names for object inflation. That is L</as> indicates the
3518 slot name in which the column value will be stored within the
3519 L<Row|DBIx::Class::Row> object. The value will then be accessible via this
3520 identifier by the C<get_column> method (or via the object accessor B<if one
3521 with the same name already exists>) as shown below. The L</as> attribute has
3522 B<nothing to do> with the SQL-side C<AS>. See L</select> for details.
3524 $rs = $schema->resultset('Employee')->search(undef, {
3527 { count => 'employeeid' },
3528 { max => { length => 'name' }, -as => 'longest_name' }
3537 If the object against which the search is performed already has an accessor
3538 matching a column name specified in C<as>, the value can be retrieved using
3539 the accessor as normal:
3541 my $name = $employee->name();
3543 If on the other hand an accessor does not exist in the object, you need to
3544 use C<get_column> instead:
3546 my $employee_count = $employee->get_column('employee_count');
3548 You can create your own accessors if required - see
3549 L<DBIx::Class::Manual::Cookbook> for details.
3555 =item Value: ($rel_name | \@rel_names | \%rel_names)
3559 Contains a list of relationships that should be joined for this query. For
3562 # Get CDs by Nine Inch Nails
3563 my $rs = $schema->resultset('CD')->search(
3564 { 'artist.name' => 'Nine Inch Nails' },
3565 { join => 'artist' }
3568 Can also contain a hash reference to refer to the other relation's relations.
3571 package MyApp::Schema::Track;
3572 use base qw/DBIx::Class/;
3573 __PACKAGE__->table('track');
3574 __PACKAGE__->add_columns(qw/trackid cd position title/);
3575 __PACKAGE__->set_primary_key('trackid');
3576 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
3579 # In your application
3580 my $rs = $schema->resultset('Artist')->search(
3581 { 'track.title' => 'Teardrop' },
3583 join => { cd => 'track' },
3584 order_by => 'artist.name',
3588 You need to use the relationship (not the table) name in conditions,
3589 because they are aliased as such. The current table is aliased as "me", so
3590 you need to use me.column_name in order to avoid ambiguity. For example:
3592 # Get CDs from 1984 with a 'Foo' track
3593 my $rs = $schema->resultset('CD')->search(
3596 'tracks.name' => 'Foo'
3598 { join => 'tracks' }
3601 If the same join is supplied twice, it will be aliased to <rel>_2 (and
3602 similarly for a third time). For e.g.
3604 my $rs = $schema->resultset('Artist')->search({
3605 'cds.title' => 'Down to Earth',
3606 'cds_2.title' => 'Popular',
3608 join => [ qw/cds cds/ ],
3611 will return a set of all artists that have both a cd with title 'Down
3612 to Earth' and a cd with title 'Popular'.
3614 If you want to fetch related objects from other tables as well, see C<prefetch>
3617 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
3623 =item Value: ($rel_name | \@rel_names | \%rel_names)
3627 Contains one or more relationships that should be fetched along with
3628 the main query (when they are accessed afterwards the data will
3629 already be available, without extra queries to the database). This is
3630 useful for when you know you will need the related objects, because it
3631 saves at least one query:
3633 my $rs = $schema->resultset('Tag')->search(
3642 The initial search results in SQL like the following:
3644 SELECT tag.*, cd.*, artist.* FROM tag
3645 JOIN cd ON tag.cd = cd.cdid
3646 JOIN artist ON cd.artist = artist.artistid
3648 L<DBIx::Class> has no need to go back to the database when we access the
3649 C<cd> or C<artist> relationships, which saves us two SQL statements in this
3652 Simple prefetches will be joined automatically, so there is no need
3653 for a C<join> attribute in the above search.
3655 C<prefetch> can be used with the following relationship types: C<belongs_to>,
3656 C<has_one> (or if you're using C<add_relationship>, any relationship declared
3657 with an accessor type of 'single' or 'filter'). A more complex example that
3658 prefetches an artists cds, the tracks on those cds, and the tags associated
3659 with that artist is given below (assuming many-to-many from artists to tags):
3661 my $rs = $schema->resultset('Artist')->search(
3665 { cds => 'tracks' },
3666 { artist_tags => 'tags' }
3672 B<NOTE:> If you specify a C<prefetch> attribute, the C<join> and C<select>
3673 attributes will be ignored.
3675 B<CAVEATs>: Prefetch does a lot of deep magic. As such, it may not behave
3676 exactly as you might expect.
3682 Prefetch uses the L</cache> to populate the prefetched relationships. This
3683 may or may not be what you want.
3687 If you specify a condition on a prefetched relationship, ONLY those
3688 rows that match the prefetched condition will be fetched into that relationship.
3689 This means that adding prefetch to a search() B<may alter> what is returned by
3690 traversing a relationship. So, if you have C<< Artist->has_many(CDs) >> and you do
3692 my $artist_rs = $schema->resultset('Artist')->search({
3698 my $count = $artist_rs->first->cds->count;
3700 my $artist_rs_prefetch = $artist_rs->search( {}, { prefetch => 'cds' } );
3702 my $prefetch_count = $artist_rs_prefetch->first->cds->count;
3704 cmp_ok( $count, '==', $prefetch_count, "Counts should be the same" );
3706 that cmp_ok() may or may not pass depending on the datasets involved. This
3707 behavior may or may not survive the 0.09 transition.
3719 Makes the resultset paged and specifies the page to retrieve. Effectively
3720 identical to creating a non-pages resultset and then calling ->page($page)
3723 If L<rows> attribute is not specified it defaults to 10 rows per page.
3725 When you have a paged resultset, L</count> will only return the number
3726 of rows in the page. To get the total, use the L</pager> and call
3727 C<total_entries> on it.
3737 Specifies the maximum number of rows for direct retrieval or the number of
3738 rows per page if the page attribute or method is used.
3744 =item Value: $offset
3748 Specifies the (zero-based) row number for the first row to be returned, or the
3749 of the first row of the first page if paging is used.
3755 =item Value: \@columns
3759 A arrayref of columns to group by. Can include columns of joined tables.
3761 group_by => [qw/ column1 column2 ... /]
3767 =item Value: $condition
3771 HAVING is a select statement attribute that is applied between GROUP BY and
3772 ORDER BY. It is applied to the after the grouping calculations have been
3775 having => { 'count(employee)' => { '>=', 100 } }
3781 =item Value: (0 | 1)
3785 Set to 1 to group by all columns. If the resultset already has a group_by
3786 attribute, this setting is ignored and an appropriate warning is issued.
3792 Adds to the WHERE clause.
3794 # only return rows WHERE deleted IS NULL for all searches
3795 __PACKAGE__->resultset_attributes({ where => { deleted => undef } }); )
3797 Can be overridden by passing C<< { where => undef } >> as an attribute
3804 Set to 1 to cache search results. This prevents extra SQL queries if you
3805 revisit rows in your ResultSet:
3807 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
3809 while( my $artist = $resultset->next ) {
3813 $rs->first; # without cache, this would issue a query
3815 By default, searches are not cached.
3817 For more examples of using these attributes, see
3818 L<DBIx::Class::Manual::Cookbook>.
3824 =item Value: ( 'update' | 'shared' )
3828 Set to 'update' for a SELECT ... FOR UPDATE or 'shared' for a SELECT