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.
308 my $callsites_warned;
312 # Special-case handling for (undef, undef).
313 if ( @_ == 2 && !defined $_[1] && !defined $_[0] ) {
318 $call_attrs = pop(@_) if (
319 @_ > 1 and ( ! defined $_[-1] or ref $_[-1] eq 'HASH' )
322 # see if we can keep the cache (no $rs changes)
324 my %safe = (alias => 1, cache => 1);
325 if ( ! List::Util::first { !$safe{$_} } keys %$call_attrs and (
328 ref $_[0] eq 'HASH' && ! keys %{$_[0]}
330 ref $_[0] eq 'ARRAY' && ! @{$_[0]}
332 $cache = $self->get_cache;
335 my $old_attrs = { %{$self->{attrs}} };
336 my $old_having = delete $old_attrs->{having};
337 my $old_where = delete $old_attrs->{where};
339 # reset the selector list
340 if (List::Util::first { exists $call_attrs->{$_} } qw{columns select as}) {
341 delete @{$old_attrs}{qw{select as columns +select +as +columns include_columns}};
344 my $new_attrs = { %{$old_attrs}, %{$call_attrs} };
346 # merge new attrs into inherited
347 foreach my $key (qw/join prefetch/) {
348 next unless exists $call_attrs->{$key};
349 $new_attrs->{$key} = $self->_merge_joinpref_attr($old_attrs->{$key}, $call_attrs->{$key});
351 foreach my $key (qw/+select +as +columns include_columns bind/) {
352 next unless exists $call_attrs->{$key};
353 $new_attrs->{$key} = $self->_merge_attr($old_attrs->{$key}, $call_attrs->{$key});
356 # rip apart the rest of @_, parse a condition
359 if (ref $_[0] eq 'HASH') {
360 (keys %{$_[0]}) ? $_[0] : undef
366 $self->throw_exception('Odd number of arguments to search')
374 if( @_ > 1 and ! $self->result_source->result_class->isa('DBIx::Class::CDBICompat') ) {
375 # determine callsite obeying Carp::Clan rules (fucking ugly but don't have better ideas)
378 local $SIG{__WARN__} = sub { $w = shift };
382 carp 'search( %condition ) is deprecated, use search( \%condition ) instead'
383 unless $callsites_warned->{$callsite}++;
386 for ($old_where, $call_cond) {
388 $new_attrs->{where} = $self->_stack_cond (
389 $_, $new_attrs->{where}
394 if (defined $old_having) {
395 $new_attrs->{having} = $self->_stack_cond (
396 $old_having, $new_attrs->{having}
400 my $rs = (ref $self)->new($self->result_source, $new_attrs);
402 $rs->set_cache($cache) if ($cache);
408 my ($self, $left, $right) = @_;
409 if (defined $left xor defined $right) {
410 return defined $left ? $left : $right;
412 elsif (defined $left) {
413 return { -and => [ map
414 { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
422 =head2 search_literal
426 =item Arguments: $sql_fragment, @bind_values
428 =item Return Value: $resultset (scalar context), @row_objs (list context)
432 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
433 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
435 Pass a literal chunk of SQL to be added to the conditional part of the
438 CAVEAT: C<search_literal> is provided for Class::DBI compatibility and should
439 only be used in that context. C<search_literal> is a convenience method.
440 It is equivalent to calling $schema->search(\[]), but if you want to ensure
441 columns are bound correctly, use C<search>.
443 Example of how to use C<search> instead of C<search_literal>
445 my @cds = $cd_rs->search_literal('cdid = ? AND (artist = ? OR artist = ?)', (2, 1, 2));
446 my @cds = $cd_rs->search(\[ 'cdid = ? AND (artist = ? OR artist = ?)', [ 'cdid', 2 ], [ 'artist', 1 ], [ 'artist', 2 ] ]);
449 See L<DBIx::Class::Manual::Cookbook/Searching> and
450 L<DBIx::Class::Manual::FAQ/Searching> for searching techniques that do not
451 require C<search_literal>.
456 my ($self, $sql, @bind) = @_;
458 if ( @bind && ref($bind[-1]) eq 'HASH' ) {
461 return $self->search(\[ $sql, map [ __DUMMY__ => $_ ], @bind ], ($attr || () ));
468 =item Arguments: \%columns_values | @pk_values, \%attrs?
470 =item Return Value: $row_object | undef
474 Finds and returns a single row based on supplied criteria. Takes either a
475 hashref with the same format as L</create> (including inference of foreign
476 keys from related objects), or a list of primary key values in the same
477 order as the L<primary columns|DBIx::Class::ResultSource/primary_columns>
478 declaration on the L</result_source>.
480 In either case an attempt is made to combine conditions already existing on
481 the resultset with the condition passed to this method.
483 To aid with preparing the correct query for the storage you may supply the
484 C<key> attribute, which is the name of a
485 L<unique constraint|DBIx::Class::ResultSource/add_unique_constraint> (the
486 unique constraint corresponding to the
487 L<primary columns|DBIx::Class::ResultSource/primary_columns> is always named
488 C<primary>). If the C<key> attribute has been supplied, and DBIC is unable
489 to construct a query that satisfies the named unique constraint fully (
490 non-NULL values for each column member of the constraint) an exception is
493 If no C<key> is specified, the search is carried over all unique constraints
494 which are fully defined by the available condition.
496 If no such constraint is found, C<find> currently defaults to a simple
497 C<< search->(\%column_values) >> which may or may not do what you expect.
498 Note that this fallback behavior may be deprecated in further versions. If
499 you need to search with arbitrary conditions - use L</search>. If the query
500 resulting from this fallback produces more than one row, a warning to the
501 effect is issued, though only the first row is constructed and returned as
504 In addition to C<key>, L</find> recognizes and applies standard
505 L<resultset attributes|/ATTRIBUTES> in the same way as L</search> does.
507 Note that if you have extra concerns about the correctness of the resulting
508 query you need to specify the C<key> attribute and supply the entire condition
509 as an argument to find (since it is not always possible to perform the
510 combination of the resultset condition with the supplied one, especially if
511 the resultset condition contains literal sql).
513 For example, to find a row by its primary key:
515 my $cd = $schema->resultset('CD')->find(5);
517 You can also find a row by a specific unique constraint:
519 my $cd = $schema->resultset('CD')->find(
521 artist => 'Massive Attack',
522 title => 'Mezzanine',
524 { key => 'cd_artist_title' }
527 See also L</find_or_create> and L</update_or_create>.
533 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
535 my $rsrc = $self->result_source;
537 # Parse out the condition from input
539 if (ref $_[0] eq 'HASH') {
540 $call_cond = { %{$_[0]} };
543 my $constraint = exists $attrs->{key} ? $attrs->{key} : 'primary';
544 my @c_cols = $rsrc->unique_constraint_columns($constraint);
546 $self->throw_exception(
547 "No constraint columns, maybe a malformed '$constraint' constraint?"
550 $self->throw_exception (
551 'find() expects either a column/value hashref, or a list of values '
552 . "corresponding to the columns of the specified unique constraint '$constraint'"
553 ) unless @c_cols == @_;
556 @{$call_cond}{@c_cols} = @_;
560 for my $key (keys %$call_cond) {
562 my $keyref = ref($call_cond->{$key})
564 my $relinfo = $rsrc->relationship_info($key)
566 my $val = delete $call_cond->{$key};
568 next if $keyref eq 'ARRAY'; # has_many for multi_create
570 my $rel_q = $rsrc->_resolve_condition(
571 $relinfo->{cond}, $val, $key
573 die "Can't handle complex relationship conditions in find" if ref($rel_q) ne 'HASH';
574 @related{keys %$rel_q} = values %$rel_q;
578 # relationship conditions take precedence (?)
579 @{$call_cond}{keys %related} = values %related;
581 my $alias = exists $attrs->{alias} ? $attrs->{alias} : $self->{attrs}{alias};
583 if (exists $attrs->{key}) {
584 $final_cond = $self->_qualify_cond_columns (
586 $self->_build_unique_cond (
594 elsif ($self->{attrs}{accessor} and $self->{attrs}{accessor} eq 'single') {
595 # This means that we got here after a merger of relationship conditions
596 # in ::Relationship::Base::search_related (the row method), and furthermore
597 # the relationship is of the 'single' type. This means that the condition
598 # provided by the relationship (already attached to $self) is sufficient,
599 # as there can be only one row in the database that would satisfy the
603 # no key was specified - fall down to heuristics mode:
604 # run through all unique queries registered on the resultset, and
605 # 'OR' all qualifying queries together
606 my (@unique_queries, %seen_column_combinations);
607 for my $c_name ($rsrc->unique_constraint_names) {
608 next if $seen_column_combinations{
609 join "\x00", sort $rsrc->unique_constraint_columns($c_name)
612 push @unique_queries, try {
613 $self->_build_unique_cond ($c_name, $call_cond)
617 $final_cond = @unique_queries
618 ? [ map { $self->_qualify_cond_columns($_, $alias) } @unique_queries ]
619 : $self->_non_unique_find_fallback ($call_cond, $attrs)
623 # Run the query, passing the result_class since it should propagate for find
624 my $rs = $self->search ($final_cond, {result_class => $self->result_class, %$attrs});
625 if (keys %{$rs->_resolved_attrs->{collapse}}) {
627 carp "Query returned more than one row" if $rs->next;
635 # This is a stop-gap method as agreed during the discussion on find() cleanup:
636 # http://lists.scsys.co.uk/pipermail/dbix-class/2010-October/009535.html
638 # It is invoked when find() is called in legacy-mode with insufficiently-unique
639 # condition. It is provided for overrides until a saner way forward is devised
641 # *NOTE* This is not a public method, and it's *GUARANTEED* to disappear down
642 # the road. Please adjust your tests accordingly to catch this situation early
643 # DBIx::Class::ResultSet->can('_non_unique_find_fallback') is reasonable
645 # The method will not be removed without an adequately complete replacement
646 # for strict-mode enforcement
647 sub _non_unique_find_fallback {
648 my ($self, $cond, $attrs) = @_;
650 return $self->_qualify_cond_columns(
652 exists $attrs->{alias}
654 : $self->{attrs}{alias}
659 sub _qualify_cond_columns {
660 my ($self, $cond, $alias) = @_;
662 my %aliased = %$cond;
663 for (keys %aliased) {
664 $aliased{"$alias.$_"} = delete $aliased{$_}
671 sub _build_unique_cond {
672 my ($self, $constraint_name, $extra_cond) = @_;
674 my @c_cols = $self->result_source->unique_constraint_columns($constraint_name);
676 # combination may fail if $self->{cond} is non-trivial
677 my ($final_cond) = try {
678 $self->_merge_with_rscond ($extra_cond)
683 # trim out everything not in $columns
684 $final_cond = { map { $_ => $final_cond->{$_} } @c_cols };
686 if (my @missing = grep { ! defined $final_cond->{$_} } (@c_cols) ) {
687 $self->throw_exception( sprintf ( "Unable to satisfy requested constraint '%s', no values for column(s): %s",
689 join (', ', map { "'$_'" } @missing),
696 =head2 search_related
700 =item Arguments: $rel, $cond, \%attrs?
702 =item Return Value: $new_resultset
706 $new_rs = $cd_rs->search_related('artist', {
710 Searches the specified relationship, optionally specifying a condition and
711 attributes for matching records. See L</ATTRIBUTES> for more information.
716 return shift->related_resultset(shift)->search(@_);
719 =head2 search_related_rs
721 This method works exactly the same as search_related, except that
722 it guarantees a resultset, even in list context.
726 sub search_related_rs {
727 return shift->related_resultset(shift)->search_rs(@_);
734 =item Arguments: none
736 =item Return Value: $cursor
740 Returns a storage-driven cursor to the given resultset. See
741 L<DBIx::Class::Cursor> for more information.
748 my $attrs = $self->_resolved_attrs_copy;
750 return $self->{cursor}
751 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
752 $attrs->{where},$attrs);
759 =item Arguments: $cond?
761 =item Return Value: $row_object | undef
765 my $cd = $schema->resultset('CD')->single({ year => 2001 });
767 Inflates the first result without creating a cursor if the resultset has
768 any records in it; if not returns C<undef>. Used by L</find> as a lean version
771 While this method can take an optional search condition (just like L</search>)
772 being a fast-code-path it does not recognize search attributes. If you need to
773 add extra joins or similar, call L</search> and then chain-call L</single> on the
774 L<DBIx::Class::ResultSet> returned.
780 As of 0.08100, this method enforces the assumption that the preceding
781 query returns only one row. If more than one row is returned, you will receive
784 Query returned more than one row
786 In this case, you should be using L</next> or L</find> instead, or if you really
787 know what you are doing, use the L</rows> attribute to explicitly limit the size
790 This method will also throw an exception if it is called on a resultset prefetching
791 has_many, as such a prefetch implies fetching multiple rows from the database in
792 order to assemble the resulting object.
799 my ($self, $where) = @_;
801 $self->throw_exception('single() only takes search conditions, no attributes. You want ->search( $cond, $attrs )->single()');
804 my $attrs = $self->_resolved_attrs_copy;
806 if (keys %{$attrs->{collapse}}) {
807 $self->throw_exception(
808 'single() can not be used on resultsets prefetching has_many. Use find( \%cond ) or next() instead'
813 if (defined $attrs->{where}) {
816 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
817 $where, delete $attrs->{where} ]
820 $attrs->{where} = $where;
824 my @data = $self->result_source->storage->select_single(
825 $attrs->{from}, $attrs->{select},
826 $attrs->{where}, $attrs
829 return (@data ? ($self->_construct_object(@data))[0] : undef);
835 # Recursively collapse the query, accumulating values for each column.
837 sub _collapse_query {
838 my ($self, $query, $collapsed) = @_;
842 if (ref $query eq 'ARRAY') {
843 foreach my $subquery (@$query) {
844 next unless ref $subquery; # -or
845 $collapsed = $self->_collapse_query($subquery, $collapsed);
848 elsif (ref $query eq 'HASH') {
849 if (keys %$query and (keys %$query)[0] eq '-and') {
850 foreach my $subquery (@{$query->{-and}}) {
851 $collapsed = $self->_collapse_query($subquery, $collapsed);
855 foreach my $col (keys %$query) {
856 my $value = $query->{$col};
857 $collapsed->{$col}{$value}++;
869 =item Arguments: $cond?
871 =item Return Value: $resultsetcolumn
875 my $max_length = $rs->get_column('length')->max;
877 Returns a L<DBIx::Class::ResultSetColumn> instance for a column of the ResultSet.
882 my ($self, $column) = @_;
883 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
891 =item Arguments: $cond, \%attrs?
893 =item Return Value: $resultset (scalar context), @row_objs (list context)
897 # WHERE title LIKE '%blue%'
898 $cd_rs = $rs->search_like({ title => '%blue%'});
900 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
901 that this is simply a convenience method retained for ex Class::DBI users.
902 You most likely want to use L</search> with specific operators.
904 For more information, see L<DBIx::Class::Manual::Cookbook>.
906 This method is deprecated and will be removed in 0.09. Use L</search()>
907 instead. An example conversion is:
909 ->search_like({ foo => 'bar' });
913 ->search({ foo => { like => 'bar' } });
920 'search_like() is deprecated and will be removed in DBIC version 0.09.'
921 .' Instead use ->search({ x => { -like => "y%" } })'
922 .' (note the outer pair of {}s - they are important!)'
924 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
925 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
926 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
927 return $class->search($query, { %$attrs });
934 =item Arguments: $first, $last
936 =item Return Value: $resultset (scalar context), @row_objs (list context)
940 Returns a resultset or object list representing a subset of elements from the
941 resultset slice is called on. Indexes are from 0, i.e., to get the first
944 my ($one, $two, $three) = $rs->slice(0, 2);
949 my ($self, $min, $max) = @_;
950 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
951 $attrs->{offset} = $self->{attrs}{offset} || 0;
952 $attrs->{offset} += $min;
953 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
954 return $self->search(undef, $attrs);
955 #my $slice = (ref $self)->new($self->result_source, $attrs);
956 #return (wantarray ? $slice->all : $slice);
963 =item Arguments: none
965 =item Return Value: $result | undef
969 Returns the next element in the resultset (C<undef> is there is none).
971 Can be used to efficiently iterate over records in the resultset:
973 my $rs = $schema->resultset('CD')->search;
974 while (my $cd = $rs->next) {
978 Note that you need to store the resultset object, and call C<next> on it.
979 Calling C<< resultset('Table')->next >> repeatedly will always return the
980 first record from the resultset.
986 if (my $cache = $self->get_cache) {
987 $self->{all_cache_position} ||= 0;
988 return $cache->[$self->{all_cache_position}++];
990 if ($self->{attrs}{cache}) {
991 delete $self->{pager};
992 $self->{all_cache_position} = 1;
993 return ($self->all)[0];
995 if ($self->{stashed_objects}) {
996 my $obj = shift(@{$self->{stashed_objects}});
997 delete $self->{stashed_objects} unless @{$self->{stashed_objects}};
1001 exists $self->{stashed_row}
1002 ? @{delete $self->{stashed_row}}
1003 : $self->cursor->next
1005 return undef unless (@row);
1006 my ($row, @more) = $self->_construct_object(@row);
1007 $self->{stashed_objects} = \@more if @more;
1011 sub _construct_object {
1012 my ($self, @row) = @_;
1014 my $info = $self->_collapse_result($self->{_attrs}{as}, \@row)
1016 my @new = $self->result_class->inflate_result($self->result_source, @$info);
1017 @new = $self->{_attrs}{record_filter}->(@new)
1018 if exists $self->{_attrs}{record_filter};
1022 sub _collapse_result {
1023 my ($self, $as_proto, $row) = @_;
1027 # 'foo' => [ undef, 'foo' ]
1028 # 'foo.bar' => [ 'foo', 'bar' ]
1029 # 'foo.bar.baz' => [ 'foo.bar', 'baz' ]
1031 my @construct_as = map { [ (/^(?:(.*)\.)?([^.]+)$/) ] } @$as_proto;
1033 my %collapse = %{$self->{_attrs}{collapse}||{}};
1037 # if we're doing collapsing (has_many prefetch) we need to grab records
1038 # until the PK changes, so fill @pri_index. if not, we leave it empty so
1039 # we know we don't have to bother.
1041 # the reason for not using the collapse stuff directly is because if you
1042 # had for e.g. two artists in a row with no cds, the collapse info for
1043 # both would be NULL (undef) so you'd lose the second artist
1045 # store just the index so we can check the array positions from the row
1046 # without having to contruct the full hash
1048 if (keys %collapse) {
1049 my %pri = map { ($_ => 1) } $self->result_source->_pri_cols;
1050 foreach my $i (0 .. $#construct_as) {
1051 next if defined($construct_as[$i][0]); # only self table
1052 if (delete $pri{$construct_as[$i][1]}) {
1053 push(@pri_index, $i);
1055 last unless keys %pri; # short circuit (Johnny Five Is Alive!)
1059 # no need to do an if, it'll be empty if @pri_index is empty anyway
1061 my %pri_vals = map { ($_ => $copy[$_]) } @pri_index;
1065 do { # no need to check anything at the front, we always want the first row
1069 foreach my $this_as (@construct_as) {
1070 $const{$this_as->[0]||''}{$this_as->[1]} = shift(@copy);
1073 push(@const_rows, \%const);
1075 } until ( # no pri_index => no collapse => drop straight out
1078 do { # get another row, stash it, drop out if different PK
1080 @copy = $self->cursor->next;
1081 $self->{stashed_row} = \@copy;
1083 # last thing in do block, counts as true if anything doesn't match
1085 # check xor defined first for NULL vs. NOT NULL then if one is
1086 # defined the other must be so check string equality
1089 (defined $pri_vals{$_} ^ defined $copy[$_])
1090 || (defined $pri_vals{$_} && ($pri_vals{$_} ne $copy[$_]))
1095 my $alias = $self->{attrs}{alias};
1102 foreach my $const (@const_rows) {
1103 scalar @const_keys or do {
1104 @const_keys = sort { length($a) <=> length($b) } keys %$const;
1106 foreach my $key (@const_keys) {
1109 my @parts = split(/\./, $key);
1111 my $data = $const->{$key};
1112 foreach my $p (@parts) {
1113 $target = $target->[1]->{$p} ||= [];
1115 if ($cur eq ".${key}" && (my @ckey = @{$collapse{$cur}||[]})) {
1116 # collapsing at this point and on final part
1117 my $pos = $collapse_pos{$cur};
1118 CK: foreach my $ck (@ckey) {
1119 if (!defined $pos->{$ck} || $pos->{$ck} ne $data->{$ck}) {
1120 $collapse_pos{$cur} = $data;
1121 delete @collapse_pos{ # clear all positioning for sub-entries
1122 grep { m/^\Q${cur}.\E/ } keys %collapse_pos
1129 if (exists $collapse{$cur}) {
1130 $target = $target->[-1];
1133 $target->[0] = $data;
1135 $info->[0] = $const->{$key};
1143 =head2 result_source
1147 =item Arguments: $result_source?
1149 =item Return Value: $result_source
1153 An accessor for the primary ResultSource object from which this ResultSet
1160 =item Arguments: $result_class?
1162 =item Return Value: $result_class
1166 An accessor for the class to use when creating row objects. Defaults to
1167 C<< result_source->result_class >> - which in most cases is the name of the
1168 L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class.
1170 Note that changing the result_class will also remove any components
1171 that were originally loaded in the source class via
1172 L<DBIx::Class::ResultSource/load_components>. Any overloaded methods
1173 in the original source class will not run.
1178 my ($self, $result_class) = @_;
1179 if ($result_class) {
1180 unless (ref $result_class) { # don't fire this for an object
1181 $self->ensure_class_loaded($result_class);
1183 $self->_result_class($result_class);
1184 # THIS LINE WOULD BE A BUG - this accessor specifically exists to
1185 # permit the user to set result class on one result set only; it only
1186 # chains if provided to search()
1187 #$self->{attrs}{result_class} = $result_class if ref $self;
1189 $self->_result_class;
1196 =item Arguments: $cond, \%attrs??
1198 =item Return Value: $count
1202 Performs an SQL C<COUNT> with the same query as the resultset was built
1203 with to find the number of elements. Passing arguments is equivalent to
1204 C<< $rs->search ($cond, \%attrs)->count >>
1210 return $self->search(@_)->count if @_ and defined $_[0];
1211 return scalar @{ $self->get_cache } if $self->get_cache;
1213 my $attrs = $self->_resolved_attrs_copy;
1215 # this is a little optimization - it is faster to do the limit
1216 # adjustments in software, instead of a subquery
1217 my $rows = delete $attrs->{rows};
1218 my $offset = delete $attrs->{offset};
1221 if ($self->_has_resolved_attr (qw/collapse group_by/)) {
1222 $crs = $self->_count_subq_rs ($attrs);
1225 $crs = $self->_count_rs ($attrs);
1227 my $count = $crs->next;
1229 $count -= $offset if $offset;
1230 $count = $rows if $rows and $rows < $count;
1231 $count = 0 if ($count < 0);
1240 =item Arguments: $cond, \%attrs??
1242 =item Return Value: $count_rs
1246 Same as L</count> but returns a L<DBIx::Class::ResultSetColumn> object.
1247 This can be very handy for subqueries:
1249 ->search( { amount => $some_rs->count_rs->as_query } )
1251 As with regular resultsets the SQL query will be executed only after
1252 the resultset is accessed via L</next> or L</all>. That would return
1253 the same single value obtainable via L</count>.
1259 return $self->search(@_)->count_rs if @_;
1261 # this may look like a lack of abstraction (count() does about the same)
1262 # but in fact an _rs *must* use a subquery for the limits, as the
1263 # software based limiting can not be ported if this $rs is to be used
1264 # in a subquery itself (i.e. ->as_query)
1265 if ($self->_has_resolved_attr (qw/collapse group_by offset rows/)) {
1266 return $self->_count_subq_rs;
1269 return $self->_count_rs;
1274 # returns a ResultSetColumn object tied to the count query
1277 my ($self, $attrs) = @_;
1279 my $rsrc = $self->result_source;
1280 $attrs ||= $self->_resolved_attrs;
1282 my $tmp_attrs = { %$attrs };
1283 # take off any limits, record_filter is cdbi, and no point of ordering nor locking a count
1284 delete @{$tmp_attrs}{qw/rows offset order_by record_filter for/};
1286 # overwrite the selector (supplied by the storage)
1287 $tmp_attrs->{select} = $rsrc->storage->_count_select ($rsrc, $attrs);
1288 $tmp_attrs->{as} = 'count';
1290 my $tmp_rs = $rsrc->resultset_class->new($rsrc, $tmp_attrs)->get_column ('count');
1296 # same as above but uses a subquery
1298 sub _count_subq_rs {
1299 my ($self, $attrs) = @_;
1301 my $rsrc = $self->result_source;
1302 $attrs ||= $self->_resolved_attrs;
1304 my $sub_attrs = { %$attrs };
1305 # extra selectors do not go in the subquery and there is no point of ordering it, nor locking it
1306 delete @{$sub_attrs}{qw/collapse select _prefetch_select as order_by for/};
1308 # if we multi-prefetch we group_by primary keys only as this is what we would
1309 # get out of the rs via ->next/->all. We *DO WANT* to clobber old group_by regardless
1310 if ( keys %{$attrs->{collapse}} ) {
1311 $sub_attrs->{group_by} = [ map { "$attrs->{alias}.$_" } ($rsrc->_pri_cols) ]
1314 # Calculate subquery selector
1315 if (my $g = $sub_attrs->{group_by}) {
1317 my $sql_maker = $rsrc->storage->sql_maker;
1319 # necessary as the group_by may refer to aliased functions
1321 for my $sel (@{$attrs->{select}}) {
1322 $sel_index->{$sel->{-as}} = $sel
1323 if (ref $sel eq 'HASH' and $sel->{-as});
1326 # anything from the original select mentioned on the group-by needs to make it to the inner selector
1327 # also look for named aggregates referred in the having clause
1328 # having often contains scalarrefs - thus parse it out entirely
1330 if ($attrs->{having}) {
1331 local $sql_maker->{having_bind};
1332 local $sql_maker->{quote_char} = $sql_maker->{quote_char};
1333 local $sql_maker->{name_sep} = $sql_maker->{name_sep};
1334 unless (defined $sql_maker->{quote_char} and length $sql_maker->{quote_char}) {
1335 $sql_maker->{quote_char} = [ "\x00", "\xFF" ];
1336 # if we don't unset it we screw up retarded but unfortunately working
1337 # 'MAX(foo.bar)' => { '>', 3 }
1338 $sql_maker->{name_sep} = '';
1341 my ($lquote, $rquote, $sep) = map { quotemeta $_ } ($sql_maker->_quote_chars, $sql_maker->name_sep);
1343 my $sql = $sql_maker->_parse_rs_attrs ({ having => $attrs->{having} });
1345 # search for both a proper quoted qualified string, for a naive unquoted scalarref
1346 # and if all fails for an utterly naive quoted scalar-with-function
1348 $rquote $sep $lquote (.+?) $rquote
1350 [\s,] \w+ \. (\w+) [\s,]
1352 [\s,] $lquote (.+?) $rquote [\s,]
1354 push @parts, ($1 || $2 || $3); # one of them matched if we got here
1359 my $colpiece = $sel_index->{$_} || $_;
1361 # unqualify join-based group_by's. Arcane but possible query
1362 # also horrible horrible hack to alias a column (not a func.)
1363 # (probably need to introduce SQLA syntax)
1364 if ($colpiece =~ /\./ && $colpiece !~ /^$attrs->{alias}\./) {
1367 $colpiece = \ sprintf ('%s AS %s', map { $sql_maker->_quote ($_) } ($colpiece, $as) );
1369 push @{$sub_attrs->{select}}, $colpiece;
1373 my @pcols = map { "$attrs->{alias}.$_" } ($rsrc->primary_columns);
1374 $sub_attrs->{select} = @pcols ? \@pcols : [ 1 ];
1377 return $rsrc->resultset_class
1378 ->new ($rsrc, $sub_attrs)
1380 ->search ({}, { columns => { count => $rsrc->storage->_count_select ($rsrc, $attrs) } })
1381 ->get_column ('count');
1388 =head2 count_literal
1392 =item Arguments: $sql_fragment, @bind_values
1394 =item Return Value: $count
1398 Counts the results in a literal query. Equivalent to calling L</search_literal>
1399 with the passed arguments, then L</count>.
1403 sub count_literal { shift->search_literal(@_)->count; }
1409 =item Arguments: none
1411 =item Return Value: @objects
1415 Returns all elements in the resultset. Called implicitly if the resultset
1416 is returned in list context.
1423 $self->throw_exception("all() doesn't take any arguments, you probably wanted ->search(...)->all()");
1426 return @{ $self->get_cache } if $self->get_cache;
1430 if (keys %{$self->_resolved_attrs->{collapse}}) {
1431 # Using $self->cursor->all is really just an optimisation.
1432 # If we're collapsing has_many prefetches it probably makes
1433 # very little difference, and this is cleaner than hacking
1434 # _construct_object to survive the approach
1435 $self->cursor->reset;
1436 my @row = $self->cursor->next;
1438 push(@obj, $self->_construct_object(@row));
1439 @row = (exists $self->{stashed_row}
1440 ? @{delete $self->{stashed_row}}
1441 : $self->cursor->next);
1444 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
1447 $self->set_cache(\@obj) if $self->{attrs}{cache};
1456 =item Arguments: none
1458 =item Return Value: $self
1462 Resets the resultset's cursor, so you can iterate through the elements again.
1463 Implicitly resets the storage cursor, so a subsequent L</next> will trigger
1470 delete $self->{_attrs} if exists $self->{_attrs};
1471 $self->{all_cache_position} = 0;
1472 $self->cursor->reset;
1480 =item Arguments: none
1482 =item Return Value: $object | undef
1486 Resets the resultset and returns an object for the first result (or C<undef>
1487 if the resultset is empty).
1492 return $_[0]->reset->next;
1498 # Determines whether and what type of subquery is required for the $rs operation.
1499 # If grouping is necessary either supplies its own, or verifies the current one
1500 # After all is done delegates to the proper storage method.
1502 sub _rs_update_delete {
1503 my ($self, $op, $values) = @_;
1505 my $rsrc = $self->result_source;
1507 # if a condition exists we need to strip all table qualifiers
1508 # if this is not possible we'll force a subquery below
1509 my $cond = $rsrc->schema->storage->_strip_cond_qualifiers ($self->{cond});
1511 my $needs_group_by_subq = $self->_has_resolved_attr (qw/collapse group_by -join/);
1512 my $needs_subq = $needs_group_by_subq || (not defined $cond) || $self->_has_resolved_attr(qw/rows offset/);
1514 if ($needs_group_by_subq or $needs_subq) {
1516 # make a new $rs selecting only the PKs (that's all we really need)
1517 my $attrs = $self->_resolved_attrs_copy;
1520 delete $attrs->{$_} for qw/collapse _collapse_order_by select _prefetch_select as/;
1521 $attrs->{columns} = [ map { "$attrs->{alias}.$_" } ($self->result_source->_pri_cols) ];
1523 if ($needs_group_by_subq) {
1524 # make sure no group_by was supplied, or if there is one - make sure it matches
1525 # the columns compiled above perfectly. Anything else can not be sanely executed
1526 # on most databases so croak right then and there
1528 if (my $g = $attrs->{group_by}) {
1529 my @current_group_by = map
1530 { $_ =~ /\./ ? $_ : "$attrs->{alias}.$_" }
1535 join ("\x00", sort @current_group_by)
1537 join ("\x00", sort @{$attrs->{columns}} )
1539 $self->throw_exception (
1540 "You have just attempted a $op operation on a resultset which does group_by"
1541 . ' on columns other than the primary keys, while DBIC internally needs to retrieve'
1542 . ' the primary keys in a subselect. All sane RDBMS engines do not support this'
1543 . ' kind of queries. Please retry the operation with a modified group_by or'
1544 . ' without using one at all.'
1549 $attrs->{group_by} = $attrs->{columns};
1553 my $subrs = (ref $self)->new($rsrc, $attrs);
1554 return $self->result_source->storage->_subq_update_delete($subrs, $op, $values);
1557 return $rsrc->storage->$op(
1559 $op eq 'update' ? $values : (),
1569 =item Arguments: \%values
1571 =item Return Value: $storage_rv
1575 Sets the specified columns in the resultset to the supplied values in a
1576 single query. Note that this will not run any accessor/set_column/update
1577 triggers, nor will it update any row object instances derived from this
1578 resultset (this includes the contents of the L<resultset cache|/set_cache>
1579 if any). See L</update_all> if you need to execute any on-update
1580 triggers or cascades defined either by you or a
1581 L<result component|DBIx::Class::Manual::Component/WHAT_IS_A_COMPONENT>.
1583 The return value is a pass through of what the underlying
1584 storage backend returned, and may vary. See L<DBI/execute> for the most
1589 Note that L</update> does not process/deflate any of the values passed in.
1590 This is unlike the corresponding L<DBIx::Class::Row/update>. The user must
1591 ensure manually that any value passed to this method will stringify to
1592 something the RDBMS knows how to deal with. A notable example is the
1593 handling of L<DateTime> objects, for more info see:
1594 L<DBIx::Class::Manual::Cookbook/Formatting_DateTime_objects_in_queries>.
1599 my ($self, $values) = @_;
1600 $self->throw_exception('Values for update must be a hash')
1601 unless ref $values eq 'HASH';
1603 return $self->_rs_update_delete ('update', $values);
1610 =item Arguments: \%values
1612 =item Return Value: 1
1616 Fetches all objects and updates them one at a time via
1617 L<DBIx::Class::Row/update>. Note that C<update_all> will run DBIC defined
1618 triggers, while L</update> will not.
1623 my ($self, $values) = @_;
1624 $self->throw_exception('Values for update_all must be a hash')
1625 unless ref $values eq 'HASH';
1627 my $guard = $self->result_source->schema->txn_scope_guard;
1628 $_->update($values) for $self->all;
1637 =item Arguments: none
1639 =item Return Value: $storage_rv
1643 Deletes the rows matching this resultset in a single query. Note that this
1644 will not run any delete triggers, nor will it alter the
1645 L<in_storage|DBIx::Class::Row/in_storage> status of any row object instances
1646 derived from this resultset (this includes the contents of the
1647 L<resultset cache|/set_cache> if any). See L</delete_all> if you need to
1648 execute any on-delete triggers or cascades defined either by you or a
1649 L<result component|DBIx::Class::Manual::Component/WHAT_IS_A_COMPONENT>.
1651 The return value is a pass through of what the underlying storage backend
1652 returned, and may vary. See L<DBI/execute> for the most common case.
1658 $self->throw_exception('delete does not accept any arguments')
1661 return $self->_rs_update_delete ('delete');
1668 =item Arguments: none
1670 =item Return Value: 1
1674 Fetches all objects and deletes them one at a time via
1675 L<DBIx::Class::Row/delete>. Note that C<delete_all> will run DBIC defined
1676 triggers, while L</delete> will not.
1682 $self->throw_exception('delete_all does not accept any arguments')
1685 my $guard = $self->result_source->schema->txn_scope_guard;
1686 $_->delete for $self->all;
1695 =item Arguments: \@data;
1699 Accepts either an arrayref of hashrefs or alternatively an arrayref of arrayrefs.
1700 For the arrayref of hashrefs style each hashref should be a structure suitable
1701 forsubmitting to a $resultset->create(...) method.
1703 In void context, C<insert_bulk> in L<DBIx::Class::Storage::DBI> is used
1704 to insert the data, as this is a faster method.
1706 Otherwise, each set of data is inserted into the database using
1707 L<DBIx::Class::ResultSet/create>, and the resulting objects are
1708 accumulated into an array. The array itself, or an array reference
1709 is returned depending on scalar or list context.
1711 Example: Assuming an Artist Class that has many CDs Classes relating:
1713 my $Artist_rs = $schema->resultset("Artist");
1715 ## Void Context Example
1716 $Artist_rs->populate([
1717 { artistid => 4, name => 'Manufactured Crap', cds => [
1718 { title => 'My First CD', year => 2006 },
1719 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
1722 { artistid => 5, name => 'Angsty-Whiny Girl', cds => [
1723 { title => 'My parents sold me to a record company', year => 2005 },
1724 { title => 'Why Am I So Ugly?', year => 2006 },
1725 { title => 'I Got Surgery and am now Popular', year => 2007 }
1730 ## Array Context Example
1731 my ($ArtistOne, $ArtistTwo, $ArtistThree) = $Artist_rs->populate([
1732 { name => "Artist One"},
1733 { name => "Artist Two"},
1734 { name => "Artist Three", cds=> [
1735 { title => "First CD", year => 2007},
1736 { title => "Second CD", year => 2008},
1740 print $ArtistOne->name; ## response is 'Artist One'
1741 print $ArtistThree->cds->count ## reponse is '2'
1743 For the arrayref of arrayrefs style, the first element should be a list of the
1744 fieldsnames to which the remaining elements are rows being inserted. For
1747 $Arstist_rs->populate([
1748 [qw/artistid name/],
1749 [100, 'A Formally Unknown Singer'],
1750 [101, 'A singer that jumped the shark two albums ago'],
1751 [102, 'An actually cool singer'],
1754 Please note an important effect on your data when choosing between void and
1755 wantarray context. Since void context goes straight to C<insert_bulk> in
1756 L<DBIx::Class::Storage::DBI> this will skip any component that is overriding
1757 C<insert>. So if you are using something like L<DBIx-Class-UUIDColumns> to
1758 create primary keys for you, you will find that your PKs are empty. In this
1759 case you will have to use the wantarray context in order to create those
1767 # cruft placed in standalone method
1768 my $data = $self->_normalize_populate_args(@_);
1770 if(defined wantarray) {
1772 foreach my $item (@$data) {
1773 push(@created, $self->create($item));
1775 return wantarray ? @created : \@created;
1777 my $first = $data->[0];
1779 # if a column is a registered relationship, and is a non-blessed hash/array, consider
1780 # it relationship data
1781 my (@rels, @columns);
1782 for (keys %$first) {
1783 my $ref = ref $first->{$_};
1784 $self->result_source->has_relationship($_) && ($ref eq 'ARRAY' or $ref eq 'HASH')
1790 my @pks = $self->result_source->primary_columns;
1792 ## do the belongs_to relationships
1793 foreach my $index (0..$#$data) {
1795 # delegate to create() for any dataset without primary keys with specified relationships
1796 if (grep { !defined $data->[$index]->{$_} } @pks ) {
1798 if (grep { ref $data->[$index]{$r} eq $_ } qw/HASH ARRAY/) { # a related set must be a HASH or AoH
1799 my @ret = $self->populate($data);
1805 foreach my $rel (@rels) {
1806 next unless ref $data->[$index]->{$rel} eq "HASH";
1807 my $result = $self->related_resultset($rel)->create($data->[$index]->{$rel});
1808 my ($reverse) = keys %{$self->result_source->reverse_relationship_info($rel)};
1809 my $related = $result->result_source->_resolve_condition(
1810 $result->result_source->relationship_info($reverse)->{cond},
1815 delete $data->[$index]->{$rel};
1816 $data->[$index] = {%{$data->[$index]}, %$related};
1818 push @columns, keys %$related if $index == 0;
1822 ## inherit the data locked in the conditions of the resultset
1823 my ($rs_data) = $self->_merge_with_rscond({});
1824 delete @{$rs_data}{@columns};
1825 my @inherit_cols = keys %$rs_data;
1826 my @inherit_data = values %$rs_data;
1828 ## do bulk insert on current row
1829 $self->result_source->storage->insert_bulk(
1830 $self->result_source,
1831 [@columns, @inherit_cols],
1832 [ map { [ @$_{@columns}, @inherit_data ] } @$data ],
1835 ## do the has_many relationships
1836 foreach my $item (@$data) {
1838 foreach my $rel (@rels) {
1839 next unless $item->{$rel} && ref $item->{$rel} eq "ARRAY";
1841 my $parent = $self->find({map { $_ => $item->{$_} } @pks})
1842 || $self->throw_exception('Cannot find the relating object.');
1844 my $child = $parent->$rel;
1846 my $related = $child->result_source->_resolve_condition(
1847 $parent->result_source->relationship_info($rel)->{cond},
1852 my @rows_to_add = ref $item->{$rel} eq 'ARRAY' ? @{$item->{$rel}} : ($item->{$rel});
1853 my @populate = map { {%$_, %$related} } @rows_to_add;
1855 $child->populate( \@populate );
1862 # populate() argumnets went over several incarnations
1863 # What we ultimately support is AoH
1864 sub _normalize_populate_args {
1865 my ($self, $arg) = @_;
1867 if (ref $arg eq 'ARRAY') {
1868 if (ref $arg->[0] eq 'HASH') {
1871 elsif (ref $arg->[0] eq 'ARRAY') {
1873 my @colnames = @{$arg->[0]};
1874 foreach my $values (@{$arg}[1 .. $#$arg]) {
1875 push @ret, { map { $colnames[$_] => $values->[$_] } (0 .. $#colnames) };
1881 $self->throw_exception('Populate expects an arrayref of hashrefs or arrayref of arrayrefs');
1888 =item Arguments: none
1890 =item Return Value: $pager
1894 Return Value a L<Data::Page> object for the current resultset. Only makes
1895 sense for queries with a C<page> attribute.
1897 To get the full count of entries for a paged resultset, call
1898 C<total_entries> on the L<Data::Page> object.
1902 # make a wizard good for both a scalar and a hashref
1903 my $mk_lazy_count_wizard = sub {
1904 require Variable::Magic;
1906 my $stash = { total_rs => shift };
1907 my $slot = shift; # only used by the hashref magic
1909 my $magic = Variable::Magic::wizard (
1910 data => sub { $stash },
1916 # set value lazily, and dispell for good
1917 ${$_[0]} = $_[1]{total_rs}->count;
1918 Variable::Magic::dispell (${$_[0]}, $_[1]{magic_selfref});
1922 # an explicit set implies dispell as well
1923 # the unless() is to work around "fun and giggles" below
1924 Variable::Magic::dispell (${$_[0]}, $_[1]{magic_selfref})
1925 unless (caller(2))[3] eq 'DBIx::Class::ResultSet::pager';
1932 if ($_[2] eq $slot and !$_[1]{inactive}) {
1933 my $cnt = $_[1]{total_rs}->count;
1934 $_[0]->{$slot} = $cnt;
1936 # attempting to dispell in a fetch handle (works in store), seems
1937 # to invariable segfault on 5.10, 5.12, 5.13 :(
1938 # so use an inactivator instead
1939 #Variable::Magic::dispell (%{$_[0]}, $_[1]{magic_selfref});
1945 if (! $_[1]{inactive} and $_[2] eq $slot) {
1946 #Variable::Magic::dispell (%{$_[0]}, $_[1]{magic_selfref});
1948 unless (caller(2))[3] eq 'DBIx::Class::ResultSet::pager';
1955 $stash->{magic_selfref} = $magic;
1956 weaken ($stash->{magic_selfref}); # this fails on 5.8.1
1961 # the tie class for 5.8.1
1963 package # hide from pause
1964 DBIx::Class::__DBIC_LAZY_RS_COUNT__;
1965 use base qw/Tie::Hash/;
1967 sub FIRSTKEY { my $dummy = scalar keys %{$_[0]{data}}; each %{$_[0]{data}} }
1968 sub NEXTKEY { each %{$_[0]{data}} }
1969 sub EXISTS { exists $_[0]{data}{$_[1]} }
1970 sub DELETE { delete $_[0]{data}{$_[1]} }
1971 sub CLEAR { %{$_[0]{data}} = () }
1972 sub SCALAR { scalar %{$_[0]{data}} }
1975 $_[1]{data} = {%{$_[1]{selfref}}};
1976 %{$_[1]{selfref}} = ();
1977 Scalar::Util::weaken ($_[1]{selfref});
1978 return bless ($_[1], $_[0]);
1982 if ($_[1] eq $_[0]{slot}) {
1983 my $cnt = $_[0]{data}{$_[1]} = $_[0]{total_rs}->count;
1984 untie %{$_[0]{selfref}};
1985 %{$_[0]{selfref}} = %{$_[0]{data}};
1994 $_[0]{data}{$_[1]} = $_[2];
1995 if ($_[1] eq $_[0]{slot}) {
1996 untie %{$_[0]{selfref}};
1997 %{$_[0]{selfref}} = %{$_[0]{data}};
2006 return $self->{pager} if $self->{pager};
2008 if ($self->get_cache) {
2009 $self->throw_exception ('Pagers on cached resultsets are not supported');
2012 my $attrs = $self->{attrs};
2013 if (!defined $attrs->{page}) {
2014 $self->throw_exception("Can't create pager for non-paged rs");
2016 elsif ($attrs->{page} <= 0) {
2017 $self->throw_exception('Invalid page number (page-numbers are 1-based)');
2019 $attrs->{rows} ||= 10;
2021 # throw away the paging flags and re-run the count (possibly
2022 # with a subselect) to get the real total count
2023 my $count_attrs = { %$attrs };
2024 delete $count_attrs->{$_} for qw/rows offset page pager/;
2025 my $total_rs = (ref $self)->new($self->result_source, $count_attrs);
2028 ### the following may seem awkward and dirty, but it's a thought-experiment
2029 ### necessary for future development of DBIx::DS. Do *NOT* change this code
2030 ### before talking to ribasushi/mst
2032 my $pager = Data::Page->new(
2033 0, #start with an empty set
2035 $self->{attrs}{page},
2038 my $data_slot = 'total_entries';
2040 # Since we are interested in a cached value (once it's set - it's set), every
2041 # technique will detach from the magic-host once the time comes to fire the
2042 # ->count (or in the segfaulting case of >= 5.10 it will deactivate itself)
2044 if ($] < 5.008003) {
2045 # 5.8.1 throws 'Modification of a read-only value attempted' when one tries
2046 # to weakref the magic container :(
2048 tie (%$pager, 'DBIx::Class::__DBIC_LAZY_RS_COUNT__',
2049 { slot => $data_slot, total_rs => $total_rs, selfref => $pager }
2052 elsif ($] < 5.010) {
2053 # We can use magic on the hash value slot. It's interesting that the magic is
2054 # attached to the hash-slot, and does *not* stop working once I do the dummy
2055 # assignments after the cast()
2056 # tested on 5.8.3 and 5.8.9
2057 my $magic = $mk_lazy_count_wizard->($total_rs);
2058 Variable::Magic::cast ( $pager->{$data_slot}, $magic );
2060 # this is for fun and giggles
2061 $pager->{$data_slot} = -1;
2062 $pager->{$data_slot} = 0;
2064 # this does not work for scalars, but works with
2066 #my %vals = %$pager;
2071 # And the uvar magic
2072 # works on 5.10.1, 5.12.1 and 5.13.4 in its current form,
2073 # however see the wizard maker for more notes
2074 my $magic = $mk_lazy_count_wizard->($total_rs, $data_slot);
2075 Variable::Magic::cast ( %$pager, $magic );
2078 $pager->{$data_slot} = -1;
2079 $pager->{$data_slot} = 0;
2087 return $self->{pager} = $pager;
2094 =item Arguments: $page_number
2096 =item Return Value: $rs
2100 Returns a resultset for the $page_number page of the resultset on which page
2101 is called, where each page contains a number of rows equal to the 'rows'
2102 attribute set on the resultset (10 by default).
2107 my ($self, $page) = @_;
2108 return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
2115 =item Arguments: \%vals
2117 =item Return Value: $rowobject
2121 Creates a new row object in the resultset's result class and returns
2122 it. The row is not inserted into the database at this point, call
2123 L<DBIx::Class::Row/insert> to do that. Calling L<DBIx::Class::Row/in_storage>
2124 will tell you whether the row object has been inserted or not.
2126 Passes the hashref of input on to L<DBIx::Class::Row/new>.
2131 my ($self, $values) = @_;
2132 $self->throw_exception( "new_result needs a hash" )
2133 unless (ref $values eq 'HASH');
2135 my ($merged_cond, $cols_from_relations) = $self->_merge_with_rscond($values);
2139 @$cols_from_relations
2140 ? (-cols_from_relations => $cols_from_relations)
2142 -source_handle => $self->_source_handle,
2143 -result_source => $self->result_source, # DO NOT REMOVE THIS, REQUIRED
2146 return $self->result_class->new(\%new);
2149 # _merge_with_rscond
2151 # Takes a simple hash of K/V data and returns its copy merged with the
2152 # condition already present on the resultset. Additionally returns an
2153 # arrayref of value/condition names, which were inferred from related
2154 # objects (this is needed for in-memory related objects)
2155 sub _merge_with_rscond {
2156 my ($self, $data) = @_;
2158 my (%new_data, @cols_from_relations);
2160 my $alias = $self->{attrs}{alias};
2162 if (! defined $self->{cond}) {
2163 # just massage $data below
2165 elsif ($self->{cond} eq $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION) {
2166 %new_data = %{ $self->{attrs}{related_objects} || {} }; # nothing might have been inserted yet
2167 @cols_from_relations = keys %new_data;
2169 elsif (ref $self->{cond} ne 'HASH') {
2170 $self->throw_exception(
2171 "Can't abstract implicit construct, resultset condition not a hash"
2175 # precendence must be given to passed values over values inherited from
2176 # the cond, so the order here is important.
2177 my $collapsed_cond = $self->_collapse_cond($self->{cond});
2178 my %implied = %{$self->_remove_alias($collapsed_cond, $alias)};
2180 while ( my($col, $value) = each %implied ) {
2181 my $vref = ref $value;
2182 if ($vref eq 'HASH' && keys(%$value) && (keys %$value)[0] eq '=') {
2183 $new_data{$col} = $value->{'='};
2185 elsif( !$vref or $vref eq 'SCALAR' or blessed($value) ) {
2186 $new_data{$col} = $value;
2193 %{ $self->_remove_alias($data, $alias) },
2196 return (\%new_data, \@cols_from_relations);
2199 # _has_resolved_attr
2201 # determines if the resultset defines at least one
2202 # of the attributes supplied
2204 # used to determine if a subquery is neccessary
2206 # supports some virtual attributes:
2208 # This will scan for any joins being present on the resultset.
2209 # It is not a mere key-search but a deep inspection of {from}
2212 sub _has_resolved_attr {
2213 my ($self, @attr_names) = @_;
2215 my $attrs = $self->_resolved_attrs;
2219 for my $n (@attr_names) {
2220 if (grep { $n eq $_ } (qw/-join/) ) {
2221 $extra_checks{$n}++;
2225 my $attr = $attrs->{$n};
2227 next if not defined $attr;
2229 if (ref $attr eq 'HASH') {
2230 return 1 if keys %$attr;
2232 elsif (ref $attr eq 'ARRAY') {
2240 # a resolved join is expressed as a multi-level from
2242 $extra_checks{-join}
2244 ref $attrs->{from} eq 'ARRAY'
2246 @{$attrs->{from}} > 1
2254 # Recursively collapse the condition.
2256 sub _collapse_cond {
2257 my ($self, $cond, $collapsed) = @_;
2261 if (ref $cond eq 'ARRAY') {
2262 foreach my $subcond (@$cond) {
2263 next unless ref $subcond; # -or
2264 $collapsed = $self->_collapse_cond($subcond, $collapsed);
2267 elsif (ref $cond eq 'HASH') {
2268 if (keys %$cond and (keys %$cond)[0] eq '-and') {
2269 foreach my $subcond (@{$cond->{-and}}) {
2270 $collapsed = $self->_collapse_cond($subcond, $collapsed);
2274 foreach my $col (keys %$cond) {
2275 my $value = $cond->{$col};
2276 $collapsed->{$col} = $value;
2286 # Remove the specified alias from the specified query hash. A copy is made so
2287 # the original query is not modified.
2290 my ($self, $query, $alias) = @_;
2292 my %orig = %{ $query || {} };
2295 foreach my $key (keys %orig) {
2297 $unaliased{$key} = $orig{$key};
2300 $unaliased{$1} = $orig{$key}
2301 if $key =~ m/^(?:\Q$alias\E\.)?([^.]+)$/;
2311 =item Arguments: none
2313 =item Return Value: \[ $sql, @bind ]
2317 Returns the SQL query and bind vars associated with the invocant.
2319 This is generally used as the RHS for a subquery.
2326 my $attrs = $self->_resolved_attrs_copy;
2331 # my ($sql, \@bind, \%dbi_bind_attrs) = _select_args_to_query (...)
2332 # $sql also has no wrapping parenthesis in list ctx
2334 my $sqlbind = $self->result_source->storage
2335 ->_select_args_to_query ($attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs);
2344 =item Arguments: \%vals, \%attrs?
2346 =item Return Value: $rowobject
2350 my $artist = $schema->resultset('Artist')->find_or_new(
2351 { artist => 'fred' }, { key => 'artists' });
2353 $cd->cd_to_producer->find_or_new({ producer => $producer },
2354 { key => 'primary });
2356 Find an existing record from this resultset using L</find>. if none exists,
2357 instantiate a new result object and return it. The object will not be saved
2358 into your storage until you call L<DBIx::Class::Row/insert> on it.
2360 You most likely want this method when looking for existing rows using a unique
2361 constraint that is not the primary key, or looking for related rows.
2363 If you want objects to be saved immediately, use L</find_or_create> instead.
2365 B<Note>: Make sure to read the documentation of L</find> and understand the
2366 significance of the C<key> attribute, as its lack may skew your search, and
2367 subsequently result in spurious new objects.
2369 B<Note>: Take care when using C<find_or_new> with a table having
2370 columns with default values that you intend to be automatically
2371 supplied by the database (e.g. an auto_increment primary key column).
2372 In normal usage, the value of such columns should NOT be included at
2373 all in the call to C<find_or_new>, even when set to C<undef>.
2379 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2380 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
2381 if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2384 return $self->new_result($hash);
2391 =item Arguments: \%vals
2393 =item Return Value: a L<DBIx::Class::Row> $object
2397 Attempt to create a single new row or a row with multiple related rows
2398 in the table represented by the resultset (and related tables). This
2399 will not check for duplicate rows before inserting, use
2400 L</find_or_create> to do that.
2402 To create one row for this resultset, pass a hashref of key/value
2403 pairs representing the columns of the table and the values you wish to
2404 store. If the appropriate relationships are set up, foreign key fields
2405 can also be passed an object representing the foreign row, and the
2406 value will be set to its primary key.
2408 To create related objects, pass a hashref of related-object column values
2409 B<keyed on the relationship name>. If the relationship is of type C<multi>
2410 (L<DBIx::Class::Relationship/has_many>) - pass an arrayref of hashrefs.
2411 The process will correctly identify columns holding foreign keys, and will
2412 transparently populate them from the keys of the corresponding relation.
2413 This can be applied recursively, and will work correctly for a structure
2414 with an arbitrary depth and width, as long as the relationships actually
2415 exists and the correct column data has been supplied.
2418 Instead of hashrefs of plain related data (key/value pairs), you may
2419 also pass new or inserted objects. New objects (not inserted yet, see
2420 L</new>), will be inserted into their appropriate tables.
2422 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
2424 Example of creating a new row.
2426 $person_rs->create({
2427 name=>"Some Person",
2428 email=>"somebody@someplace.com"
2431 Example of creating a new row and also creating rows in a related C<has_many>
2432 or C<has_one> resultset. Note Arrayref.
2435 { artistid => 4, name => 'Manufactured Crap', cds => [
2436 { title => 'My First CD', year => 2006 },
2437 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
2442 Example of creating a new row and also creating a row in a related
2443 C<belongs_to> resultset. Note Hashref.
2446 title=>"Music for Silly Walks",
2449 name=>"Silly Musician",
2457 When subclassing ResultSet never attempt to override this method. Since
2458 it is a simple shortcut for C<< $self->new_result($attrs)->insert >>, a
2459 lot of the internals simply never call it, so your override will be
2460 bypassed more often than not. Override either L<new|DBIx::Class::Row/new>
2461 or L<insert|DBIx::Class::Row/insert> depending on how early in the
2462 L</create> process you need to intervene.
2469 my ($self, $attrs) = @_;
2470 $self->throw_exception( "create needs a hashref" )
2471 unless ref $attrs eq 'HASH';
2472 return $self->new_result($attrs)->insert;
2475 =head2 find_or_create
2479 =item Arguments: \%vals, \%attrs?
2481 =item Return Value: $rowobject
2485 $cd->cd_to_producer->find_or_create({ producer => $producer },
2486 { key => 'primary' });
2488 Tries to find a record based on its primary key or unique constraints; if none
2489 is found, creates one and returns that instead.
2491 my $cd = $schema->resultset('CD')->find_or_create({
2493 artist => 'Massive Attack',
2494 title => 'Mezzanine',
2498 Also takes an optional C<key> attribute, to search by a specific key or unique
2499 constraint. For example:
2501 my $cd = $schema->resultset('CD')->find_or_create(
2503 artist => 'Massive Attack',
2504 title => 'Mezzanine',
2506 { key => 'cd_artist_title' }
2509 B<Note>: Make sure to read the documentation of L</find> and understand the
2510 significance of the C<key> attribute, as its lack may skew your search, and
2511 subsequently result in spurious row creation.
2513 B<Note>: Because find_or_create() reads from the database and then
2514 possibly inserts based on the result, this method is subject to a race
2515 condition. Another process could create a record in the table after
2516 the find has completed and before the create has started. To avoid
2517 this problem, use find_or_create() inside a transaction.
2519 B<Note>: Take care when using C<find_or_create> with a table having
2520 columns with default values that you intend to be automatically
2521 supplied by the database (e.g. an auto_increment primary key column).
2522 In normal usage, the value of such columns should NOT be included at
2523 all in the call to C<find_or_create>, even when set to C<undef>.
2525 See also L</find> and L</update_or_create>. For information on how to declare
2526 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2530 sub find_or_create {
2532 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2533 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
2534 if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2537 return $self->create($hash);
2540 =head2 update_or_create
2544 =item Arguments: \%col_values, { key => $unique_constraint }?
2546 =item Return Value: $row_object
2550 $resultset->update_or_create({ col => $val, ... });
2552 Like L</find_or_create>, but if a row is found it is immediately updated via
2553 C<< $found_row->update (\%col_values) >>.
2556 Takes an optional C<key> attribute to search on a specific unique constraint.
2559 # In your application
2560 my $cd = $schema->resultset('CD')->update_or_create(
2562 artist => 'Massive Attack',
2563 title => 'Mezzanine',
2566 { key => 'cd_artist_title' }
2569 $cd->cd_to_producer->update_or_create({
2570 producer => $producer,
2576 B<Note>: Make sure to read the documentation of L</find> and understand the
2577 significance of the C<key> attribute, as its lack may skew your search, and
2578 subsequently result in spurious row creation.
2580 B<Note>: Take care when using C<update_or_create> with a table having
2581 columns with default values that you intend to be automatically
2582 supplied by the database (e.g. an auto_increment primary key column).
2583 In normal usage, the value of such columns should NOT be included at
2584 all in the call to C<update_or_create>, even when set to C<undef>.
2586 See also L</find> and L</find_or_create>. For information on how to declare
2587 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2591 sub update_or_create {
2593 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2594 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
2596 my $row = $self->find($cond, $attrs);
2598 $row->update($cond);
2602 return $self->create($cond);
2605 =head2 update_or_new
2609 =item Arguments: \%col_values, { key => $unique_constraint }?
2611 =item Return Value: $rowobject
2615 $resultset->update_or_new({ col => $val, ... });
2617 Like L</find_or_new> but if a row is found it is immediately updated via
2618 C<< $found_row->update (\%col_values) >>.
2622 # In your application
2623 my $cd = $schema->resultset('CD')->update_or_new(
2625 artist => 'Massive Attack',
2626 title => 'Mezzanine',
2629 { key => 'cd_artist_title' }
2632 if ($cd->in_storage) {
2633 # the cd was updated
2636 # the cd is not yet in the database, let's insert it
2640 B<Note>: Make sure to read the documentation of L</find> and understand the
2641 significance of the C<key> attribute, as its lack may skew your search, and
2642 subsequently result in spurious new objects.
2644 B<Note>: Take care when using C<update_or_new> with a table having
2645 columns with default values that you intend to be automatically
2646 supplied by the database (e.g. an auto_increment primary key column).
2647 In normal usage, the value of such columns should NOT be included at
2648 all in the call to C<update_or_new>, even when set to C<undef>.
2650 See also L</find>, L</find_or_create> and L</find_or_new>.
2656 my $attrs = ( @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {} );
2657 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
2659 my $row = $self->find( $cond, $attrs );
2660 if ( defined $row ) {
2661 $row->update($cond);
2665 return $self->new_result($cond);
2672 =item Arguments: none
2674 =item Return Value: \@cache_objects | undef
2678 Gets the contents of the cache for the resultset, if the cache is set.
2680 The cache is populated either by using the L</prefetch> attribute to
2681 L</search> or by calling L</set_cache>.
2693 =item Arguments: \@cache_objects
2695 =item Return Value: \@cache_objects
2699 Sets the contents of the cache for the resultset. Expects an arrayref
2700 of objects of the same class as those produced by the resultset. Note that
2701 if the cache is set the resultset will return the cached objects rather
2702 than re-querying the database even if the cache attr is not set.
2704 The contents of the cache can also be populated by using the
2705 L</prefetch> attribute to L</search>.
2710 my ( $self, $data ) = @_;
2711 $self->throw_exception("set_cache requires an arrayref")
2712 if defined($data) && (ref $data ne 'ARRAY');
2713 $self->{all_cache} = $data;
2720 =item Arguments: none
2722 =item Return Value: undef
2726 Clears the cache for the resultset.
2731 shift->set_cache(undef);
2738 =item Arguments: none
2740 =item Return Value: true, if the resultset has been paginated
2748 return !!$self->{attrs}{page};
2755 =item Arguments: none
2757 =item Return Value: true, if the resultset has been ordered with C<order_by>.
2765 return scalar $self->result_source->storage->_extract_order_criteria($self->{attrs}{order_by});
2768 =head2 related_resultset
2772 =item Arguments: $relationship_name
2774 =item Return Value: $resultset
2778 Returns a related resultset for the supplied relationship name.
2780 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
2784 sub related_resultset {
2785 my ($self, $rel) = @_;
2787 $self->{related_resultsets} ||= {};
2788 return $self->{related_resultsets}{$rel} ||= do {
2789 my $rsrc = $self->result_source;
2790 my $rel_info = $rsrc->relationship_info($rel);
2792 $self->throw_exception(
2793 "search_related: result source '" . $rsrc->source_name .
2794 "' has no such relationship $rel")
2797 my $attrs = $self->_chain_relationship($rel);
2799 my $join_count = $attrs->{seen_join}{$rel};
2801 my $alias = $self->result_source->storage
2802 ->relname_to_table_alias($rel, $join_count);
2804 # since this is search_related, and we already slid the select window inwards
2805 # (the select/as attrs were deleted in the beginning), we need to flip all
2806 # left joins to inner, so we get the expected results
2807 # read the comment on top of the actual function to see what this does
2808 $attrs->{from} = $rsrc->schema->storage->_inner_join_to_node ($attrs->{from}, $alias);
2811 #XXX - temp fix for result_class bug. There likely is a more elegant fix -groditi
2812 delete @{$attrs}{qw(result_class alias)};
2816 if (my $cache = $self->get_cache) {
2817 if ($cache->[0] && $cache->[0]->related_resultset($rel)->get_cache) {
2818 $new_cache = [ map { @{$_->related_resultset($rel)->get_cache} }
2823 my $rel_source = $rsrc->related_source($rel);
2827 # The reason we do this now instead of passing the alias to the
2828 # search_rs below is that if you wrap/overload resultset on the
2829 # source you need to know what alias it's -going- to have for things
2830 # to work sanely (e.g. RestrictWithObject wants to be able to add
2831 # extra query restrictions, and these may need to be $alias.)
2833 my $rel_attrs = $rel_source->resultset_attributes;
2834 local $rel_attrs->{alias} = $alias;
2836 $rel_source->resultset
2840 where => $attrs->{where},
2843 $new->set_cache($new_cache) if $new_cache;
2848 =head2 current_source_alias
2852 =item Arguments: none
2854 =item Return Value: $source_alias
2858 Returns the current table alias for the result source this resultset is built
2859 on, that will be used in the SQL query. Usually it is C<me>.
2861 Currently the source alias that refers to the result set returned by a
2862 L</search>/L</find> family method depends on how you got to the resultset: it's
2863 C<me> by default, but eg. L</search_related> aliases it to the related result
2864 source name (and keeps C<me> referring to the original result set). The long
2865 term goal is to make L<DBIx::Class> always alias the current resultset as C<me>
2866 (and make this method unnecessary).
2868 Thus it's currently necessary to use this method in predefined queries (see
2869 L<DBIx::Class::Manual::Cookbook/Predefined searches>) when referring to the
2870 source alias of the current result set:
2872 # in a result set class
2874 my ($self, $user) = @_;
2876 my $me = $self->current_source_alias;
2878 return $self->search(
2879 "$me.modified" => $user->id,
2885 sub current_source_alias {
2888 return ($self->{attrs} || {})->{alias} || 'me';
2891 =head2 as_subselect_rs
2895 =item Arguments: none
2897 =item Return Value: $resultset
2901 Act as a barrier to SQL symbols. The resultset provided will be made into a
2902 "virtual view" by including it as a subquery within the from clause. From this
2903 point on, any joined tables are inaccessible to ->search on the resultset (as if
2904 it were simply where-filtered without joins). For example:
2906 my $rs = $schema->resultset('Bar')->search({'x.name' => 'abc'},{ join => 'x' });
2908 # 'x' now pollutes the query namespace
2910 # So the following works as expected
2911 my $ok_rs = $rs->search({'x.other' => 1});
2913 # But this doesn't: instead of finding a 'Bar' related to two x rows (abc and
2914 # def) we look for one row with contradictory terms and join in another table
2915 # (aliased 'x_2') which we never use
2916 my $broken_rs = $rs->search({'x.name' => 'def'});
2918 my $rs2 = $rs->as_subselect_rs;
2920 # doesn't work - 'x' is no longer accessible in $rs2, having been sealed away
2921 my $not_joined_rs = $rs2->search({'x.other' => 1});
2923 # works as expected: finds a 'table' row related to two x rows (abc and def)
2924 my $correctly_joined_rs = $rs2->search({'x.name' => 'def'});
2926 Another example of when one might use this would be to select a subset of
2927 columns in a group by clause:
2929 my $rs = $schema->resultset('Bar')->search(undef, {
2930 group_by => [qw{ id foo_id baz_id }],
2931 })->as_subselect_rs->search(undef, {
2932 columns => [qw{ id foo_id }]
2935 In the above example normally columns would have to be equal to the group by,
2936 but because we isolated the group by into a subselect the above works.
2940 sub as_subselect_rs {
2943 my $attrs = $self->_resolved_attrs;
2945 my $fresh_rs = (ref $self)->new (
2946 $self->result_source
2949 # these pieces will be locked in the subquery
2950 delete $fresh_rs->{cond};
2951 delete @{$fresh_rs->{attrs}}{qw/where bind/};
2953 return $fresh_rs->search( {}, {
2955 $attrs->{alias} => $self->as_query,
2956 -alias => $attrs->{alias},
2957 -source_handle => $self->result_source->handle,
2959 alias => $attrs->{alias},
2963 # This code is called by search_related, and makes sure there
2964 # is clear separation between the joins before, during, and
2965 # after the relationship. This information is needed later
2966 # in order to properly resolve prefetch aliases (any alias
2967 # with a relation_chain_depth less than the depth of the
2968 # current prefetch is not considered)
2970 # The increments happen twice per join. An even number means a
2971 # relationship specified via a search_related, whereas an odd
2972 # number indicates a join/prefetch added via attributes
2974 # Also this code will wrap the current resultset (the one we
2975 # chain to) in a subselect IFF it contains limiting attributes
2976 sub _chain_relationship {
2977 my ($self, $rel) = @_;
2978 my $source = $self->result_source;
2979 my $attrs = { %{$self->{attrs}||{}} };
2981 # we need to take the prefetch the attrs into account before we
2982 # ->_resolve_join as otherwise they get lost - captainL
2983 my $join = $self->_merge_joinpref_attr( $attrs->{join}, $attrs->{prefetch} );
2985 delete @{$attrs}{qw/join prefetch collapse group_by distinct select as columns +select +as +columns/};
2987 my $seen = { %{ (delete $attrs->{seen_join}) || {} } };
2990 my @force_subq_attrs = qw/offset rows group_by having/;
2993 ($attrs->{from} && ref $attrs->{from} ne 'ARRAY')
2995 $self->_has_resolved_attr (@force_subq_attrs)
2997 # Nuke the prefetch (if any) before the new $rs attrs
2998 # are resolved (prefetch is useless - we are wrapping
2999 # a subquery anyway).
3000 my $rs_copy = $self->search;
3001 $rs_copy->{attrs}{join} = $self->_merge_joinpref_attr (
3002 $rs_copy->{attrs}{join},
3003 delete $rs_copy->{attrs}{prefetch},
3007 -source_handle => $source->handle,
3008 -alias => $attrs->{alias},
3009 $attrs->{alias} => $rs_copy->as_query,
3011 delete @{$attrs}{@force_subq_attrs, qw/where bind/};
3012 $seen->{-relation_chain_depth} = 0;
3014 elsif ($attrs->{from}) { #shallow copy suffices
3015 $from = [ @{$attrs->{from}} ];
3019 -source_handle => $source->handle,
3020 -alias => $attrs->{alias},
3021 $attrs->{alias} => $source->from,
3025 my $jpath = ($seen->{-relation_chain_depth})
3026 ? $from->[-1][0]{-join_path}
3029 my @requested_joins = $source->_resolve_join(
3036 push @$from, @requested_joins;
3038 $seen->{-relation_chain_depth}++;
3040 # if $self already had a join/prefetch specified on it, the requested
3041 # $rel might very well be already included. What we do in this case
3042 # is effectively a no-op (except that we bump up the chain_depth on
3043 # the join in question so we could tell it *is* the search_related)
3046 # we consider the last one thus reverse
3047 for my $j (reverse @requested_joins) {
3048 my ($last_j) = keys %{$j->[0]{-join_path}[-1]};
3049 if ($rel eq $last_j) {
3050 $j->[0]{-relation_chain_depth}++;
3056 unless ($already_joined) {
3057 push @$from, $source->_resolve_join(
3065 $seen->{-relation_chain_depth}++;
3067 return {%$attrs, from => $from, seen_join => $seen};
3070 # too many times we have to do $attrs = { %{$self->_resolved_attrs} }
3071 sub _resolved_attrs_copy {
3073 return { %{$self->_resolved_attrs (@_)} };
3076 sub _resolved_attrs {
3078 return $self->{_attrs} if $self->{_attrs};
3080 my $attrs = { %{ $self->{attrs} || {} } };
3081 my $source = $self->result_source;
3082 my $alias = $attrs->{alias};
3085 # resolve selectors, this one is quite hairy
3087 my $selection_pieces;
3089 $attrs->{columns} ||= delete $attrs->{cols}
3090 if exists $attrs->{cols};
3092 # disassemble columns / +columns
3094 $selection_pieces->{columns}{select},
3095 $selection_pieces->{columns}{as},
3096 $selection_pieces->{'+columns'}{select},
3097 $selection_pieces->{'+columns'}{as},
3102 for my $colbit (@$_) {
3104 if (ref $colbit eq 'HASH') {
3105 for my $as (keys %$colbit) {
3106 push @sel, $colbit->{$as};
3119 (ref $attrs->{columns} eq 'ARRAY' ? delete $attrs->{columns} : [ delete $attrs->{columns} ]),
3120 # include_columns is a legacy add-on to +columns
3121 [ map { ref $_ eq 'ARRAY' ? @$_ : ($_ || () ) } delete @{$attrs}{qw/+columns include_columns/} ] )
3124 # make copies of select/as and +select/+as
3126 $selection_pieces->{'select/as'}{select},
3127 $selection_pieces->{'select/as'}{as},
3128 $selection_pieces->{'+select/+as'}{select},
3129 $selection_pieces->{'+select/+as'}{as},
3131 { $_ ? [ ref $_ eq 'ARRAY' ? @$_ : $_ ] : [] }
3132 ( delete @{$attrs}{qw/select as +select +as/} )
3135 # default to * only when neither no non-plus selectors are available
3137 ! @{$selection_pieces->{'select/as'}{select}}
3139 ! @{$selection_pieces->{'columns'}{select}}
3141 for ($source->columns) {
3142 push @{$selection_pieces->{'select/as'}{select}}, $_;
3143 push @{$selection_pieces->{'select/as'}{as}}, $_;
3147 # final composition order (important)
3148 my @sel_pairs = grep {
3149 $selection_pieces->{$_}
3152 ( $selection_pieces->{$_}{select} && @{$selection_pieces->{$_}{select}} )
3154 ( $selection_pieces->{$_}{as} && @{$selection_pieces->{$_}{as}} )
3156 } qw|columns select/as +columns +select/+as|;
3158 # fill in missing as bits for each pair
3159 # if it's the last pair we can let things slide ( bare +select is sadly popular)
3162 for my $i (0 .. $#sel_pairs) {
3164 my $pairname = $sel_pairs[$i];
3166 my ($sel, $as) = @{$selection_pieces->{$pairname}}{qw/select as/};
3168 $self->throw_exception(
3169 "Unable to assemble final selection list: $pairname specified in addition to unbalanced $sel_pairs[$i-1]"
3170 ) if ($out_of_sync);
3172 if (@$sel == @$as) {
3175 elsif (@$sel < @$as) {
3176 $self->throw_exception(
3177 "More 'as' elements than 'select' elements for $pairname, unable to continue"
3181 # try to deduce the 'as' part, will work only if all the selectors are "plain", or contain an explicit -as
3182 # if we can not deduce something - stop right there and leave the rest of the selector un-as'ed
3183 # if there is an extra selection pair coming after that - it will die due to out_of_sync being set
3184 for my $j ($#$as+1 .. $#$sel) {
3185 if (my $ref = ref $sel->[$j]) {
3186 if ($ref eq 'HASH' and exists $sel->[$j]{-as}) {
3187 push @$as, $sel->[$j]{-as};
3195 push @$as, $sel->[$j];
3201 # assume all unqualified selectors to apply to the current alias (legacy stuff)
3202 # disqualify all $alias.col as-bits (collapser mandated)
3203 for (values %$selection_pieces) {
3204 $_->{select} = [ map { (ref $_ or $_ =~ /\./) ? $_ : "$alias.$_" } @{$_->{select}} ];
3205 $_->{as} = [ map { $_ =~ /^\Q$alias.\E(.+)$/ ? $1 : $_ } @{$_->{as}} ];
3210 $attrs->{select} = $self->_merge_attr ($attrs->{select}, $selection_pieces->{$_}{select});
3211 $attrs->{as} = $self->_merge_attr ($attrs->{as}, $selection_pieces->{$_}{as});
3214 # de-duplicate the result (remove *identical* select/as pairs)
3215 # and also die on duplicate {as} pointing to different {select}s
3216 # not using a c-style for as the condition is prone to shrinkage
3219 while ($i <= $#{$attrs->{as}} ) {
3220 my ($sel, $as) = map { $attrs->{$_}[$i] } (qw/select as/);
3222 if ($seen->{"$sel \x00\x00 $as"}++) {
3224 for @{$attrs}{qw/select as/};
3226 elsif ($seen->{$as}++) {
3227 $self->throw_exception(
3228 "inflate_result() alias '$as' specified twice with different SQL-side {select}-ors"
3236 ## selector resolution done
3240 $attrs->{from} ||= [{
3241 -source_handle => $source->handle,
3242 -alias => $self->{attrs}{alias},
3243 $self->{attrs}{alias} => $source->from,
3246 if ( $attrs->{join} || $attrs->{prefetch} ) {
3248 $self->throw_exception ('join/prefetch can not be used with a custom {from}')
3249 if ref $attrs->{from} ne 'ARRAY';
3251 my $join = delete $attrs->{join} || {};
3253 if ( defined $attrs->{prefetch} ) {
3254 $join = $self->_merge_joinpref_attr( $join, $attrs->{prefetch} );
3257 $attrs->{from} = # have to copy here to avoid corrupting the original
3259 @{ $attrs->{from} },
3260 $source->_resolve_join(
3263 { %{ $attrs->{seen_join} || {} } },
3264 ( $attrs->{seen_join} && keys %{$attrs->{seen_join}})
3265 ? $attrs->{from}[-1][0]{-join_path}
3272 if ( defined $attrs->{order_by} ) {
3273 $attrs->{order_by} = (
3274 ref( $attrs->{order_by} ) eq 'ARRAY'
3275 ? [ @{ $attrs->{order_by} } ]
3276 : [ $attrs->{order_by} || () ]
3280 if ($attrs->{group_by} and ref $attrs->{group_by} ne 'ARRAY') {
3281 $attrs->{group_by} = [ $attrs->{group_by} ];
3284 # generate the distinct induced group_by early, as prefetch will be carried via a
3285 # subquery (since a group_by is present)
3286 if (delete $attrs->{distinct}) {
3287 if ($attrs->{group_by}) {
3288 carp ("Useless use of distinct on a grouped resultset ('distinct' is ignored when a 'group_by' is present)");
3291 $attrs->{group_by} = $source->storage->_group_over_selection (
3292 @{$attrs}{qw/from select order_by/}
3297 $attrs->{collapse} ||= {};
3298 if ( my $prefetch = delete $attrs->{prefetch} ) {
3299 $prefetch = $self->_merge_joinpref_attr( {}, $prefetch );
3301 my $prefetch_ordering = [];
3303 # this is a separate structure (we don't look in {from} directly)
3304 # as the resolver needs to shift things off the lists to work
3305 # properly (identical-prefetches on different branches)
3307 if (ref $attrs->{from} eq 'ARRAY') {
3309 my $start_depth = $attrs->{seen_join}{-relation_chain_depth} || 0;
3311 for my $j ( @{$attrs->{from}}[1 .. $#{$attrs->{from}} ] ) {
3312 next unless $j->[0]{-alias};
3313 next unless $j->[0]{-join_path};
3314 next if ($j->[0]{-relation_chain_depth} || 0) < $start_depth;
3316 my @jpath = map { keys %$_ } @{$j->[0]{-join_path}};
3319 $p = $p->{$_} ||= {} for @jpath[ ($start_depth/2) .. $#jpath]; #only even depths are actual jpath boundaries
3320 push @{$p->{-join_aliases} }, $j->[0]{-alias};
3325 $source->_resolve_prefetch( $prefetch, $alias, $join_map, $prefetch_ordering, $attrs->{collapse} );
3327 # we need to somehow mark which columns came from prefetch
3328 $attrs->{_prefetch_select} = [ map { $_->[0] } @prefetch ];
3330 push @{ $attrs->{select} }, @{$attrs->{_prefetch_select}};
3331 push @{ $attrs->{as} }, (map { $_->[1] } @prefetch);
3333 push( @{$attrs->{order_by}}, @$prefetch_ordering );
3334 $attrs->{_collapse_order_by} = \@$prefetch_ordering;
3337 # if both page and offset are specified, produce a combined offset
3338 # even though it doesn't make much sense, this is what pre 081xx has
3340 if (my $page = delete $attrs->{page}) {
3342 ($attrs->{rows} * ($page - 1))
3344 ($attrs->{offset} || 0)
3348 return $self->{_attrs} = $attrs;
3352 my ($self, $attr) = @_;
3354 if (ref $attr eq 'HASH') {
3355 return $self->_rollout_hash($attr);
3356 } elsif (ref $attr eq 'ARRAY') {
3357 return $self->_rollout_array($attr);
3363 sub _rollout_array {
3364 my ($self, $attr) = @_;
3367 foreach my $element (@{$attr}) {
3368 if (ref $element eq 'HASH') {
3369 push( @rolled_array, @{ $self->_rollout_hash( $element ) } );
3370 } elsif (ref $element eq 'ARRAY') {
3371 # XXX - should probably recurse here
3372 push( @rolled_array, @{$self->_rollout_array($element)} );
3374 push( @rolled_array, $element );
3377 return \@rolled_array;
3381 my ($self, $attr) = @_;
3384 foreach my $key (keys %{$attr}) {
3385 push( @rolled_array, { $key => $attr->{$key} } );
3387 return \@rolled_array;
3390 sub _calculate_score {
3391 my ($self, $a, $b) = @_;
3393 if (defined $a xor defined $b) {
3396 elsif (not defined $a) {
3400 if (ref $b eq 'HASH') {
3401 my ($b_key) = keys %{$b};
3402 if (ref $a eq 'HASH') {
3403 my ($a_key) = keys %{$a};
3404 if ($a_key eq $b_key) {
3405 return (1 + $self->_calculate_score( $a->{$a_key}, $b->{$b_key} ));
3410 return ($a eq $b_key) ? 1 : 0;
3413 if (ref $a eq 'HASH') {
3414 my ($a_key) = keys %{$a};
3415 return ($b eq $a_key) ? 1 : 0;
3417 return ($b eq $a) ? 1 : 0;
3422 sub _merge_joinpref_attr {
3423 my ($self, $orig, $import) = @_;
3425 return $import unless defined($orig);
3426 return $orig unless defined($import);
3428 $orig = $self->_rollout_attr($orig);
3429 $import = $self->_rollout_attr($import);
3432 foreach my $import_element ( @{$import} ) {
3433 # find best candidate from $orig to merge $b_element into
3434 my $best_candidate = { position => undef, score => 0 }; my $position = 0;
3435 foreach my $orig_element ( @{$orig} ) {
3436 my $score = $self->_calculate_score( $orig_element, $import_element );
3437 if ($score > $best_candidate->{score}) {
3438 $best_candidate->{position} = $position;
3439 $best_candidate->{score} = $score;
3443 my ($import_key) = ( ref $import_element eq 'HASH' ) ? keys %{$import_element} : ($import_element);
3445 if ($best_candidate->{score} == 0 || exists $seen_keys->{$import_key}) {
3446 push( @{$orig}, $import_element );
3448 my $orig_best = $orig->[$best_candidate->{position}];
3449 # merge orig_best and b_element together and replace original with merged
3450 if (ref $orig_best ne 'HASH') {
3451 $orig->[$best_candidate->{position}] = $import_element;
3452 } elsif (ref $import_element eq 'HASH') {
3453 my ($key) = keys %{$orig_best};
3454 $orig->[$best_candidate->{position}] = { $key => $self->_merge_joinpref_attr($orig_best->{$key}, $import_element->{$key}) };
3457 $seen_keys->{$import_key} = 1; # don't merge the same key twice
3468 my $hm = Hash::Merge->new;
3470 $hm->specify_behavior({
3473 my ($defl, $defr) = map { defined $_ } (@_[0,1]);
3475 if ($defl xor $defr) {
3476 return $defl ? $_[0] : $_[1];
3481 elsif (__HM_DEDUP and $_[0] eq $_[1]) {
3485 return [$_[0], $_[1]];
3489 return $_[1] if !defined $_[0];
3490 return $_[1] if __HM_DEDUP and List::Util::first { $_ eq $_[0] } @{$_[1]};
3491 return [$_[0], @{$_[1]}]
3494 return $_[1] if !defined $_[0];
3495 return $_[0] if !keys %{$_[1]};
3496 return [$_[0], $_[1]]
3501 return $_[0] if !defined $_[1];
3502 return $_[0] if __HM_DEDUP and List::Util::first { $_ eq $_[1] } @{$_[0]};
3503 return [@{$_[0]}, $_[1]]
3506 my @ret = @{$_[0]} or return $_[1];
3507 return [ @ret, @{$_[1]} ] unless __HM_DEDUP;
3508 my %idx = map { $_ => 1 } @ret;
3509 push @ret, grep { ! defined $idx{$_} } (@{$_[1]});
3513 return [ $_[1] ] if ! @{$_[0]};
3514 return $_[0] if !keys %{$_[1]};
3515 return $_[0] if __HM_DEDUP and List::Util::first { $_ eq $_[1] } @{$_[0]};
3516 return [ @{$_[0]}, $_[1] ];
3521 return $_[0] if !defined $_[1];
3522 return $_[1] if !keys %{$_[0]};
3523 return [$_[0], $_[1]]
3526 return $_[0] if !@{$_[1]};
3527 return $_[1] if !keys %{$_[0]};
3528 return $_[1] if __HM_DEDUP and List::Util::first { $_ eq $_[0] } @{$_[1]};
3529 return [ $_[0], @{$_[1]} ];
3532 return $_[0] if !keys %{$_[1]};
3533 return $_[1] if !keys %{$_[0]};
3534 return $_[0] if $_[0] eq $_[1];
3535 return [ $_[0], $_[1] ];
3538 } => 'DBIC_RS_ATTR_MERGER');
3542 return $hm->merge ($_[1], $_[2]);
3550 $self->_source_handle($_[0]->handle);
3552 $self->_source_handle->resolve;
3557 sub STORABLE_freeze {
3558 my ($self, $cloning) = @_;
3559 my $to_serialize = { %$self };
3561 # A cursor in progress can't be serialized (and would make little sense anyway)
3562 delete $to_serialize->{cursor};
3564 return nfreeze($to_serialize);
3567 # need this hook for symmetry
3569 my ($self, $cloning, $serialized) = @_;
3571 %$self = %{ thaw($serialized) };
3577 =head2 throw_exception
3579 See L<DBIx::Class::Schema/throw_exception> for details.
3583 sub throw_exception {
3586 if (ref $self && $self->_source_handle->schema) {
3587 $self->_source_handle->schema->throw_exception(@_)
3590 DBIx::Class::Exception->throw(@_);
3594 # XXX: FIXME: Attributes docs need clearing up
3598 Attributes are used to refine a ResultSet in various ways when
3599 searching for data. They can be passed to any method which takes an
3600 C<\%attrs> argument. See L</search>, L</search_rs>, L</find>,
3603 These are in no particular order:
3609 =item Value: ( $order_by | \@order_by | \%order_by )
3613 Which column(s) to order the results by.
3615 [The full list of suitable values is documented in
3616 L<SQL::Abstract/"ORDER BY CLAUSES">; the following is a summary of
3619 If a single column name, or an arrayref of names is supplied, the
3620 argument is passed through directly to SQL. The hashref syntax allows
3621 for connection-agnostic specification of ordering direction:
3623 For descending order:
3625 order_by => { -desc => [qw/col1 col2 col3/] }
3627 For explicit ascending order:
3629 order_by => { -asc => 'col' }
3631 The old scalarref syntax (i.e. order_by => \'year DESC') is still
3632 supported, although you are strongly encouraged to use the hashref
3633 syntax as outlined above.
3639 =item Value: \@columns
3643 Shortcut to request a particular set of columns to be retrieved. Each
3644 column spec may be a string (a table column name), or a hash (in which
3645 case the key is the C<as> value, and the value is used as the C<select>
3646 expression). Adds C<me.> onto the start of any column without a C<.> in
3647 it and sets C<select> from that, then auto-populates C<as> from
3648 C<select> as normal. (You may also use the C<cols> attribute, as in
3649 earlier versions of DBIC.)
3651 Essentially C<columns> does the same as L</select> and L</as>.
3653 columns => [ 'foo', { bar => 'baz' } ]
3657 select => [qw/foo baz/],
3664 =item Value: \@columns
3668 Indicates additional columns to be selected from storage. Works the same
3669 as L</columns> but adds columns to the selection. (You may also use the
3670 C<include_columns> attribute, as in earlier versions of DBIC). For
3673 $schema->resultset('CD')->search(undef, {
3674 '+columns' => ['artist.name'],
3678 would return all CDs and include a 'name' column to the information
3679 passed to object inflation. Note that the 'artist' is the name of the
3680 column (or relationship) accessor, and 'name' is the name of the column
3681 accessor in the related table.
3683 =head2 include_columns
3687 =item Value: \@columns
3691 Deprecated. Acts as a synonym for L</+columns> for backward compatibility.
3697 =item Value: \@select_columns
3701 Indicates which columns should be selected from the storage. You can use
3702 column names, or in the case of RDBMS back ends, function or stored procedure
3705 $rs = $schema->resultset('Employee')->search(undef, {
3708 { count => 'employeeid' },
3709 { max => { length => 'name' }, -as => 'longest_name' }
3714 SELECT name, COUNT( employeeid ), MAX( LENGTH( name ) ) AS longest_name FROM employee
3716 B<NOTE:> You will almost always need a corresponding L</as> attribute when you
3717 use L</select>, to instruct DBIx::Class how to store the result of the column.
3718 Also note that the L</as> attribute has nothing to do with the SQL-side 'AS'
3719 identifier aliasing. You can however alias a function, so you can use it in
3720 e.g. an C<ORDER BY> clause. This is done via the C<-as> B<select function
3721 attribute> supplied as shown in the example above.
3727 Indicates additional columns to be selected from storage. Works the same as
3728 L</select> but adds columns to the default selection, instead of specifying
3737 Indicates additional column names for those added via L</+select>. See L</as>.
3745 =item Value: \@inflation_names
3749 Indicates column names for object inflation. That is L</as> indicates the
3750 slot name in which the column value will be stored within the
3751 L<Row|DBIx::Class::Row> object. The value will then be accessible via this
3752 identifier by the C<get_column> method (or via the object accessor B<if one
3753 with the same name already exists>) as shown below. The L</as> attribute has
3754 B<nothing to do> with the SQL-side C<AS>. See L</select> for details.
3756 $rs = $schema->resultset('Employee')->search(undef, {
3759 { count => 'employeeid' },
3760 { max => { length => 'name' }, -as => 'longest_name' }
3769 If the object against which the search is performed already has an accessor
3770 matching a column name specified in C<as>, the value can be retrieved using
3771 the accessor as normal:
3773 my $name = $employee->name();
3775 If on the other hand an accessor does not exist in the object, you need to
3776 use C<get_column> instead:
3778 my $employee_count = $employee->get_column('employee_count');
3780 You can create your own accessors if required - see
3781 L<DBIx::Class::Manual::Cookbook> for details.
3787 =item Value: ($rel_name | \@rel_names | \%rel_names)
3791 Contains a list of relationships that should be joined for this query. For
3794 # Get CDs by Nine Inch Nails
3795 my $rs = $schema->resultset('CD')->search(
3796 { 'artist.name' => 'Nine Inch Nails' },
3797 { join => 'artist' }
3800 Can also contain a hash reference to refer to the other relation's relations.
3803 package MyApp::Schema::Track;
3804 use base qw/DBIx::Class/;
3805 __PACKAGE__->table('track');
3806 __PACKAGE__->add_columns(qw/trackid cd position title/);
3807 __PACKAGE__->set_primary_key('trackid');
3808 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
3811 # In your application
3812 my $rs = $schema->resultset('Artist')->search(
3813 { 'track.title' => 'Teardrop' },
3815 join => { cd => 'track' },
3816 order_by => 'artist.name',
3820 You need to use the relationship (not the table) name in conditions,
3821 because they are aliased as such. The current table is aliased as "me", so
3822 you need to use me.column_name in order to avoid ambiguity. For example:
3824 # Get CDs from 1984 with a 'Foo' track
3825 my $rs = $schema->resultset('CD')->search(
3828 'tracks.name' => 'Foo'
3830 { join => 'tracks' }
3833 If the same join is supplied twice, it will be aliased to <rel>_2 (and
3834 similarly for a third time). For e.g.
3836 my $rs = $schema->resultset('Artist')->search({
3837 'cds.title' => 'Down to Earth',
3838 'cds_2.title' => 'Popular',
3840 join => [ qw/cds cds/ ],
3843 will return a set of all artists that have both a cd with title 'Down
3844 to Earth' and a cd with title 'Popular'.
3846 If you want to fetch related objects from other tables as well, see C<prefetch>
3849 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
3855 =item Value: ($rel_name | \@rel_names | \%rel_names)
3859 Contains one or more relationships that should be fetched along with
3860 the main query (when they are accessed afterwards the data will
3861 already be available, without extra queries to the database). This is
3862 useful for when you know you will need the related objects, because it
3863 saves at least one query:
3865 my $rs = $schema->resultset('Tag')->search(
3874 The initial search results in SQL like the following:
3876 SELECT tag.*, cd.*, artist.* FROM tag
3877 JOIN cd ON tag.cd = cd.cdid
3878 JOIN artist ON cd.artist = artist.artistid
3880 L<DBIx::Class> has no need to go back to the database when we access the
3881 C<cd> or C<artist> relationships, which saves us two SQL statements in this
3884 Simple prefetches will be joined automatically, so there is no need
3885 for a C<join> attribute in the above search.
3887 C<prefetch> can be used with the following relationship types: C<belongs_to>,
3888 C<has_one> (or if you're using C<add_relationship>, any relationship declared
3889 with an accessor type of 'single' or 'filter'). A more complex example that
3890 prefetches an artists cds, the tracks on those cds, and the tags associated
3891 with that artist is given below (assuming many-to-many from artists to tags):
3893 my $rs = $schema->resultset('Artist')->search(
3897 { cds => 'tracks' },
3898 { artist_tags => 'tags' }
3904 B<NOTE:> If you specify a C<prefetch> attribute, the C<join> and C<select>
3905 attributes will be ignored.
3907 B<CAVEATs>: Prefetch does a lot of deep magic. As such, it may not behave
3908 exactly as you might expect.
3914 Prefetch uses the L</cache> to populate the prefetched relationships. This
3915 may or may not be what you want.
3919 If you specify a condition on a prefetched relationship, ONLY those
3920 rows that match the prefetched condition will be fetched into that relationship.
3921 This means that adding prefetch to a search() B<may alter> what is returned by
3922 traversing a relationship. So, if you have C<< Artist->has_many(CDs) >> and you do
3924 my $artist_rs = $schema->resultset('Artist')->search({
3930 my $count = $artist_rs->first->cds->count;
3932 my $artist_rs_prefetch = $artist_rs->search( {}, { prefetch => 'cds' } );
3934 my $prefetch_count = $artist_rs_prefetch->first->cds->count;
3936 cmp_ok( $count, '==', $prefetch_count, "Counts should be the same" );
3938 that cmp_ok() may or may not pass depending on the datasets involved. This
3939 behavior may or may not survive the 0.09 transition.
3951 Makes the resultset paged and specifies the page to retrieve. Effectively
3952 identical to creating a non-pages resultset and then calling ->page($page)
3955 If L<rows> attribute is not specified it defaults to 10 rows per page.
3957 When you have a paged resultset, L</count> will only return the number
3958 of rows in the page. To get the total, use the L</pager> and call
3959 C<total_entries> on it.
3969 Specifies the maximum number of rows for direct retrieval or the number of
3970 rows per page if the page attribute or method is used.
3976 =item Value: $offset
3980 Specifies the (zero-based) row number for the first row to be returned, or the
3981 of the first row of the first page if paging is used.
3987 =item Value: \@columns
3991 A arrayref of columns to group by. Can include columns of joined tables.
3993 group_by => [qw/ column1 column2 ... /]
3999 =item Value: $condition
4003 HAVING is a select statement attribute that is applied between GROUP BY and
4004 ORDER BY. It is applied to the after the grouping calculations have been
4007 having => { 'count_employee' => { '>=', 100 } }
4009 or with an in-place function in which case literal SQL is required:
4011 having => \[ 'count(employee) >= ?', [ count => 100 ] ]
4017 =item Value: (0 | 1)
4021 Set to 1 to group by all columns. If the resultset already has a group_by
4022 attribute, this setting is ignored and an appropriate warning is issued.
4028 Adds to the WHERE clause.
4030 # only return rows WHERE deleted IS NULL for all searches
4031 __PACKAGE__->resultset_attributes({ where => { deleted => undef } }); )
4033 Can be overridden by passing C<< { where => undef } >> as an attribute
4040 Set to 1 to cache search results. This prevents extra SQL queries if you
4041 revisit rows in your ResultSet:
4043 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
4045 while( my $artist = $resultset->next ) {
4049 $rs->first; # without cache, this would issue a query
4051 By default, searches are not cached.
4053 For more examples of using these attributes, see
4054 L<DBIx::Class::Manual::Cookbook>.
4060 =item Value: ( 'update' | 'shared' )
4064 Set to 'update' for a SELECT ... FOR UPDATE or 'shared' for a SELECT