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>.
250 Note that L</search> does not process/deflate any of the values passed in the
251 L<SQL::Abstract>-compatible search condition structure. This is unlike other
252 condition-bound methods L</new>, L</create> and L</find>. The user must ensure
253 manually that any value passed to this method will stringify to something the
254 RDBMS knows how to deal with. A notable example is the handling of L<DateTime>
255 objects, for more info see:
256 L<DBIx::Class::Manual::Cookbook/Formatting_DateTime_objects_in_queries>.
262 my $rs = $self->search_rs( @_ );
264 my $want = wantarray;
268 elsif (defined $want) {
272 $self->throw_exception ('->search is *not* a mutator, calling it in void context makes no sense');
280 =item Arguments: $cond, \%attrs?
282 =item Return Value: $resultset
286 This method does the same exact thing as search() except it will
287 always return a resultset, even in list context.
294 # Special-case handling for (undef, undef).
295 if ( @_ == 2 && !defined $_[1] && !defined $_[0] ) {
300 $call_attrs = pop(@_) if (
301 @_ > 1 and ( ! defined $_[-1] or ref $_[-1] eq 'HASH' )
304 # see if we can keep the cache (no $rs changes)
306 my %safe = (alias => 1, cache => 1);
307 if ( ! List::Util::first { !$safe{$_} } keys %$call_attrs and (
310 ref $_[0] eq 'HASH' && ! keys %{$_[0]}
312 ref $_[0] eq 'ARRAY' && ! @{$_[0]}
314 $cache = $self->get_cache;
317 my $old_attrs = { %{$self->{attrs}} };
318 my $old_having = delete $old_attrs->{having};
319 my $old_where = delete $old_attrs->{where};
321 # reset the selector list
322 if (List::Util::first { exists $call_attrs->{$_} } qw{columns select as}) {
323 delete @{$old_attrs}{qw{select as columns +select +as +columns include_columns}};
326 my $new_attrs = { %{$old_attrs}, %{$call_attrs} };
328 # merge new attrs into inherited
329 foreach my $key (qw/join prefetch +select +as +columns include_columns bind/) {
330 next unless exists $call_attrs->{$key};
331 $new_attrs->{$key} = $self->_merge_attr($old_attrs->{$key}, $call_attrs->{$key});
334 # rip apart the rest of @_, parse a condition
337 if (ref $_[0] eq 'HASH') {
338 (keys %{$_[0]}) ? $_[0] : undef
344 $self->throw_exception('Odd number of arguments to search')
352 carp 'search( %condition ) is deprecated, use search( \%condition ) instead'
353 if (@_ > 1 and ! $self->result_source->result_class->isa('DBIx::Class::CDBICompat') );
355 for ($old_where, $call_cond) {
357 $new_attrs->{where} = $self->_stack_cond (
358 $_, $new_attrs->{where}
363 if (defined $old_having) {
364 $new_attrs->{having} = $self->_stack_cond (
365 $old_having, $new_attrs->{having}
369 my $rs = (ref $self)->new($self->result_source, $new_attrs);
371 $rs->set_cache($cache) if ($cache);
377 my ($self, $left, $right) = @_;
378 if (defined $left xor defined $right) {
379 return defined $left ? $left : $right;
381 elsif (defined $left) {
382 return { -and => [ map
383 { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
391 =head2 search_literal
395 =item Arguments: $sql_fragment, @bind_values
397 =item Return Value: $resultset (scalar context), @row_objs (list context)
401 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
402 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
404 Pass a literal chunk of SQL to be added to the conditional part of the
407 CAVEAT: C<search_literal> is provided for Class::DBI compatibility and should
408 only be used in that context. C<search_literal> is a convenience method.
409 It is equivalent to calling $schema->search(\[]), but if you want to ensure
410 columns are bound correctly, use C<search>.
412 Example of how to use C<search> instead of C<search_literal>
414 my @cds = $cd_rs->search_literal('cdid = ? AND (artist = ? OR artist = ?)', (2, 1, 2));
415 my @cds = $cd_rs->search(\[ 'cdid = ? AND (artist = ? OR artist = ?)', [ 'cdid', 2 ], [ 'artist', 1 ], [ 'artist', 2 ] ]);
418 See L<DBIx::Class::Manual::Cookbook/Searching> and
419 L<DBIx::Class::Manual::FAQ/Searching> for searching techniques that do not
420 require C<search_literal>.
425 my ($self, $sql, @bind) = @_;
427 if ( @bind && ref($bind[-1]) eq 'HASH' ) {
430 return $self->search(\[ $sql, map [ __DUMMY__ => $_ ], @bind ], ($attr || () ));
437 =item Arguments: \%columns_values | @pk_values, \%attrs?
439 =item Return Value: $row_object | undef
443 Finds and returns a single row based on supplied criteria. Takes either a
444 hashref with the same format as L</create> (including inference of foreign
445 keys from related objects), or a list of primary key values in the same
446 order as the L<primary columns|DBIx::Class::ResultSource/primary_columns>
447 declaration on the L</result_source>.
449 In either case an attempt is made to combine conditions already existing on
450 the resultset with the condition passed to this method.
452 To aid with preparing the correct query for the storage you may supply the
453 C<key> attribute, which is the name of a
454 L<unique constraint|DBIx::Class::ResultSource/add_unique_constraint> (the
455 unique constraint corresponding to the
456 L<primary columns|DBIx::Class::ResultSource/primary_columns> is always named
457 C<primary>). If the C<key> attribute has been supplied, and DBIC is unable
458 to construct a query that satisfies the named unique constraint fully (
459 non-NULL values for each column member of the constraint) an exception is
462 If no C<key> is specified, the search is carried over all unique constraints
463 which are fully defined by the available condition.
465 If no such constraint is found, C<find> currently defaults to a simple
466 C<< search->(\%column_values) >> which may or may not do what you expect.
467 Note that this fallback behavior may be deprecated in further versions. If
468 you need to search with arbitrary conditions - use L</search>. If the query
469 resulting from this fallback produces more than one row, a warning to the
470 effect is issued, though only the first row is constructed and returned as
473 In addition to C<key>, L</find> recognizes and applies standard
474 L<resultset attributes|/ATTRIBUTES> in the same way as L</search> does.
476 Note that if you have extra concerns about the correctness of the resulting
477 query you need to specify the C<key> attribute and supply the entire condition
478 as an argument to find (since it is not always possible to perform the
479 combination of the resultset condition with the supplied one, especially if
480 the resultset condition contains literal sql).
482 For example, to find a row by its primary key:
484 my $cd = $schema->resultset('CD')->find(5);
486 You can also find a row by a specific unique constraint:
488 my $cd = $schema->resultset('CD')->find(
490 artist => 'Massive Attack',
491 title => 'Mezzanine',
493 { key => 'cd_artist_title' }
496 See also L</find_or_create> and L</update_or_create>.
502 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
504 my $rsrc = $self->result_source;
506 # Parse out the condition from input
508 if (ref $_[0] eq 'HASH') {
509 $call_cond = { %{$_[0]} };
512 my $constraint = exists $attrs->{key} ? $attrs->{key} : 'primary';
513 my @c_cols = $rsrc->unique_constraint_columns($constraint);
515 $self->throw_exception(
516 "No constraint columns, maybe a malformed '$constraint' constraint?"
519 $self->throw_exception (
520 'find() expects either a column/value hashref, or a list of values '
521 . "corresponding to the columns of the specified unique constraint '$constraint'"
522 ) unless @c_cols == @_;
525 @{$call_cond}{@c_cols} = @_;
529 for my $key (keys %$call_cond) {
531 my $keyref = ref($call_cond->{$key})
533 my $relinfo = $rsrc->relationship_info($key)
535 my $val = delete $call_cond->{$key};
537 next if $keyref eq 'ARRAY'; # has_many for multi_create
539 my $rel_q = $rsrc->_resolve_condition(
540 $relinfo->{cond}, $val, $key
542 die "Can't handle complex relationship conditions in find" if ref($rel_q) ne 'HASH';
543 @related{keys %$rel_q} = values %$rel_q;
547 # relationship conditions take precedence (?)
548 @{$call_cond}{keys %related} = values %related;
550 my $alias = exists $attrs->{alias} ? $attrs->{alias} : $self->{attrs}{alias};
552 if (exists $attrs->{key}) {
553 $final_cond = $self->_qualify_cond_columns (
555 $self->_build_unique_cond (
563 elsif ($self->{attrs}{accessor} and $self->{attrs}{accessor} eq 'single') {
564 # This means that we got here after a merger of relationship conditions
565 # in ::Relationship::Base::search_related (the row method), and furthermore
566 # the relationship is of the 'single' type. This means that the condition
567 # provided by the relationship (already attached to $self) is sufficient,
568 # as there can be only one row in the database that would satisfy the
572 # no key was specified - fall down to heuristics mode:
573 # run through all unique queries registered on the resultset, and
574 # 'OR' all qualifying queries together
575 my (@unique_queries, %seen_column_combinations);
576 for my $c_name ($rsrc->unique_constraint_names) {
577 next if $seen_column_combinations{
578 join "\x00", sort $rsrc->unique_constraint_columns($c_name)
581 push @unique_queries, try {
582 $self->_build_unique_cond ($c_name, $call_cond)
586 $final_cond = @unique_queries
587 ? [ map { $self->_qualify_cond_columns($_, $alias) } @unique_queries ]
588 : $self->_non_unique_find_fallback ($call_cond, $attrs)
592 # Run the query, passing the result_class since it should propagate for find
593 my $rs = $self->search ($final_cond, {result_class => $self->result_class, %$attrs});
594 if (keys %{$rs->_resolved_attrs->{collapse}}) {
596 carp "Query returned more than one row" if $rs->next;
604 # This is a stop-gap method as agreed during the discussion on find() cleanup:
605 # http://lists.scsys.co.uk/pipermail/dbix-class/2010-October/009535.html
607 # It is invoked when find() is called in legacy-mode with insufficiently-unique
608 # condition. It is provided for overrides until a saner way forward is devised
610 # *NOTE* This is not a public method, and it's *GUARANTEED* to disappear down
611 # the road. Please adjust your tests accordingly to catch this situation early
612 # DBIx::Class::ResultSet->can('_non_unique_find_fallback') is reasonable
614 # The method will not be removed without an adequately complete replacement
615 # for strict-mode enforcement
616 sub _non_unique_find_fallback {
617 my ($self, $cond, $attrs) = @_;
619 return $self->_qualify_cond_columns(
621 exists $attrs->{alias}
623 : $self->{attrs}{alias}
628 sub _qualify_cond_columns {
629 my ($self, $cond, $alias) = @_;
631 my %aliased = %$cond;
632 for (keys %aliased) {
633 $aliased{"$alias.$_"} = delete $aliased{$_}
640 sub _build_unique_cond {
641 my ($self, $constraint_name, $extra_cond) = @_;
643 my @c_cols = $self->result_source->unique_constraint_columns($constraint_name);
645 # combination may fail if $self->{cond} is non-trivial
646 my ($final_cond) = try {
647 $self->_merge_with_rscond ($extra_cond)
652 # trim out everything not in $columns
653 $final_cond = { map { $_ => $final_cond->{$_} } @c_cols };
655 if (my @missing = grep { ! defined $final_cond->{$_} } (@c_cols) ) {
656 $self->throw_exception( sprintf ( "Unable to satisfy requested constraint '%s', no values for column(s): %s",
658 join (', ', map { "'$_'" } @missing),
665 =head2 search_related
669 =item Arguments: $rel, $cond, \%attrs?
671 =item Return Value: $new_resultset
675 $new_rs = $cd_rs->search_related('artist', {
679 Searches the specified relationship, optionally specifying a condition and
680 attributes for matching records. See L</ATTRIBUTES> for more information.
685 return shift->related_resultset(shift)->search(@_);
688 =head2 search_related_rs
690 This method works exactly the same as search_related, except that
691 it guarantees a resultset, even in list context.
695 sub search_related_rs {
696 return shift->related_resultset(shift)->search_rs(@_);
703 =item Arguments: none
705 =item Return Value: $cursor
709 Returns a storage-driven cursor to the given resultset. See
710 L<DBIx::Class::Cursor> for more information.
717 my $attrs = $self->_resolved_attrs_copy;
719 return $self->{cursor}
720 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
721 $attrs->{where},$attrs);
728 =item Arguments: $cond?
730 =item Return Value: $row_object | undef
734 my $cd = $schema->resultset('CD')->single({ year => 2001 });
736 Inflates the first result without creating a cursor if the resultset has
737 any records in it; if not returns C<undef>. Used by L</find> as a lean version
740 While this method can take an optional search condition (just like L</search>)
741 being a fast-code-path it does not recognize search attributes. If you need to
742 add extra joins or similar, call L</search> and then chain-call L</single> on the
743 L<DBIx::Class::ResultSet> returned.
749 As of 0.08100, this method enforces the assumption that the preceding
750 query returns only one row. If more than one row is returned, you will receive
753 Query returned more than one row
755 In this case, you should be using L</next> or L</find> instead, or if you really
756 know what you are doing, use the L</rows> attribute to explicitly limit the size
759 This method will also throw an exception if it is called on a resultset prefetching
760 has_many, as such a prefetch implies fetching multiple rows from the database in
761 order to assemble the resulting object.
768 my ($self, $where) = @_;
770 $self->throw_exception('single() only takes search conditions, no attributes. You want ->search( $cond, $attrs )->single()');
773 my $attrs = $self->_resolved_attrs_copy;
775 if (keys %{$attrs->{collapse}}) {
776 $self->throw_exception(
777 'single() can not be used on resultsets prefetching has_many. Use find( \%cond ) or next() instead'
782 if (defined $attrs->{where}) {
785 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
786 $where, delete $attrs->{where} ]
789 $attrs->{where} = $where;
793 my @data = $self->result_source->storage->select_single(
794 $attrs->{from}, $attrs->{select},
795 $attrs->{where}, $attrs
798 return (@data ? ($self->_construct_object(@data))[0] : undef);
804 # Recursively collapse the query, accumulating values for each column.
806 sub _collapse_query {
807 my ($self, $query, $collapsed) = @_;
811 if (ref $query eq 'ARRAY') {
812 foreach my $subquery (@$query) {
813 next unless ref $subquery; # -or
814 $collapsed = $self->_collapse_query($subquery, $collapsed);
817 elsif (ref $query eq 'HASH') {
818 if (keys %$query and (keys %$query)[0] eq '-and') {
819 foreach my $subquery (@{$query->{-and}}) {
820 $collapsed = $self->_collapse_query($subquery, $collapsed);
824 foreach my $col (keys %$query) {
825 my $value = $query->{$col};
826 $collapsed->{$col}{$value}++;
838 =item Arguments: $cond?
840 =item Return Value: $resultsetcolumn
844 my $max_length = $rs->get_column('length')->max;
846 Returns a L<DBIx::Class::ResultSetColumn> instance for a column of the ResultSet.
851 my ($self, $column) = @_;
852 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
860 =item Arguments: $cond, \%attrs?
862 =item Return Value: $resultset (scalar context), @row_objs (list context)
866 # WHERE title LIKE '%blue%'
867 $cd_rs = $rs->search_like({ title => '%blue%'});
869 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
870 that this is simply a convenience method retained for ex Class::DBI users.
871 You most likely want to use L</search> with specific operators.
873 For more information, see L<DBIx::Class::Manual::Cookbook>.
875 This method is deprecated and will be removed in 0.09. Use L</search()>
876 instead. An example conversion is:
878 ->search_like({ foo => 'bar' });
882 ->search({ foo => { like => 'bar' } });
889 'search_like() is deprecated and will be removed in DBIC version 0.09.'
890 .' Instead use ->search({ x => { -like => "y%" } })'
891 .' (note the outer pair of {}s - they are important!)'
893 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
894 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
895 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
896 return $class->search($query, { %$attrs });
903 =item Arguments: $first, $last
905 =item Return Value: $resultset (scalar context), @row_objs (list context)
909 Returns a resultset or object list representing a subset of elements from the
910 resultset slice is called on. Indexes are from 0, i.e., to get the first
913 my ($one, $two, $three) = $rs->slice(0, 2);
918 my ($self, $min, $max) = @_;
919 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
920 $attrs->{offset} = $self->{attrs}{offset} || 0;
921 $attrs->{offset} += $min;
922 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
923 return $self->search(undef, $attrs);
924 #my $slice = (ref $self)->new($self->result_source, $attrs);
925 #return (wantarray ? $slice->all : $slice);
932 =item Arguments: none
934 =item Return Value: $result | undef
938 Returns the next element in the resultset (C<undef> is there is none).
940 Can be used to efficiently iterate over records in the resultset:
942 my $rs = $schema->resultset('CD')->search;
943 while (my $cd = $rs->next) {
947 Note that you need to store the resultset object, and call C<next> on it.
948 Calling C<< resultset('Table')->next >> repeatedly will always return the
949 first record from the resultset.
955 if (my $cache = $self->get_cache) {
956 $self->{all_cache_position} ||= 0;
957 return $cache->[$self->{all_cache_position}++];
959 if ($self->{attrs}{cache}) {
960 delete $self->{pager};
961 $self->{all_cache_position} = 1;
962 return ($self->all)[0];
964 if ($self->{stashed_objects}) {
965 my $obj = shift(@{$self->{stashed_objects}});
966 delete $self->{stashed_objects} unless @{$self->{stashed_objects}};
970 exists $self->{stashed_row}
971 ? @{delete $self->{stashed_row}}
972 : $self->cursor->next
974 return undef unless (@row);
975 my ($row, @more) = $self->_construct_object(@row);
976 $self->{stashed_objects} = \@more if @more;
980 sub _construct_object {
981 my ($self, @row) = @_;
983 my $info = $self->_collapse_result($self->{_attrs}{as}, \@row)
985 my @new = $self->result_class->inflate_result($self->result_source, @$info);
986 @new = $self->{_attrs}{record_filter}->(@new)
987 if exists $self->{_attrs}{record_filter};
991 sub _collapse_result {
992 my ($self, $as_proto, $row) = @_;
996 # 'foo' => [ undef, 'foo' ]
997 # 'foo.bar' => [ 'foo', 'bar' ]
998 # 'foo.bar.baz' => [ 'foo.bar', 'baz' ]
1000 my @construct_as = map { [ (/^(?:(.*)\.)?([^.]+)$/) ] } @$as_proto;
1002 my %collapse = %{$self->{_attrs}{collapse}||{}};
1006 # if we're doing collapsing (has_many prefetch) we need to grab records
1007 # until the PK changes, so fill @pri_index. if not, we leave it empty so
1008 # we know we don't have to bother.
1010 # the reason for not using the collapse stuff directly is because if you
1011 # had for e.g. two artists in a row with no cds, the collapse info for
1012 # both would be NULL (undef) so you'd lose the second artist
1014 # store just the index so we can check the array positions from the row
1015 # without having to contruct the full hash
1017 if (keys %collapse) {
1018 my %pri = map { ($_ => 1) } $self->result_source->_pri_cols;
1019 foreach my $i (0 .. $#construct_as) {
1020 next if defined($construct_as[$i][0]); # only self table
1021 if (delete $pri{$construct_as[$i][1]}) {
1022 push(@pri_index, $i);
1024 last unless keys %pri; # short circuit (Johnny Five Is Alive!)
1028 # no need to do an if, it'll be empty if @pri_index is empty anyway
1030 my %pri_vals = map { ($_ => $copy[$_]) } @pri_index;
1034 do { # no need to check anything at the front, we always want the first row
1038 foreach my $this_as (@construct_as) {
1039 $const{$this_as->[0]||''}{$this_as->[1]} = shift(@copy);
1042 push(@const_rows, \%const);
1044 } until ( # no pri_index => no collapse => drop straight out
1047 do { # get another row, stash it, drop out if different PK
1049 @copy = $self->cursor->next;
1050 $self->{stashed_row} = \@copy;
1052 # last thing in do block, counts as true if anything doesn't match
1054 # check xor defined first for NULL vs. NOT NULL then if one is
1055 # defined the other must be so check string equality
1058 (defined $pri_vals{$_} ^ defined $copy[$_])
1059 || (defined $pri_vals{$_} && ($pri_vals{$_} ne $copy[$_]))
1064 my $alias = $self->{attrs}{alias};
1071 foreach my $const (@const_rows) {
1072 scalar @const_keys or do {
1073 @const_keys = sort { length($a) <=> length($b) } keys %$const;
1075 foreach my $key (@const_keys) {
1078 my @parts = split(/\./, $key);
1080 my $data = $const->{$key};
1081 foreach my $p (@parts) {
1082 $target = $target->[1]->{$p} ||= [];
1084 if ($cur eq ".${key}" && (my @ckey = @{$collapse{$cur}||[]})) {
1085 # collapsing at this point and on final part
1086 my $pos = $collapse_pos{$cur};
1087 CK: foreach my $ck (@ckey) {
1088 if (!defined $pos->{$ck} || $pos->{$ck} ne $data->{$ck}) {
1089 $collapse_pos{$cur} = $data;
1090 delete @collapse_pos{ # clear all positioning for sub-entries
1091 grep { m/^\Q${cur}.\E/ } keys %collapse_pos
1098 if (exists $collapse{$cur}) {
1099 $target = $target->[-1];
1102 $target->[0] = $data;
1104 $info->[0] = $const->{$key};
1112 =head2 result_source
1116 =item Arguments: $result_source?
1118 =item Return Value: $result_source
1122 An accessor for the primary ResultSource object from which this ResultSet
1129 =item Arguments: $result_class?
1131 =item Return Value: $result_class
1135 An accessor for the class to use when creating row objects. Defaults to
1136 C<< result_source->result_class >> - which in most cases is the name of the
1137 L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class.
1139 Note that changing the result_class will also remove any components
1140 that were originally loaded in the source class via
1141 L<DBIx::Class::ResultSource/load_components>. Any overloaded methods
1142 in the original source class will not run.
1147 my ($self, $result_class) = @_;
1148 if ($result_class) {
1149 unless (ref $result_class) { # don't fire this for an object
1150 $self->ensure_class_loaded($result_class);
1152 $self->_result_class($result_class);
1153 # THIS LINE WOULD BE A BUG - this accessor specifically exists to
1154 # permit the user to set result class on one result set only; it only
1155 # chains if provided to search()
1156 #$self->{attrs}{result_class} = $result_class if ref $self;
1158 $self->_result_class;
1165 =item Arguments: $cond, \%attrs??
1167 =item Return Value: $count
1171 Performs an SQL C<COUNT> with the same query as the resultset was built
1172 with to find the number of elements. Passing arguments is equivalent to
1173 C<< $rs->search ($cond, \%attrs)->count >>
1179 return $self->search(@_)->count if @_ and defined $_[0];
1180 return scalar @{ $self->get_cache } if $self->get_cache;
1182 my $attrs = $self->_resolved_attrs_copy;
1184 # this is a little optimization - it is faster to do the limit
1185 # adjustments in software, instead of a subquery
1186 my $rows = delete $attrs->{rows};
1187 my $offset = delete $attrs->{offset};
1190 if ($self->_has_resolved_attr (qw/collapse group_by/)) {
1191 $crs = $self->_count_subq_rs ($attrs);
1194 $crs = $self->_count_rs ($attrs);
1196 my $count = $crs->next;
1198 $count -= $offset if $offset;
1199 $count = $rows if $rows and $rows < $count;
1200 $count = 0 if ($count < 0);
1209 =item Arguments: $cond, \%attrs??
1211 =item Return Value: $count_rs
1215 Same as L</count> but returns a L<DBIx::Class::ResultSetColumn> object.
1216 This can be very handy for subqueries:
1218 ->search( { amount => $some_rs->count_rs->as_query } )
1220 As with regular resultsets the SQL query will be executed only after
1221 the resultset is accessed via L</next> or L</all>. That would return
1222 the same single value obtainable via L</count>.
1228 return $self->search(@_)->count_rs if @_;
1230 # this may look like a lack of abstraction (count() does about the same)
1231 # but in fact an _rs *must* use a subquery for the limits, as the
1232 # software based limiting can not be ported if this $rs is to be used
1233 # in a subquery itself (i.e. ->as_query)
1234 if ($self->_has_resolved_attr (qw/collapse group_by offset rows/)) {
1235 return $self->_count_subq_rs;
1238 return $self->_count_rs;
1243 # returns a ResultSetColumn object tied to the count query
1246 my ($self, $attrs) = @_;
1248 my $rsrc = $self->result_source;
1249 $attrs ||= $self->_resolved_attrs;
1251 my $tmp_attrs = { %$attrs };
1252 # take off any limits, record_filter is cdbi, and no point of ordering nor locking a count
1253 delete @{$tmp_attrs}{qw/rows offset order_by record_filter for/};
1255 # overwrite the selector (supplied by the storage)
1256 $tmp_attrs->{select} = $rsrc->storage->_count_select ($rsrc, $attrs);
1257 $tmp_attrs->{as} = 'count';
1259 my $tmp_rs = $rsrc->resultset_class->new($rsrc, $tmp_attrs)->get_column ('count');
1265 # same as above but uses a subquery
1267 sub _count_subq_rs {
1268 my ($self, $attrs) = @_;
1270 my $rsrc = $self->result_source;
1271 $attrs ||= $self->_resolved_attrs;
1273 my $sub_attrs = { %$attrs };
1274 # extra selectors do not go in the subquery and there is no point of ordering it, nor locking it
1275 delete @{$sub_attrs}{qw/collapse select _prefetch_select as order_by for/};
1277 # if we multi-prefetch we group_by primary keys only as this is what we would
1278 # get out of the rs via ->next/->all. We *DO WANT* to clobber old group_by regardless
1279 if ( keys %{$attrs->{collapse}} ) {
1280 $sub_attrs->{group_by} = [ map { "$attrs->{alias}.$_" } ($rsrc->_pri_cols) ]
1283 # Calculate subquery selector
1284 if (my $g = $sub_attrs->{group_by}) {
1286 my $sql_maker = $rsrc->storage->sql_maker;
1288 # necessary as the group_by may refer to aliased functions
1290 for my $sel (@{$attrs->{select}}) {
1291 $sel_index->{$sel->{-as}} = $sel
1292 if (ref $sel eq 'HASH' and $sel->{-as});
1295 for my $g_part (@$g) {
1296 my $colpiece = $sel_index->{$g_part} || $g_part;
1298 # disqualify join-based group_by's. Arcane but possible query
1299 # also horrible horrible hack to alias a column (not a func.)
1300 # (probably need to introduce SQLA syntax)
1301 if ($colpiece =~ /\./ && $colpiece !~ /^$attrs->{alias}\./) {
1304 $colpiece = \ sprintf ('%s AS %s', map { $sql_maker->_quote ($_) } ($colpiece, $as) );
1306 push @{$sub_attrs->{select}}, $colpiece;
1310 my @pcols = map { "$attrs->{alias}.$_" } ($rsrc->primary_columns);
1311 $sub_attrs->{select} = @pcols ? \@pcols : [ 1 ];
1314 return $rsrc->resultset_class
1315 ->new ($rsrc, $sub_attrs)
1317 ->search ({}, { columns => { count => $rsrc->storage->_count_select ($rsrc, $attrs) } })
1318 ->get_column ('count');
1325 =head2 count_literal
1329 =item Arguments: $sql_fragment, @bind_values
1331 =item Return Value: $count
1335 Counts the results in a literal query. Equivalent to calling L</search_literal>
1336 with the passed arguments, then L</count>.
1340 sub count_literal { shift->search_literal(@_)->count; }
1346 =item Arguments: none
1348 =item Return Value: @objects
1352 Returns all elements in the resultset. Called implicitly if the resultset
1353 is returned in list context.
1360 $self->throw_exception("all() doesn't take any arguments, you probably wanted ->search(...)->all()");
1363 return @{ $self->get_cache } if $self->get_cache;
1367 if (keys %{$self->_resolved_attrs->{collapse}}) {
1368 # Using $self->cursor->all is really just an optimisation.
1369 # If we're collapsing has_many prefetches it probably makes
1370 # very little difference, and this is cleaner than hacking
1371 # _construct_object to survive the approach
1372 $self->cursor->reset;
1373 my @row = $self->cursor->next;
1375 push(@obj, $self->_construct_object(@row));
1376 @row = (exists $self->{stashed_row}
1377 ? @{delete $self->{stashed_row}}
1378 : $self->cursor->next);
1381 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
1384 $self->set_cache(\@obj) if $self->{attrs}{cache};
1393 =item Arguments: none
1395 =item Return Value: $self
1399 Resets the resultset's cursor, so you can iterate through the elements again.
1400 Implicitly resets the storage cursor, so a subsequent L</next> will trigger
1407 delete $self->{_attrs} if exists $self->{_attrs};
1408 $self->{all_cache_position} = 0;
1409 $self->cursor->reset;
1417 =item Arguments: none
1419 =item Return Value: $object | undef
1423 Resets the resultset and returns an object for the first result (or C<undef>
1424 if the resultset is empty).
1429 return $_[0]->reset->next;
1435 # Determines whether and what type of subquery is required for the $rs operation.
1436 # If grouping is necessary either supplies its own, or verifies the current one
1437 # After all is done delegates to the proper storage method.
1439 sub _rs_update_delete {
1440 my ($self, $op, $values) = @_;
1442 my $rsrc = $self->result_source;
1444 # if a condition exists we need to strip all table qualifiers
1445 # if this is not possible we'll force a subquery below
1446 my $cond = $rsrc->schema->storage->_strip_cond_qualifiers ($self->{cond});
1448 my $needs_group_by_subq = $self->_has_resolved_attr (qw/collapse group_by -join/);
1449 my $needs_subq = $needs_group_by_subq || (not defined $cond) || $self->_has_resolved_attr(qw/rows offset/);
1451 if ($needs_group_by_subq or $needs_subq) {
1453 # make a new $rs selecting only the PKs (that's all we really need)
1454 my $attrs = $self->_resolved_attrs_copy;
1457 delete $attrs->{$_} for qw/collapse _collapse_order_by select _prefetch_select as/;
1458 $attrs->{columns} = [ map { "$attrs->{alias}.$_" } ($self->result_source->_pri_cols) ];
1460 if ($needs_group_by_subq) {
1461 # make sure no group_by was supplied, or if there is one - make sure it matches
1462 # the columns compiled above perfectly. Anything else can not be sanely executed
1463 # on most databases so croak right then and there
1465 if (my $g = $attrs->{group_by}) {
1466 my @current_group_by = map
1467 { $_ =~ /\./ ? $_ : "$attrs->{alias}.$_" }
1472 join ("\x00", sort @current_group_by)
1474 join ("\x00", sort @{$attrs->{columns}} )
1476 $self->throw_exception (
1477 "You have just attempted a $op operation on a resultset which does group_by"
1478 . ' on columns other than the primary keys, while DBIC internally needs to retrieve'
1479 . ' the primary keys in a subselect. All sane RDBMS engines do not support this'
1480 . ' kind of queries. Please retry the operation with a modified group_by or'
1481 . ' without using one at all.'
1486 $attrs->{group_by} = $attrs->{columns};
1490 my $subrs = (ref $self)->new($rsrc, $attrs);
1491 return $self->result_source->storage->_subq_update_delete($subrs, $op, $values);
1494 return $rsrc->storage->$op(
1496 $op eq 'update' ? $values : (),
1506 =item Arguments: \%values
1508 =item Return Value: $storage_rv
1512 Sets the specified columns in the resultset to the supplied values in a
1513 single query. Note that this will not run any accessor/set_column/update
1514 triggers, nor will it update any row object instances derived from this
1515 resultset (this includes the contents of the L<resultset cache|/set_cache>
1516 if any). See L</update_all> if you need to execute any on-update
1517 triggers or cascades defined either by you or a
1518 L<result component|DBIx::Class::Manual::Component/WHAT_IS_A_COMPONENT>.
1520 The return value is a pass through of what the underlying
1521 storage backend returned, and may vary. See L<DBI/execute> for the most
1526 Note that L</update> does not process/deflate any of the values passed in.
1527 This is unlike the corresponding L<DBIx::Class::Row/update>. The user must
1528 ensure manually that any value passed to this method will stringify to
1529 something the RDBMS knows how to deal with. A notable example is the
1530 handling of L<DateTime> objects, for more info see:
1531 L<DBIx::Class::Manual::Cookbook/Formatting_DateTime_objects_in_queries>.
1536 my ($self, $values) = @_;
1537 $self->throw_exception('Values for update must be a hash')
1538 unless ref $values eq 'HASH';
1540 return $self->_rs_update_delete ('update', $values);
1547 =item Arguments: \%values
1549 =item Return Value: 1
1553 Fetches all objects and updates them one at a time via
1554 L<DBIx::Class::Row/update>. Note that C<update_all> will run DBIC defined
1555 triggers, while L</update> will not.
1560 my ($self, $values) = @_;
1561 $self->throw_exception('Values for update_all must be a hash')
1562 unless ref $values eq 'HASH';
1564 my $guard = $self->result_source->schema->txn_scope_guard;
1565 $_->update($values) for $self->all;
1574 =item Arguments: none
1576 =item Return Value: $storage_rv
1580 Deletes the rows matching this resultset in a single query. Note that this
1581 will not run any delete triggers, nor will it alter the
1582 L<in_storage|DBIx::Class::Row/in_storage> status of any row object instances
1583 derived from this resultset (this includes the contents of the
1584 L<resultset cache|/set_cache> if any). See L</delete_all> if you need to
1585 execute any on-delete triggers or cascades defined either by you or a
1586 L<result component|DBIx::Class::Manual::Component/WHAT_IS_A_COMPONENT>.
1588 The return value is a pass through of what the underlying storage backend
1589 returned, and may vary. See L<DBI/execute> for the most common case.
1595 $self->throw_exception('delete does not accept any arguments')
1598 return $self->_rs_update_delete ('delete');
1605 =item Arguments: none
1607 =item Return Value: 1
1611 Fetches all objects and deletes them one at a time via
1612 L<DBIx::Class::Row/delete>. Note that C<delete_all> will run DBIC defined
1613 triggers, while L</delete> will not.
1619 $self->throw_exception('delete_all does not accept any arguments')
1622 my $guard = $self->result_source->schema->txn_scope_guard;
1623 $_->delete for $self->all;
1632 =item Arguments: \@data;
1636 Accepts either an arrayref of hashrefs or alternatively an arrayref of arrayrefs.
1637 For the arrayref of hashrefs style each hashref should be a structure suitable
1638 forsubmitting to a $resultset->create(...) method.
1640 In void context, C<insert_bulk> in L<DBIx::Class::Storage::DBI> is used
1641 to insert the data, as this is a faster method.
1643 Otherwise, each set of data is inserted into the database using
1644 L<DBIx::Class::ResultSet/create>, and the resulting objects are
1645 accumulated into an array. The array itself, or an array reference
1646 is returned depending on scalar or list context.
1648 Example: Assuming an Artist Class that has many CDs Classes relating:
1650 my $Artist_rs = $schema->resultset("Artist");
1652 ## Void Context Example
1653 $Artist_rs->populate([
1654 { artistid => 4, name => 'Manufactured Crap', cds => [
1655 { title => 'My First CD', year => 2006 },
1656 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
1659 { artistid => 5, name => 'Angsty-Whiny Girl', cds => [
1660 { title => 'My parents sold me to a record company', year => 2005 },
1661 { title => 'Why Am I So Ugly?', year => 2006 },
1662 { title => 'I Got Surgery and am now Popular', year => 2007 }
1667 ## Array Context Example
1668 my ($ArtistOne, $ArtistTwo, $ArtistThree) = $Artist_rs->populate([
1669 { name => "Artist One"},
1670 { name => "Artist Two"},
1671 { name => "Artist Three", cds=> [
1672 { title => "First CD", year => 2007},
1673 { title => "Second CD", year => 2008},
1677 print $ArtistOne->name; ## response is 'Artist One'
1678 print $ArtistThree->cds->count ## reponse is '2'
1680 For the arrayref of arrayrefs style, the first element should be a list of the
1681 fieldsnames to which the remaining elements are rows being inserted. For
1684 $Arstist_rs->populate([
1685 [qw/artistid name/],
1686 [100, 'A Formally Unknown Singer'],
1687 [101, 'A singer that jumped the shark two albums ago'],
1688 [102, 'An actually cool singer'],
1691 Please note an important effect on your data when choosing between void and
1692 wantarray context. Since void context goes straight to C<insert_bulk> in
1693 L<DBIx::Class::Storage::DBI> this will skip any component that is overriding
1694 C<insert>. So if you are using something like L<DBIx-Class-UUIDColumns> to
1695 create primary keys for you, you will find that your PKs are empty. In this
1696 case you will have to use the wantarray context in order to create those
1704 # cruft placed in standalone method
1705 my $data = $self->_normalize_populate_args(@_);
1707 if(defined wantarray) {
1709 foreach my $item (@$data) {
1710 push(@created, $self->create($item));
1712 return wantarray ? @created : \@created;
1714 my $first = $data->[0];
1716 # if a column is a registered relationship, and is a non-blessed hash/array, consider
1717 # it relationship data
1718 my (@rels, @columns);
1719 for (keys %$first) {
1720 my $ref = ref $first->{$_};
1721 $self->result_source->has_relationship($_) && ($ref eq 'ARRAY' or $ref eq 'HASH')
1727 my @pks = $self->result_source->primary_columns;
1729 ## do the belongs_to relationships
1730 foreach my $index (0..$#$data) {
1732 # delegate to create() for any dataset without primary keys with specified relationships
1733 if (grep { !defined $data->[$index]->{$_} } @pks ) {
1735 if (grep { ref $data->[$index]{$r} eq $_ } qw/HASH ARRAY/) { # a related set must be a HASH or AoH
1736 my @ret = $self->populate($data);
1742 foreach my $rel (@rels) {
1743 next unless ref $data->[$index]->{$rel} eq "HASH";
1744 my $result = $self->related_resultset($rel)->create($data->[$index]->{$rel});
1745 my ($reverse) = keys %{$self->result_source->reverse_relationship_info($rel)};
1746 my $related = $result->result_source->_resolve_condition(
1747 $result->result_source->relationship_info($reverse)->{cond},
1752 delete $data->[$index]->{$rel};
1753 $data->[$index] = {%{$data->[$index]}, %$related};
1755 push @columns, keys %$related if $index == 0;
1759 ## inherit the data locked in the conditions of the resultset
1760 my ($rs_data) = $self->_merge_with_rscond({});
1761 delete @{$rs_data}{@columns};
1762 my @inherit_cols = keys %$rs_data;
1763 my @inherit_data = values %$rs_data;
1765 ## do bulk insert on current row
1766 $self->result_source->storage->insert_bulk(
1767 $self->result_source,
1768 [@columns, @inherit_cols],
1769 [ map { [ @$_{@columns}, @inherit_data ] } @$data ],
1772 ## do the has_many relationships
1773 foreach my $item (@$data) {
1775 foreach my $rel (@rels) {
1776 next unless $item->{$rel} && ref $item->{$rel} eq "ARRAY";
1778 my $parent = $self->find({map { $_ => $item->{$_} } @pks})
1779 || $self->throw_exception('Cannot find the relating object.');
1781 my $child = $parent->$rel;
1783 my $related = $child->result_source->_resolve_condition(
1784 $parent->result_source->relationship_info($rel)->{cond},
1789 my @rows_to_add = ref $item->{$rel} eq 'ARRAY' ? @{$item->{$rel}} : ($item->{$rel});
1790 my @populate = map { {%$_, %$related} } @rows_to_add;
1792 $child->populate( \@populate );
1799 # populate() argumnets went over several incarnations
1800 # What we ultimately support is AoH
1801 sub _normalize_populate_args {
1802 my ($self, $arg) = @_;
1804 if (ref $arg eq 'ARRAY') {
1805 if (ref $arg->[0] eq 'HASH') {
1808 elsif (ref $arg->[0] eq 'ARRAY') {
1810 my @colnames = @{$arg->[0]};
1811 foreach my $values (@{$arg}[1 .. $#$arg]) {
1812 push @ret, { map { $colnames[$_] => $values->[$_] } (0 .. $#colnames) };
1818 $self->throw_exception('Populate expects an arrayref of hashrefs or arrayref of arrayrefs');
1825 =item Arguments: none
1827 =item Return Value: $pager
1831 Return Value a L<Data::Page> object for the current resultset. Only makes
1832 sense for queries with a C<page> attribute.
1834 To get the full count of entries for a paged resultset, call
1835 C<total_entries> on the L<Data::Page> object.
1839 # make a wizard good for both a scalar and a hashref
1840 my $mk_lazy_count_wizard = sub {
1841 require Variable::Magic;
1843 my $stash = { total_rs => shift };
1844 my $slot = shift; # only used by the hashref magic
1846 my $magic = Variable::Magic::wizard (
1847 data => sub { $stash },
1853 # set value lazily, and dispell for good
1854 ${$_[0]} = $_[1]{total_rs}->count;
1855 Variable::Magic::dispell (${$_[0]}, $_[1]{magic_selfref});
1859 # an explicit set implies dispell as well
1860 # the unless() is to work around "fun and giggles" below
1861 Variable::Magic::dispell (${$_[0]}, $_[1]{magic_selfref})
1862 unless (caller(2))[3] eq 'DBIx::Class::ResultSet::pager';
1869 if ($_[2] eq $slot and !$_[1]{inactive}) {
1870 my $cnt = $_[1]{total_rs}->count;
1871 $_[0]->{$slot} = $cnt;
1873 # attempting to dispell in a fetch handle (works in store), seems
1874 # to invariable segfault on 5.10, 5.12, 5.13 :(
1875 # so use an inactivator instead
1876 #Variable::Magic::dispell (%{$_[0]}, $_[1]{magic_selfref});
1882 if (! $_[1]{inactive} and $_[2] eq $slot) {
1883 #Variable::Magic::dispell (%{$_[0]}, $_[1]{magic_selfref});
1885 unless (caller(2))[3] eq 'DBIx::Class::ResultSet::pager';
1892 $stash->{magic_selfref} = $magic;
1893 weaken ($stash->{magic_selfref}); # this fails on 5.8.1
1898 # the tie class for 5.8.1
1900 package # hide from pause
1901 DBIx::Class::__DBIC_LAZY_RS_COUNT__;
1902 use base qw/Tie::Hash/;
1904 sub FIRSTKEY { my $dummy = scalar keys %{$_[0]{data}}; each %{$_[0]{data}} }
1905 sub NEXTKEY { each %{$_[0]{data}} }
1906 sub EXISTS { exists $_[0]{data}{$_[1]} }
1907 sub DELETE { delete $_[0]{data}{$_[1]} }
1908 sub CLEAR { %{$_[0]{data}} = () }
1909 sub SCALAR { scalar %{$_[0]{data}} }
1912 $_[1]{data} = {%{$_[1]{selfref}}};
1913 %{$_[1]{selfref}} = ();
1914 Scalar::Util::weaken ($_[1]{selfref});
1915 return bless ($_[1], $_[0]);
1919 if ($_[1] eq $_[0]{slot}) {
1920 my $cnt = $_[0]{data}{$_[1]} = $_[0]{total_rs}->count;
1921 untie %{$_[0]{selfref}};
1922 %{$_[0]{selfref}} = %{$_[0]{data}};
1931 $_[0]{data}{$_[1]} = $_[2];
1932 if ($_[1] eq $_[0]{slot}) {
1933 untie %{$_[0]{selfref}};
1934 %{$_[0]{selfref}} = %{$_[0]{data}};
1943 return $self->{pager} if $self->{pager};
1945 if ($self->get_cache) {
1946 $self->throw_exception ('Pagers on cached resultsets are not supported');
1949 my $attrs = $self->{attrs};
1950 $self->throw_exception("Can't create pager for non-paged rs")
1951 unless $self->{attrs}{page};
1952 $attrs->{rows} ||= 10;
1954 # throw away the paging flags and re-run the count (possibly
1955 # with a subselect) to get the real total count
1956 my $count_attrs = { %$attrs };
1957 delete $count_attrs->{$_} for qw/rows offset page pager/;
1958 my $total_rs = (ref $self)->new($self->result_source, $count_attrs);
1961 ### the following may seem awkward and dirty, but it's a thought-experiment
1962 ### necessary for future development of DBIx::DS. Do *NOT* change this code
1963 ### before talking to ribasushi/mst
1965 my $pager = Data::Page->new(
1966 0, #start with an empty set
1968 $self->{attrs}{page},
1971 my $data_slot = 'total_entries';
1973 # Since we are interested in a cached value (once it's set - it's set), every
1974 # technique will detach from the magic-host once the time comes to fire the
1975 # ->count (or in the segfaulting case of >= 5.10 it will deactivate itself)
1977 if ($] < 5.008003) {
1978 # 5.8.1 throws 'Modification of a read-only value attempted' when one tries
1979 # to weakref the magic container :(
1981 tie (%$pager, 'DBIx::Class::__DBIC_LAZY_RS_COUNT__',
1982 { slot => $data_slot, total_rs => $total_rs, selfref => $pager }
1985 elsif ($] < 5.010) {
1986 # We can use magic on the hash value slot. It's interesting that the magic is
1987 # attached to the hash-slot, and does *not* stop working once I do the dummy
1988 # assignments after the cast()
1989 # tested on 5.8.3 and 5.8.9
1990 my $magic = $mk_lazy_count_wizard->($total_rs);
1991 Variable::Magic::cast ( $pager->{$data_slot}, $magic );
1993 # this is for fun and giggles
1994 $pager->{$data_slot} = -1;
1995 $pager->{$data_slot} = 0;
1997 # this does not work for scalars, but works with
1999 #my %vals = %$pager;
2004 # And the uvar magic
2005 # works on 5.10.1, 5.12.1 and 5.13.4 in its current form,
2006 # however see the wizard maker for more notes
2007 my $magic = $mk_lazy_count_wizard->($total_rs, $data_slot);
2008 Variable::Magic::cast ( %$pager, $magic );
2011 $pager->{$data_slot} = -1;
2012 $pager->{$data_slot} = 0;
2020 return $self->{pager} = $pager;
2027 =item Arguments: $page_number
2029 =item Return Value: $rs
2033 Returns a resultset for the $page_number page of the resultset on which page
2034 is called, where each page contains a number of rows equal to the 'rows'
2035 attribute set on the resultset (10 by default).
2040 my ($self, $page) = @_;
2041 return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
2048 =item Arguments: \%vals
2050 =item Return Value: $rowobject
2054 Creates a new row object in the resultset's result class and returns
2055 it. The row is not inserted into the database at this point, call
2056 L<DBIx::Class::Row/insert> to do that. Calling L<DBIx::Class::Row/in_storage>
2057 will tell you whether the row object has been inserted or not.
2059 Passes the hashref of input on to L<DBIx::Class::Row/new>.
2064 my ($self, $values) = @_;
2065 $self->throw_exception( "new_result needs a hash" )
2066 unless (ref $values eq 'HASH');
2068 my ($merged_cond, $cols_from_relations) = $self->_merge_with_rscond($values);
2072 @$cols_from_relations
2073 ? (-cols_from_relations => $cols_from_relations)
2075 -source_handle => $self->_source_handle,
2076 -result_source => $self->result_source, # DO NOT REMOVE THIS, REQUIRED
2079 return $self->result_class->new(\%new);
2082 # _merge_with_rscond
2084 # Takes a simple hash of K/V data and returns its copy merged with the
2085 # condition already present on the resultset. Additionally returns an
2086 # arrayref of value/condition names, which were inferred from related
2087 # objects (this is needed for in-memory related objects)
2088 sub _merge_with_rscond {
2089 my ($self, $data) = @_;
2091 my (%new_data, @cols_from_relations);
2093 my $alias = $self->{attrs}{alias};
2095 if (! defined $self->{cond}) {
2096 # just massage $data below
2098 elsif ($self->{cond} eq $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION) {
2099 %new_data = %{ $self->{attrs}{related_objects} || {} }; # nothing might have been inserted yet
2100 @cols_from_relations = keys %new_data;
2102 elsif (ref $self->{cond} ne 'HASH') {
2103 $self->throw_exception(
2104 "Can't abstract implicit construct, resultset condition not a hash"
2108 # precendence must be given to passed values over values inherited from
2109 # the cond, so the order here is important.
2110 my $collapsed_cond = $self->_collapse_cond($self->{cond});
2111 my %implied = %{$self->_remove_alias($collapsed_cond, $alias)};
2113 while ( my($col, $value) = each %implied ) {
2114 my $vref = ref $value;
2115 if ($vref eq 'HASH' && keys(%$value) && (keys %$value)[0] eq '=') {
2116 $new_data{$col} = $value->{'='};
2118 elsif( !$vref or $vref eq 'SCALAR' or blessed($value) ) {
2119 $new_data{$col} = $value;
2126 %{ $self->_remove_alias($data, $alias) },
2129 return (\%new_data, \@cols_from_relations);
2132 # _has_resolved_attr
2134 # determines if the resultset defines at least one
2135 # of the attributes supplied
2137 # used to determine if a subquery is neccessary
2139 # supports some virtual attributes:
2141 # This will scan for any joins being present on the resultset.
2142 # It is not a mere key-search but a deep inspection of {from}
2145 sub _has_resolved_attr {
2146 my ($self, @attr_names) = @_;
2148 my $attrs = $self->_resolved_attrs;
2152 for my $n (@attr_names) {
2153 if (grep { $n eq $_ } (qw/-join/) ) {
2154 $extra_checks{$n}++;
2158 my $attr = $attrs->{$n};
2160 next if not defined $attr;
2162 if (ref $attr eq 'HASH') {
2163 return 1 if keys %$attr;
2165 elsif (ref $attr eq 'ARRAY') {
2173 # a resolved join is expressed as a multi-level from
2175 $extra_checks{-join}
2177 ref $attrs->{from} eq 'ARRAY'
2179 @{$attrs->{from}} > 1
2187 # Recursively collapse the condition.
2189 sub _collapse_cond {
2190 my ($self, $cond, $collapsed) = @_;
2194 if (ref $cond eq 'ARRAY') {
2195 foreach my $subcond (@$cond) {
2196 next unless ref $subcond; # -or
2197 $collapsed = $self->_collapse_cond($subcond, $collapsed);
2200 elsif (ref $cond eq 'HASH') {
2201 if (keys %$cond and (keys %$cond)[0] eq '-and') {
2202 foreach my $subcond (@{$cond->{-and}}) {
2203 $collapsed = $self->_collapse_cond($subcond, $collapsed);
2207 foreach my $col (keys %$cond) {
2208 my $value = $cond->{$col};
2209 $collapsed->{$col} = $value;
2219 # Remove the specified alias from the specified query hash. A copy is made so
2220 # the original query is not modified.
2223 my ($self, $query, $alias) = @_;
2225 my %orig = %{ $query || {} };
2228 foreach my $key (keys %orig) {
2230 $unaliased{$key} = $orig{$key};
2233 $unaliased{$1} = $orig{$key}
2234 if $key =~ m/^(?:\Q$alias\E\.)?([^.]+)$/;
2244 =item Arguments: none
2246 =item Return Value: \[ $sql, @bind ]
2250 Returns the SQL query and bind vars associated with the invocant.
2252 This is generally used as the RHS for a subquery.
2259 my $attrs = $self->_resolved_attrs_copy;
2264 # my ($sql, \@bind, \%dbi_bind_attrs) = _select_args_to_query (...)
2265 # $sql also has no wrapping parenthesis in list ctx
2267 my $sqlbind = $self->result_source->storage
2268 ->_select_args_to_query ($attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs);
2277 =item Arguments: \%vals, \%attrs?
2279 =item Return Value: $rowobject
2283 my $artist = $schema->resultset('Artist')->find_or_new(
2284 { artist => 'fred' }, { key => 'artists' });
2286 $cd->cd_to_producer->find_or_new({ producer => $producer },
2287 { key => 'primary });
2289 Find an existing record from this resultset using L</find>. if none exists,
2290 instantiate a new result object and return it. The object will not be saved
2291 into your storage until you call L<DBIx::Class::Row/insert> on it.
2293 You most likely want this method when looking for existing rows using a unique
2294 constraint that is not the primary key, or looking for related rows.
2296 If you want objects to be saved immediately, use L</find_or_create> instead.
2298 B<Note>: Make sure to read the documentation of L</find> and understand the
2299 significance of the C<key> attribute, as its lack may skew your search, and
2300 subsequently result in spurious new objects.
2302 B<Note>: Take care when using C<find_or_new> with a table having
2303 columns with default values that you intend to be automatically
2304 supplied by the database (e.g. an auto_increment primary key column).
2305 In normal usage, the value of such columns should NOT be included at
2306 all in the call to C<find_or_new>, even when set to C<undef>.
2312 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2313 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
2314 if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2317 return $self->new_result($hash);
2324 =item Arguments: \%vals
2326 =item Return Value: a L<DBIx::Class::Row> $object
2330 Attempt to create a single new row or a row with multiple related rows
2331 in the table represented by the resultset (and related tables). This
2332 will not check for duplicate rows before inserting, use
2333 L</find_or_create> to do that.
2335 To create one row for this resultset, pass a hashref of key/value
2336 pairs representing the columns of the table and the values you wish to
2337 store. If the appropriate relationships are set up, foreign key fields
2338 can also be passed an object representing the foreign row, and the
2339 value will be set to its primary key.
2341 To create related objects, pass a hashref of related-object column values
2342 B<keyed on the relationship name>. If the relationship is of type C<multi>
2343 (L<DBIx::Class::Relationship/has_many>) - pass an arrayref of hashrefs.
2344 The process will correctly identify columns holding foreign keys, and will
2345 transparently populate them from the keys of the corresponding relation.
2346 This can be applied recursively, and will work correctly for a structure
2347 with an arbitrary depth and width, as long as the relationships actually
2348 exists and the correct column data has been supplied.
2351 Instead of hashrefs of plain related data (key/value pairs), you may
2352 also pass new or inserted objects. New objects (not inserted yet, see
2353 L</new>), will be inserted into their appropriate tables.
2355 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
2357 Example of creating a new row.
2359 $person_rs->create({
2360 name=>"Some Person",
2361 email=>"somebody@someplace.com"
2364 Example of creating a new row and also creating rows in a related C<has_many>
2365 or C<has_one> resultset. Note Arrayref.
2368 { artistid => 4, name => 'Manufactured Crap', cds => [
2369 { title => 'My First CD', year => 2006 },
2370 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
2375 Example of creating a new row and also creating a row in a related
2376 C<belongs_to> resultset. Note Hashref.
2379 title=>"Music for Silly Walks",
2382 name=>"Silly Musician",
2390 When subclassing ResultSet never attempt to override this method. Since
2391 it is a simple shortcut for C<< $self->new_result($attrs)->insert >>, a
2392 lot of the internals simply never call it, so your override will be
2393 bypassed more often than not. Override either L<new|DBIx::Class::Row/new>
2394 or L<insert|DBIx::Class::Row/insert> depending on how early in the
2395 L</create> process you need to intervene.
2402 my ($self, $attrs) = @_;
2403 $self->throw_exception( "create needs a hashref" )
2404 unless ref $attrs eq 'HASH';
2405 return $self->new_result($attrs)->insert;
2408 =head2 find_or_create
2412 =item Arguments: \%vals, \%attrs?
2414 =item Return Value: $rowobject
2418 $cd->cd_to_producer->find_or_create({ producer => $producer },
2419 { key => 'primary' });
2421 Tries to find a record based on its primary key or unique constraints; if none
2422 is found, creates one and returns that instead.
2424 my $cd = $schema->resultset('CD')->find_or_create({
2426 artist => 'Massive Attack',
2427 title => 'Mezzanine',
2431 Also takes an optional C<key> attribute, to search by a specific key or unique
2432 constraint. For example:
2434 my $cd = $schema->resultset('CD')->find_or_create(
2436 artist => 'Massive Attack',
2437 title => 'Mezzanine',
2439 { key => 'cd_artist_title' }
2442 B<Note>: Make sure to read the documentation of L</find> and understand the
2443 significance of the C<key> attribute, as its lack may skew your search, and
2444 subsequently result in spurious row creation.
2446 B<Note>: Because find_or_create() reads from the database and then
2447 possibly inserts based on the result, this method is subject to a race
2448 condition. Another process could create a record in the table after
2449 the find has completed and before the create has started. To avoid
2450 this problem, use find_or_create() inside a transaction.
2452 B<Note>: Take care when using C<find_or_create> with a table having
2453 columns with default values that you intend to be automatically
2454 supplied by the database (e.g. an auto_increment primary key column).
2455 In normal usage, the value of such columns should NOT be included at
2456 all in the call to C<find_or_create>, even when set to C<undef>.
2458 See also L</find> and L</update_or_create>. For information on how to declare
2459 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2463 sub find_or_create {
2465 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2466 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
2467 if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2470 return $self->create($hash);
2473 =head2 update_or_create
2477 =item Arguments: \%col_values, { key => $unique_constraint }?
2479 =item Return Value: $row_object
2483 $resultset->update_or_create({ col => $val, ... });
2485 Like L</find_or_create>, but if a row is found it is immediately updated via
2486 C<< $found_row->update (\%col_values) >>.
2489 Takes an optional C<key> attribute to search on a specific unique constraint.
2492 # In your application
2493 my $cd = $schema->resultset('CD')->update_or_create(
2495 artist => 'Massive Attack',
2496 title => 'Mezzanine',
2499 { key => 'cd_artist_title' }
2502 $cd->cd_to_producer->update_or_create({
2503 producer => $producer,
2509 B<Note>: Make sure to read the documentation of L</find> and understand the
2510 significance of the C<key> attribute, as its lack may skew your search, and
2511 subsequently result in spurious row creation.
2513 B<Note>: Take care when using C<update_or_create> with a table having
2514 columns with default values that you intend to be automatically
2515 supplied by the database (e.g. an auto_increment primary key column).
2516 In normal usage, the value of such columns should NOT be included at
2517 all in the call to C<update_or_create>, even when set to C<undef>.
2519 See also L</find> and L</find_or_create>. For information on how to declare
2520 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2524 sub update_or_create {
2526 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2527 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
2529 my $row = $self->find($cond, $attrs);
2531 $row->update($cond);
2535 return $self->create($cond);
2538 =head2 update_or_new
2542 =item Arguments: \%col_values, { key => $unique_constraint }?
2544 =item Return Value: $rowobject
2548 $resultset->update_or_new({ col => $val, ... });
2550 Like L</find_or_new> but if a row is found it is immediately updated via
2551 C<< $found_row->update (\%col_values) >>.
2555 # In your application
2556 my $cd = $schema->resultset('CD')->update_or_new(
2558 artist => 'Massive Attack',
2559 title => 'Mezzanine',
2562 { key => 'cd_artist_title' }
2565 if ($cd->in_storage) {
2566 # the cd was updated
2569 # the cd is not yet in the database, let's insert it
2573 B<Note>: Make sure to read the documentation of L</find> and understand the
2574 significance of the C<key> attribute, as its lack may skew your search, and
2575 subsequently result in spurious new objects.
2577 B<Note>: Take care when using C<update_or_new> with a table having
2578 columns with default values that you intend to be automatically
2579 supplied by the database (e.g. an auto_increment primary key column).
2580 In normal usage, the value of such columns should NOT be included at
2581 all in the call to C<update_or_new>, even when set to C<undef>.
2583 See also L</find>, L</find_or_create> and L</find_or_new>.
2589 my $attrs = ( @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {} );
2590 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
2592 my $row = $self->find( $cond, $attrs );
2593 if ( defined $row ) {
2594 $row->update($cond);
2598 return $self->new_result($cond);
2605 =item Arguments: none
2607 =item Return Value: \@cache_objects | undef
2611 Gets the contents of the cache for the resultset, if the cache is set.
2613 The cache is populated either by using the L</prefetch> attribute to
2614 L</search> or by calling L</set_cache>.
2626 =item Arguments: \@cache_objects
2628 =item Return Value: \@cache_objects
2632 Sets the contents of the cache for the resultset. Expects an arrayref
2633 of objects of the same class as those produced by the resultset. Note that
2634 if the cache is set the resultset will return the cached objects rather
2635 than re-querying the database even if the cache attr is not set.
2637 The contents of the cache can also be populated by using the
2638 L</prefetch> attribute to L</search>.
2643 my ( $self, $data ) = @_;
2644 $self->throw_exception("set_cache requires an arrayref")
2645 if defined($data) && (ref $data ne 'ARRAY');
2646 $self->{all_cache} = $data;
2653 =item Arguments: none
2655 =item Return Value: undef
2659 Clears the cache for the resultset.
2664 shift->set_cache(undef);
2671 =item Arguments: none
2673 =item Return Value: true, if the resultset has been paginated
2681 return !!$self->{attrs}{page};
2688 =item Arguments: none
2690 =item Return Value: true, if the resultset has been ordered with C<order_by>.
2698 return scalar $self->result_source->storage->_extract_order_columns($self->{attrs}{order_by});
2701 =head2 related_resultset
2705 =item Arguments: $relationship_name
2707 =item Return Value: $resultset
2711 Returns a related resultset for the supplied relationship name.
2713 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
2717 sub related_resultset {
2718 my ($self, $rel) = @_;
2720 $self->{related_resultsets} ||= {};
2721 return $self->{related_resultsets}{$rel} ||= do {
2722 my $rsrc = $self->result_source;
2723 my $rel_info = $rsrc->relationship_info($rel);
2725 $self->throw_exception(
2726 "search_related: result source '" . $rsrc->source_name .
2727 "' has no such relationship $rel")
2730 my $attrs = $self->_chain_relationship($rel);
2732 my $join_count = $attrs->{seen_join}{$rel};
2734 my $alias = $self->result_source->storage
2735 ->relname_to_table_alias($rel, $join_count);
2737 # since this is search_related, and we already slid the select window inwards
2738 # (the select/as attrs were deleted in the beginning), we need to flip all
2739 # left joins to inner, so we get the expected results
2740 # read the comment on top of the actual function to see what this does
2741 $attrs->{from} = $rsrc->schema->storage->_inner_join_to_node ($attrs->{from}, $alias);
2744 #XXX - temp fix for result_class bug. There likely is a more elegant fix -groditi
2745 delete @{$attrs}{qw(result_class alias)};
2749 if (my $cache = $self->get_cache) {
2750 if ($cache->[0] && $cache->[0]->related_resultset($rel)->get_cache) {
2751 $new_cache = [ map { @{$_->related_resultset($rel)->get_cache} }
2756 my $rel_source = $rsrc->related_source($rel);
2760 # The reason we do this now instead of passing the alias to the
2761 # search_rs below is that if you wrap/overload resultset on the
2762 # source you need to know what alias it's -going- to have for things
2763 # to work sanely (e.g. RestrictWithObject wants to be able to add
2764 # extra query restrictions, and these may need to be $alias.)
2766 my $rel_attrs = $rel_source->resultset_attributes;
2767 local $rel_attrs->{alias} = $alias;
2769 $rel_source->resultset
2773 where => $attrs->{where},
2776 $new->set_cache($new_cache) if $new_cache;
2781 =head2 current_source_alias
2785 =item Arguments: none
2787 =item Return Value: $source_alias
2791 Returns the current table alias for the result source this resultset is built
2792 on, that will be used in the SQL query. Usually it is C<me>.
2794 Currently the source alias that refers to the result set returned by a
2795 L</search>/L</find> family method depends on how you got to the resultset: it's
2796 C<me> by default, but eg. L</search_related> aliases it to the related result
2797 source name (and keeps C<me> referring to the original result set). The long
2798 term goal is to make L<DBIx::Class> always alias the current resultset as C<me>
2799 (and make this method unnecessary).
2801 Thus it's currently necessary to use this method in predefined queries (see
2802 L<DBIx::Class::Manual::Cookbook/Predefined searches>) when referring to the
2803 source alias of the current result set:
2805 # in a result set class
2807 my ($self, $user) = @_;
2809 my $me = $self->current_source_alias;
2811 return $self->search(
2812 "$me.modified" => $user->id,
2818 sub current_source_alias {
2821 return ($self->{attrs} || {})->{alias} || 'me';
2824 =head2 as_subselect_rs
2828 =item Arguments: none
2830 =item Return Value: $resultset
2834 Act as a barrier to SQL symbols. The resultset provided will be made into a
2835 "virtual view" by including it as a subquery within the from clause. From this
2836 point on, any joined tables are inaccessible to ->search on the resultset (as if
2837 it were simply where-filtered without joins). For example:
2839 my $rs = $schema->resultset('Bar')->search({'x.name' => 'abc'},{ join => 'x' });
2841 # 'x' now pollutes the query namespace
2843 # So the following works as expected
2844 my $ok_rs = $rs->search({'x.other' => 1});
2846 # But this doesn't: instead of finding a 'Bar' related to two x rows (abc and
2847 # def) we look for one row with contradictory terms and join in another table
2848 # (aliased 'x_2') which we never use
2849 my $broken_rs = $rs->search({'x.name' => 'def'});
2851 my $rs2 = $rs->as_subselect_rs;
2853 # doesn't work - 'x' is no longer accessible in $rs2, having been sealed away
2854 my $not_joined_rs = $rs2->search({'x.other' => 1});
2856 # works as expected: finds a 'table' row related to two x rows (abc and def)
2857 my $correctly_joined_rs = $rs2->search({'x.name' => 'def'});
2859 Another example of when one might use this would be to select a subset of
2860 columns in a group by clause:
2862 my $rs = $schema->resultset('Bar')->search(undef, {
2863 group_by => [qw{ id foo_id baz_id }],
2864 })->as_subselect_rs->search(undef, {
2865 columns => [qw{ id foo_id }]
2868 In the above example normally columns would have to be equal to the group by,
2869 but because we isolated the group by into a subselect the above works.
2873 sub as_subselect_rs {
2876 my $attrs = $self->_resolved_attrs;
2878 my $fresh_rs = (ref $self)->new (
2879 $self->result_source
2882 # these pieces will be locked in the subquery
2883 delete $fresh_rs->{cond};
2884 delete @{$fresh_rs->{attrs}}{qw/where bind/};
2886 return $fresh_rs->search( {}, {
2888 $attrs->{alias} => $self->as_query,
2889 -alias => $attrs->{alias},
2890 -source_handle => $self->result_source->handle,
2892 alias => $attrs->{alias},
2896 # This code is called by search_related, and makes sure there
2897 # is clear separation between the joins before, during, and
2898 # after the relationship. This information is needed later
2899 # in order to properly resolve prefetch aliases (any alias
2900 # with a relation_chain_depth less than the depth of the
2901 # current prefetch is not considered)
2903 # The increments happen twice per join. An even number means a
2904 # relationship specified via a search_related, whereas an odd
2905 # number indicates a join/prefetch added via attributes
2907 # Also this code will wrap the current resultset (the one we
2908 # chain to) in a subselect IFF it contains limiting attributes
2909 sub _chain_relationship {
2910 my ($self, $rel) = @_;
2911 my $source = $self->result_source;
2912 my $attrs = { %{$self->{attrs}||{}} };
2914 # we need to take the prefetch the attrs into account before we
2915 # ->_resolve_join as otherwise they get lost - captainL
2916 my $join = $self->_merge_attr( $attrs->{join}, $attrs->{prefetch} );
2918 delete @{$attrs}{qw/join prefetch collapse group_by distinct select as columns +select +as +columns/};
2920 my $seen = { %{ (delete $attrs->{seen_join}) || {} } };
2923 my @force_subq_attrs = qw/offset rows group_by having/;
2926 ($attrs->{from} && ref $attrs->{from} ne 'ARRAY')
2928 $self->_has_resolved_attr (@force_subq_attrs)
2930 # Nuke the prefetch (if any) before the new $rs attrs
2931 # are resolved (prefetch is useless - we are wrapping
2932 # a subquery anyway).
2933 my $rs_copy = $self->search;
2934 $rs_copy->{attrs}{join} = $self->_merge_attr (
2935 $rs_copy->{attrs}{join},
2936 delete $rs_copy->{attrs}{prefetch},
2940 -source_handle => $source->handle,
2941 -alias => $attrs->{alias},
2942 $attrs->{alias} => $rs_copy->as_query,
2944 delete @{$attrs}{@force_subq_attrs, qw/where bind/};
2945 $seen->{-relation_chain_depth} = 0;
2947 elsif ($attrs->{from}) { #shallow copy suffices
2948 $from = [ @{$attrs->{from}} ];
2952 -source_handle => $source->handle,
2953 -alias => $attrs->{alias},
2954 $attrs->{alias} => $source->from,
2958 my $jpath = ($seen->{-relation_chain_depth})
2959 ? $from->[-1][0]{-join_path}
2962 my @requested_joins = $source->_resolve_join(
2969 push @$from, @requested_joins;
2971 $seen->{-relation_chain_depth}++;
2973 # if $self already had a join/prefetch specified on it, the requested
2974 # $rel might very well be already included. What we do in this case
2975 # is effectively a no-op (except that we bump up the chain_depth on
2976 # the join in question so we could tell it *is* the search_related)
2979 # we consider the last one thus reverse
2980 for my $j (reverse @requested_joins) {
2981 my ($last_j) = keys %{$j->[0]{-join_path}[-1]};
2982 if ($rel eq $last_j) {
2983 $j->[0]{-relation_chain_depth}++;
2989 unless ($already_joined) {
2990 push @$from, $source->_resolve_join(
2998 $seen->{-relation_chain_depth}++;
3000 return {%$attrs, from => $from, seen_join => $seen};
3003 # too many times we have to do $attrs = { %{$self->_resolved_attrs} }
3004 sub _resolved_attrs_copy {
3006 return { %{$self->_resolved_attrs (@_)} };
3009 sub _resolved_attrs {
3011 return $self->{_attrs} if $self->{_attrs};
3013 my $attrs = { %{ $self->{attrs} || {} } };
3014 my $source = $self->result_source;
3015 my $alias = $attrs->{alias};
3017 $attrs->{columns} ||= delete $attrs->{cols} if exists $attrs->{cols};
3020 # build columns (as long as select isn't set) into a set of as/select hashes
3021 unless ( $attrs->{select} ) {
3024 if ( ref $attrs->{columns} eq 'ARRAY' ) {
3025 @cols = @{ delete $attrs->{columns}}
3026 } elsif ( defined $attrs->{columns} ) {
3027 @cols = delete $attrs->{columns}
3029 @cols = $source->columns
3033 if ( ref $_ eq 'HASH' ) {
3036 my $key = /^\Q${alias}.\E(.+)$/
3042 push @colbits, { $key => $value };
3047 # add the additional columns on
3048 foreach (qw{include_columns +columns}) {
3049 if ( $attrs->{$_} ) {
3050 my @list = ( ref($attrs->{$_}) eq 'ARRAY' )
3051 ? @{ delete $attrs->{$_} }
3052 : delete $attrs->{$_};
3054 if ( ref($_) eq 'HASH' ) {
3057 my $key = ( split /\./, $_ )[-1];
3058 my $value = ( /\./ ? $_ : "$alias.$_" );
3059 push @colbits, { $key => $value };
3065 # start with initial select items
3066 if ( $attrs->{select} ) {
3068 ( ref $attrs->{select} eq 'ARRAY' )
3069 ? [ @{ $attrs->{select} } ]
3070 : [ $attrs->{select} ];
3072 if ( $attrs->{as} ) {
3075 ref $attrs->{as} eq 'ARRAY'
3076 ? [ @{ $attrs->{as} } ]
3080 $attrs->{as} = [ map {
3081 m/^\Q${alias}.\E(.+)$/
3084 } @{ $attrs->{select} }
3090 # otherwise we intialise select & as to empty
3091 $attrs->{select} = [];
3095 # now add colbits to select/as
3096 push @{ $attrs->{select} }, map values %{$_}, @colbits;
3097 push @{ $attrs->{as} }, map keys %{$_}, @colbits;
3099 if ( my $adds = delete $attrs->{'+select'} ) {
3100 $adds = [$adds] unless ref $adds eq 'ARRAY';
3101 push @{ $attrs->{select} },
3102 map { /\./ || ref $_ ? $_ : "$alias.$_" } @$adds;
3104 if ( my $adds = delete $attrs->{'+as'} ) {
3105 $adds = [$adds] unless ref $adds eq 'ARRAY';
3106 push @{ $attrs->{as} }, @$adds;
3109 $attrs->{from} ||= [{
3110 -source_handle => $source->handle,
3111 -alias => $self->{attrs}{alias},
3112 $self->{attrs}{alias} => $source->from,
3115 if ( $attrs->{join} || $attrs->{prefetch} ) {
3117 $self->throw_exception ('join/prefetch can not be used with a custom {from}')
3118 if ref $attrs->{from} ne 'ARRAY';
3120 my $join = delete $attrs->{join} || {};
3122 if ( defined $attrs->{prefetch} ) {
3123 $join = $self->_merge_attr( $join, $attrs->{prefetch} );
3126 $attrs->{from} = # have to copy here to avoid corrupting the original
3128 @{ $attrs->{from} },
3129 $source->_resolve_join(
3132 { %{ $attrs->{seen_join} || {} } },
3133 ( $attrs->{seen_join} && keys %{$attrs->{seen_join}})
3134 ? $attrs->{from}[-1][0]{-join_path}
3141 if ( defined $attrs->{order_by} ) {
3142 $attrs->{order_by} = (
3143 ref( $attrs->{order_by} ) eq 'ARRAY'
3144 ? [ @{ $attrs->{order_by} } ]
3145 : [ $attrs->{order_by} || () ]
3149 if ($attrs->{group_by} and ref $attrs->{group_by} ne 'ARRAY') {
3150 $attrs->{group_by} = [ $attrs->{group_by} ];
3153 # generate the distinct induced group_by early, as prefetch will be carried via a
3154 # subquery (since a group_by is present)
3155 if (delete $attrs->{distinct}) {
3156 if ($attrs->{group_by}) {
3157 carp ("Useless use of distinct on a grouped resultset ('distinct' is ignored when a 'group_by' is present)");
3160 $attrs->{group_by} = $source->storage->_group_over_selection (
3161 @{$attrs}{qw/from select order_by/}
3166 $attrs->{collapse} ||= {};
3167 if ( my $prefetch = delete $attrs->{prefetch} ) {
3168 $prefetch = $self->_merge_attr( {}, $prefetch );
3170 my $prefetch_ordering = [];
3172 # this is a separate structure (we don't look in {from} directly)
3173 # as the resolver needs to shift things off the lists to work
3174 # properly (identical-prefetches on different branches)
3176 if (ref $attrs->{from} eq 'ARRAY') {
3178 my $start_depth = $attrs->{seen_join}{-relation_chain_depth} || 0;
3180 for my $j ( @{$attrs->{from}}[1 .. $#{$attrs->{from}} ] ) {
3181 next unless $j->[0]{-alias};
3182 next unless $j->[0]{-join_path};
3183 next if ($j->[0]{-relation_chain_depth} || 0) < $start_depth;
3185 my @jpath = map { keys %$_ } @{$j->[0]{-join_path}};
3188 $p = $p->{$_} ||= {} for @jpath[ ($start_depth/2) .. $#jpath]; #only even depths are actual jpath boundaries
3189 push @{$p->{-join_aliases} }, $j->[0]{-alias};
3194 $source->_resolve_prefetch( $prefetch, $alias, $join_map, $prefetch_ordering, $attrs->{collapse} );
3196 # we need to somehow mark which columns came from prefetch
3197 $attrs->{_prefetch_select} = [ map { $_->[0] } @prefetch ];
3199 push @{ $attrs->{select} }, @{$attrs->{_prefetch_select}};
3200 push @{ $attrs->{as} }, (map { $_->[1] } @prefetch);
3202 push( @{$attrs->{order_by}}, @$prefetch_ordering );
3203 $attrs->{_collapse_order_by} = \@$prefetch_ordering;
3206 # if both page and offset are specified, produce a combined offset
3207 # even though it doesn't make much sense, this is what pre 081xx has
3209 if (my $page = delete $attrs->{page}) {
3211 ($attrs->{rows} * ($page - 1))
3213 ($attrs->{offset} || 0)
3217 return $self->{_attrs} = $attrs;
3221 my ($self, $attr) = @_;
3223 if (ref $attr eq 'HASH') {
3224 return $self->_rollout_hash($attr);
3225 } elsif (ref $attr eq 'ARRAY') {
3226 return $self->_rollout_array($attr);
3232 sub _rollout_array {
3233 my ($self, $attr) = @_;
3236 foreach my $element (@{$attr}) {
3237 if (ref $element eq 'HASH') {
3238 push( @rolled_array, @{ $self->_rollout_hash( $element ) } );
3239 } elsif (ref $element eq 'ARRAY') {
3240 # XXX - should probably recurse here
3241 push( @rolled_array, @{$self->_rollout_array($element)} );
3243 push( @rolled_array, $element );
3246 return \@rolled_array;
3250 my ($self, $attr) = @_;
3253 foreach my $key (keys %{$attr}) {
3254 push( @rolled_array, { $key => $attr->{$key} } );
3256 return \@rolled_array;
3259 sub _calculate_score {
3260 my ($self, $a, $b) = @_;
3262 if (defined $a xor defined $b) {
3265 elsif (not defined $a) {
3269 if (ref $b eq 'HASH') {
3270 my ($b_key) = keys %{$b};
3271 if (ref $a eq 'HASH') {
3272 my ($a_key) = keys %{$a};
3273 if ($a_key eq $b_key) {
3274 return (1 + $self->_calculate_score( $a->{$a_key}, $b->{$b_key} ));
3279 return ($a eq $b_key) ? 1 : 0;
3282 if (ref $a eq 'HASH') {
3283 my ($a_key) = keys %{$a};
3284 return ($b eq $a_key) ? 1 : 0;
3286 return ($b eq $a) ? 1 : 0;
3292 my ($self, $orig, $import) = @_;
3294 return $import unless defined($orig);
3295 return $orig unless defined($import);
3297 $orig = $self->_rollout_attr($orig);
3298 $import = $self->_rollout_attr($import);
3301 foreach my $import_element ( @{$import} ) {
3302 # find best candidate from $orig to merge $b_element into
3303 my $best_candidate = { position => undef, score => 0 }; my $position = 0;
3304 foreach my $orig_element ( @{$orig} ) {
3305 my $score = $self->_calculate_score( $orig_element, $import_element );
3306 if ($score > $best_candidate->{score}) {
3307 $best_candidate->{position} = $position;
3308 $best_candidate->{score} = $score;
3312 my ($import_key) = ( ref $import_element eq 'HASH' ) ? keys %{$import_element} : ($import_element);
3314 if ($best_candidate->{score} == 0 || exists $seen_keys->{$import_key}) {
3315 push( @{$orig}, $import_element );
3317 my $orig_best = $orig->[$best_candidate->{position}];
3318 # merge orig_best and b_element together and replace original with merged
3319 if (ref $orig_best ne 'HASH') {
3320 $orig->[$best_candidate->{position}] = $import_element;
3321 } elsif (ref $import_element eq 'HASH') {
3322 my ($key) = keys %{$orig_best};
3323 $orig->[$best_candidate->{position}] = { $key => $self->_merge_attr($orig_best->{$key}, $import_element->{$key}) };
3326 $seen_keys->{$import_key} = 1; # don't merge the same key twice
3337 $self->_source_handle($_[0]->handle);
3339 $self->_source_handle->resolve;
3344 sub STORABLE_freeze {
3345 my ($self, $cloning) = @_;
3346 my $to_serialize = { %$self };
3348 # A cursor in progress can't be serialized (and would make little sense anyway)
3349 delete $to_serialize->{cursor};
3351 return nfreeze($to_serialize);
3354 # need this hook for symmetry
3356 my ($self, $cloning, $serialized) = @_;
3358 %$self = %{ thaw($serialized) };
3364 =head2 throw_exception
3366 See L<DBIx::Class::Schema/throw_exception> for details.
3370 sub throw_exception {
3373 if (ref $self && $self->_source_handle->schema) {
3374 $self->_source_handle->schema->throw_exception(@_)
3377 DBIx::Class::Exception->throw(@_);
3381 # XXX: FIXME: Attributes docs need clearing up
3385 Attributes are used to refine a ResultSet in various ways when
3386 searching for data. They can be passed to any method which takes an
3387 C<\%attrs> argument. See L</search>, L</search_rs>, L</find>,
3390 These are in no particular order:
3396 =item Value: ( $order_by | \@order_by | \%order_by )
3400 Which column(s) to order the results by.
3402 [The full list of suitable values is documented in
3403 L<SQL::Abstract/"ORDER BY CLAUSES">; the following is a summary of
3406 If a single column name, or an arrayref of names is supplied, the
3407 argument is passed through directly to SQL. The hashref syntax allows
3408 for connection-agnostic specification of ordering direction:
3410 For descending order:
3412 order_by => { -desc => [qw/col1 col2 col3/] }
3414 For explicit ascending order:
3416 order_by => { -asc => 'col' }
3418 The old scalarref syntax (i.e. order_by => \'year DESC') is still
3419 supported, although you are strongly encouraged to use the hashref
3420 syntax as outlined above.
3426 =item Value: \@columns
3430 Shortcut to request a particular set of columns to be retrieved. Each
3431 column spec may be a string (a table column name), or a hash (in which
3432 case the key is the C<as> value, and the value is used as the C<select>
3433 expression). Adds C<me.> onto the start of any column without a C<.> in
3434 it and sets C<select> from that, then auto-populates C<as> from
3435 C<select> as normal. (You may also use the C<cols> attribute, as in
3436 earlier versions of DBIC.)
3438 Essentially C<columns> does the same as L</select> and L</as>.
3440 columns => [ 'foo', { bar => 'baz' } ]
3444 select => [qw/foo baz/],
3451 =item Value: \@columns
3455 Indicates additional columns to be selected from storage. Works the same
3456 as L</columns> but adds columns to the selection. (You may also use the
3457 C<include_columns> attribute, as in earlier versions of DBIC). For
3460 $schema->resultset('CD')->search(undef, {
3461 '+columns' => ['artist.name'],
3465 would return all CDs and include a 'name' column to the information
3466 passed to object inflation. Note that the 'artist' is the name of the
3467 column (or relationship) accessor, and 'name' is the name of the column
3468 accessor in the related table.
3470 =head2 include_columns
3474 =item Value: \@columns
3478 Deprecated. Acts as a synonym for L</+columns> for backward compatibility.
3484 =item Value: \@select_columns
3488 Indicates which columns should be selected from the storage. You can use
3489 column names, or in the case of RDBMS back ends, function or stored procedure
3492 $rs = $schema->resultset('Employee')->search(undef, {
3495 { count => 'employeeid' },
3496 { max => { length => 'name' }, -as => 'longest_name' }
3501 SELECT name, COUNT( employeeid ), MAX( LENGTH( name ) ) AS longest_name FROM employee
3503 B<NOTE:> You will almost always need a corresponding L</as> attribute when you
3504 use L</select>, to instruct DBIx::Class how to store the result of the column.
3505 Also note that the L</as> attribute has nothing to do with the SQL-side 'AS'
3506 identifier aliasing. You can however alias a function, so you can use it in
3507 e.g. an C<ORDER BY> clause. This is done via the C<-as> B<select function
3508 attribute> supplied as shown in the example above.
3514 Indicates additional columns to be selected from storage. Works the same as
3515 L</select> but adds columns to the default selection, instead of specifying
3524 Indicates additional column names for those added via L</+select>. See L</as>.
3532 =item Value: \@inflation_names
3536 Indicates column names for object inflation. That is L</as> indicates the
3537 slot name in which the column value will be stored within the
3538 L<Row|DBIx::Class::Row> object. The value will then be accessible via this
3539 identifier by the C<get_column> method (or via the object accessor B<if one
3540 with the same name already exists>) as shown below. The L</as> attribute has
3541 B<nothing to do> with the SQL-side C<AS>. See L</select> for details.
3543 $rs = $schema->resultset('Employee')->search(undef, {
3546 { count => 'employeeid' },
3547 { max => { length => 'name' }, -as => 'longest_name' }
3556 If the object against which the search is performed already has an accessor
3557 matching a column name specified in C<as>, the value can be retrieved using
3558 the accessor as normal:
3560 my $name = $employee->name();
3562 If on the other hand an accessor does not exist in the object, you need to
3563 use C<get_column> instead:
3565 my $employee_count = $employee->get_column('employee_count');
3567 You can create your own accessors if required - see
3568 L<DBIx::Class::Manual::Cookbook> for details.
3574 =item Value: ($rel_name | \@rel_names | \%rel_names)
3578 Contains a list of relationships that should be joined for this query. For
3581 # Get CDs by Nine Inch Nails
3582 my $rs = $schema->resultset('CD')->search(
3583 { 'artist.name' => 'Nine Inch Nails' },
3584 { join => 'artist' }
3587 Can also contain a hash reference to refer to the other relation's relations.
3590 package MyApp::Schema::Track;
3591 use base qw/DBIx::Class/;
3592 __PACKAGE__->table('track');
3593 __PACKAGE__->add_columns(qw/trackid cd position title/);
3594 __PACKAGE__->set_primary_key('trackid');
3595 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
3598 # In your application
3599 my $rs = $schema->resultset('Artist')->search(
3600 { 'track.title' => 'Teardrop' },
3602 join => { cd => 'track' },
3603 order_by => 'artist.name',
3607 You need to use the relationship (not the table) name in conditions,
3608 because they are aliased as such. The current table is aliased as "me", so
3609 you need to use me.column_name in order to avoid ambiguity. For example:
3611 # Get CDs from 1984 with a 'Foo' track
3612 my $rs = $schema->resultset('CD')->search(
3615 'tracks.name' => 'Foo'
3617 { join => 'tracks' }
3620 If the same join is supplied twice, it will be aliased to <rel>_2 (and
3621 similarly for a third time). For e.g.
3623 my $rs = $schema->resultset('Artist')->search({
3624 'cds.title' => 'Down to Earth',
3625 'cds_2.title' => 'Popular',
3627 join => [ qw/cds cds/ ],
3630 will return a set of all artists that have both a cd with title 'Down
3631 to Earth' and a cd with title 'Popular'.
3633 If you want to fetch related objects from other tables as well, see C<prefetch>
3636 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
3642 =item Value: ($rel_name | \@rel_names | \%rel_names)
3646 Contains one or more relationships that should be fetched along with
3647 the main query (when they are accessed afterwards the data will
3648 already be available, without extra queries to the database). This is
3649 useful for when you know you will need the related objects, because it
3650 saves at least one query:
3652 my $rs = $schema->resultset('Tag')->search(
3661 The initial search results in SQL like the following:
3663 SELECT tag.*, cd.*, artist.* FROM tag
3664 JOIN cd ON tag.cd = cd.cdid
3665 JOIN artist ON cd.artist = artist.artistid
3667 L<DBIx::Class> has no need to go back to the database when we access the
3668 C<cd> or C<artist> relationships, which saves us two SQL statements in this
3671 Simple prefetches will be joined automatically, so there is no need
3672 for a C<join> attribute in the above search.
3674 C<prefetch> can be used with the following relationship types: C<belongs_to>,
3675 C<has_one> (or if you're using C<add_relationship>, any relationship declared
3676 with an accessor type of 'single' or 'filter'). A more complex example that
3677 prefetches an artists cds, the tracks on those cds, and the tags associated
3678 with that artist is given below (assuming many-to-many from artists to tags):
3680 my $rs = $schema->resultset('Artist')->search(
3684 { cds => 'tracks' },
3685 { artist_tags => 'tags' }
3691 B<NOTE:> If you specify a C<prefetch> attribute, the C<join> and C<select>
3692 attributes will be ignored.
3694 B<CAVEATs>: Prefetch does a lot of deep magic. As such, it may not behave
3695 exactly as you might expect.
3701 Prefetch uses the L</cache> to populate the prefetched relationships. This
3702 may or may not be what you want.
3706 If you specify a condition on a prefetched relationship, ONLY those
3707 rows that match the prefetched condition will be fetched into that relationship.
3708 This means that adding prefetch to a search() B<may alter> what is returned by
3709 traversing a relationship. So, if you have C<< Artist->has_many(CDs) >> and you do
3711 my $artist_rs = $schema->resultset('Artist')->search({
3717 my $count = $artist_rs->first->cds->count;
3719 my $artist_rs_prefetch = $artist_rs->search( {}, { prefetch => 'cds' } );
3721 my $prefetch_count = $artist_rs_prefetch->first->cds->count;
3723 cmp_ok( $count, '==', $prefetch_count, "Counts should be the same" );
3725 that cmp_ok() may or may not pass depending on the datasets involved. This
3726 behavior may or may not survive the 0.09 transition.
3738 Makes the resultset paged and specifies the page to retrieve. Effectively
3739 identical to creating a non-pages resultset and then calling ->page($page)
3742 If L<rows> attribute is not specified it defaults to 10 rows per page.
3744 When you have a paged resultset, L</count> will only return the number
3745 of rows in the page. To get the total, use the L</pager> and call
3746 C<total_entries> on it.
3756 Specifies the maximum number of rows for direct retrieval or the number of
3757 rows per page if the page attribute or method is used.
3763 =item Value: $offset
3767 Specifies the (zero-based) row number for the first row to be returned, or the
3768 of the first row of the first page if paging is used.
3774 =item Value: \@columns
3778 A arrayref of columns to group by. Can include columns of joined tables.
3780 group_by => [qw/ column1 column2 ... /]
3786 =item Value: $condition
3790 HAVING is a select statement attribute that is applied between GROUP BY and
3791 ORDER BY. It is applied to the after the grouping calculations have been
3794 having => { 'count(employee)' => { '>=', 100 } }
3800 =item Value: (0 | 1)
3804 Set to 1 to group by all columns. If the resultset already has a group_by
3805 attribute, this setting is ignored and an appropriate warning is issued.
3811 Adds to the WHERE clause.
3813 # only return rows WHERE deleted IS NULL for all searches
3814 __PACKAGE__->resultset_attributes({ where => { deleted => undef } }); )
3816 Can be overridden by passing C<< { where => undef } >> as an attribute
3823 Set to 1 to cache search results. This prevents extra SQL queries if you
3824 revisit rows in your ResultSet:
3826 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
3828 while( my $artist = $resultset->next ) {
3832 $rs->first; # without cache, this would issue a query
3834 By default, searches are not cached.
3836 For more examples of using these attributes, see
3837 L<DBIx::Class::Manual::Cookbook>.
3843 =item Value: ( 'update' | 'shared' )
3847 Set to 'update' for a SELECT ... FOR UPDATE or 'shared' for a SELECT