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/;
17 # not importing first() as it will clash with our own method
24 # De-duplication in _merge_attr() is disabled, but left in for reference
25 *__HM_DEDUP = sub () { 0 };
33 __PACKAGE__->mk_group_accessors('simple' => qw/_result_class _source_handle/);
37 DBIx::Class::ResultSet - Represents a query used for fetching a set of results.
41 my $users_rs = $schema->resultset('User');
42 while( $user = $users_rs->next) {
43 print $user->username;
46 my $registered_users_rs = $schema->resultset('User')->search({ registered => 1 });
47 my @cds_in_2005 = $schema->resultset('CD')->search({ year => 2005 })->all();
51 A ResultSet is an object which stores a set of conditions representing
52 a query. It is the backbone of DBIx::Class (i.e. the really
53 important/useful bit).
55 No SQL is executed on the database when a ResultSet is created, it
56 just stores all the conditions needed to create the query.
58 A basic ResultSet representing the data of an entire table is returned
59 by calling C<resultset> on a L<DBIx::Class::Schema> and passing in a
60 L<Source|DBIx::Class::Manual::Glossary/Source> name.
62 my $users_rs = $schema->resultset('User');
64 A new ResultSet is returned from calling L</search> on an existing
65 ResultSet. The new one will contain all the conditions of the
66 original, plus any new conditions added in the C<search> call.
68 A ResultSet also incorporates an implicit iterator. L</next> and L</reset>
69 can be used to walk through all the L<DBIx::Class::Row>s the ResultSet
72 The query that the ResultSet represents is B<only> executed against
73 the database when these methods are called:
74 L</find>, L</next>, L</all>, L</first>, L</single>, L</count>.
76 If a resultset is used in a numeric context it returns the L</count>.
77 However, if it is used in a boolean context it is B<always> true. So if
78 you want to check if a resultset has any results, you must use C<if $rs
83 =head2 Chaining resultsets
85 Let's say you've got a query that needs to be run to return some data
86 to the user. But, you have an authorization system in place that
87 prevents certain users from seeing certain information. So, you want
88 to construct the basic query in one method, but add constraints to it in
93 my $request = $self->get_request; # Get a request object somehow.
94 my $schema = $self->get_schema; # Get the DBIC schema object somehow.
96 my $cd_rs = $schema->resultset('CD')->search({
97 title => $request->param('title'),
98 year => $request->param('year'),
101 $self->apply_security_policy( $cd_rs );
103 return $cd_rs->all();
106 sub apply_security_policy {
115 =head3 Resolving conditions and attributes
117 When a resultset is chained from another resultset, conditions and
118 attributes with the same keys need resolving.
120 L</join>, L</prefetch>, L</+select>, L</+as> attributes are merged
121 into the existing ones from the original resultset.
123 The L</where> and L</having> attributes, and any search conditions, are
124 merged with an SQL C<AND> to the existing condition from the original
127 All other attributes are overridden by any new ones supplied in the
130 =head2 Multiple queries
132 Since a resultset just defines a query, you can do all sorts of
133 things with it with the same object.
135 # Don't hit the DB yet.
136 my $cd_rs = $schema->resultset('CD')->search({
137 title => 'something',
141 # Each of these hits the DB individually.
142 my $count = $cd_rs->count;
143 my $most_recent = $cd_rs->get_column('date_released')->max();
144 my @records = $cd_rs->all;
146 And it's not just limited to SELECT statements.
152 $cd_rs->create({ artist => 'Fred' });
154 Which is the same as:
156 $schema->resultset('CD')->create({
157 title => 'something',
162 See: L</search>, L</count>, L</get_column>, L</all>, L</create>.
170 =item Arguments: $source, \%$attrs
172 =item Return Value: $rs
176 The resultset constructor. Takes a source object (usually a
177 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
178 L</ATTRIBUTES> below). Does not perform any queries -- these are
179 executed as needed by the other methods.
181 Generally you won't need to construct a resultset manually. You'll
182 automatically get one from e.g. a L</search> called in scalar context:
184 my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
186 IMPORTANT: If called on an object, proxies to new_result instead so
188 my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
190 will return a CD object, not a ResultSet.
196 return $class->new_result(@_) if ref $class;
198 my ($source, $attrs) = @_;
199 $source = $source->handle
200 unless $source->isa('DBIx::Class::ResultSourceHandle');
201 $attrs = { %{$attrs||{}} };
203 if ($attrs->{page}) {
204 $attrs->{rows} ||= 10;
207 $attrs->{alias} ||= 'me';
209 # Creation of {} and bless separated to mitigate RH perl bug
210 # see https://bugzilla.redhat.com/show_bug.cgi?id=196836
212 _source_handle => $source,
213 cond => $attrs->{where},
221 $attrs->{result_class} || $source->resolve->result_class
231 =item Arguments: $cond, \%attrs?
233 =item Return Value: $resultset (scalar context), @row_objs (list context)
237 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
238 my $new_rs = $cd_rs->search({ year => 2005 });
240 my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
241 # year = 2005 OR year = 2004
243 If you need to pass in additional attributes but no additional condition,
244 call it as C<search(undef, \%attrs)>.
246 # "SELECT name, artistid FROM $artist_table"
247 my @all_artists = $schema->resultset('Artist')->search(undef, {
248 columns => [qw/name artistid/],
251 For a list of attributes that can be passed to C<search>, see
252 L</ATTRIBUTES>. For more examples of using this function, see
253 L<Searching|DBIx::Class::Manual::Cookbook/Searching>. For a complete
254 documentation for the first argument, see L<SQL::Abstract>.
256 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
260 Note that L</search> does not process/deflate any of the values passed in the
261 L<SQL::Abstract>-compatible search condition structure. This is unlike other
262 condition-bound methods L</new>, L</create> and L</find>. The user must ensure
263 manually that any value passed to this method will stringify to something the
264 RDBMS knows how to deal with. A notable example is the handling of L<DateTime>
265 objects, for more info see:
266 L<DBIx::Class::Manual::Cookbook/Formatting_DateTime_objects_in_queries>.
272 my $rs = $self->search_rs( @_ );
277 elsif (defined wantarray) {
281 # we can be called by a relationship helper, which in
282 # turn may be called in void context due to some braindead
283 # overload or whatever else the user decided to be clever
284 # at this particular day. Thus limit the exception to
285 # external code calls only
286 $self->throw_exception ('->search is *not* a mutator, calling it in void context makes no sense')
287 if (caller)[0] !~ /^\QDBIx::Class::/;
297 =item Arguments: $cond, \%attrs?
299 =item Return Value: $resultset
303 This method does the same exact thing as search() except it will
304 always return a resultset, even in list context.
311 # Special-case handling for (undef, undef).
312 if ( @_ == 2 && !defined $_[1] && !defined $_[0] ) {
317 $call_attrs = pop(@_) if (
318 @_ > 1 and ( ! defined $_[-1] or ref $_[-1] eq 'HASH' )
321 # see if we can keep the cache (no $rs changes)
323 my %safe = (alias => 1, cache => 1);
324 if ( ! List::Util::first { !$safe{$_} } keys %$call_attrs and (
327 ref $_[0] eq 'HASH' && ! keys %{$_[0]}
329 ref $_[0] eq 'ARRAY' && ! @{$_[0]}
331 $cache = $self->get_cache;
334 my $old_attrs = { %{$self->{attrs}} };
335 my $old_having = delete $old_attrs->{having};
336 my $old_where = delete $old_attrs->{where};
338 # reset the selector list
339 if (List::Util::first { exists $call_attrs->{$_} } qw{columns select as}) {
340 delete @{$old_attrs}{qw{select as columns +select +as +columns include_columns}};
343 my $new_attrs = { %{$old_attrs}, %{$call_attrs} };
345 # merge new attrs into inherited
346 foreach my $key (qw/join prefetch/) {
347 next unless exists $call_attrs->{$key};
348 $new_attrs->{$key} = $self->_merge_joinpref_attr($old_attrs->{$key}, $call_attrs->{$key});
350 foreach my $key (qw/+select +as +columns include_columns bind/) {
351 next unless exists $call_attrs->{$key};
352 $new_attrs->{$key} = $self->_merge_attr($old_attrs->{$key}, $call_attrs->{$key});
355 # rip apart the rest of @_, parse a condition
358 if (ref $_[0] eq 'HASH') {
359 (keys %{$_[0]}) ? $_[0] : undef
365 $self->throw_exception('Odd number of arguments to search')
373 carp 'search( %condition ) is deprecated, use search( \%condition ) instead'
374 if (@_ > 1 and ! $self->result_source->result_class->isa('DBIx::Class::CDBICompat') );
376 for ($old_where, $call_cond) {
378 $new_attrs->{where} = $self->_stack_cond (
379 $_, $new_attrs->{where}
384 if (defined $old_having) {
385 $new_attrs->{having} = $self->_stack_cond (
386 $old_having, $new_attrs->{having}
390 my $rs = (ref $self)->new($self->result_source, $new_attrs);
392 $rs->set_cache($cache) if ($cache);
398 my ($self, $left, $right) = @_;
399 if (defined $left xor defined $right) {
400 return defined $left ? $left : $right;
402 elsif (defined $left) {
403 return { -and => [ map
404 { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
412 =head2 search_literal
416 =item Arguments: $sql_fragment, @bind_values
418 =item Return Value: $resultset (scalar context), @row_objs (list context)
422 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
423 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
425 Pass a literal chunk of SQL to be added to the conditional part of the
428 CAVEAT: C<search_literal> is provided for Class::DBI compatibility and should
429 only be used in that context. C<search_literal> is a convenience method.
430 It is equivalent to calling $schema->search(\[]), but if you want to ensure
431 columns are bound correctly, use C<search>.
433 Example of how to use C<search> instead of C<search_literal>
435 my @cds = $cd_rs->search_literal('cdid = ? AND (artist = ? OR artist = ?)', (2, 1, 2));
436 my @cds = $cd_rs->search(\[ 'cdid = ? AND (artist = ? OR artist = ?)', [ 'cdid', 2 ], [ 'artist', 1 ], [ 'artist', 2 ] ]);
439 See L<DBIx::Class::Manual::Cookbook/Searching> and
440 L<DBIx::Class::Manual::FAQ/Searching> for searching techniques that do not
441 require C<search_literal>.
446 my ($self, $sql, @bind) = @_;
448 if ( @bind && ref($bind[-1]) eq 'HASH' ) {
451 return $self->search(\[ $sql, map [ __DUMMY__ => $_ ], @bind ], ($attr || () ));
458 =item Arguments: \%columns_values | @pk_values, \%attrs?
460 =item Return Value: $row_object | undef
464 Finds and returns a single row based on supplied criteria. Takes either a
465 hashref with the same format as L</create> (including inference of foreign
466 keys from related objects), or a list of primary key values in the same
467 order as the L<primary columns|DBIx::Class::ResultSource/primary_columns>
468 declaration on the L</result_source>.
470 In either case an attempt is made to combine conditions already existing on
471 the resultset with the condition passed to this method.
473 To aid with preparing the correct query for the storage you may supply the
474 C<key> attribute, which is the name of a
475 L<unique constraint|DBIx::Class::ResultSource/add_unique_constraint> (the
476 unique constraint corresponding to the
477 L<primary columns|DBIx::Class::ResultSource/primary_columns> is always named
478 C<primary>). If the C<key> attribute has been supplied, and DBIC is unable
479 to construct a query that satisfies the named unique constraint fully (
480 non-NULL values for each column member of the constraint) an exception is
483 If no C<key> is specified, the search is carried over all unique constraints
484 which are fully defined by the available condition.
486 If no such constraint is found, C<find> currently defaults to a simple
487 C<< search->(\%column_values) >> which may or may not do what you expect.
488 Note that this fallback behavior may be deprecated in further versions. If
489 you need to search with arbitrary conditions - use L</search>. If the query
490 resulting from this fallback produces more than one row, a warning to the
491 effect is issued, though only the first row is constructed and returned as
494 In addition to C<key>, L</find> recognizes and applies standard
495 L<resultset attributes|/ATTRIBUTES> in the same way as L</search> does.
497 Note that if you have extra concerns about the correctness of the resulting
498 query you need to specify the C<key> attribute and supply the entire condition
499 as an argument to find (since it is not always possible to perform the
500 combination of the resultset condition with the supplied one, especially if
501 the resultset condition contains literal sql).
503 For example, to find a row by its primary key:
505 my $cd = $schema->resultset('CD')->find(5);
507 You can also find a row by a specific unique constraint:
509 my $cd = $schema->resultset('CD')->find(
511 artist => 'Massive Attack',
512 title => 'Mezzanine',
514 { key => 'cd_artist_title' }
517 See also L</find_or_create> and L</update_or_create>.
523 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
525 my $rsrc = $self->result_source;
527 # Parse out the condition from input
529 if (ref $_[0] eq 'HASH') {
530 $call_cond = { %{$_[0]} };
533 my $constraint = exists $attrs->{key} ? $attrs->{key} : 'primary';
534 my @c_cols = $rsrc->unique_constraint_columns($constraint);
536 $self->throw_exception(
537 "No constraint columns, maybe a malformed '$constraint' constraint?"
540 $self->throw_exception (
541 'find() expects either a column/value hashref, or a list of values '
542 . "corresponding to the columns of the specified unique constraint '$constraint'"
543 ) unless @c_cols == @_;
546 @{$call_cond}{@c_cols} = @_;
550 for my $key (keys %$call_cond) {
552 my $keyref = ref($call_cond->{$key})
554 my $relinfo = $rsrc->relationship_info($key)
556 my $val = delete $call_cond->{$key};
558 next if $keyref eq 'ARRAY'; # has_many for multi_create
560 my $rel_q = $rsrc->_resolve_condition(
561 $relinfo->{cond}, $val, $key
563 die "Can't handle complex relationship conditions in find" if ref($rel_q) ne 'HASH';
564 @related{keys %$rel_q} = values %$rel_q;
568 # relationship conditions take precedence (?)
569 @{$call_cond}{keys %related} = values %related;
571 my $alias = exists $attrs->{alias} ? $attrs->{alias} : $self->{attrs}{alias};
573 if (exists $attrs->{key}) {
574 $final_cond = $self->_qualify_cond_columns (
576 $self->_build_unique_cond (
584 elsif ($self->{attrs}{accessor} and $self->{attrs}{accessor} eq 'single') {
585 # This means that we got here after a merger of relationship conditions
586 # in ::Relationship::Base::search_related (the row method), and furthermore
587 # the relationship is of the 'single' type. This means that the condition
588 # provided by the relationship (already attached to $self) is sufficient,
589 # as there can be only one row in the database that would satisfy the
593 # no key was specified - fall down to heuristics mode:
594 # run through all unique queries registered on the resultset, and
595 # 'OR' all qualifying queries together
596 my (@unique_queries, %seen_column_combinations);
597 for my $c_name ($rsrc->unique_constraint_names) {
598 next if $seen_column_combinations{
599 join "\x00", sort $rsrc->unique_constraint_columns($c_name)
602 push @unique_queries, try {
603 $self->_build_unique_cond ($c_name, $call_cond)
607 $final_cond = @unique_queries
608 ? [ map { $self->_qualify_cond_columns($_, $alias) } @unique_queries ]
609 : $self->_non_unique_find_fallback ($call_cond, $attrs)
613 # Run the query, passing the result_class since it should propagate for find
614 my $rs = $self->search ($final_cond, {result_class => $self->result_class, %$attrs});
615 if (keys %{$rs->_resolved_attrs->{collapse}}) {
617 carp "Query returned more than one row" if $rs->next;
625 # This is a stop-gap method as agreed during the discussion on find() cleanup:
626 # http://lists.scsys.co.uk/pipermail/dbix-class/2010-October/009535.html
628 # It is invoked when find() is called in legacy-mode with insufficiently-unique
629 # condition. It is provided for overrides until a saner way forward is devised
631 # *NOTE* This is not a public method, and it's *GUARANTEED* to disappear down
632 # the road. Please adjust your tests accordingly to catch this situation early
633 # DBIx::Class::ResultSet->can('_non_unique_find_fallback') is reasonable
635 # The method will not be removed without an adequately complete replacement
636 # for strict-mode enforcement
637 sub _non_unique_find_fallback {
638 my ($self, $cond, $attrs) = @_;
640 return $self->_qualify_cond_columns(
642 exists $attrs->{alias}
644 : $self->{attrs}{alias}
649 sub _qualify_cond_columns {
650 my ($self, $cond, $alias) = @_;
652 my %aliased = %$cond;
653 for (keys %aliased) {
654 $aliased{"$alias.$_"} = delete $aliased{$_}
661 sub _build_unique_cond {
662 my ($self, $constraint_name, $extra_cond) = @_;
664 my @c_cols = $self->result_source->unique_constraint_columns($constraint_name);
666 # combination may fail if $self->{cond} is non-trivial
667 my ($final_cond) = try {
668 $self->_merge_with_rscond ($extra_cond)
673 # trim out everything not in $columns
674 $final_cond = { map { $_ => $final_cond->{$_} } @c_cols };
676 if (my @missing = grep { ! defined $final_cond->{$_} } (@c_cols) ) {
677 $self->throw_exception( sprintf ( "Unable to satisfy requested constraint '%s', no values for column(s): %s",
679 join (', ', map { "'$_'" } @missing),
686 =head2 search_related
690 =item Arguments: $rel, $cond, \%attrs?
692 =item Return Value: $new_resultset
696 $new_rs = $cd_rs->search_related('artist', {
700 Searches the specified relationship, optionally specifying a condition and
701 attributes for matching records. See L</ATTRIBUTES> for more information.
706 return shift->related_resultset(shift)->search(@_);
709 =head2 search_related_rs
711 This method works exactly the same as search_related, except that
712 it guarantees a resultset, even in list context.
716 sub search_related_rs {
717 return shift->related_resultset(shift)->search_rs(@_);
724 =item Arguments: none
726 =item Return Value: $cursor
730 Returns a storage-driven cursor to the given resultset. See
731 L<DBIx::Class::Cursor> for more information.
738 my $attrs = $self->_resolved_attrs_copy;
740 return $self->{cursor}
741 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
742 $attrs->{where},$attrs);
749 =item Arguments: $cond?
751 =item Return Value: $row_object | undef
755 my $cd = $schema->resultset('CD')->single({ year => 2001 });
757 Inflates the first result without creating a cursor if the resultset has
758 any records in it; if not returns C<undef>. Used by L</find> as a lean version
761 While this method can take an optional search condition (just like L</search>)
762 being a fast-code-path it does not recognize search attributes. If you need to
763 add extra joins or similar, call L</search> and then chain-call L</single> on the
764 L<DBIx::Class::ResultSet> returned.
770 As of 0.08100, this method enforces the assumption that the preceding
771 query returns only one row. If more than one row is returned, you will receive
774 Query returned more than one row
776 In this case, you should be using L</next> or L</find> instead, or if you really
777 know what you are doing, use the L</rows> attribute to explicitly limit the size
780 This method will also throw an exception if it is called on a resultset prefetching
781 has_many, as such a prefetch implies fetching multiple rows from the database in
782 order to assemble the resulting object.
789 my ($self, $where) = @_;
791 $self->throw_exception('single() only takes search conditions, no attributes. You want ->search( $cond, $attrs )->single()');
794 my $attrs = $self->_resolved_attrs_copy;
796 if (keys %{$attrs->{collapse}}) {
797 $self->throw_exception(
798 'single() can not be used on resultsets prefetching has_many. Use find( \%cond ) or next() instead'
803 if (defined $attrs->{where}) {
806 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
807 $where, delete $attrs->{where} ]
810 $attrs->{where} = $where;
814 my @data = $self->result_source->storage->select_single(
815 $attrs->{from}, $attrs->{select},
816 $attrs->{where}, $attrs
819 return (@data ? ($self->_construct_object(@data))[0] : undef);
825 # Recursively collapse the query, accumulating values for each column.
827 sub _collapse_query {
828 my ($self, $query, $collapsed) = @_;
832 if (ref $query eq 'ARRAY') {
833 foreach my $subquery (@$query) {
834 next unless ref $subquery; # -or
835 $collapsed = $self->_collapse_query($subquery, $collapsed);
838 elsif (ref $query eq 'HASH') {
839 if (keys %$query and (keys %$query)[0] eq '-and') {
840 foreach my $subquery (@{$query->{-and}}) {
841 $collapsed = $self->_collapse_query($subquery, $collapsed);
845 foreach my $col (keys %$query) {
846 my $value = $query->{$col};
847 $collapsed->{$col}{$value}++;
859 =item Arguments: $cond?
861 =item Return Value: $resultsetcolumn
865 my $max_length = $rs->get_column('length')->max;
867 Returns a L<DBIx::Class::ResultSetColumn> instance for a column of the ResultSet.
872 my ($self, $column) = @_;
873 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
881 =item Arguments: $cond, \%attrs?
883 =item Return Value: $resultset (scalar context), @row_objs (list context)
887 # WHERE title LIKE '%blue%'
888 $cd_rs = $rs->search_like({ title => '%blue%'});
890 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
891 that this is simply a convenience method retained for ex Class::DBI users.
892 You most likely want to use L</search> with specific operators.
894 For more information, see L<DBIx::Class::Manual::Cookbook>.
896 This method is deprecated and will be removed in 0.09. Use L</search()>
897 instead. An example conversion is:
899 ->search_like({ foo => 'bar' });
903 ->search({ foo => { like => 'bar' } });
910 'search_like() is deprecated and will be removed in DBIC version 0.09.'
911 .' Instead use ->search({ x => { -like => "y%" } })'
912 .' (note the outer pair of {}s - they are important!)'
914 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
915 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
916 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
917 return $class->search($query, { %$attrs });
924 =item Arguments: $first, $last
926 =item Return Value: $resultset (scalar context), @row_objs (list context)
930 Returns a resultset or object list representing a subset of elements from the
931 resultset slice is called on. Indexes are from 0, i.e., to get the first
934 my ($one, $two, $three) = $rs->slice(0, 2);
939 my ($self, $min, $max) = @_;
940 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
941 $attrs->{offset} = $self->{attrs}{offset} || 0;
942 $attrs->{offset} += $min;
943 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
944 return $self->search(undef, $attrs);
945 #my $slice = (ref $self)->new($self->result_source, $attrs);
946 #return (wantarray ? $slice->all : $slice);
953 =item Arguments: none
955 =item Return Value: $result | undef
959 Returns the next element in the resultset (C<undef> is there is none).
961 Can be used to efficiently iterate over records in the resultset:
963 my $rs = $schema->resultset('CD')->search;
964 while (my $cd = $rs->next) {
968 Note that you need to store the resultset object, and call C<next> on it.
969 Calling C<< resultset('Table')->next >> repeatedly will always return the
970 first record from the resultset.
976 if (my $cache = $self->get_cache) {
977 $self->{all_cache_position} ||= 0;
978 return $cache->[$self->{all_cache_position}++];
980 if ($self->{attrs}{cache}) {
981 delete $self->{pager};
982 $self->{all_cache_position} = 1;
983 return ($self->all)[0];
985 if ($self->{stashed_objects}) {
986 my $obj = shift(@{$self->{stashed_objects}});
987 delete $self->{stashed_objects} unless @{$self->{stashed_objects}};
991 exists $self->{stashed_row}
992 ? @{delete $self->{stashed_row}}
993 : $self->cursor->next
995 return undef unless (@row);
996 my ($row, @more) = $self->_construct_object(@row);
997 $self->{stashed_objects} = \@more if @more;
1001 sub _construct_object {
1002 my ($self, @row) = @_;
1004 my $info = $self->_collapse_result($self->{_attrs}{as}, \@row)
1006 my @new = $self->result_class->inflate_result($self->result_source, @$info);
1007 @new = $self->{_attrs}{record_filter}->(@new)
1008 if exists $self->{_attrs}{record_filter};
1012 sub _collapse_result {
1013 my ($self, $as_proto, $row) = @_;
1017 # 'foo' => [ undef, 'foo' ]
1018 # 'foo.bar' => [ 'foo', 'bar' ]
1019 # 'foo.bar.baz' => [ 'foo.bar', 'baz' ]
1021 my @construct_as = map { [ (/^(?:(.*)\.)?([^.]+)$/) ] } @$as_proto;
1023 my %collapse = %{$self->{_attrs}{collapse}||{}};
1027 # if we're doing collapsing (has_many prefetch) we need to grab records
1028 # until the PK changes, so fill @pri_index. if not, we leave it empty so
1029 # we know we don't have to bother.
1031 # the reason for not using the collapse stuff directly is because if you
1032 # had for e.g. two artists in a row with no cds, the collapse info for
1033 # both would be NULL (undef) so you'd lose the second artist
1035 # store just the index so we can check the array positions from the row
1036 # without having to contruct the full hash
1038 if (keys %collapse) {
1039 my %pri = map { ($_ => 1) } $self->result_source->_pri_cols;
1040 foreach my $i (0 .. $#construct_as) {
1041 next if defined($construct_as[$i][0]); # only self table
1042 if (delete $pri{$construct_as[$i][1]}) {
1043 push(@pri_index, $i);
1045 last unless keys %pri; # short circuit (Johnny Five Is Alive!)
1049 # no need to do an if, it'll be empty if @pri_index is empty anyway
1051 my %pri_vals = map { ($_ => $copy[$_]) } @pri_index;
1055 do { # no need to check anything at the front, we always want the first row
1059 foreach my $this_as (@construct_as) {
1060 $const{$this_as->[0]||''}{$this_as->[1]} = shift(@copy);
1063 push(@const_rows, \%const);
1065 } until ( # no pri_index => no collapse => drop straight out
1068 do { # get another row, stash it, drop out if different PK
1070 @copy = $self->cursor->next;
1071 $self->{stashed_row} = \@copy;
1073 # last thing in do block, counts as true if anything doesn't match
1075 # check xor defined first for NULL vs. NOT NULL then if one is
1076 # defined the other must be so check string equality
1079 (defined $pri_vals{$_} ^ defined $copy[$_])
1080 || (defined $pri_vals{$_} && ($pri_vals{$_} ne $copy[$_]))
1085 my $alias = $self->{attrs}{alias};
1092 foreach my $const (@const_rows) {
1093 scalar @const_keys or do {
1094 @const_keys = sort { length($a) <=> length($b) } keys %$const;
1096 foreach my $key (@const_keys) {
1099 my @parts = split(/\./, $key);
1101 my $data = $const->{$key};
1102 foreach my $p (@parts) {
1103 $target = $target->[1]->{$p} ||= [];
1105 if ($cur eq ".${key}" && (my @ckey = @{$collapse{$cur}||[]})) {
1106 # collapsing at this point and on final part
1107 my $pos = $collapse_pos{$cur};
1108 CK: foreach my $ck (@ckey) {
1109 if (!defined $pos->{$ck} || $pos->{$ck} ne $data->{$ck}) {
1110 $collapse_pos{$cur} = $data;
1111 delete @collapse_pos{ # clear all positioning for sub-entries
1112 grep { m/^\Q${cur}.\E/ } keys %collapse_pos
1119 if (exists $collapse{$cur}) {
1120 $target = $target->[-1];
1123 $target->[0] = $data;
1125 $info->[0] = $const->{$key};
1133 =head2 result_source
1137 =item Arguments: $result_source?
1139 =item Return Value: $result_source
1143 An accessor for the primary ResultSource object from which this ResultSet
1150 =item Arguments: $result_class?
1152 =item Return Value: $result_class
1156 An accessor for the class to use when creating row objects. Defaults to
1157 C<< result_source->result_class >> - which in most cases is the name of the
1158 L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class.
1160 Note that changing the result_class will also remove any components
1161 that were originally loaded in the source class via
1162 L<DBIx::Class::ResultSource/load_components>. Any overloaded methods
1163 in the original source class will not run.
1168 my ($self, $result_class) = @_;
1169 if ($result_class) {
1170 unless (ref $result_class) { # don't fire this for an object
1171 $self->ensure_class_loaded($result_class);
1173 $self->_result_class($result_class);
1174 # THIS LINE WOULD BE A BUG - this accessor specifically exists to
1175 # permit the user to set result class on one result set only; it only
1176 # chains if provided to search()
1177 #$self->{attrs}{result_class} = $result_class if ref $self;
1179 $self->_result_class;
1186 =item Arguments: $cond, \%attrs??
1188 =item Return Value: $count
1192 Performs an SQL C<COUNT> with the same query as the resultset was built
1193 with to find the number of elements. Passing arguments is equivalent to
1194 C<< $rs->search ($cond, \%attrs)->count >>
1200 return $self->search(@_)->count if @_ and defined $_[0];
1201 return scalar @{ $self->get_cache } if $self->get_cache;
1203 my $attrs = $self->_resolved_attrs_copy;
1205 # this is a little optimization - it is faster to do the limit
1206 # adjustments in software, instead of a subquery
1207 my $rows = delete $attrs->{rows};
1208 my $offset = delete $attrs->{offset};
1211 if ($self->_has_resolved_attr (qw/collapse group_by/)) {
1212 $crs = $self->_count_subq_rs ($attrs);
1215 $crs = $self->_count_rs ($attrs);
1217 my $count = $crs->next;
1219 $count -= $offset if $offset;
1220 $count = $rows if $rows and $rows < $count;
1221 $count = 0 if ($count < 0);
1230 =item Arguments: $cond, \%attrs??
1232 =item Return Value: $count_rs
1236 Same as L</count> but returns a L<DBIx::Class::ResultSetColumn> object.
1237 This can be very handy for subqueries:
1239 ->search( { amount => $some_rs->count_rs->as_query } )
1241 As with regular resultsets the SQL query will be executed only after
1242 the resultset is accessed via L</next> or L</all>. That would return
1243 the same single value obtainable via L</count>.
1249 return $self->search(@_)->count_rs if @_;
1251 # this may look like a lack of abstraction (count() does about the same)
1252 # but in fact an _rs *must* use a subquery for the limits, as the
1253 # software based limiting can not be ported if this $rs is to be used
1254 # in a subquery itself (i.e. ->as_query)
1255 if ($self->_has_resolved_attr (qw/collapse group_by offset rows/)) {
1256 return $self->_count_subq_rs;
1259 return $self->_count_rs;
1264 # returns a ResultSetColumn object tied to the count query
1267 my ($self, $attrs) = @_;
1269 my $rsrc = $self->result_source;
1270 $attrs ||= $self->_resolved_attrs;
1272 my $tmp_attrs = { %$attrs };
1273 # take off any limits, record_filter is cdbi, and no point of ordering nor locking a count
1274 delete @{$tmp_attrs}{qw/rows offset order_by record_filter for/};
1276 # overwrite the selector (supplied by the storage)
1277 $tmp_attrs->{select} = $rsrc->storage->_count_select ($rsrc, $attrs);
1278 $tmp_attrs->{as} = 'count';
1280 my $tmp_rs = $rsrc->resultset_class->new($rsrc, $tmp_attrs)->get_column ('count');
1286 # same as above but uses a subquery
1288 sub _count_subq_rs {
1289 my ($self, $attrs) = @_;
1291 my $rsrc = $self->result_source;
1292 $attrs ||= $self->_resolved_attrs;
1294 my $sub_attrs = { %$attrs };
1295 # extra selectors do not go in the subquery and there is no point of ordering it, nor locking it
1296 delete @{$sub_attrs}{qw/collapse select _prefetch_select as order_by for/};
1298 # if we multi-prefetch we group_by primary keys only as this is what we would
1299 # get out of the rs via ->next/->all. We *DO WANT* to clobber old group_by regardless
1300 if ( keys %{$attrs->{collapse}} ) {
1301 $sub_attrs->{group_by} = [ map { "$attrs->{alias}.$_" } ($rsrc->_pri_cols) ]
1304 # Calculate subquery selector
1305 if (my $g = $sub_attrs->{group_by}) {
1307 my $sql_maker = $rsrc->storage->sql_maker;
1309 # necessary as the group_by may refer to aliased functions
1311 for my $sel (@{$attrs->{select}}) {
1312 $sel_index->{$sel->{-as}} = $sel
1313 if (ref $sel eq 'HASH' and $sel->{-as});
1316 # anything from the original select mentioned on the group-by needs to make it to the inner selector
1317 # also look for named aggregates referred in the having clause
1318 # having often contains scalarrefs - thus parse it out entirely
1320 if ($attrs->{having}) {
1321 local $sql_maker->{having_bind};
1322 local $sql_maker->{quote_char} = $sql_maker->{quote_char};
1323 local $sql_maker->{name_sep} = $sql_maker->{name_sep};
1324 unless (defined $sql_maker->{quote_char} and length $sql_maker->{quote_char}) {
1325 $sql_maker->{quote_char} = [ "\x00", "\xFF" ];
1326 # if we don't unset it we screw up retarded but unfortunately working
1327 # 'MAX(foo.bar)' => { '>', 3 }
1328 $sql_maker->{name_sep} = '';
1331 my ($lquote, $rquote, $sep) = map { quotemeta $_ } ($sql_maker->_quote_chars, $sql_maker->name_sep);
1333 my $sql = $sql_maker->_parse_rs_attrs ({ having => $attrs->{having} });
1335 # search for both a proper quoted qualified string, for a naive unquoted scalarref
1336 # and if all fails for an utterly naive quoted scalar-with-function
1338 $rquote $sep $lquote (.+?) $rquote
1340 [\s,] \w+ \. (\w+) [\s,]
1342 [\s,] $lquote (.+?) $rquote [\s,]
1344 push @parts, ($1 || $2 || $3); # one of them matched if we got here
1349 my $colpiece = $sel_index->{$_} || $_;
1351 # unqualify join-based group_by's. Arcane but possible query
1352 # also horrible horrible hack to alias a column (not a func.)
1353 # (probably need to introduce SQLA syntax)
1354 if ($colpiece =~ /\./ && $colpiece !~ /^$attrs->{alias}\./) {
1357 $colpiece = \ sprintf ('%s AS %s', map { $sql_maker->_quote ($_) } ($colpiece, $as) );
1359 push @{$sub_attrs->{select}}, $colpiece;
1363 my @pcols = map { "$attrs->{alias}.$_" } ($rsrc->primary_columns);
1364 $sub_attrs->{select} = @pcols ? \@pcols : [ 1 ];
1367 return $rsrc->resultset_class
1368 ->new ($rsrc, $sub_attrs)
1370 ->search ({}, { columns => { count => $rsrc->storage->_count_select ($rsrc, $attrs) } })
1371 ->get_column ('count');
1378 =head2 count_literal
1382 =item Arguments: $sql_fragment, @bind_values
1384 =item Return Value: $count
1388 Counts the results in a literal query. Equivalent to calling L</search_literal>
1389 with the passed arguments, then L</count>.
1393 sub count_literal { shift->search_literal(@_)->count; }
1399 =item Arguments: none
1401 =item Return Value: @objects
1405 Returns all elements in the resultset. Called implicitly if the resultset
1406 is returned in list context.
1413 $self->throw_exception("all() doesn't take any arguments, you probably wanted ->search(...)->all()");
1416 return @{ $self->get_cache } if $self->get_cache;
1420 if (keys %{$self->_resolved_attrs->{collapse}}) {
1421 # Using $self->cursor->all is really just an optimisation.
1422 # If we're collapsing has_many prefetches it probably makes
1423 # very little difference, and this is cleaner than hacking
1424 # _construct_object to survive the approach
1425 $self->cursor->reset;
1426 my @row = $self->cursor->next;
1428 push(@obj, $self->_construct_object(@row));
1429 @row = (exists $self->{stashed_row}
1430 ? @{delete $self->{stashed_row}}
1431 : $self->cursor->next);
1434 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
1437 $self->set_cache(\@obj) if $self->{attrs}{cache};
1446 =item Arguments: none
1448 =item Return Value: $self
1452 Resets the resultset's cursor, so you can iterate through the elements again.
1453 Implicitly resets the storage cursor, so a subsequent L</next> will trigger
1460 delete $self->{_attrs} if exists $self->{_attrs};
1461 $self->{all_cache_position} = 0;
1462 $self->cursor->reset;
1470 =item Arguments: none
1472 =item Return Value: $object | undef
1476 Resets the resultset and returns an object for the first result (or C<undef>
1477 if the resultset is empty).
1482 return $_[0]->reset->next;
1488 # Determines whether and what type of subquery is required for the $rs operation.
1489 # If grouping is necessary either supplies its own, or verifies the current one
1490 # After all is done delegates to the proper storage method.
1492 sub _rs_update_delete {
1493 my ($self, $op, $values) = @_;
1495 my $rsrc = $self->result_source;
1497 # if a condition exists we need to strip all table qualifiers
1498 # if this is not possible we'll force a subquery below
1499 my $cond = $rsrc->schema->storage->_strip_cond_qualifiers ($self->{cond});
1501 my $needs_group_by_subq = $self->_has_resolved_attr (qw/collapse group_by -join/);
1502 my $needs_subq = $needs_group_by_subq || (not defined $cond) || $self->_has_resolved_attr(qw/rows offset/);
1504 if ($needs_group_by_subq or $needs_subq) {
1506 # make a new $rs selecting only the PKs (that's all we really need)
1507 my $attrs = $self->_resolved_attrs_copy;
1510 delete $attrs->{$_} for qw/collapse _collapse_order_by select _prefetch_select as/;
1511 $attrs->{columns} = [ map { "$attrs->{alias}.$_" } ($self->result_source->_pri_cols) ];
1513 if ($needs_group_by_subq) {
1514 # make sure no group_by was supplied, or if there is one - make sure it matches
1515 # the columns compiled above perfectly. Anything else can not be sanely executed
1516 # on most databases so croak right then and there
1518 if (my $g = $attrs->{group_by}) {
1519 my @current_group_by = map
1520 { $_ =~ /\./ ? $_ : "$attrs->{alias}.$_" }
1525 join ("\x00", sort @current_group_by)
1527 join ("\x00", sort @{$attrs->{columns}} )
1529 $self->throw_exception (
1530 "You have just attempted a $op operation on a resultset which does group_by"
1531 . ' on columns other than the primary keys, while DBIC internally needs to retrieve'
1532 . ' the primary keys in a subselect. All sane RDBMS engines do not support this'
1533 . ' kind of queries. Please retry the operation with a modified group_by or'
1534 . ' without using one at all.'
1539 $attrs->{group_by} = $attrs->{columns};
1543 my $subrs = (ref $self)->new($rsrc, $attrs);
1544 return $self->result_source->storage->_subq_update_delete($subrs, $op, $values);
1547 return $rsrc->storage->$op(
1549 $op eq 'update' ? $values : (),
1559 =item Arguments: \%values
1561 =item Return Value: $storage_rv
1565 Sets the specified columns in the resultset to the supplied values in a
1566 single query. Note that this will not run any accessor/set_column/update
1567 triggers, nor will it update any row object instances derived from this
1568 resultset (this includes the contents of the L<resultset cache|/set_cache>
1569 if any). See L</update_all> if you need to execute any on-update
1570 triggers or cascades defined either by you or a
1571 L<result component|DBIx::Class::Manual::Component/WHAT_IS_A_COMPONENT>.
1573 The return value is a pass through of what the underlying
1574 storage backend returned, and may vary. See L<DBI/execute> for the most
1579 Note that L</update> does not process/deflate any of the values passed in.
1580 This is unlike the corresponding L<DBIx::Class::Row/update>. The user must
1581 ensure manually that any value passed to this method will stringify to
1582 something the RDBMS knows how to deal with. A notable example is the
1583 handling of L<DateTime> objects, for more info see:
1584 L<DBIx::Class::Manual::Cookbook/Formatting_DateTime_objects_in_queries>.
1589 my ($self, $values) = @_;
1590 $self->throw_exception('Values for update must be a hash')
1591 unless ref $values eq 'HASH';
1593 return $self->_rs_update_delete ('update', $values);
1600 =item Arguments: \%values
1602 =item Return Value: 1
1606 Fetches all objects and updates them one at a time via
1607 L<DBIx::Class::Row/update>. Note that C<update_all> will run DBIC defined
1608 triggers, while L</update> will not.
1613 my ($self, $values) = @_;
1614 $self->throw_exception('Values for update_all must be a hash')
1615 unless ref $values eq 'HASH';
1617 my $guard = $self->result_source->schema->txn_scope_guard;
1618 $_->update($values) for $self->all;
1627 =item Arguments: none
1629 =item Return Value: $storage_rv
1633 Deletes the rows matching this resultset in a single query. Note that this
1634 will not run any delete triggers, nor will it alter the
1635 L<in_storage|DBIx::Class::Row/in_storage> status of any row object instances
1636 derived from this resultset (this includes the contents of the
1637 L<resultset cache|/set_cache> if any). See L</delete_all> if you need to
1638 execute any on-delete triggers or cascades defined either by you or a
1639 L<result component|DBIx::Class::Manual::Component/WHAT_IS_A_COMPONENT>.
1641 The return value is a pass through of what the underlying storage backend
1642 returned, and may vary. See L<DBI/execute> for the most common case.
1648 $self->throw_exception('delete does not accept any arguments')
1651 return $self->_rs_update_delete ('delete');
1658 =item Arguments: none
1660 =item Return Value: 1
1664 Fetches all objects and deletes them one at a time via
1665 L<DBIx::Class::Row/delete>. Note that C<delete_all> will run DBIC defined
1666 triggers, while L</delete> will not.
1672 $self->throw_exception('delete_all does not accept any arguments')
1675 my $guard = $self->result_source->schema->txn_scope_guard;
1676 $_->delete for $self->all;
1685 =item Arguments: \@data;
1689 Accepts either an arrayref of hashrefs or alternatively an arrayref of arrayrefs.
1690 For the arrayref of hashrefs style each hashref should be a structure suitable
1691 forsubmitting to a $resultset->create(...) method.
1693 In void context, C<insert_bulk> in L<DBIx::Class::Storage::DBI> is used
1694 to insert the data, as this is a faster method.
1696 Otherwise, each set of data is inserted into the database using
1697 L<DBIx::Class::ResultSet/create>, and the resulting objects are
1698 accumulated into an array. The array itself, or an array reference
1699 is returned depending on scalar or list context.
1701 Example: Assuming an Artist Class that has many CDs Classes relating:
1703 my $Artist_rs = $schema->resultset("Artist");
1705 ## Void Context Example
1706 $Artist_rs->populate([
1707 { artistid => 4, name => 'Manufactured Crap', cds => [
1708 { title => 'My First CD', year => 2006 },
1709 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
1712 { artistid => 5, name => 'Angsty-Whiny Girl', cds => [
1713 { title => 'My parents sold me to a record company', year => 2005 },
1714 { title => 'Why Am I So Ugly?', year => 2006 },
1715 { title => 'I Got Surgery and am now Popular', year => 2007 }
1720 ## Array Context Example
1721 my ($ArtistOne, $ArtistTwo, $ArtistThree) = $Artist_rs->populate([
1722 { name => "Artist One"},
1723 { name => "Artist Two"},
1724 { name => "Artist Three", cds=> [
1725 { title => "First CD", year => 2007},
1726 { title => "Second CD", year => 2008},
1730 print $ArtistOne->name; ## response is 'Artist One'
1731 print $ArtistThree->cds->count ## reponse is '2'
1733 For the arrayref of arrayrefs style, the first element should be a list of the
1734 fieldsnames to which the remaining elements are rows being inserted. For
1737 $Arstist_rs->populate([
1738 [qw/artistid name/],
1739 [100, 'A Formally Unknown Singer'],
1740 [101, 'A singer that jumped the shark two albums ago'],
1741 [102, 'An actually cool singer'],
1744 Please note an important effect on your data when choosing between void and
1745 wantarray context. Since void context goes straight to C<insert_bulk> in
1746 L<DBIx::Class::Storage::DBI> this will skip any component that is overriding
1747 C<insert>. So if you are using something like L<DBIx-Class-UUIDColumns> to
1748 create primary keys for you, you will find that your PKs are empty. In this
1749 case you will have to use the wantarray context in order to create those
1757 # cruft placed in standalone method
1758 my $data = $self->_normalize_populate_args(@_);
1760 if(defined wantarray) {
1762 foreach my $item (@$data) {
1763 push(@created, $self->create($item));
1765 return wantarray ? @created : \@created;
1767 my $first = $data->[0];
1769 # if a column is a registered relationship, and is a non-blessed hash/array, consider
1770 # it relationship data
1771 my (@rels, @columns);
1772 for (keys %$first) {
1773 my $ref = ref $first->{$_};
1774 $self->result_source->has_relationship($_) && ($ref eq 'ARRAY' or $ref eq 'HASH')
1780 my @pks = $self->result_source->primary_columns;
1782 ## do the belongs_to relationships
1783 foreach my $index (0..$#$data) {
1785 # delegate to create() for any dataset without primary keys with specified relationships
1786 if (grep { !defined $data->[$index]->{$_} } @pks ) {
1788 if (grep { ref $data->[$index]{$r} eq $_ } qw/HASH ARRAY/) { # a related set must be a HASH or AoH
1789 my @ret = $self->populate($data);
1795 foreach my $rel (@rels) {
1796 next unless ref $data->[$index]->{$rel} eq "HASH";
1797 my $result = $self->related_resultset($rel)->create($data->[$index]->{$rel});
1798 my ($reverse) = keys %{$self->result_source->reverse_relationship_info($rel)};
1799 my $related = $result->result_source->_resolve_condition(
1800 $result->result_source->relationship_info($reverse)->{cond},
1805 delete $data->[$index]->{$rel};
1806 $data->[$index] = {%{$data->[$index]}, %$related};
1808 push @columns, keys %$related if $index == 0;
1812 ## inherit the data locked in the conditions of the resultset
1813 my ($rs_data) = $self->_merge_with_rscond({});
1814 delete @{$rs_data}{@columns};
1815 my @inherit_cols = keys %$rs_data;
1816 my @inherit_data = values %$rs_data;
1818 ## do bulk insert on current row
1819 $self->result_source->storage->insert_bulk(
1820 $self->result_source,
1821 [@columns, @inherit_cols],
1822 [ map { [ @$_{@columns}, @inherit_data ] } @$data ],
1825 ## do the has_many relationships
1826 foreach my $item (@$data) {
1828 foreach my $rel (@rels) {
1829 next unless $item->{$rel} && ref $item->{$rel} eq "ARRAY";
1831 my $parent = $self->find({map { $_ => $item->{$_} } @pks})
1832 || $self->throw_exception('Cannot find the relating object.');
1834 my $child = $parent->$rel;
1836 my $related = $child->result_source->_resolve_condition(
1837 $parent->result_source->relationship_info($rel)->{cond},
1842 my @rows_to_add = ref $item->{$rel} eq 'ARRAY' ? @{$item->{$rel}} : ($item->{$rel});
1843 my @populate = map { {%$_, %$related} } @rows_to_add;
1845 $child->populate( \@populate );
1852 # populate() argumnets went over several incarnations
1853 # What we ultimately support is AoH
1854 sub _normalize_populate_args {
1855 my ($self, $arg) = @_;
1857 if (ref $arg eq 'ARRAY') {
1858 if (ref $arg->[0] eq 'HASH') {
1861 elsif (ref $arg->[0] eq 'ARRAY') {
1863 my @colnames = @{$arg->[0]};
1864 foreach my $values (@{$arg}[1 .. $#$arg]) {
1865 push @ret, { map { $colnames[$_] => $values->[$_] } (0 .. $#colnames) };
1871 $self->throw_exception('Populate expects an arrayref of hashrefs or arrayref of arrayrefs');
1878 =item Arguments: none
1880 =item Return Value: $pager
1884 Return Value a L<Data::Page> object for the current resultset. Only makes
1885 sense for queries with a C<page> attribute.
1887 To get the full count of entries for a paged resultset, call
1888 C<total_entries> on the L<Data::Page> object.
1892 # make a wizard good for both a scalar and a hashref
1893 my $mk_lazy_count_wizard = sub {
1894 require Variable::Magic;
1896 my $stash = { total_rs => shift };
1897 my $slot = shift; # only used by the hashref magic
1899 my $magic = Variable::Magic::wizard (
1900 data => sub { $stash },
1906 # set value lazily, and dispell for good
1907 ${$_[0]} = $_[1]{total_rs}->count;
1908 Variable::Magic::dispell (${$_[0]}, $_[1]{magic_selfref});
1912 # an explicit set implies dispell as well
1913 # the unless() is to work around "fun and giggles" below
1914 Variable::Magic::dispell (${$_[0]}, $_[1]{magic_selfref})
1915 unless (caller(2))[3] eq 'DBIx::Class::ResultSet::pager';
1922 if ($_[2] eq $slot and !$_[1]{inactive}) {
1923 my $cnt = $_[1]{total_rs}->count;
1924 $_[0]->{$slot} = $cnt;
1926 # attempting to dispell in a fetch handle (works in store), seems
1927 # to invariable segfault on 5.10, 5.12, 5.13 :(
1928 # so use an inactivator instead
1929 #Variable::Magic::dispell (%{$_[0]}, $_[1]{magic_selfref});
1935 if (! $_[1]{inactive} and $_[2] eq $slot) {
1936 #Variable::Magic::dispell (%{$_[0]}, $_[1]{magic_selfref});
1938 unless (caller(2))[3] eq 'DBIx::Class::ResultSet::pager';
1945 $stash->{magic_selfref} = $magic;
1946 weaken ($stash->{magic_selfref}); # this fails on 5.8.1
1951 # the tie class for 5.8.1
1953 package # hide from pause
1954 DBIx::Class::__DBIC_LAZY_RS_COUNT__;
1955 use base qw/Tie::Hash/;
1957 sub FIRSTKEY { my $dummy = scalar keys %{$_[0]{data}}; each %{$_[0]{data}} }
1958 sub NEXTKEY { each %{$_[0]{data}} }
1959 sub EXISTS { exists $_[0]{data}{$_[1]} }
1960 sub DELETE { delete $_[0]{data}{$_[1]} }
1961 sub CLEAR { %{$_[0]{data}} = () }
1962 sub SCALAR { scalar %{$_[0]{data}} }
1965 $_[1]{data} = {%{$_[1]{selfref}}};
1966 %{$_[1]{selfref}} = ();
1967 Scalar::Util::weaken ($_[1]{selfref});
1968 return bless ($_[1], $_[0]);
1972 if ($_[1] eq $_[0]{slot}) {
1973 my $cnt = $_[0]{data}{$_[1]} = $_[0]{total_rs}->count;
1974 untie %{$_[0]{selfref}};
1975 %{$_[0]{selfref}} = %{$_[0]{data}};
1984 $_[0]{data}{$_[1]} = $_[2];
1985 if ($_[1] eq $_[0]{slot}) {
1986 untie %{$_[0]{selfref}};
1987 %{$_[0]{selfref}} = %{$_[0]{data}};
1996 return $self->{pager} if $self->{pager};
1998 if ($self->get_cache) {
1999 $self->throw_exception ('Pagers on cached resultsets are not supported');
2002 my $attrs = $self->{attrs};
2003 if (!defined $attrs->{page}) {
2004 $self->throw_exception("Can't create pager for non-paged rs");
2006 elsif ($attrs->{page} <= 0) {
2007 $self->throw_exception('Invalid page number (page-numbers are 1-based)');
2009 $attrs->{rows} ||= 10;
2011 # throw away the paging flags and re-run the count (possibly
2012 # with a subselect) to get the real total count
2013 my $count_attrs = { %$attrs };
2014 delete $count_attrs->{$_} for qw/rows offset page pager/;
2015 my $total_rs = (ref $self)->new($self->result_source, $count_attrs);
2018 ### the following may seem awkward and dirty, but it's a thought-experiment
2019 ### necessary for future development of DBIx::DS. Do *NOT* change this code
2020 ### before talking to ribasushi/mst
2022 my $pager = Data::Page->new(
2023 0, #start with an empty set
2025 $self->{attrs}{page},
2028 my $data_slot = 'total_entries';
2030 # Since we are interested in a cached value (once it's set - it's set), every
2031 # technique will detach from the magic-host once the time comes to fire the
2032 # ->count (or in the segfaulting case of >= 5.10 it will deactivate itself)
2034 if ($] < 5.008003) {
2035 # 5.8.1 throws 'Modification of a read-only value attempted' when one tries
2036 # to weakref the magic container :(
2038 tie (%$pager, 'DBIx::Class::__DBIC_LAZY_RS_COUNT__',
2039 { slot => $data_slot, total_rs => $total_rs, selfref => $pager }
2042 elsif ($] < 5.010) {
2043 # We can use magic on the hash value slot. It's interesting that the magic is
2044 # attached to the hash-slot, and does *not* stop working once I do the dummy
2045 # assignments after the cast()
2046 # tested on 5.8.3 and 5.8.9
2047 my $magic = $mk_lazy_count_wizard->($total_rs);
2048 Variable::Magic::cast ( $pager->{$data_slot}, $magic );
2050 # this is for fun and giggles
2051 $pager->{$data_slot} = -1;
2052 $pager->{$data_slot} = 0;
2054 # this does not work for scalars, but works with
2056 #my %vals = %$pager;
2061 # And the uvar magic
2062 # works on 5.10.1, 5.12.1 and 5.13.4 in its current form,
2063 # however see the wizard maker for more notes
2064 my $magic = $mk_lazy_count_wizard->($total_rs, $data_slot);
2065 Variable::Magic::cast ( %$pager, $magic );
2068 $pager->{$data_slot} = -1;
2069 $pager->{$data_slot} = 0;
2077 return $self->{pager} = $pager;
2084 =item Arguments: $page_number
2086 =item Return Value: $rs
2090 Returns a resultset for the $page_number page of the resultset on which page
2091 is called, where each page contains a number of rows equal to the 'rows'
2092 attribute set on the resultset (10 by default).
2097 my ($self, $page) = @_;
2098 return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
2105 =item Arguments: \%vals
2107 =item Return Value: $rowobject
2111 Creates a new row object in the resultset's result class and returns
2112 it. The row is not inserted into the database at this point, call
2113 L<DBIx::Class::Row/insert> to do that. Calling L<DBIx::Class::Row/in_storage>
2114 will tell you whether the row object has been inserted or not.
2116 Passes the hashref of input on to L<DBIx::Class::Row/new>.
2121 my ($self, $values) = @_;
2122 $self->throw_exception( "new_result needs a hash" )
2123 unless (ref $values eq 'HASH');
2125 my ($merged_cond, $cols_from_relations) = $self->_merge_with_rscond($values);
2129 @$cols_from_relations
2130 ? (-cols_from_relations => $cols_from_relations)
2132 -source_handle => $self->_source_handle,
2133 -result_source => $self->result_source, # DO NOT REMOVE THIS, REQUIRED
2136 return $self->result_class->new(\%new);
2139 # _merge_with_rscond
2141 # Takes a simple hash of K/V data and returns its copy merged with the
2142 # condition already present on the resultset. Additionally returns an
2143 # arrayref of value/condition names, which were inferred from related
2144 # objects (this is needed for in-memory related objects)
2145 sub _merge_with_rscond {
2146 my ($self, $data) = @_;
2148 my (%new_data, @cols_from_relations);
2150 my $alias = $self->{attrs}{alias};
2152 if (! defined $self->{cond}) {
2153 # just massage $data below
2155 elsif ($self->{cond} eq $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION) {
2156 %new_data = %{ $self->{attrs}{related_objects} || {} }; # nothing might have been inserted yet
2157 @cols_from_relations = keys %new_data;
2159 elsif (ref $self->{cond} ne 'HASH') {
2160 $self->throw_exception(
2161 "Can't abstract implicit construct, resultset condition not a hash"
2165 # precendence must be given to passed values over values inherited from
2166 # the cond, so the order here is important.
2167 my $collapsed_cond = $self->_collapse_cond($self->{cond});
2168 my %implied = %{$self->_remove_alias($collapsed_cond, $alias)};
2170 while ( my($col, $value) = each %implied ) {
2171 my $vref = ref $value;
2172 if ($vref eq 'HASH' && keys(%$value) && (keys %$value)[0] eq '=') {
2173 $new_data{$col} = $value->{'='};
2175 elsif( !$vref or $vref eq 'SCALAR' or blessed($value) ) {
2176 $new_data{$col} = $value;
2183 %{ $self->_remove_alias($data, $alias) },
2186 return (\%new_data, \@cols_from_relations);
2189 # _has_resolved_attr
2191 # determines if the resultset defines at least one
2192 # of the attributes supplied
2194 # used to determine if a subquery is neccessary
2196 # supports some virtual attributes:
2198 # This will scan for any joins being present on the resultset.
2199 # It is not a mere key-search but a deep inspection of {from}
2202 sub _has_resolved_attr {
2203 my ($self, @attr_names) = @_;
2205 my $attrs = $self->_resolved_attrs;
2209 for my $n (@attr_names) {
2210 if (grep { $n eq $_ } (qw/-join/) ) {
2211 $extra_checks{$n}++;
2215 my $attr = $attrs->{$n};
2217 next if not defined $attr;
2219 if (ref $attr eq 'HASH') {
2220 return 1 if keys %$attr;
2222 elsif (ref $attr eq 'ARRAY') {
2230 # a resolved join is expressed as a multi-level from
2232 $extra_checks{-join}
2234 ref $attrs->{from} eq 'ARRAY'
2236 @{$attrs->{from}} > 1
2244 # Recursively collapse the condition.
2246 sub _collapse_cond {
2247 my ($self, $cond, $collapsed) = @_;
2251 if (ref $cond eq 'ARRAY') {
2252 foreach my $subcond (@$cond) {
2253 next unless ref $subcond; # -or
2254 $collapsed = $self->_collapse_cond($subcond, $collapsed);
2257 elsif (ref $cond eq 'HASH') {
2258 if (keys %$cond and (keys %$cond)[0] eq '-and') {
2259 foreach my $subcond (@{$cond->{-and}}) {
2260 $collapsed = $self->_collapse_cond($subcond, $collapsed);
2264 foreach my $col (keys %$cond) {
2265 my $value = $cond->{$col};
2266 $collapsed->{$col} = $value;
2276 # Remove the specified alias from the specified query hash. A copy is made so
2277 # the original query is not modified.
2280 my ($self, $query, $alias) = @_;
2282 my %orig = %{ $query || {} };
2285 foreach my $key (keys %orig) {
2287 $unaliased{$key} = $orig{$key};
2290 $unaliased{$1} = $orig{$key}
2291 if $key =~ m/^(?:\Q$alias\E\.)?([^.]+)$/;
2301 =item Arguments: none
2303 =item Return Value: \[ $sql, @bind ]
2307 Returns the SQL query and bind vars associated with the invocant.
2309 This is generally used as the RHS for a subquery.
2316 my $attrs = $self->_resolved_attrs_copy;
2321 # my ($sql, \@bind, \%dbi_bind_attrs) = _select_args_to_query (...)
2322 # $sql also has no wrapping parenthesis in list ctx
2324 my $sqlbind = $self->result_source->storage
2325 ->_select_args_to_query ($attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs);
2334 =item Arguments: \%vals, \%attrs?
2336 =item Return Value: $rowobject
2340 my $artist = $schema->resultset('Artist')->find_or_new(
2341 { artist => 'fred' }, { key => 'artists' });
2343 $cd->cd_to_producer->find_or_new({ producer => $producer },
2344 { key => 'primary });
2346 Find an existing record from this resultset using L</find>. if none exists,
2347 instantiate a new result object and return it. The object will not be saved
2348 into your storage until you call L<DBIx::Class::Row/insert> on it.
2350 You most likely want this method when looking for existing rows using a unique
2351 constraint that is not the primary key, or looking for related rows.
2353 If you want objects to be saved immediately, use L</find_or_create> instead.
2355 B<Note>: Make sure to read the documentation of L</find> and understand the
2356 significance of the C<key> attribute, as its lack may skew your search, and
2357 subsequently result in spurious new objects.
2359 B<Note>: Take care when using C<find_or_new> with a table having
2360 columns with default values that you intend to be automatically
2361 supplied by the database (e.g. an auto_increment primary key column).
2362 In normal usage, the value of such columns should NOT be included at
2363 all in the call to C<find_or_new>, even when set to C<undef>.
2369 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2370 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
2371 if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2374 return $self->new_result($hash);
2381 =item Arguments: \%vals
2383 =item Return Value: a L<DBIx::Class::Row> $object
2387 Attempt to create a single new row or a row with multiple related rows
2388 in the table represented by the resultset (and related tables). This
2389 will not check for duplicate rows before inserting, use
2390 L</find_or_create> to do that.
2392 To create one row for this resultset, pass a hashref of key/value
2393 pairs representing the columns of the table and the values you wish to
2394 store. If the appropriate relationships are set up, foreign key fields
2395 can also be passed an object representing the foreign row, and the
2396 value will be set to its primary key.
2398 To create related objects, pass a hashref of related-object column values
2399 B<keyed on the relationship name>. If the relationship is of type C<multi>
2400 (L<DBIx::Class::Relationship/has_many>) - pass an arrayref of hashrefs.
2401 The process will correctly identify columns holding foreign keys, and will
2402 transparently populate them from the keys of the corresponding relation.
2403 This can be applied recursively, and will work correctly for a structure
2404 with an arbitrary depth and width, as long as the relationships actually
2405 exists and the correct column data has been supplied.
2408 Instead of hashrefs of plain related data (key/value pairs), you may
2409 also pass new or inserted objects. New objects (not inserted yet, see
2410 L</new>), will be inserted into their appropriate tables.
2412 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
2414 Example of creating a new row.
2416 $person_rs->create({
2417 name=>"Some Person",
2418 email=>"somebody@someplace.com"
2421 Example of creating a new row and also creating rows in a related C<has_many>
2422 or C<has_one> resultset. Note Arrayref.
2425 { artistid => 4, name => 'Manufactured Crap', cds => [
2426 { title => 'My First CD', year => 2006 },
2427 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
2432 Example of creating a new row and also creating a row in a related
2433 C<belongs_to> resultset. Note Hashref.
2436 title=>"Music for Silly Walks",
2439 name=>"Silly Musician",
2447 When subclassing ResultSet never attempt to override this method. Since
2448 it is a simple shortcut for C<< $self->new_result($attrs)->insert >>, a
2449 lot of the internals simply never call it, so your override will be
2450 bypassed more often than not. Override either L<new|DBIx::Class::Row/new>
2451 or L<insert|DBIx::Class::Row/insert> depending on how early in the
2452 L</create> process you need to intervene.
2459 my ($self, $attrs) = @_;
2460 $self->throw_exception( "create needs a hashref" )
2461 unless ref $attrs eq 'HASH';
2462 return $self->new_result($attrs)->insert;
2465 =head2 find_or_create
2469 =item Arguments: \%vals, \%attrs?
2471 =item Return Value: $rowobject
2475 $cd->cd_to_producer->find_or_create({ producer => $producer },
2476 { key => 'primary' });
2478 Tries to find a record based on its primary key or unique constraints; if none
2479 is found, creates one and returns that instead.
2481 my $cd = $schema->resultset('CD')->find_or_create({
2483 artist => 'Massive Attack',
2484 title => 'Mezzanine',
2488 Also takes an optional C<key> attribute, to search by a specific key or unique
2489 constraint. For example:
2491 my $cd = $schema->resultset('CD')->find_or_create(
2493 artist => 'Massive Attack',
2494 title => 'Mezzanine',
2496 { key => 'cd_artist_title' }
2499 B<Note>: Make sure to read the documentation of L</find> and understand the
2500 significance of the C<key> attribute, as its lack may skew your search, and
2501 subsequently result in spurious row creation.
2503 B<Note>: Because find_or_create() reads from the database and then
2504 possibly inserts based on the result, this method is subject to a race
2505 condition. Another process could create a record in the table after
2506 the find has completed and before the create has started. To avoid
2507 this problem, use find_or_create() inside a transaction.
2509 B<Note>: Take care when using C<find_or_create> with a table having
2510 columns with default values that you intend to be automatically
2511 supplied by the database (e.g. an auto_increment primary key column).
2512 In normal usage, the value of such columns should NOT be included at
2513 all in the call to C<find_or_create>, even when set to C<undef>.
2515 See also L</find> and L</update_or_create>. For information on how to declare
2516 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2520 sub find_or_create {
2522 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2523 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
2524 if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2527 return $self->create($hash);
2530 =head2 update_or_create
2534 =item Arguments: \%col_values, { key => $unique_constraint }?
2536 =item Return Value: $row_object
2540 $resultset->update_or_create({ col => $val, ... });
2542 Like L</find_or_create>, but if a row is found it is immediately updated via
2543 C<< $found_row->update (\%col_values) >>.
2546 Takes an optional C<key> attribute to search on a specific unique constraint.
2549 # In your application
2550 my $cd = $schema->resultset('CD')->update_or_create(
2552 artist => 'Massive Attack',
2553 title => 'Mezzanine',
2556 { key => 'cd_artist_title' }
2559 $cd->cd_to_producer->update_or_create({
2560 producer => $producer,
2566 B<Note>: Make sure to read the documentation of L</find> and understand the
2567 significance of the C<key> attribute, as its lack may skew your search, and
2568 subsequently result in spurious row creation.
2570 B<Note>: Take care when using C<update_or_create> with a table having
2571 columns with default values that you intend to be automatically
2572 supplied by the database (e.g. an auto_increment primary key column).
2573 In normal usage, the value of such columns should NOT be included at
2574 all in the call to C<update_or_create>, even when set to C<undef>.
2576 See also L</find> and L</find_or_create>. For information on how to declare
2577 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2581 sub update_or_create {
2583 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2584 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
2586 my $row = $self->find($cond, $attrs);
2588 $row->update($cond);
2592 return $self->create($cond);
2595 =head2 update_or_new
2599 =item Arguments: \%col_values, { key => $unique_constraint }?
2601 =item Return Value: $rowobject
2605 $resultset->update_or_new({ col => $val, ... });
2607 Like L</find_or_new> but if a row is found it is immediately updated via
2608 C<< $found_row->update (\%col_values) >>.
2612 # In your application
2613 my $cd = $schema->resultset('CD')->update_or_new(
2615 artist => 'Massive Attack',
2616 title => 'Mezzanine',
2619 { key => 'cd_artist_title' }
2622 if ($cd->in_storage) {
2623 # the cd was updated
2626 # the cd is not yet in the database, let's insert it
2630 B<Note>: Make sure to read the documentation of L</find> and understand the
2631 significance of the C<key> attribute, as its lack may skew your search, and
2632 subsequently result in spurious new objects.
2634 B<Note>: Take care when using C<update_or_new> with a table having
2635 columns with default values that you intend to be automatically
2636 supplied by the database (e.g. an auto_increment primary key column).
2637 In normal usage, the value of such columns should NOT be included at
2638 all in the call to C<update_or_new>, even when set to C<undef>.
2640 See also L</find>, L</find_or_create> and L</find_or_new>.
2646 my $attrs = ( @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {} );
2647 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
2649 my $row = $self->find( $cond, $attrs );
2650 if ( defined $row ) {
2651 $row->update($cond);
2655 return $self->new_result($cond);
2662 =item Arguments: none
2664 =item Return Value: \@cache_objects | undef
2668 Gets the contents of the cache for the resultset, if the cache is set.
2670 The cache is populated either by using the L</prefetch> attribute to
2671 L</search> or by calling L</set_cache>.
2683 =item Arguments: \@cache_objects
2685 =item Return Value: \@cache_objects
2689 Sets the contents of the cache for the resultset. Expects an arrayref
2690 of objects of the same class as those produced by the resultset. Note that
2691 if the cache is set the resultset will return the cached objects rather
2692 than re-querying the database even if the cache attr is not set.
2694 The contents of the cache can also be populated by using the
2695 L</prefetch> attribute to L</search>.
2700 my ( $self, $data ) = @_;
2701 $self->throw_exception("set_cache requires an arrayref")
2702 if defined($data) && (ref $data ne 'ARRAY');
2703 $self->{all_cache} = $data;
2710 =item Arguments: none
2712 =item Return Value: undef
2716 Clears the cache for the resultset.
2721 shift->set_cache(undef);
2728 =item Arguments: none
2730 =item Return Value: true, if the resultset has been paginated
2738 return !!$self->{attrs}{page};
2745 =item Arguments: none
2747 =item Return Value: true, if the resultset has been ordered with C<order_by>.
2755 return scalar $self->result_source->storage->_extract_order_criteria($self->{attrs}{order_by});
2758 =head2 related_resultset
2762 =item Arguments: $relationship_name
2764 =item Return Value: $resultset
2768 Returns a related resultset for the supplied relationship name.
2770 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
2774 sub related_resultset {
2775 my ($self, $rel) = @_;
2777 $self->{related_resultsets} ||= {};
2778 return $self->{related_resultsets}{$rel} ||= do {
2779 my $rsrc = $self->result_source;
2780 my $rel_info = $rsrc->relationship_info($rel);
2782 $self->throw_exception(
2783 "search_related: result source '" . $rsrc->source_name .
2784 "' has no such relationship $rel")
2787 my $attrs = $self->_chain_relationship($rel);
2789 my $join_count = $attrs->{seen_join}{$rel};
2791 my $alias = $self->result_source->storage
2792 ->relname_to_table_alias($rel, $join_count);
2794 # since this is search_related, and we already slid the select window inwards
2795 # (the select/as attrs were deleted in the beginning), we need to flip all
2796 # left joins to inner, so we get the expected results
2797 # read the comment on top of the actual function to see what this does
2798 $attrs->{from} = $rsrc->schema->storage->_inner_join_to_node ($attrs->{from}, $alias);
2801 #XXX - temp fix for result_class bug. There likely is a more elegant fix -groditi
2802 delete @{$attrs}{qw(result_class alias)};
2806 if (my $cache = $self->get_cache) {
2807 if ($cache->[0] && $cache->[0]->related_resultset($rel)->get_cache) {
2808 $new_cache = [ map { @{$_->related_resultset($rel)->get_cache} }
2813 my $rel_source = $rsrc->related_source($rel);
2817 # The reason we do this now instead of passing the alias to the
2818 # search_rs below is that if you wrap/overload resultset on the
2819 # source you need to know what alias it's -going- to have for things
2820 # to work sanely (e.g. RestrictWithObject wants to be able to add
2821 # extra query restrictions, and these may need to be $alias.)
2823 my $rel_attrs = $rel_source->resultset_attributes;
2824 local $rel_attrs->{alias} = $alias;
2826 $rel_source->resultset
2830 where => $attrs->{where},
2833 $new->set_cache($new_cache) if $new_cache;
2838 =head2 current_source_alias
2842 =item Arguments: none
2844 =item Return Value: $source_alias
2848 Returns the current table alias for the result source this resultset is built
2849 on, that will be used in the SQL query. Usually it is C<me>.
2851 Currently the source alias that refers to the result set returned by a
2852 L</search>/L</find> family method depends on how you got to the resultset: it's
2853 C<me> by default, but eg. L</search_related> aliases it to the related result
2854 source name (and keeps C<me> referring to the original result set). The long
2855 term goal is to make L<DBIx::Class> always alias the current resultset as C<me>
2856 (and make this method unnecessary).
2858 Thus it's currently necessary to use this method in predefined queries (see
2859 L<DBIx::Class::Manual::Cookbook/Predefined searches>) when referring to the
2860 source alias of the current result set:
2862 # in a result set class
2864 my ($self, $user) = @_;
2866 my $me = $self->current_source_alias;
2868 return $self->search(
2869 "$me.modified" => $user->id,
2875 sub current_source_alias {
2878 return ($self->{attrs} || {})->{alias} || 'me';
2881 =head2 as_subselect_rs
2885 =item Arguments: none
2887 =item Return Value: $resultset
2891 Act as a barrier to SQL symbols. The resultset provided will be made into a
2892 "virtual view" by including it as a subquery within the from clause. From this
2893 point on, any joined tables are inaccessible to ->search on the resultset (as if
2894 it were simply where-filtered without joins). For example:
2896 my $rs = $schema->resultset('Bar')->search({'x.name' => 'abc'},{ join => 'x' });
2898 # 'x' now pollutes the query namespace
2900 # So the following works as expected
2901 my $ok_rs = $rs->search({'x.other' => 1});
2903 # But this doesn't: instead of finding a 'Bar' related to two x rows (abc and
2904 # def) we look for one row with contradictory terms and join in another table
2905 # (aliased 'x_2') which we never use
2906 my $broken_rs = $rs->search({'x.name' => 'def'});
2908 my $rs2 = $rs->as_subselect_rs;
2910 # doesn't work - 'x' is no longer accessible in $rs2, having been sealed away
2911 my $not_joined_rs = $rs2->search({'x.other' => 1});
2913 # works as expected: finds a 'table' row related to two x rows (abc and def)
2914 my $correctly_joined_rs = $rs2->search({'x.name' => 'def'});
2916 Another example of when one might use this would be to select a subset of
2917 columns in a group by clause:
2919 my $rs = $schema->resultset('Bar')->search(undef, {
2920 group_by => [qw{ id foo_id baz_id }],
2921 })->as_subselect_rs->search(undef, {
2922 columns => [qw{ id foo_id }]
2925 In the above example normally columns would have to be equal to the group by,
2926 but because we isolated the group by into a subselect the above works.
2930 sub as_subselect_rs {
2933 my $attrs = $self->_resolved_attrs;
2935 my $fresh_rs = (ref $self)->new (
2936 $self->result_source
2939 # these pieces will be locked in the subquery
2940 delete $fresh_rs->{cond};
2941 delete @{$fresh_rs->{attrs}}{qw/where bind/};
2943 return $fresh_rs->search( {}, {
2945 $attrs->{alias} => $self->as_query,
2946 -alias => $attrs->{alias},
2947 -source_handle => $self->result_source->handle,
2949 alias => $attrs->{alias},
2953 # This code is called by search_related, and makes sure there
2954 # is clear separation between the joins before, during, and
2955 # after the relationship. This information is needed later
2956 # in order to properly resolve prefetch aliases (any alias
2957 # with a relation_chain_depth less than the depth of the
2958 # current prefetch is not considered)
2960 # The increments happen twice per join. An even number means a
2961 # relationship specified via a search_related, whereas an odd
2962 # number indicates a join/prefetch added via attributes
2964 # Also this code will wrap the current resultset (the one we
2965 # chain to) in a subselect IFF it contains limiting attributes
2966 sub _chain_relationship {
2967 my ($self, $rel) = @_;
2968 my $source = $self->result_source;
2969 my $attrs = { %{$self->{attrs}||{}} };
2971 # we need to take the prefetch the attrs into account before we
2972 # ->_resolve_join as otherwise they get lost - captainL
2973 my $join = $self->_merge_joinpref_attr( $attrs->{join}, $attrs->{prefetch} );
2975 delete @{$attrs}{qw/join prefetch collapse group_by distinct select as columns +select +as +columns/};
2977 my $seen = { %{ (delete $attrs->{seen_join}) || {} } };
2980 my @force_subq_attrs = qw/offset rows group_by having/;
2983 ($attrs->{from} && ref $attrs->{from} ne 'ARRAY')
2985 $self->_has_resolved_attr (@force_subq_attrs)
2987 # Nuke the prefetch (if any) before the new $rs attrs
2988 # are resolved (prefetch is useless - we are wrapping
2989 # a subquery anyway).
2990 my $rs_copy = $self->search;
2991 $rs_copy->{attrs}{join} = $self->_merge_joinpref_attr (
2992 $rs_copy->{attrs}{join},
2993 delete $rs_copy->{attrs}{prefetch},
2997 -source_handle => $source->handle,
2998 -alias => $attrs->{alias},
2999 $attrs->{alias} => $rs_copy->as_query,
3001 delete @{$attrs}{@force_subq_attrs, qw/where bind/};
3002 $seen->{-relation_chain_depth} = 0;
3004 elsif ($attrs->{from}) { #shallow copy suffices
3005 $from = [ @{$attrs->{from}} ];
3009 -source_handle => $source->handle,
3010 -alias => $attrs->{alias},
3011 $attrs->{alias} => $source->from,
3015 my $jpath = ($seen->{-relation_chain_depth})
3016 ? $from->[-1][0]{-join_path}
3019 my @requested_joins = $source->_resolve_join(
3026 push @$from, @requested_joins;
3028 $seen->{-relation_chain_depth}++;
3030 # if $self already had a join/prefetch specified on it, the requested
3031 # $rel might very well be already included. What we do in this case
3032 # is effectively a no-op (except that we bump up the chain_depth on
3033 # the join in question so we could tell it *is* the search_related)
3036 # we consider the last one thus reverse
3037 for my $j (reverse @requested_joins) {
3038 my ($last_j) = keys %{$j->[0]{-join_path}[-1]};
3039 if ($rel eq $last_j) {
3040 $j->[0]{-relation_chain_depth}++;
3046 unless ($already_joined) {
3047 push @$from, $source->_resolve_join(
3055 $seen->{-relation_chain_depth}++;
3057 return {%$attrs, from => $from, seen_join => $seen};
3060 # too many times we have to do $attrs = { %{$self->_resolved_attrs} }
3061 sub _resolved_attrs_copy {
3063 return { %{$self->_resolved_attrs (@_)} };
3066 sub _resolved_attrs {
3068 return $self->{_attrs} if $self->{_attrs};
3070 my $attrs = { %{ $self->{attrs} || {} } };
3071 my $source = $self->result_source;
3072 my $alias = $attrs->{alias};
3075 # resolve selectors, this one is quite hairy
3077 my $selection_pieces;
3079 $attrs->{columns} ||= delete $attrs->{cols}
3080 if exists $attrs->{cols};
3082 # disassemble columns / +columns
3084 $selection_pieces->{columns}{select},
3085 $selection_pieces->{columns}{as},
3086 $selection_pieces->{'+columns'}{select},
3087 $selection_pieces->{'+columns'}{as},
3092 for my $colbit (@$_) {
3094 if (ref $colbit eq 'HASH') {
3095 for my $as (keys %$colbit) {
3096 push @sel, $colbit->{$as};
3109 (ref $attrs->{columns} eq 'ARRAY' ? delete $attrs->{columns} : [ delete $attrs->{columns} ]),
3110 # include_columns is a legacy add-on to +columns
3111 [ map { ref $_ eq 'ARRAY' ? @$_ : ($_ || () ) } delete @{$attrs}{qw/+columns include_columns/} ] )
3114 # make copies of select/as and +select/+as
3116 $selection_pieces->{'select/as'}{select},
3117 $selection_pieces->{'select/as'}{as},
3118 $selection_pieces->{'+select/+as'}{select},
3119 $selection_pieces->{'+select/+as'}{as},
3121 { $_ ? [ ref $_ eq 'ARRAY' ? @$_ : $_ ] : [] }
3122 ( delete @{$attrs}{qw/select as +select +as/} )
3125 # default to * only when neither no non-plus selectors are available
3127 ! @{$selection_pieces->{'select/as'}{select}}
3129 ! @{$selection_pieces->{'columns'}{select}}
3131 for ($source->columns) {
3132 push @{$selection_pieces->{'select/as'}{select}}, $_;
3133 push @{$selection_pieces->{'select/as'}{as}}, $_;
3137 # final composition order (important)
3138 my @sel_pairs = grep {
3139 $selection_pieces->{$_}
3142 ( $selection_pieces->{$_}{select} && @{$selection_pieces->{$_}{select}} )
3144 ( $selection_pieces->{$_}{as} && @{$selection_pieces->{$_}{as}} )
3146 } qw|columns select/as +columns +select/+as|;
3148 # fill in missing as bits for each pair
3149 # if it's the last pair we can let things slide ( bare +select is sadly popular)
3152 for my $i (0 .. $#sel_pairs) {
3154 my $pairname = $sel_pairs[$i];
3156 my ($sel, $as) = @{$selection_pieces->{$pairname}}{qw/select as/};
3158 $self->throw_exception(
3159 "Unable to assemble final selection list: $pairname specified in addition to unbalanced $sel_pairs[$i-1]"
3160 ) if ($out_of_sync);
3162 if (@$sel == @$as) {
3165 elsif (@$sel < @$as) {
3166 $self->throw_exception(
3167 "More 'as' elements than 'select' elements for $pairname, unable to continue"
3171 # try to deduce the 'as' part, will work only if all the selectors are "plain", or contain an explicit -as
3172 # if we can not deduce something - stop right there and leave the rest of the selector un-as'ed
3173 # if there is an extra selection pair coming after that - it will die due to out_of_sync being set
3174 for my $j ($#$as+1 .. $#$sel) {
3175 if (my $ref = ref $sel->[$j]) {
3176 if ($ref eq 'HASH' and exists $sel->[$j]{-as}) {
3177 push @$as, $sel->[$j]{-as};
3185 push @$as, $sel->[$j];
3191 # assume all unqualified selectors to apply to the current alias (legacy stuff)
3192 # disqualify all $alias.col as-bits (collapser mandated)
3193 for (values %$selection_pieces) {
3194 $_->{select} = [ map { (ref $_ or $_ =~ /\./) ? $_ : "$alias.$_" } @{$_->{select}} ];
3195 $_->{as} = [ map { $_ =~ /^\Q$alias.\E(.+)$/ ? $1 : $_ } @{$_->{as}} ];
3200 $attrs->{select} = $self->_merge_attr ($attrs->{select}, $selection_pieces->{$_}{select});
3201 $attrs->{as} = $self->_merge_attr ($attrs->{as}, $selection_pieces->{$_}{as});
3204 # de-duplicate the result (remove *identical* select/as pairs)
3205 # and also die on duplicate {as} pointing to different {select}s
3206 # not using a c-style for as the condition is prone to shrinkage
3209 while ($i <= $#{$attrs->{as}} ) {
3210 my ($sel, $as) = map { $attrs->{$_}[$i] } (qw/select as/);
3212 if ($seen->{"$sel \x00\x00 $as"}++) {
3214 for @{$attrs}{qw/select as/};
3216 elsif ($seen->{$as}++) {
3217 $self->throw_exception(
3218 "inflate_result() alias '$as' specified twice with different SQL-side {select}-ors"
3226 ## selector resolution done
3230 $attrs->{from} ||= [{
3231 -source_handle => $source->handle,
3232 -alias => $self->{attrs}{alias},
3233 $self->{attrs}{alias} => $source->from,
3236 if ( $attrs->{join} || $attrs->{prefetch} ) {
3238 $self->throw_exception ('join/prefetch can not be used with a custom {from}')
3239 if ref $attrs->{from} ne 'ARRAY';
3241 my $join = delete $attrs->{join} || {};
3243 if ( defined $attrs->{prefetch} ) {
3244 $join = $self->_merge_joinpref_attr( $join, $attrs->{prefetch} );
3247 $attrs->{from} = # have to copy here to avoid corrupting the original
3249 @{ $attrs->{from} },
3250 $source->_resolve_join(
3253 { %{ $attrs->{seen_join} || {} } },
3254 ( $attrs->{seen_join} && keys %{$attrs->{seen_join}})
3255 ? $attrs->{from}[-1][0]{-join_path}
3262 if ( defined $attrs->{order_by} ) {
3263 $attrs->{order_by} = (
3264 ref( $attrs->{order_by} ) eq 'ARRAY'
3265 ? [ @{ $attrs->{order_by} } ]
3266 : [ $attrs->{order_by} || () ]
3270 if ($attrs->{group_by} and ref $attrs->{group_by} ne 'ARRAY') {
3271 $attrs->{group_by} = [ $attrs->{group_by} ];
3274 # generate the distinct induced group_by early, as prefetch will be carried via a
3275 # subquery (since a group_by is present)
3276 if (delete $attrs->{distinct}) {
3277 if ($attrs->{group_by}) {
3278 carp ("Useless use of distinct on a grouped resultset ('distinct' is ignored when a 'group_by' is present)");
3281 $attrs->{group_by} = $source->storage->_group_over_selection (
3282 @{$attrs}{qw/from select order_by/}
3287 $attrs->{collapse} ||= {};
3288 if ( my $prefetch = delete $attrs->{prefetch} ) {
3289 $prefetch = $self->_merge_joinpref_attr( {}, $prefetch );
3291 my $prefetch_ordering = [];
3293 # this is a separate structure (we don't look in {from} directly)
3294 # as the resolver needs to shift things off the lists to work
3295 # properly (identical-prefetches on different branches)
3297 if (ref $attrs->{from} eq 'ARRAY') {
3299 my $start_depth = $attrs->{seen_join}{-relation_chain_depth} || 0;
3301 for my $j ( @{$attrs->{from}}[1 .. $#{$attrs->{from}} ] ) {
3302 next unless $j->[0]{-alias};
3303 next unless $j->[0]{-join_path};
3304 next if ($j->[0]{-relation_chain_depth} || 0) < $start_depth;
3306 my @jpath = map { keys %$_ } @{$j->[0]{-join_path}};
3309 $p = $p->{$_} ||= {} for @jpath[ ($start_depth/2) .. $#jpath]; #only even depths are actual jpath boundaries
3310 push @{$p->{-join_aliases} }, $j->[0]{-alias};
3315 $source->_resolve_prefetch( $prefetch, $alias, $join_map, $prefetch_ordering, $attrs->{collapse} );
3317 # we need to somehow mark which columns came from prefetch
3318 $attrs->{_prefetch_select} = [ map { $_->[0] } @prefetch ];
3320 push @{ $attrs->{select} }, @{$attrs->{_prefetch_select}};
3321 push @{ $attrs->{as} }, (map { $_->[1] } @prefetch);
3323 push( @{$attrs->{order_by}}, @$prefetch_ordering );
3324 $attrs->{_collapse_order_by} = \@$prefetch_ordering;
3327 # if both page and offset are specified, produce a combined offset
3328 # even though it doesn't make much sense, this is what pre 081xx has
3330 if (my $page = delete $attrs->{page}) {
3332 ($attrs->{rows} * ($page - 1))
3334 ($attrs->{offset} || 0)
3338 return $self->{_attrs} = $attrs;
3342 my ($self, $attr) = @_;
3344 if (ref $attr eq 'HASH') {
3345 return $self->_rollout_hash($attr);
3346 } elsif (ref $attr eq 'ARRAY') {
3347 return $self->_rollout_array($attr);
3353 sub _rollout_array {
3354 my ($self, $attr) = @_;
3357 foreach my $element (@{$attr}) {
3358 if (ref $element eq 'HASH') {
3359 push( @rolled_array, @{ $self->_rollout_hash( $element ) } );
3360 } elsif (ref $element eq 'ARRAY') {
3361 # XXX - should probably recurse here
3362 push( @rolled_array, @{$self->_rollout_array($element)} );
3364 push( @rolled_array, $element );
3367 return \@rolled_array;
3371 my ($self, $attr) = @_;
3374 foreach my $key (keys %{$attr}) {
3375 push( @rolled_array, { $key => $attr->{$key} } );
3377 return \@rolled_array;
3380 sub _calculate_score {
3381 my ($self, $a, $b) = @_;
3383 if (defined $a xor defined $b) {
3386 elsif (not defined $a) {
3390 if (ref $b eq 'HASH') {
3391 my ($b_key) = keys %{$b};
3392 if (ref $a eq 'HASH') {
3393 my ($a_key) = keys %{$a};
3394 if ($a_key eq $b_key) {
3395 return (1 + $self->_calculate_score( $a->{$a_key}, $b->{$b_key} ));
3400 return ($a eq $b_key) ? 1 : 0;
3403 if (ref $a eq 'HASH') {
3404 my ($a_key) = keys %{$a};
3405 return ($b eq $a_key) ? 1 : 0;
3407 return ($b eq $a) ? 1 : 0;
3412 sub _merge_joinpref_attr {
3413 my ($self, $orig, $import) = @_;
3415 return $import unless defined($orig);
3416 return $orig unless defined($import);
3418 $orig = $self->_rollout_attr($orig);
3419 $import = $self->_rollout_attr($import);
3422 foreach my $import_element ( @{$import} ) {
3423 # find best candidate from $orig to merge $b_element into
3424 my $best_candidate = { position => undef, score => 0 }; my $position = 0;
3425 foreach my $orig_element ( @{$orig} ) {
3426 my $score = $self->_calculate_score( $orig_element, $import_element );
3427 if ($score > $best_candidate->{score}) {
3428 $best_candidate->{position} = $position;
3429 $best_candidate->{score} = $score;
3433 my ($import_key) = ( ref $import_element eq 'HASH' ) ? keys %{$import_element} : ($import_element);
3435 if ($best_candidate->{score} == 0 || exists $seen_keys->{$import_key}) {
3436 push( @{$orig}, $import_element );
3438 my $orig_best = $orig->[$best_candidate->{position}];
3439 # merge orig_best and b_element together and replace original with merged
3440 if (ref $orig_best ne 'HASH') {
3441 $orig->[$best_candidate->{position}] = $import_element;
3442 } elsif (ref $import_element eq 'HASH') {
3443 my ($key) = keys %{$orig_best};
3444 $orig->[$best_candidate->{position}] = { $key => $self->_merge_joinpref_attr($orig_best->{$key}, $import_element->{$key}) };
3447 $seen_keys->{$import_key} = 1; # don't merge the same key twice
3458 my $hm = Hash::Merge->new;
3460 $hm->specify_behavior({
3463 my ($defl, $defr) = map { defined $_ } (@_[0,1]);
3465 if ($defl xor $defr) {
3466 return $defl ? $_[0] : $_[1];
3471 elsif (__HM_DEDUP and $_[0] eq $_[1]) {
3475 return [$_[0], $_[1]];
3479 return $_[1] if !defined $_[0];
3480 return $_[1] if __HM_DEDUP and List::Util::first { $_ eq $_[0] } @{$_[1]};
3481 return [$_[0], @{$_[1]}]
3484 return $_[1] if !defined $_[0];
3485 return $_[0] if !keys %{$_[1]};
3486 return [$_[0], $_[1]]
3491 return $_[0] if !defined $_[1];
3492 return $_[0] if __HM_DEDUP and List::Util::first { $_ eq $_[1] } @{$_[0]};
3493 return [@{$_[0]}, $_[1]]
3496 my @ret = @{$_[0]} or return $_[1];
3497 return [ @ret, @{$_[1]} ] unless __HM_DEDUP;
3498 my %idx = map { $_ => 1 } @ret;
3499 push @ret, grep { ! defined $idx{$_} } (@{$_[1]});
3503 return [ $_[1] ] if ! @{$_[0]};
3504 return $_[0] if !keys %{$_[1]};
3505 return $_[0] if __HM_DEDUP and List::Util::first { $_ eq $_[1] } @{$_[0]};
3506 return [ @{$_[0]}, $_[1] ];
3511 return $_[0] if !defined $_[1];
3512 return $_[1] if !keys %{$_[0]};
3513 return [$_[0], $_[1]]
3516 return $_[0] if !@{$_[1]};
3517 return $_[1] if !keys %{$_[0]};
3518 return $_[1] if __HM_DEDUP and List::Util::first { $_ eq $_[0] } @{$_[1]};
3519 return [ $_[0], @{$_[1]} ];
3522 return $_[0] if !keys %{$_[1]};
3523 return $_[1] if !keys %{$_[0]};
3524 return $_[0] if $_[0] eq $_[1];
3525 return [ $_[0], $_[1] ];
3528 } => 'DBIC_RS_ATTR_MERGER');
3532 return $hm->merge ($_[1], $_[2]);
3540 $self->_source_handle($_[0]->handle);
3542 $self->_source_handle->resolve;
3547 sub STORABLE_freeze {
3548 my ($self, $cloning) = @_;
3549 my $to_serialize = { %$self };
3551 # A cursor in progress can't be serialized (and would make little sense anyway)
3552 delete $to_serialize->{cursor};
3554 return nfreeze($to_serialize);
3557 # need this hook for symmetry
3559 my ($self, $cloning, $serialized) = @_;
3561 %$self = %{ thaw($serialized) };
3567 =head2 throw_exception
3569 See L<DBIx::Class::Schema/throw_exception> for details.
3573 sub throw_exception {
3576 if (ref $self && $self->_source_handle->schema) {
3577 $self->_source_handle->schema->throw_exception(@_)
3580 DBIx::Class::Exception->throw(@_);
3584 # XXX: FIXME: Attributes docs need clearing up
3588 Attributes are used to refine a ResultSet in various ways when
3589 searching for data. They can be passed to any method which takes an
3590 C<\%attrs> argument. See L</search>, L</search_rs>, L</find>,
3593 These are in no particular order:
3599 =item Value: ( $order_by | \@order_by | \%order_by )
3603 Which column(s) to order the results by.
3605 [The full list of suitable values is documented in
3606 L<SQL::Abstract/"ORDER BY CLAUSES">; the following is a summary of
3609 If a single column name, or an arrayref of names is supplied, the
3610 argument is passed through directly to SQL. The hashref syntax allows
3611 for connection-agnostic specification of ordering direction:
3613 For descending order:
3615 order_by => { -desc => [qw/col1 col2 col3/] }
3617 For explicit ascending order:
3619 order_by => { -asc => 'col' }
3621 The old scalarref syntax (i.e. order_by => \'year DESC') is still
3622 supported, although you are strongly encouraged to use the hashref
3623 syntax as outlined above.
3629 =item Value: \@columns
3633 Shortcut to request a particular set of columns to be retrieved. Each
3634 column spec may be a string (a table column name), or a hash (in which
3635 case the key is the C<as> value, and the value is used as the C<select>
3636 expression). Adds C<me.> onto the start of any column without a C<.> in
3637 it and sets C<select> from that, then auto-populates C<as> from
3638 C<select> as normal. (You may also use the C<cols> attribute, as in
3639 earlier versions of DBIC.)
3641 Essentially C<columns> does the same as L</select> and L</as>.
3643 columns => [ 'foo', { bar => 'baz' } ]
3647 select => [qw/foo baz/],
3654 =item Value: \@columns
3658 Indicates additional columns to be selected from storage. Works the same
3659 as L</columns> but adds columns to the selection. (You may also use the
3660 C<include_columns> attribute, as in earlier versions of DBIC). For
3663 $schema->resultset('CD')->search(undef, {
3664 '+columns' => ['artist.name'],
3668 would return all CDs and include a 'name' column to the information
3669 passed to object inflation. Note that the 'artist' is the name of the
3670 column (or relationship) accessor, and 'name' is the name of the column
3671 accessor in the related table.
3673 =head2 include_columns
3677 =item Value: \@columns
3681 Deprecated. Acts as a synonym for L</+columns> for backward compatibility.
3687 =item Value: \@select_columns
3691 Indicates which columns should be selected from the storage. You can use
3692 column names, or in the case of RDBMS back ends, function or stored procedure
3695 $rs = $schema->resultset('Employee')->search(undef, {
3698 { count => 'employeeid' },
3699 { max => { length => 'name' }, -as => 'longest_name' }
3704 SELECT name, COUNT( employeeid ), MAX( LENGTH( name ) ) AS longest_name FROM employee
3706 B<NOTE:> You will almost always need a corresponding L</as> attribute when you
3707 use L</select>, to instruct DBIx::Class how to store the result of the column.
3708 Also note that the L</as> attribute has nothing to do with the SQL-side 'AS'
3709 identifier aliasing. You can however alias a function, so you can use it in
3710 e.g. an C<ORDER BY> clause. This is done via the C<-as> B<select function
3711 attribute> supplied as shown in the example above.
3717 Indicates additional columns to be selected from storage. Works the same as
3718 L</select> but adds columns to the default selection, instead of specifying
3727 Indicates additional column names for those added via L</+select>. See L</as>.
3735 =item Value: \@inflation_names
3739 Indicates column names for object inflation. That is L</as> indicates the
3740 slot name in which the column value will be stored within the
3741 L<Row|DBIx::Class::Row> object. The value will then be accessible via this
3742 identifier by the C<get_column> method (or via the object accessor B<if one
3743 with the same name already exists>) as shown below. The L</as> attribute has
3744 B<nothing to do> with the SQL-side C<AS>. See L</select> for details.
3746 $rs = $schema->resultset('Employee')->search(undef, {
3749 { count => 'employeeid' },
3750 { max => { length => 'name' }, -as => 'longest_name' }
3759 If the object against which the search is performed already has an accessor
3760 matching a column name specified in C<as>, the value can be retrieved using
3761 the accessor as normal:
3763 my $name = $employee->name();
3765 If on the other hand an accessor does not exist in the object, you need to
3766 use C<get_column> instead:
3768 my $employee_count = $employee->get_column('employee_count');
3770 You can create your own accessors if required - see
3771 L<DBIx::Class::Manual::Cookbook> for details.
3777 =item Value: ($rel_name | \@rel_names | \%rel_names)
3781 Contains a list of relationships that should be joined for this query. For
3784 # Get CDs by Nine Inch Nails
3785 my $rs = $schema->resultset('CD')->search(
3786 { 'artist.name' => 'Nine Inch Nails' },
3787 { join => 'artist' }
3790 Can also contain a hash reference to refer to the other relation's relations.
3793 package MyApp::Schema::Track;
3794 use base qw/DBIx::Class/;
3795 __PACKAGE__->table('track');
3796 __PACKAGE__->add_columns(qw/trackid cd position title/);
3797 __PACKAGE__->set_primary_key('trackid');
3798 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
3801 # In your application
3802 my $rs = $schema->resultset('Artist')->search(
3803 { 'track.title' => 'Teardrop' },
3805 join => { cd => 'track' },
3806 order_by => 'artist.name',
3810 You need to use the relationship (not the table) name in conditions,
3811 because they are aliased as such. The current table is aliased as "me", so
3812 you need to use me.column_name in order to avoid ambiguity. For example:
3814 # Get CDs from 1984 with a 'Foo' track
3815 my $rs = $schema->resultset('CD')->search(
3818 'tracks.name' => 'Foo'
3820 { join => 'tracks' }
3823 If the same join is supplied twice, it will be aliased to <rel>_2 (and
3824 similarly for a third time). For e.g.
3826 my $rs = $schema->resultset('Artist')->search({
3827 'cds.title' => 'Down to Earth',
3828 'cds_2.title' => 'Popular',
3830 join => [ qw/cds cds/ ],
3833 will return a set of all artists that have both a cd with title 'Down
3834 to Earth' and a cd with title 'Popular'.
3836 If you want to fetch related objects from other tables as well, see C<prefetch>
3839 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
3845 =item Value: ($rel_name | \@rel_names | \%rel_names)
3849 Contains one or more relationships that should be fetched along with
3850 the main query (when they are accessed afterwards the data will
3851 already be available, without extra queries to the database). This is
3852 useful for when you know you will need the related objects, because it
3853 saves at least one query:
3855 my $rs = $schema->resultset('Tag')->search(
3864 The initial search results in SQL like the following:
3866 SELECT tag.*, cd.*, artist.* FROM tag
3867 JOIN cd ON tag.cd = cd.cdid
3868 JOIN artist ON cd.artist = artist.artistid
3870 L<DBIx::Class> has no need to go back to the database when we access the
3871 C<cd> or C<artist> relationships, which saves us two SQL statements in this
3874 Simple prefetches will be joined automatically, so there is no need
3875 for a C<join> attribute in the above search.
3877 C<prefetch> can be used with the following relationship types: C<belongs_to>,
3878 C<has_one> (or if you're using C<add_relationship>, any relationship declared
3879 with an accessor type of 'single' or 'filter'). A more complex example that
3880 prefetches an artists cds, the tracks on those cds, and the tags associated
3881 with that artist is given below (assuming many-to-many from artists to tags):
3883 my $rs = $schema->resultset('Artist')->search(
3887 { cds => 'tracks' },
3888 { artist_tags => 'tags' }
3894 B<NOTE:> If you specify a C<prefetch> attribute, the C<join> and C<select>
3895 attributes will be ignored.
3897 B<CAVEATs>: Prefetch does a lot of deep magic. As such, it may not behave
3898 exactly as you might expect.
3904 Prefetch uses the L</cache> to populate the prefetched relationships. This
3905 may or may not be what you want.
3909 If you specify a condition on a prefetched relationship, ONLY those
3910 rows that match the prefetched condition will be fetched into that relationship.
3911 This means that adding prefetch to a search() B<may alter> what is returned by
3912 traversing a relationship. So, if you have C<< Artist->has_many(CDs) >> and you do
3914 my $artist_rs = $schema->resultset('Artist')->search({
3920 my $count = $artist_rs->first->cds->count;
3922 my $artist_rs_prefetch = $artist_rs->search( {}, { prefetch => 'cds' } );
3924 my $prefetch_count = $artist_rs_prefetch->first->cds->count;
3926 cmp_ok( $count, '==', $prefetch_count, "Counts should be the same" );
3928 that cmp_ok() may or may not pass depending on the datasets involved. This
3929 behavior may or may not survive the 0.09 transition.
3941 Makes the resultset paged and specifies the page to retrieve. Effectively
3942 identical to creating a non-pages resultset and then calling ->page($page)
3945 If L<rows> attribute is not specified it defaults to 10 rows per page.
3947 When you have a paged resultset, L</count> will only return the number
3948 of rows in the page. To get the total, use the L</pager> and call
3949 C<total_entries> on it.
3959 Specifies the maximum number of rows for direct retrieval or the number of
3960 rows per page if the page attribute or method is used.
3966 =item Value: $offset
3970 Specifies the (zero-based) row number for the first row to be returned, or the
3971 of the first row of the first page if paging is used.
3977 =item Value: \@columns
3981 A arrayref of columns to group by. Can include columns of joined tables.
3983 group_by => [qw/ column1 column2 ... /]
3989 =item Value: $condition
3993 HAVING is a select statement attribute that is applied between GROUP BY and
3994 ORDER BY. It is applied to the after the grouping calculations have been
3997 having => { 'count(employee)' => { '>=', 100 } }
4003 =item Value: (0 | 1)
4007 Set to 1 to group by all columns. If the resultset already has a group_by
4008 attribute, this setting is ignored and an appropriate warning is issued.
4014 Adds to the WHERE clause.
4016 # only return rows WHERE deleted IS NULL for all searches
4017 __PACKAGE__->resultset_attributes({ where => { deleted => undef } }); )
4019 Can be overridden by passing C<< { where => undef } >> as an attribute
4026 Set to 1 to cache search results. This prevents extra SQL queries if you
4027 revisit rows in your ResultSet:
4029 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
4031 while( my $artist = $resultset->next ) {
4035 $rs->first; # without cache, this would issue a query
4037 By default, searches are not cached.
4039 For more examples of using these attributes, see
4040 L<DBIx::Class::Manual::Cookbook>.
4046 =item Value: ( 'update' | 'shared' )
4050 Set to 'update' for a SELECT ... FOR UPDATE or 'shared' for a SELECT