1 package DBIx::Class::ResultSet;
5 use base qw/DBIx::Class/;
6 use Carp::Clan qw/^DBIx::Class/;
7 use DBIx::Class::Exception;
9 use DBIx::Class::ResultSetColumn;
10 use DBIx::Class::ResultSourceHandle;
12 use Scalar::Util qw/blessed weaken/;
14 use Storable qw/nfreeze thaw/;
16 # not importing first() as it will clash with our own method
23 # De-duplication in _merge_attr() is disabled, but left in for reference
24 # (the merger is used for other things that ought not to be de-duped)
25 *__HM_DEDUP = sub () { 0 };
33 __PACKAGE__->mk_group_accessors('simple' => qw/_result_class result_source/);
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->resolve
200 if $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 result_source => $source,
213 cond => $attrs->{where},
221 $attrs->{result_class} || $source->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] ) {
319 if (ref $_[-1] eq 'HASH') {
320 # copy for _normalize_selection
321 $call_attrs = { %{ pop @_ } };
323 elsif (! defined $_[-1] ) {
324 pop @_; # search({}, undef)
328 # see if we can keep the cache (no $rs changes)
330 my %safe = (alias => 1, cache => 1);
331 if ( ! List::Util::first { !$safe{$_} } keys %$call_attrs and (
334 ref $_[0] eq 'HASH' && ! keys %{$_[0]}
336 ref $_[0] eq 'ARRAY' && ! @{$_[0]}
338 $cache = $self->get_cache;
341 my $rsrc = $self->result_source;
343 my $old_attrs = { %{$self->{attrs}} };
344 my $old_having = delete $old_attrs->{having};
345 my $old_where = delete $old_attrs->{where};
347 my $new_attrs = { %$old_attrs };
349 # take care of call attrs (only if anything is changing)
350 if (keys %$call_attrs) {
352 $self->throw_exception ('_trailing_select is not a public attribute - do not use it in search()')
353 if ( exists $call_attrs->{_trailing_select} or exists $call_attrs->{'+_trailing_select'} );
355 my @selector_attrs = qw/select as columns cols +select +as +columns include_columns _trailing_select +_trailing_select/;
357 # Normalize the selector list (operates on the passed-in attr structure)
358 # Need to do it on every chain instead of only once on _resolved_attrs, in
359 # order to separate 'as'-ed from blind 'select's
360 $self->_normalize_selection ($call_attrs);
362 # start with blind overwriting merge, exclude selector attrs
363 $new_attrs = { %{$old_attrs}, %{$call_attrs} };
364 delete @{$new_attrs}{@selector_attrs};
366 # reset the current selector list if new selectors are supplied
367 if (List::Util::first { exists $call_attrs->{$_} } qw/columns cols select as/) {
368 delete @{$old_attrs}{@selector_attrs};
371 for (@selector_attrs) {
372 $new_attrs->{$_} = $self->_merge_attr($old_attrs->{$_}, $call_attrs->{$_})
373 if ( exists $old_attrs->{$_} or exists $call_attrs->{$_} );
376 # older deprecated name, use only if {columns} is not there
377 if (my $c = delete $new_attrs->{cols}) {
378 if ($new_attrs->{columns}) {
379 carp "Resultset specifies both the 'columns' and the legacy 'cols' attributes - ignoring 'cols'";
382 $new_attrs->{columns} = $c;
387 # join/prefetch use their own crazy merging heuristics
388 foreach my $key (qw/join prefetch/) {
389 $new_attrs->{$key} = $self->_merge_joinpref_attr($old_attrs->{$key}, $call_attrs->{$key})
390 if exists $call_attrs->{$key};
393 # stack binds together
394 $new_attrs->{bind} = [ @{ $old_attrs->{bind} || [] }, @{ $call_attrs->{bind} || [] } ];
398 # rip apart the rest of @_, parse a condition
401 if (ref $_[0] eq 'HASH') {
402 (keys %{$_[0]}) ? $_[0] : undef
408 $self->throw_exception('Odd number of arguments to search')
416 if( @_ > 1 and ! $rsrc->result_class->isa('DBIx::Class::CDBICompat') ) {
417 # determine callsite obeying Carp::Clan rules (fucking ugly but don't have better ideas)
420 local $SIG{__WARN__} = sub { $w = shift };
424 carp 'search( %condition ) is deprecated, use search( \%condition ) instead'
425 unless $callsites_warned->{$callsite}++;
428 for ($old_where, $call_cond) {
430 $new_attrs->{where} = $self->_stack_cond (
431 $_, $new_attrs->{where}
436 if (defined $old_having) {
437 $new_attrs->{having} = $self->_stack_cond (
438 $old_having, $new_attrs->{having}
442 my $rs = (ref $self)->new($rsrc, $new_attrs);
444 $rs->set_cache($cache) if ($cache);
449 sub _normalize_selection {
450 my ($self, $attrs) = @_;
453 $attrs->{'+columns'} = $self->_merge_attr($attrs->{'+columns'}, delete $attrs->{include_columns})
454 if exists $attrs->{include_columns};
456 # Keep the X vs +X separation until _resolved_attrs time - this allows to
457 # delay the decision on whether to use a default select list ($rsrc->columns)
458 # allowing stuff like the remove_columns helper to work
460 # select/as +select/+as pairs need special handling - the amount of select/as
461 # elements in each pair does *not* have to be equal (think multicolumn
462 # selectors like distinct(foo, bar) ). If the selector is bare (no 'as'
463 # supplied at all) - try to infer the alias, either from the -as parameter
464 # of the selector spec, or use the parameter whole if it looks like a column
465 # name (ugly legacy heuristic). If all fails - leave the selector bare (which
466 # is ok as well), but transport it over a separate attribute to make sure it is
467 # the last thing in the select list, thus unable to throw off the corresponding
469 for my $pref ('', '+') {
471 my ($sel, $as) = map {
472 my $key = "${pref}${_}";
474 my $val = [ ref $attrs->{$key} eq 'ARRAY'
476 : $attrs->{$key} || ()
478 delete $attrs->{$key};
482 if (! @$as and ! @$sel ) {
485 elsif (@$as and ! @$sel) {
486 $self->throw_exception(
487 "Unable to handle ${pref}as specification (@$as) without a corresponding ${pref}select"
491 # no as part supplied at all - try to deduce
492 # if any @$as has been supplied we assume the user knows what (s)he is doing
493 # and blindly keep stacking up pieces
494 my (@new_sel, @new_trailing);
496 if ( ref $_ eq 'HASH' and exists $_->{-as} ) {
497 push @$as, $_->{-as};
500 # assume any plain no-space, no-parenthesis string to be a column spec
501 # FIXME - this is retarded but is necessary to support shit like 'count(foo)'
502 elsif ( ! ref $_ and $_ =~ /^ [^\s\(\)]+ $/x) {
506 # if all else fails - shove the selection to the trailing stack and move on
508 push @new_trailing, $_;
513 $attrs->{"${pref}_trailing_select"} = $self->_merge_attr($attrs->{"${pref}_trailing_select"}, \@new_trailing)
516 elsif (@$as < @$sel) {
517 $self->throw_exception(
518 "Unable to handle an ${pref}as specification (@$as) with less elements than the corresponding ${pref}select"
522 # now see what the result for this pair looks like:
525 # if balanced - treat as a columns entry
526 $attrs->{"${pref}columns"} = $self->_merge_attr(
527 $attrs->{"${pref}columns"},
528 [ map { +{ $as->[$_] => $sel->[$_] } } ( 0 .. $#$as ) ]
532 # unbalanced - shove in select/as, not subject to deduplication in _resolved_attrs
533 $attrs->{"${pref}select"} = $self->_merge_attr($attrs->{"${pref}select"}, $sel);
534 $attrs->{"${pref}as"} = $self->_merge_attr($attrs->{"${pref}as"}, $as);
541 my ($self, $left, $right) = @_;
542 if (defined $left xor defined $right) {
543 return defined $left ? $left : $right;
545 elsif (defined $left) {
546 return { -and => [ map
547 { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
555 =head2 search_literal
559 =item Arguments: $sql_fragment, @bind_values
561 =item Return Value: $resultset (scalar context), @row_objs (list context)
565 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
566 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
568 Pass a literal chunk of SQL to be added to the conditional part of the
571 CAVEAT: C<search_literal> is provided for Class::DBI compatibility and should
572 only be used in that context. C<search_literal> is a convenience method.
573 It is equivalent to calling $schema->search(\[]), but if you want to ensure
574 columns are bound correctly, use C<search>.
576 Example of how to use C<search> instead of C<search_literal>
578 my @cds = $cd_rs->search_literal('cdid = ? AND (artist = ? OR artist = ?)', (2, 1, 2));
579 my @cds = $cd_rs->search(\[ 'cdid = ? AND (artist = ? OR artist = ?)', [ 'cdid', 2 ], [ 'artist', 1 ], [ 'artist', 2 ] ]);
582 See L<DBIx::Class::Manual::Cookbook/Searching> and
583 L<DBIx::Class::Manual::FAQ/Searching> for searching techniques that do not
584 require C<search_literal>.
589 my ($self, $sql, @bind) = @_;
591 if ( @bind && ref($bind[-1]) eq 'HASH' ) {
594 return $self->search(\[ $sql, map [ __DUMMY__ => $_ ], @bind ], ($attr || () ));
601 =item Arguments: \%columns_values | @pk_values, \%attrs?
603 =item Return Value: $row_object | undef
607 Finds and returns a single row based on supplied criteria. Takes either a
608 hashref with the same format as L</create> (including inference of foreign
609 keys from related objects), or a list of primary key values in the same
610 order as the L<primary columns|DBIx::Class::ResultSource/primary_columns>
611 declaration on the L</result_source>.
613 In either case an attempt is made to combine conditions already existing on
614 the resultset with the condition passed to this method.
616 To aid with preparing the correct query for the storage you may supply the
617 C<key> attribute, which is the name of a
618 L<unique constraint|DBIx::Class::ResultSource/add_unique_constraint> (the
619 unique constraint corresponding to the
620 L<primary columns|DBIx::Class::ResultSource/primary_columns> is always named
621 C<primary>). If the C<key> attribute has been supplied, and DBIC is unable
622 to construct a query that satisfies the named unique constraint fully (
623 non-NULL values for each column member of the constraint) an exception is
626 If no C<key> is specified, the search is carried over all unique constraints
627 which are fully defined by the available condition.
629 If no such constraint is found, C<find> currently defaults to a simple
630 C<< search->(\%column_values) >> which may or may not do what you expect.
631 Note that this fallback behavior may be deprecated in further versions. If
632 you need to search with arbitrary conditions - use L</search>. If the query
633 resulting from this fallback produces more than one row, a warning to the
634 effect is issued, though only the first row is constructed and returned as
637 In addition to C<key>, L</find> recognizes and applies standard
638 L<resultset attributes|/ATTRIBUTES> in the same way as L</search> does.
640 Note that if you have extra concerns about the correctness of the resulting
641 query you need to specify the C<key> attribute and supply the entire condition
642 as an argument to find (since it is not always possible to perform the
643 combination of the resultset condition with the supplied one, especially if
644 the resultset condition contains literal sql).
646 For example, to find a row by its primary key:
648 my $cd = $schema->resultset('CD')->find(5);
650 You can also find a row by a specific unique constraint:
652 my $cd = $schema->resultset('CD')->find(
654 artist => 'Massive Attack',
655 title => 'Mezzanine',
657 { key => 'cd_artist_title' }
660 See also L</find_or_create> and L</update_or_create>.
666 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
668 my $rsrc = $self->result_source;
670 # Parse out the condition from input
672 if (ref $_[0] eq 'HASH') {
673 $call_cond = { %{$_[0]} };
676 my $constraint = exists $attrs->{key} ? $attrs->{key} : 'primary';
677 my @c_cols = $rsrc->unique_constraint_columns($constraint);
679 $self->throw_exception(
680 "No constraint columns, maybe a malformed '$constraint' constraint?"
683 $self->throw_exception (
684 'find() expects either a column/value hashref, or a list of values '
685 . "corresponding to the columns of the specified unique constraint '$constraint'"
686 ) unless @c_cols == @_;
689 @{$call_cond}{@c_cols} = @_;
693 for my $key (keys %$call_cond) {
695 my $keyref = ref($call_cond->{$key})
697 my $relinfo = $rsrc->relationship_info($key)
699 my $val = delete $call_cond->{$key};
701 next if $keyref eq 'ARRAY'; # has_many for multi_create
703 my $rel_q = $rsrc->_resolve_condition(
704 $relinfo->{cond}, $val, $key
706 die "Can't handle complex relationship conditions in find" if ref($rel_q) ne 'HASH';
707 @related{keys %$rel_q} = values %$rel_q;
711 # relationship conditions take precedence (?)
712 @{$call_cond}{keys %related} = values %related;
714 my $alias = exists $attrs->{alias} ? $attrs->{alias} : $self->{attrs}{alias};
716 if (exists $attrs->{key}) {
717 $final_cond = $self->_qualify_cond_columns (
719 $self->_build_unique_cond (
727 elsif ($self->{attrs}{accessor} and $self->{attrs}{accessor} eq 'single') {
728 # This means that we got here after a merger of relationship conditions
729 # in ::Relationship::Base::search_related (the row method), and furthermore
730 # the relationship is of the 'single' type. This means that the condition
731 # provided by the relationship (already attached to $self) is sufficient,
732 # as there can be only one row in the database that would satisfy the
736 # no key was specified - fall down to heuristics mode:
737 # run through all unique queries registered on the resultset, and
738 # 'OR' all qualifying queries together
739 my (@unique_queries, %seen_column_combinations);
740 for my $c_name ($rsrc->unique_constraint_names) {
741 next if $seen_column_combinations{
742 join "\x00", sort $rsrc->unique_constraint_columns($c_name)
745 push @unique_queries, try {
746 $self->_build_unique_cond ($c_name, $call_cond)
750 $final_cond = @unique_queries
751 ? [ map { $self->_qualify_cond_columns($_, $alias) } @unique_queries ]
752 : $self->_non_unique_find_fallback ($call_cond, $attrs)
756 # Run the query, passing the result_class since it should propagate for find
757 my $rs = $self->search ($final_cond, {result_class => $self->result_class, %$attrs});
758 if (keys %{$rs->_resolved_attrs->{collapse}}) {
760 carp "Query returned more than one row" if $rs->next;
768 # This is a stop-gap method as agreed during the discussion on find() cleanup:
769 # http://lists.scsys.co.uk/pipermail/dbix-class/2010-October/009535.html
771 # It is invoked when find() is called in legacy-mode with insufficiently-unique
772 # condition. It is provided for overrides until a saner way forward is devised
774 # *NOTE* This is not a public method, and it's *GUARANTEED* to disappear down
775 # the road. Please adjust your tests accordingly to catch this situation early
776 # DBIx::Class::ResultSet->can('_non_unique_find_fallback') is reasonable
778 # The method will not be removed without an adequately complete replacement
779 # for strict-mode enforcement
780 sub _non_unique_find_fallback {
781 my ($self, $cond, $attrs) = @_;
783 return $self->_qualify_cond_columns(
785 exists $attrs->{alias}
787 : $self->{attrs}{alias}
792 sub _qualify_cond_columns {
793 my ($self, $cond, $alias) = @_;
795 my %aliased = %$cond;
796 for (keys %aliased) {
797 $aliased{"$alias.$_"} = delete $aliased{$_}
804 sub _build_unique_cond {
805 my ($self, $constraint_name, $extra_cond) = @_;
807 my @c_cols = $self->result_source->unique_constraint_columns($constraint_name);
809 # combination may fail if $self->{cond} is non-trivial
810 my ($final_cond) = try {
811 $self->_merge_with_rscond ($extra_cond)
816 # trim out everything not in $columns
817 $final_cond = { map { $_ => $final_cond->{$_} } @c_cols };
819 if (my @missing = grep { ! defined $final_cond->{$_} } (@c_cols) ) {
820 $self->throw_exception( sprintf ( "Unable to satisfy requested constraint '%s', no values for column(s): %s",
822 join (', ', map { "'$_'" } @missing),
829 =head2 search_related
833 =item Arguments: $rel, $cond, \%attrs?
835 =item Return Value: $new_resultset
839 $new_rs = $cd_rs->search_related('artist', {
843 Searches the specified relationship, optionally specifying a condition and
844 attributes for matching records. See L</ATTRIBUTES> for more information.
849 return shift->related_resultset(shift)->search(@_);
852 =head2 search_related_rs
854 This method works exactly the same as search_related, except that
855 it guarantees a resultset, even in list context.
859 sub search_related_rs {
860 return shift->related_resultset(shift)->search_rs(@_);
867 =item Arguments: none
869 =item Return Value: $cursor
873 Returns a storage-driven cursor to the given resultset. See
874 L<DBIx::Class::Cursor> for more information.
881 my $attrs = $self->_resolved_attrs_copy;
883 return $self->{cursor}
884 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
885 $attrs->{where},$attrs);
892 =item Arguments: $cond?
894 =item Return Value: $row_object | undef
898 my $cd = $schema->resultset('CD')->single({ year => 2001 });
900 Inflates the first result without creating a cursor if the resultset has
901 any records in it; if not returns C<undef>. Used by L</find> as a lean version
904 While this method can take an optional search condition (just like L</search>)
905 being a fast-code-path it does not recognize search attributes. If you need to
906 add extra joins or similar, call L</search> and then chain-call L</single> on the
907 L<DBIx::Class::ResultSet> returned.
913 As of 0.08100, this method enforces the assumption that the preceding
914 query returns only one row. If more than one row is returned, you will receive
917 Query returned more than one row
919 In this case, you should be using L</next> or L</find> instead, or if you really
920 know what you are doing, use the L</rows> attribute to explicitly limit the size
923 This method will also throw an exception if it is called on a resultset prefetching
924 has_many, as such a prefetch implies fetching multiple rows from the database in
925 order to assemble the resulting object.
932 my ($self, $where) = @_;
934 $self->throw_exception('single() only takes search conditions, no attributes. You want ->search( $cond, $attrs )->single()');
937 my $attrs = $self->_resolved_attrs_copy;
939 if (keys %{$attrs->{collapse}}) {
940 $self->throw_exception(
941 'single() can not be used on resultsets prefetching has_many. Use find( \%cond ) or next() instead'
946 if (defined $attrs->{where}) {
949 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
950 $where, delete $attrs->{where} ]
953 $attrs->{where} = $where;
957 my @data = $self->result_source->storage->select_single(
958 $attrs->{from}, $attrs->{select},
959 $attrs->{where}, $attrs
962 return (@data ? ($self->_construct_object(@data))[0] : undef);
968 # Recursively collapse the query, accumulating values for each column.
970 sub _collapse_query {
971 my ($self, $query, $collapsed) = @_;
975 if (ref $query eq 'ARRAY') {
976 foreach my $subquery (@$query) {
977 next unless ref $subquery; # -or
978 $collapsed = $self->_collapse_query($subquery, $collapsed);
981 elsif (ref $query eq 'HASH') {
982 if (keys %$query and (keys %$query)[0] eq '-and') {
983 foreach my $subquery (@{$query->{-and}}) {
984 $collapsed = $self->_collapse_query($subquery, $collapsed);
988 foreach my $col (keys %$query) {
989 my $value = $query->{$col};
990 $collapsed->{$col}{$value}++;
1002 =item Arguments: $cond?
1004 =item Return Value: $resultsetcolumn
1008 my $max_length = $rs->get_column('length')->max;
1010 Returns a L<DBIx::Class::ResultSetColumn> instance for a column of the ResultSet.
1015 my ($self, $column) = @_;
1016 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
1024 =item Arguments: $cond, \%attrs?
1026 =item Return Value: $resultset (scalar context), @row_objs (list context)
1030 # WHERE title LIKE '%blue%'
1031 $cd_rs = $rs->search_like({ title => '%blue%'});
1033 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
1034 that this is simply a convenience method retained for ex Class::DBI users.
1035 You most likely want to use L</search> with specific operators.
1037 For more information, see L<DBIx::Class::Manual::Cookbook>.
1039 This method is deprecated and will be removed in 0.09. Use L</search()>
1040 instead. An example conversion is:
1042 ->search_like({ foo => 'bar' });
1046 ->search({ foo => { like => 'bar' } });
1053 'search_like() is deprecated and will be removed in DBIC version 0.09.'
1054 .' Instead use ->search({ x => { -like => "y%" } })'
1055 .' (note the outer pair of {}s - they are important!)'
1057 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1058 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
1059 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
1060 return $class->search($query, { %$attrs });
1067 =item Arguments: $first, $last
1069 =item Return Value: $resultset (scalar context), @row_objs (list context)
1073 Returns a resultset or object list representing a subset of elements from the
1074 resultset slice is called on. Indexes are from 0, i.e., to get the first
1075 three records, call:
1077 my ($one, $two, $three) = $rs->slice(0, 2);
1082 my ($self, $min, $max) = @_;
1083 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
1084 $attrs->{offset} = $self->{attrs}{offset} || 0;
1085 $attrs->{offset} += $min;
1086 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
1087 return $self->search(undef, $attrs);
1088 #my $slice = (ref $self)->new($self->result_source, $attrs);
1089 #return (wantarray ? $slice->all : $slice);
1096 =item Arguments: none
1098 =item Return Value: $result | undef
1102 Returns the next element in the resultset (C<undef> is there is none).
1104 Can be used to efficiently iterate over records in the resultset:
1106 my $rs = $schema->resultset('CD')->search;
1107 while (my $cd = $rs->next) {
1111 Note that you need to store the resultset object, and call C<next> on it.
1112 Calling C<< resultset('Table')->next >> repeatedly will always return the
1113 first record from the resultset.
1119 if (my $cache = $self->get_cache) {
1120 $self->{all_cache_position} ||= 0;
1121 return $cache->[$self->{all_cache_position}++];
1123 if ($self->{attrs}{cache}) {
1124 delete $self->{pager};
1125 $self->{all_cache_position} = 1;
1126 return ($self->all)[0];
1128 if ($self->{stashed_objects}) {
1129 my $obj = shift(@{$self->{stashed_objects}});
1130 delete $self->{stashed_objects} unless @{$self->{stashed_objects}};
1134 exists $self->{stashed_row}
1135 ? @{delete $self->{stashed_row}}
1136 : $self->cursor->next
1138 return undef unless (@row);
1139 my ($row, @more) = $self->_construct_object(@row);
1140 $self->{stashed_objects} = \@more if @more;
1144 sub _construct_object {
1145 my ($self, @row) = @_;
1147 my $info = $self->_collapse_result($self->{_attrs}{as}, \@row)
1149 my @new = $self->result_class->inflate_result($self->result_source, @$info);
1150 @new = $self->{_attrs}{record_filter}->(@new)
1151 if exists $self->{_attrs}{record_filter};
1155 sub _collapse_result {
1156 my ($self, $as_proto, $row) = @_;
1160 # 'foo' => [ undef, 'foo' ]
1161 # 'foo.bar' => [ 'foo', 'bar' ]
1162 # 'foo.bar.baz' => [ 'foo.bar', 'baz' ]
1164 my @construct_as = map { [ (/^(?:(.*)\.)?([^.]+)$/) ] } @$as_proto;
1166 my %collapse = %{$self->{_attrs}{collapse}||{}};
1170 # if we're doing collapsing (has_many prefetch) we need to grab records
1171 # until the PK changes, so fill @pri_index. if not, we leave it empty so
1172 # we know we don't have to bother.
1174 # the reason for not using the collapse stuff directly is because if you
1175 # had for e.g. two artists in a row with no cds, the collapse info for
1176 # both would be NULL (undef) so you'd lose the second artist
1178 # store just the index so we can check the array positions from the row
1179 # without having to contruct the full hash
1181 if (keys %collapse) {
1182 my %pri = map { ($_ => 1) } $self->result_source->_pri_cols;
1183 foreach my $i (0 .. $#construct_as) {
1184 next if defined($construct_as[$i][0]); # only self table
1185 if (delete $pri{$construct_as[$i][1]}) {
1186 push(@pri_index, $i);
1188 last unless keys %pri; # short circuit (Johnny Five Is Alive!)
1192 # no need to do an if, it'll be empty if @pri_index is empty anyway
1194 my %pri_vals = map { ($_ => $copy[$_]) } @pri_index;
1198 do { # no need to check anything at the front, we always want the first row
1202 foreach my $this_as (@construct_as) {
1203 $const{$this_as->[0]||''}{$this_as->[1]} = shift(@copy);
1206 push(@const_rows, \%const);
1208 } until ( # no pri_index => no collapse => drop straight out
1211 do { # get another row, stash it, drop out if different PK
1213 @copy = $self->cursor->next;
1214 $self->{stashed_row} = \@copy;
1216 # last thing in do block, counts as true if anything doesn't match
1218 # check xor defined first for NULL vs. NOT NULL then if one is
1219 # defined the other must be so check string equality
1222 (defined $pri_vals{$_} ^ defined $copy[$_])
1223 || (defined $pri_vals{$_} && ($pri_vals{$_} ne $copy[$_]))
1228 my $alias = $self->{attrs}{alias};
1235 foreach my $const (@const_rows) {
1236 scalar @const_keys or do {
1237 @const_keys = sort { length($a) <=> length($b) } keys %$const;
1239 foreach my $key (@const_keys) {
1242 my @parts = split(/\./, $key);
1244 my $data = $const->{$key};
1245 foreach my $p (@parts) {
1246 $target = $target->[1]->{$p} ||= [];
1248 if ($cur eq ".${key}" && (my @ckey = @{$collapse{$cur}||[]})) {
1249 # collapsing at this point and on final part
1250 my $pos = $collapse_pos{$cur};
1251 CK: foreach my $ck (@ckey) {
1252 if (!defined $pos->{$ck} || $pos->{$ck} ne $data->{$ck}) {
1253 $collapse_pos{$cur} = $data;
1254 delete @collapse_pos{ # clear all positioning for sub-entries
1255 grep { m/^\Q${cur}.\E/ } keys %collapse_pos
1262 if (exists $collapse{$cur}) {
1263 $target = $target->[-1];
1266 $target->[0] = $data;
1268 $info->[0] = $const->{$key};
1276 =head2 result_source
1280 =item Arguments: $result_source?
1282 =item Return Value: $result_source
1286 An accessor for the primary ResultSource object from which this ResultSet
1293 =item Arguments: $result_class?
1295 =item Return Value: $result_class
1299 An accessor for the class to use when creating row objects. Defaults to
1300 C<< result_source->result_class >> - which in most cases is the name of the
1301 L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class.
1303 Note that changing the result_class will also remove any components
1304 that were originally loaded in the source class via
1305 L<DBIx::Class::ResultSource/load_components>. Any overloaded methods
1306 in the original source class will not run.
1311 my ($self, $result_class) = @_;
1312 if ($result_class) {
1313 unless (ref $result_class) { # don't fire this for an object
1314 $self->ensure_class_loaded($result_class);
1316 $self->_result_class($result_class);
1317 # THIS LINE WOULD BE A BUG - this accessor specifically exists to
1318 # permit the user to set result class on one result set only; it only
1319 # chains if provided to search()
1320 #$self->{attrs}{result_class} = $result_class if ref $self;
1322 $self->_result_class;
1329 =item Arguments: $cond, \%attrs??
1331 =item Return Value: $count
1335 Performs an SQL C<COUNT> with the same query as the resultset was built
1336 with to find the number of elements. Passing arguments is equivalent to
1337 C<< $rs->search ($cond, \%attrs)->count >>
1343 return $self->search(@_)->count if @_ and defined $_[0];
1344 return scalar @{ $self->get_cache } if $self->get_cache;
1346 my $attrs = $self->_resolved_attrs_copy;
1348 # this is a little optimization - it is faster to do the limit
1349 # adjustments in software, instead of a subquery
1350 my $rows = delete $attrs->{rows};
1351 my $offset = delete $attrs->{offset};
1354 if ($self->_has_resolved_attr (qw/collapse group_by/)) {
1355 $crs = $self->_count_subq_rs ($attrs);
1358 $crs = $self->_count_rs ($attrs);
1360 my $count = $crs->next;
1362 $count -= $offset if $offset;
1363 $count = $rows if $rows and $rows < $count;
1364 $count = 0 if ($count < 0);
1373 =item Arguments: $cond, \%attrs??
1375 =item Return Value: $count_rs
1379 Same as L</count> but returns a L<DBIx::Class::ResultSetColumn> object.
1380 This can be very handy for subqueries:
1382 ->search( { amount => $some_rs->count_rs->as_query } )
1384 As with regular resultsets the SQL query will be executed only after
1385 the resultset is accessed via L</next> or L</all>. That would return
1386 the same single value obtainable via L</count>.
1392 return $self->search(@_)->count_rs if @_;
1394 # this may look like a lack of abstraction (count() does about the same)
1395 # but in fact an _rs *must* use a subquery for the limits, as the
1396 # software based limiting can not be ported if this $rs is to be used
1397 # in a subquery itself (i.e. ->as_query)
1398 if ($self->_has_resolved_attr (qw/collapse group_by offset rows/)) {
1399 return $self->_count_subq_rs;
1402 return $self->_count_rs;
1407 # returns a ResultSetColumn object tied to the count query
1410 my ($self, $attrs) = @_;
1412 my $rsrc = $self->result_source;
1413 $attrs ||= $self->_resolved_attrs;
1415 my $tmp_attrs = { %$attrs };
1416 # take off any limits, record_filter is cdbi, and no point of ordering nor locking a count
1417 delete @{$tmp_attrs}{qw/rows offset order_by record_filter for/};
1419 # overwrite the selector (supplied by the storage)
1420 $tmp_attrs->{select} = $rsrc->storage->_count_select ($rsrc, $attrs);
1421 $tmp_attrs->{as} = 'count';
1422 delete @{$tmp_attrs}{qw/columns _trailing_select/};
1424 my $tmp_rs = $rsrc->resultset_class->new($rsrc, $tmp_attrs)->get_column ('count');
1430 # same as above but uses a subquery
1432 sub _count_subq_rs {
1433 my ($self, $attrs) = @_;
1435 my $rsrc = $self->result_source;
1436 $attrs ||= $self->_resolved_attrs;
1438 my $sub_attrs = { %$attrs };
1439 # extra selectors do not go in the subquery and there is no point of ordering it, nor locking it
1440 delete @{$sub_attrs}{qw/collapse columns as select _prefetch_selector_range _trailing_select order_by for/};
1442 # if we multi-prefetch we group_by primary keys only as this is what we would
1443 # get out of the rs via ->next/->all. We *DO WANT* to clobber old group_by regardless
1444 if ( keys %{$attrs->{collapse}} ) {
1445 $sub_attrs->{group_by} = [ map { "$attrs->{alias}.$_" } ($rsrc->_pri_cols) ]
1448 # Calculate subquery selector
1449 if (my $g = $sub_attrs->{group_by}) {
1451 my $sql_maker = $rsrc->storage->sql_maker;
1453 # necessary as the group_by may refer to aliased functions
1455 for my $sel (@{$attrs->{select}}) {
1456 $sel_index->{$sel->{-as}} = $sel
1457 if (ref $sel eq 'HASH' and $sel->{-as});
1460 # anything from the original select mentioned on the group-by needs to make it to the inner selector
1461 # also look for named aggregates referred in the having clause
1462 # having often contains scalarrefs - thus parse it out entirely
1464 if ($attrs->{having}) {
1465 local $sql_maker->{having_bind};
1466 local $sql_maker->{quote_char} = $sql_maker->{quote_char};
1467 local $sql_maker->{name_sep} = $sql_maker->{name_sep};
1468 unless (defined $sql_maker->{quote_char} and length $sql_maker->{quote_char}) {
1469 $sql_maker->{quote_char} = [ "\x00", "\xFF" ];
1470 # if we don't unset it we screw up retarded but unfortunately working
1471 # 'MAX(foo.bar)' => { '>', 3 }
1472 $sql_maker->{name_sep} = '';
1475 my ($lquote, $rquote, $sep) = map { quotemeta $_ } ($sql_maker->_quote_chars, $sql_maker->name_sep);
1477 my $sql = $sql_maker->_parse_rs_attrs ({ having => $attrs->{having} });
1479 # search for both a proper quoted qualified string, for a naive unquoted scalarref
1480 # and if all fails for an utterly naive quoted scalar-with-function
1482 $rquote $sep $lquote (.+?) $rquote
1484 [\s,] \w+ \. (\w+) [\s,]
1486 [\s,] $lquote (.+?) $rquote [\s,]
1488 push @parts, ($1 || $2 || $3); # one of them matched if we got here
1493 my $colpiece = $sel_index->{$_} || $_;
1495 # unqualify join-based group_by's. Arcane but possible query
1496 # also horrible horrible hack to alias a column (not a func.)
1497 # (probably need to introduce SQLA syntax)
1498 if ($colpiece =~ /\./ && $colpiece !~ /^$attrs->{alias}\./) {
1501 $colpiece = \ sprintf ('%s AS %s', map { $sql_maker->_quote ($_) } ($colpiece, $as) );
1503 push @{$sub_attrs->{select}}, $colpiece;
1507 my @pcols = map { "$attrs->{alias}.$_" } ($rsrc->primary_columns);
1508 $sub_attrs->{select} = @pcols ? \@pcols : [ 1 ];
1511 return $rsrc->resultset_class
1512 ->new ($rsrc, $sub_attrs)
1514 ->search ({}, { columns => { count => $rsrc->storage->_count_select ($rsrc, $attrs) } })
1515 ->get_column ('count');
1522 =head2 count_literal
1526 =item Arguments: $sql_fragment, @bind_values
1528 =item Return Value: $count
1532 Counts the results in a literal query. Equivalent to calling L</search_literal>
1533 with the passed arguments, then L</count>.
1537 sub count_literal { shift->search_literal(@_)->count; }
1543 =item Arguments: none
1545 =item Return Value: @objects
1549 Returns all elements in the resultset. Called implicitly if the resultset
1550 is returned in list context.
1557 $self->throw_exception("all() doesn't take any arguments, you probably wanted ->search(...)->all()");
1560 return @{ $self->get_cache } if $self->get_cache;
1564 if (keys %{$self->_resolved_attrs->{collapse}}) {
1565 # Using $self->cursor->all is really just an optimisation.
1566 # If we're collapsing has_many prefetches it probably makes
1567 # very little difference, and this is cleaner than hacking
1568 # _construct_object to survive the approach
1569 $self->cursor->reset;
1570 my @row = $self->cursor->next;
1572 push(@obj, $self->_construct_object(@row));
1573 @row = (exists $self->{stashed_row}
1574 ? @{delete $self->{stashed_row}}
1575 : $self->cursor->next);
1578 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
1581 $self->set_cache(\@obj) if $self->{attrs}{cache};
1590 =item Arguments: none
1592 =item Return Value: $self
1596 Resets the resultset's cursor, so you can iterate through the elements again.
1597 Implicitly resets the storage cursor, so a subsequent L</next> will trigger
1604 delete $self->{_attrs} if exists $self->{_attrs};
1605 $self->{all_cache_position} = 0;
1606 $self->cursor->reset;
1614 =item Arguments: none
1616 =item Return Value: $object | undef
1620 Resets the resultset and returns an object for the first result (or C<undef>
1621 if the resultset is empty).
1626 return $_[0]->reset->next;
1632 # Determines whether and what type of subquery is required for the $rs operation.
1633 # If grouping is necessary either supplies its own, or verifies the current one
1634 # After all is done delegates to the proper storage method.
1636 sub _rs_update_delete {
1637 my ($self, $op, $values) = @_;
1639 my $rsrc = $self->result_source;
1641 # if a condition exists we need to strip all table qualifiers
1642 # if this is not possible we'll force a subquery below
1643 my $cond = $rsrc->schema->storage->_strip_cond_qualifiers ($self->{cond});
1645 my $needs_group_by_subq = $self->_has_resolved_attr (qw/collapse group_by -join/);
1646 my $needs_subq = $needs_group_by_subq || (not defined $cond) || $self->_has_resolved_attr(qw/rows offset/);
1648 if ($needs_group_by_subq or $needs_subq) {
1650 # make a new $rs selecting only the PKs (that's all we really need)
1651 my $attrs = $self->_resolved_attrs_copy;
1654 delete $attrs->{$_} for qw/collapse _collapse_order_by select _prefetch_selector_range as/;
1655 $attrs->{columns} = [ map { "$attrs->{alias}.$_" } ($self->result_source->_pri_cols) ];
1657 if ($needs_group_by_subq) {
1658 # make sure no group_by was supplied, or if there is one - make sure it matches
1659 # the columns compiled above perfectly. Anything else can not be sanely executed
1660 # on most databases so croak right then and there
1662 if (my $g = $attrs->{group_by}) {
1663 my @current_group_by = map
1664 { $_ =~ /\./ ? $_ : "$attrs->{alias}.$_" }
1669 join ("\x00", sort @current_group_by)
1671 join ("\x00", sort @{$attrs->{columns}} )
1673 $self->throw_exception (
1674 "You have just attempted a $op operation on a resultset which does group_by"
1675 . ' on columns other than the primary keys, while DBIC internally needs to retrieve'
1676 . ' the primary keys in a subselect. All sane RDBMS engines do not support this'
1677 . ' kind of queries. Please retry the operation with a modified group_by or'
1678 . ' without using one at all.'
1683 $attrs->{group_by} = $attrs->{columns};
1687 my $subrs = (ref $self)->new($rsrc, $attrs);
1688 return $self->result_source->storage->_subq_update_delete($subrs, $op, $values);
1691 return $rsrc->storage->$op(
1693 $op eq 'update' ? $values : (),
1703 =item Arguments: \%values
1705 =item Return Value: $storage_rv
1709 Sets the specified columns in the resultset to the supplied values in a
1710 single query. Note that this will not run any accessor/set_column/update
1711 triggers, nor will it update any row object instances derived from this
1712 resultset (this includes the contents of the L<resultset cache|/set_cache>
1713 if any). See L</update_all> if you need to execute any on-update
1714 triggers or cascades defined either by you or a
1715 L<result component|DBIx::Class::Manual::Component/WHAT_IS_A_COMPONENT>.
1717 The return value is a pass through of what the underlying
1718 storage backend returned, and may vary. See L<DBI/execute> for the most
1723 Note that L</update> does not process/deflate any of the values passed in.
1724 This is unlike the corresponding L<DBIx::Class::Row/update>. The user must
1725 ensure manually that any value passed to this method will stringify to
1726 something the RDBMS knows how to deal with. A notable example is the
1727 handling of L<DateTime> objects, for more info see:
1728 L<DBIx::Class::Manual::Cookbook/Formatting_DateTime_objects_in_queries>.
1733 my ($self, $values) = @_;
1734 $self->throw_exception('Values for update must be a hash')
1735 unless ref $values eq 'HASH';
1737 return $self->_rs_update_delete ('update', $values);
1744 =item Arguments: \%values
1746 =item Return Value: 1
1750 Fetches all objects and updates them one at a time via
1751 L<DBIx::Class::Row/update>. Note that C<update_all> will run DBIC defined
1752 triggers, while L</update> will not.
1757 my ($self, $values) = @_;
1758 $self->throw_exception('Values for update_all must be a hash')
1759 unless ref $values eq 'HASH';
1761 my $guard = $self->result_source->schema->txn_scope_guard;
1762 $_->update($values) for $self->all;
1771 =item Arguments: none
1773 =item Return Value: $storage_rv
1777 Deletes the rows matching this resultset in a single query. Note that this
1778 will not run any delete triggers, nor will it alter the
1779 L<in_storage|DBIx::Class::Row/in_storage> status of any row object instances
1780 derived from this resultset (this includes the contents of the
1781 L<resultset cache|/set_cache> if any). See L</delete_all> if you need to
1782 execute any on-delete triggers or cascades defined either by you or a
1783 L<result component|DBIx::Class::Manual::Component/WHAT_IS_A_COMPONENT>.
1785 The return value is a pass through of what the underlying storage backend
1786 returned, and may vary. See L<DBI/execute> for the most common case.
1792 $self->throw_exception('delete does not accept any arguments')
1795 return $self->_rs_update_delete ('delete');
1802 =item Arguments: none
1804 =item Return Value: 1
1808 Fetches all objects and deletes them one at a time via
1809 L<DBIx::Class::Row/delete>. Note that C<delete_all> will run DBIC defined
1810 triggers, while L</delete> will not.
1816 $self->throw_exception('delete_all does not accept any arguments')
1819 my $guard = $self->result_source->schema->txn_scope_guard;
1820 $_->delete for $self->all;
1829 =item Arguments: \@data;
1833 Accepts either an arrayref of hashrefs or alternatively an arrayref of arrayrefs.
1834 For the arrayref of hashrefs style each hashref should be a structure suitable
1835 forsubmitting to a $resultset->create(...) method.
1837 In void context, C<insert_bulk> in L<DBIx::Class::Storage::DBI> is used
1838 to insert the data, as this is a faster method.
1840 Otherwise, each set of data is inserted into the database using
1841 L<DBIx::Class::ResultSet/create>, and the resulting objects are
1842 accumulated into an array. The array itself, or an array reference
1843 is returned depending on scalar or list context.
1845 Example: Assuming an Artist Class that has many CDs Classes relating:
1847 my $Artist_rs = $schema->resultset("Artist");
1849 ## Void Context Example
1850 $Artist_rs->populate([
1851 { artistid => 4, name => 'Manufactured Crap', cds => [
1852 { title => 'My First CD', year => 2006 },
1853 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
1856 { artistid => 5, name => 'Angsty-Whiny Girl', cds => [
1857 { title => 'My parents sold me to a record company', year => 2005 },
1858 { title => 'Why Am I So Ugly?', year => 2006 },
1859 { title => 'I Got Surgery and am now Popular', year => 2007 }
1864 ## Array Context Example
1865 my ($ArtistOne, $ArtistTwo, $ArtistThree) = $Artist_rs->populate([
1866 { name => "Artist One"},
1867 { name => "Artist Two"},
1868 { name => "Artist Three", cds=> [
1869 { title => "First CD", year => 2007},
1870 { title => "Second CD", year => 2008},
1874 print $ArtistOne->name; ## response is 'Artist One'
1875 print $ArtistThree->cds->count ## reponse is '2'
1877 For the arrayref of arrayrefs style, the first element should be a list of the
1878 fieldsnames to which the remaining elements are rows being inserted. For
1881 $Arstist_rs->populate([
1882 [qw/artistid name/],
1883 [100, 'A Formally Unknown Singer'],
1884 [101, 'A singer that jumped the shark two albums ago'],
1885 [102, 'An actually cool singer'],
1888 Please note an important effect on your data when choosing between void and
1889 wantarray context. Since void context goes straight to C<insert_bulk> in
1890 L<DBIx::Class::Storage::DBI> this will skip any component that is overriding
1891 C<insert>. So if you are using something like L<DBIx-Class-UUIDColumns> to
1892 create primary keys for you, you will find that your PKs are empty. In this
1893 case you will have to use the wantarray context in order to create those
1901 # cruft placed in standalone method
1902 my $data = $self->_normalize_populate_args(@_);
1904 if(defined wantarray) {
1906 foreach my $item (@$data) {
1907 push(@created, $self->create($item));
1909 return wantarray ? @created : \@created;
1912 my $first = $data->[0];
1914 # if a column is a registered relationship, and is a non-blessed hash/array, consider
1915 # it relationship data
1916 my (@rels, @columns);
1917 my $rsrc = $self->result_source;
1918 my $rels = { map { $_ => $rsrc->relationship_info($_) } $rsrc->relationships };
1919 for (keys %$first) {
1920 my $ref = ref $first->{$_};
1921 $rels->{$_} && ($ref eq 'ARRAY' or $ref eq 'HASH')
1927 my @pks = $rsrc->primary_columns;
1929 ## do the belongs_to relationships
1930 foreach my $index (0..$#$data) {
1932 # delegate to create() for any dataset without primary keys with specified relationships
1933 if (grep { !defined $data->[$index]->{$_} } @pks ) {
1935 if (grep { ref $data->[$index]{$r} eq $_ } qw/HASH ARRAY/) { # a related set must be a HASH or AoH
1936 my @ret = $self->populate($data);
1942 foreach my $rel (@rels) {
1943 next unless ref $data->[$index]->{$rel} eq "HASH";
1944 my $result = $self->related_resultset($rel)->create($data->[$index]->{$rel});
1945 my ($reverse_relname, $reverse_relinfo) = %{$rsrc->reverse_relationship_info($rel)};
1946 my $related = $result->result_source->_resolve_condition(
1947 $reverse_relinfo->{cond},
1952 delete $data->[$index]->{$rel};
1953 $data->[$index] = {%{$data->[$index]}, %$related};
1955 push @columns, keys %$related if $index == 0;
1959 ## inherit the data locked in the conditions of the resultset
1960 my ($rs_data) = $self->_merge_with_rscond({});
1961 delete @{$rs_data}{@columns};
1962 my @inherit_cols = keys %$rs_data;
1963 my @inherit_data = values %$rs_data;
1965 ## do bulk insert on current row
1966 $rsrc->storage->insert_bulk(
1968 [@columns, @inherit_cols],
1969 [ map { [ @$_{@columns}, @inherit_data ] } @$data ],
1972 ## do the has_many relationships
1973 foreach my $item (@$data) {
1977 foreach my $rel (@rels) {
1978 next unless ref $item->{$rel} eq "ARRAY" && @{ $item->{$rel} };
1980 $main_row ||= $self->new_result({map { $_ => $item->{$_} } @pks});
1982 my $child = $main_row->$rel;
1984 my $related = $child->result_source->_resolve_condition(
1985 $rels->{$rel}{cond},
1990 my @rows_to_add = ref $item->{$rel} eq 'ARRAY' ? @{$item->{$rel}} : ($item->{$rel});
1991 my @populate = map { {%$_, %$related} } @rows_to_add;
1993 $child->populate( \@populate );
2000 # populate() argumnets went over several incarnations
2001 # What we ultimately support is AoH
2002 sub _normalize_populate_args {
2003 my ($self, $arg) = @_;
2005 if (ref $arg eq 'ARRAY') {
2006 if (ref $arg->[0] eq 'HASH') {
2009 elsif (ref $arg->[0] eq 'ARRAY') {
2011 my @colnames = @{$arg->[0]};
2012 foreach my $values (@{$arg}[1 .. $#$arg]) {
2013 push @ret, { map { $colnames[$_] => $values->[$_] } (0 .. $#colnames) };
2019 $self->throw_exception('Populate expects an arrayref of hashrefs or arrayref of arrayrefs');
2026 =item Arguments: none
2028 =item Return Value: $pager
2032 Return Value a L<Data::Page> object for the current resultset. Only makes
2033 sense for queries with a C<page> attribute.
2035 To get the full count of entries for a paged resultset, call
2036 C<total_entries> on the L<Data::Page> object.
2040 # make a wizard good for both a scalar and a hashref
2041 my $mk_lazy_count_wizard = sub {
2042 require Variable::Magic;
2044 my $stash = { total_rs => shift };
2045 my $slot = shift; # only used by the hashref magic
2047 my $magic = Variable::Magic::wizard (
2048 data => sub { $stash },
2054 # set value lazily, and dispell for good
2055 ${$_[0]} = $_[1]{total_rs}->count;
2056 Variable::Magic::dispell (${$_[0]}, $_[1]{magic_selfref});
2060 # an explicit set implies dispell as well
2061 # the unless() is to work around "fun and giggles" below
2062 Variable::Magic::dispell (${$_[0]}, $_[1]{magic_selfref})
2063 unless (caller(2))[3] eq 'DBIx::Class::ResultSet::pager';
2070 if ($_[2] eq $slot and !$_[1]{inactive}) {
2071 my $cnt = $_[1]{total_rs}->count;
2072 $_[0]->{$slot} = $cnt;
2074 # attempting to dispell in a fetch handle (works in store), seems
2075 # to invariable segfault on 5.10, 5.12, 5.13 :(
2076 # so use an inactivator instead
2077 #Variable::Magic::dispell (%{$_[0]}, $_[1]{magic_selfref});
2083 if (! $_[1]{inactive} and $_[2] eq $slot) {
2084 #Variable::Magic::dispell (%{$_[0]}, $_[1]{magic_selfref});
2086 unless (caller(2))[3] eq 'DBIx::Class::ResultSet::pager';
2093 $stash->{magic_selfref} = $magic;
2094 weaken ($stash->{magic_selfref}); # this fails on 5.8.1
2099 # the tie class for 5.8.1
2101 package # hide from pause
2102 DBIx::Class::__DBIC_LAZY_RS_COUNT__;
2103 use base qw/Tie::Hash/;
2105 sub FIRSTKEY { my $dummy = scalar keys %{$_[0]{data}}; each %{$_[0]{data}} }
2106 sub NEXTKEY { each %{$_[0]{data}} }
2107 sub EXISTS { exists $_[0]{data}{$_[1]} }
2108 sub DELETE { delete $_[0]{data}{$_[1]} }
2109 sub CLEAR { %{$_[0]{data}} = () }
2110 sub SCALAR { scalar %{$_[0]{data}} }
2113 $_[1]{data} = {%{$_[1]{selfref}}};
2114 %{$_[1]{selfref}} = ();
2115 Scalar::Util::weaken ($_[1]{selfref});
2116 return bless ($_[1], $_[0]);
2120 if ($_[1] eq $_[0]{slot}) {
2121 my $cnt = $_[0]{data}{$_[1]} = $_[0]{total_rs}->count;
2122 untie %{$_[0]{selfref}};
2123 %{$_[0]{selfref}} = %{$_[0]{data}};
2132 $_[0]{data}{$_[1]} = $_[2];
2133 if ($_[1] eq $_[0]{slot}) {
2134 untie %{$_[0]{selfref}};
2135 %{$_[0]{selfref}} = %{$_[0]{data}};
2144 return $self->{pager} if $self->{pager};
2146 if ($self->get_cache) {
2147 $self->throw_exception ('Pagers on cached resultsets are not supported');
2150 my $attrs = $self->{attrs};
2151 if (!defined $attrs->{page}) {
2152 $self->throw_exception("Can't create pager for non-paged rs");
2154 elsif ($attrs->{page} <= 0) {
2155 $self->throw_exception('Invalid page number (page-numbers are 1-based)');
2157 $attrs->{rows} ||= 10;
2159 # throw away the paging flags and re-run the count (possibly
2160 # with a subselect) to get the real total count
2161 my $count_attrs = { %$attrs };
2162 delete $count_attrs->{$_} for qw/rows offset page pager/;
2163 my $total_rs = (ref $self)->new($self->result_source, $count_attrs);
2166 ### the following may seem awkward and dirty, but it's a thought-experiment
2167 ### necessary for future development of DBIx::DS. Do *NOT* change this code
2168 ### before talking to ribasushi/mst
2170 my $pager = Data::Page->new(
2171 0, #start with an empty set
2173 $self->{attrs}{page},
2176 my $data_slot = 'total_entries';
2178 # Since we are interested in a cached value (once it's set - it's set), every
2179 # technique will detach from the magic-host once the time comes to fire the
2180 # ->count (or in the segfaulting case of >= 5.10 it will deactivate itself)
2182 if ($] < 5.008003) {
2183 # 5.8.1 throws 'Modification of a read-only value attempted' when one tries
2184 # to weakref the magic container :(
2186 tie (%$pager, 'DBIx::Class::__DBIC_LAZY_RS_COUNT__',
2187 { slot => $data_slot, total_rs => $total_rs, selfref => $pager }
2190 elsif ($] < 5.010) {
2191 # We can use magic on the hash value slot. It's interesting that the magic is
2192 # attached to the hash-slot, and does *not* stop working once I do the dummy
2193 # assignments after the cast()
2194 # tested on 5.8.3 and 5.8.9
2195 my $magic = $mk_lazy_count_wizard->($total_rs);
2196 Variable::Magic::cast ( $pager->{$data_slot}, $magic );
2198 # this is for fun and giggles
2199 $pager->{$data_slot} = -1;
2200 $pager->{$data_slot} = 0;
2202 # this does not work for scalars, but works with
2204 #my %vals = %$pager;
2209 # And the uvar magic
2210 # works on 5.10.1, 5.12.1 and 5.13.4 in its current form,
2211 # however see the wizard maker for more notes
2212 my $magic = $mk_lazy_count_wizard->($total_rs, $data_slot);
2213 Variable::Magic::cast ( %$pager, $magic );
2216 $pager->{$data_slot} = -1;
2217 $pager->{$data_slot} = 0;
2225 return $self->{pager} = $pager;
2232 =item Arguments: $page_number
2234 =item Return Value: $rs
2238 Returns a resultset for the $page_number page of the resultset on which page
2239 is called, where each page contains a number of rows equal to the 'rows'
2240 attribute set on the resultset (10 by default).
2245 my ($self, $page) = @_;
2246 return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
2253 =item Arguments: \%vals
2255 =item Return Value: $rowobject
2259 Creates a new row object in the resultset's result class and returns
2260 it. The row is not inserted into the database at this point, call
2261 L<DBIx::Class::Row/insert> to do that. Calling L<DBIx::Class::Row/in_storage>
2262 will tell you whether the row object has been inserted or not.
2264 Passes the hashref of input on to L<DBIx::Class::Row/new>.
2269 my ($self, $values) = @_;
2270 $self->throw_exception( "new_result needs a hash" )
2271 unless (ref $values eq 'HASH');
2273 my ($merged_cond, $cols_from_relations) = $self->_merge_with_rscond($values);
2277 @$cols_from_relations
2278 ? (-cols_from_relations => $cols_from_relations)
2280 -result_source => $self->result_source, # DO NOT REMOVE THIS, REQUIRED
2283 return $self->result_class->new(\%new);
2286 # _merge_with_rscond
2288 # Takes a simple hash of K/V data and returns its copy merged with the
2289 # condition already present on the resultset. Additionally returns an
2290 # arrayref of value/condition names, which were inferred from related
2291 # objects (this is needed for in-memory related objects)
2292 sub _merge_with_rscond {
2293 my ($self, $data) = @_;
2295 my (%new_data, @cols_from_relations);
2297 my $alias = $self->{attrs}{alias};
2299 if (! defined $self->{cond}) {
2300 # just massage $data below
2302 elsif ($self->{cond} eq $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION) {
2303 %new_data = %{ $self->{attrs}{related_objects} || {} }; # nothing might have been inserted yet
2304 @cols_from_relations = keys %new_data;
2306 elsif (ref $self->{cond} ne 'HASH') {
2307 $self->throw_exception(
2308 "Can't abstract implicit construct, resultset condition not a hash"
2312 # precendence must be given to passed values over values inherited from
2313 # the cond, so the order here is important.
2314 my $collapsed_cond = $self->_collapse_cond($self->{cond});
2315 my %implied = %{$self->_remove_alias($collapsed_cond, $alias)};
2317 while ( my($col, $value) = each %implied ) {
2318 my $vref = ref $value;
2319 if ($vref eq 'HASH' && keys(%$value) && (keys %$value)[0] eq '=') {
2320 $new_data{$col} = $value->{'='};
2322 elsif( !$vref or $vref eq 'SCALAR' or blessed($value) ) {
2323 $new_data{$col} = $value;
2330 %{ $self->_remove_alias($data, $alias) },
2333 return (\%new_data, \@cols_from_relations);
2336 # _has_resolved_attr
2338 # determines if the resultset defines at least one
2339 # of the attributes supplied
2341 # used to determine if a subquery is neccessary
2343 # supports some virtual attributes:
2345 # This will scan for any joins being present on the resultset.
2346 # It is not a mere key-search but a deep inspection of {from}
2349 sub _has_resolved_attr {
2350 my ($self, @attr_names) = @_;
2352 my $attrs = $self->_resolved_attrs;
2356 for my $n (@attr_names) {
2357 if (grep { $n eq $_ } (qw/-join/) ) {
2358 $extra_checks{$n}++;
2362 my $attr = $attrs->{$n};
2364 next if not defined $attr;
2366 if (ref $attr eq 'HASH') {
2367 return 1 if keys %$attr;
2369 elsif (ref $attr eq 'ARRAY') {
2377 # a resolved join is expressed as a multi-level from
2379 $extra_checks{-join}
2381 ref $attrs->{from} eq 'ARRAY'
2383 @{$attrs->{from}} > 1
2391 # Recursively collapse the condition.
2393 sub _collapse_cond {
2394 my ($self, $cond, $collapsed) = @_;
2398 if (ref $cond eq 'ARRAY') {
2399 foreach my $subcond (@$cond) {
2400 next unless ref $subcond; # -or
2401 $collapsed = $self->_collapse_cond($subcond, $collapsed);
2404 elsif (ref $cond eq 'HASH') {
2405 if (keys %$cond and (keys %$cond)[0] eq '-and') {
2406 foreach my $subcond (@{$cond->{-and}}) {
2407 $collapsed = $self->_collapse_cond($subcond, $collapsed);
2411 foreach my $col (keys %$cond) {
2412 my $value = $cond->{$col};
2413 $collapsed->{$col} = $value;
2423 # Remove the specified alias from the specified query hash. A copy is made so
2424 # the original query is not modified.
2427 my ($self, $query, $alias) = @_;
2429 my %orig = %{ $query || {} };
2432 foreach my $key (keys %orig) {
2434 $unaliased{$key} = $orig{$key};
2437 $unaliased{$1} = $orig{$key}
2438 if $key =~ m/^(?:\Q$alias\E\.)?([^.]+)$/;
2448 =item Arguments: none
2450 =item Return Value: \[ $sql, @bind ]
2454 Returns the SQL query and bind vars associated with the invocant.
2456 This is generally used as the RHS for a subquery.
2463 my $attrs = $self->_resolved_attrs_copy;
2468 # my ($sql, \@bind, \%dbi_bind_attrs) = _select_args_to_query (...)
2469 # $sql also has no wrapping parenthesis in list ctx
2471 my $sqlbind = $self->result_source->storage
2472 ->_select_args_to_query ($attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs);
2481 =item Arguments: \%vals, \%attrs?
2483 =item Return Value: $rowobject
2487 my $artist = $schema->resultset('Artist')->find_or_new(
2488 { artist => 'fred' }, { key => 'artists' });
2490 $cd->cd_to_producer->find_or_new({ producer => $producer },
2491 { key => 'primary });
2493 Find an existing record from this resultset using L</find>. if none exists,
2494 instantiate a new result object and return it. The object will not be saved
2495 into your storage until you call L<DBIx::Class::Row/insert> on it.
2497 You most likely want this method when looking for existing rows using a unique
2498 constraint that is not the primary key, or looking for related rows.
2500 If you want objects to be saved immediately, use L</find_or_create> instead.
2502 B<Note>: Make sure to read the documentation of L</find> and understand the
2503 significance of the C<key> attribute, as its lack may skew your search, and
2504 subsequently result in spurious new objects.
2506 B<Note>: Take care when using C<find_or_new> with a table having
2507 columns with default values that you intend to be automatically
2508 supplied by the database (e.g. an auto_increment primary key column).
2509 In normal usage, the value of such columns should NOT be included at
2510 all in the call to C<find_or_new>, even when set to C<undef>.
2516 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2517 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
2518 if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2521 return $self->new_result($hash);
2528 =item Arguments: \%vals
2530 =item Return Value: a L<DBIx::Class::Row> $object
2534 Attempt to create a single new row or a row with multiple related rows
2535 in the table represented by the resultset (and related tables). This
2536 will not check for duplicate rows before inserting, use
2537 L</find_or_create> to do that.
2539 To create one row for this resultset, pass a hashref of key/value
2540 pairs representing the columns of the table and the values you wish to
2541 store. If the appropriate relationships are set up, foreign key fields
2542 can also be passed an object representing the foreign row, and the
2543 value will be set to its primary key.
2545 To create related objects, pass a hashref of related-object column values
2546 B<keyed on the relationship name>. If the relationship is of type C<multi>
2547 (L<DBIx::Class::Relationship/has_many>) - pass an arrayref of hashrefs.
2548 The process will correctly identify columns holding foreign keys, and will
2549 transparently populate them from the keys of the corresponding relation.
2550 This can be applied recursively, and will work correctly for a structure
2551 with an arbitrary depth and width, as long as the relationships actually
2552 exists and the correct column data has been supplied.
2555 Instead of hashrefs of plain related data (key/value pairs), you may
2556 also pass new or inserted objects. New objects (not inserted yet, see
2557 L</new>), will be inserted into their appropriate tables.
2559 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
2561 Example of creating a new row.
2563 $person_rs->create({
2564 name=>"Some Person",
2565 email=>"somebody@someplace.com"
2568 Example of creating a new row and also creating rows in a related C<has_many>
2569 or C<has_one> resultset. Note Arrayref.
2572 { artistid => 4, name => 'Manufactured Crap', cds => [
2573 { title => 'My First CD', year => 2006 },
2574 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
2579 Example of creating a new row and also creating a row in a related
2580 C<belongs_to> resultset. Note Hashref.
2583 title=>"Music for Silly Walks",
2586 name=>"Silly Musician",
2594 When subclassing ResultSet never attempt to override this method. Since
2595 it is a simple shortcut for C<< $self->new_result($attrs)->insert >>, a
2596 lot of the internals simply never call it, so your override will be
2597 bypassed more often than not. Override either L<new|DBIx::Class::Row/new>
2598 or L<insert|DBIx::Class::Row/insert> depending on how early in the
2599 L</create> process you need to intervene.
2606 my ($self, $attrs) = @_;
2607 $self->throw_exception( "create needs a hashref" )
2608 unless ref $attrs eq 'HASH';
2609 return $self->new_result($attrs)->insert;
2612 =head2 find_or_create
2616 =item Arguments: \%vals, \%attrs?
2618 =item Return Value: $rowobject
2622 $cd->cd_to_producer->find_or_create({ producer => $producer },
2623 { key => 'primary' });
2625 Tries to find a record based on its primary key or unique constraints; if none
2626 is found, creates one and returns that instead.
2628 my $cd = $schema->resultset('CD')->find_or_create({
2630 artist => 'Massive Attack',
2631 title => 'Mezzanine',
2635 Also takes an optional C<key> attribute, to search by a specific key or unique
2636 constraint. For example:
2638 my $cd = $schema->resultset('CD')->find_or_create(
2640 artist => 'Massive Attack',
2641 title => 'Mezzanine',
2643 { key => 'cd_artist_title' }
2646 B<Note>: Make sure to read the documentation of L</find> and understand the
2647 significance of the C<key> attribute, as its lack may skew your search, and
2648 subsequently result in spurious row creation.
2650 B<Note>: Because find_or_create() reads from the database and then
2651 possibly inserts based on the result, this method is subject to a race
2652 condition. Another process could create a record in the table after
2653 the find has completed and before the create has started. To avoid
2654 this problem, use find_or_create() inside a transaction.
2656 B<Note>: Take care when using C<find_or_create> with a table having
2657 columns with default values that you intend to be automatically
2658 supplied by the database (e.g. an auto_increment primary key column).
2659 In normal usage, the value of such columns should NOT be included at
2660 all in the call to C<find_or_create>, even when set to C<undef>.
2662 See also L</find> and L</update_or_create>. For information on how to declare
2663 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2667 sub find_or_create {
2669 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2670 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
2671 if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2674 return $self->create($hash);
2677 =head2 update_or_create
2681 =item Arguments: \%col_values, { key => $unique_constraint }?
2683 =item Return Value: $row_object
2687 $resultset->update_or_create({ col => $val, ... });
2689 Like L</find_or_create>, but if a row is found it is immediately updated via
2690 C<< $found_row->update (\%col_values) >>.
2693 Takes an optional C<key> attribute to search on a specific unique constraint.
2696 # In your application
2697 my $cd = $schema->resultset('CD')->update_or_create(
2699 artist => 'Massive Attack',
2700 title => 'Mezzanine',
2703 { key => 'cd_artist_title' }
2706 $cd->cd_to_producer->update_or_create({
2707 producer => $producer,
2713 B<Note>: Make sure to read the documentation of L</find> and understand the
2714 significance of the C<key> attribute, as its lack may skew your search, and
2715 subsequently result in spurious row creation.
2717 B<Note>: Take care when using C<update_or_create> with a table having
2718 columns with default values that you intend to be automatically
2719 supplied by the database (e.g. an auto_increment primary key column).
2720 In normal usage, the value of such columns should NOT be included at
2721 all in the call to C<update_or_create>, even when set to C<undef>.
2723 See also L</find> and L</find_or_create>. For information on how to declare
2724 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2728 sub update_or_create {
2730 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2731 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
2733 my $row = $self->find($cond, $attrs);
2735 $row->update($cond);
2739 return $self->create($cond);
2742 =head2 update_or_new
2746 =item Arguments: \%col_values, { key => $unique_constraint }?
2748 =item Return Value: $rowobject
2752 $resultset->update_or_new({ col => $val, ... });
2754 Like L</find_or_new> but if a row is found it is immediately updated via
2755 C<< $found_row->update (\%col_values) >>.
2759 # In your application
2760 my $cd = $schema->resultset('CD')->update_or_new(
2762 artist => 'Massive Attack',
2763 title => 'Mezzanine',
2766 { key => 'cd_artist_title' }
2769 if ($cd->in_storage) {
2770 # the cd was updated
2773 # the cd is not yet in the database, let's insert it
2777 B<Note>: Make sure to read the documentation of L</find> and understand the
2778 significance of the C<key> attribute, as its lack may skew your search, and
2779 subsequently result in spurious new objects.
2781 B<Note>: Take care when using C<update_or_new> with a table having
2782 columns with default values that you intend to be automatically
2783 supplied by the database (e.g. an auto_increment primary key column).
2784 In normal usage, the value of such columns should NOT be included at
2785 all in the call to C<update_or_new>, even when set to C<undef>.
2787 See also L</find>, L</find_or_create> and L</find_or_new>.
2793 my $attrs = ( @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {} );
2794 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
2796 my $row = $self->find( $cond, $attrs );
2797 if ( defined $row ) {
2798 $row->update($cond);
2802 return $self->new_result($cond);
2809 =item Arguments: none
2811 =item Return Value: \@cache_objects | undef
2815 Gets the contents of the cache for the resultset, if the cache is set.
2817 The cache is populated either by using the L</prefetch> attribute to
2818 L</search> or by calling L</set_cache>.
2830 =item Arguments: \@cache_objects
2832 =item Return Value: \@cache_objects
2836 Sets the contents of the cache for the resultset. Expects an arrayref
2837 of objects of the same class as those produced by the resultset. Note that
2838 if the cache is set the resultset will return the cached objects rather
2839 than re-querying the database even if the cache attr is not set.
2841 The contents of the cache can also be populated by using the
2842 L</prefetch> attribute to L</search>.
2847 my ( $self, $data ) = @_;
2848 $self->throw_exception("set_cache requires an arrayref")
2849 if defined($data) && (ref $data ne 'ARRAY');
2850 $self->{all_cache} = $data;
2857 =item Arguments: none
2859 =item Return Value: undef
2863 Clears the cache for the resultset.
2868 shift->set_cache(undef);
2875 =item Arguments: none
2877 =item Return Value: true, if the resultset has been paginated
2885 return !!$self->{attrs}{page};
2892 =item Arguments: none
2894 =item Return Value: true, if the resultset has been ordered with C<order_by>.
2902 return scalar $self->result_source->storage->_extract_order_criteria($self->{attrs}{order_by});
2905 =head2 related_resultset
2909 =item Arguments: $relationship_name
2911 =item Return Value: $resultset
2915 Returns a related resultset for the supplied relationship name.
2917 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
2921 sub related_resultset {
2922 my ($self, $rel) = @_;
2924 $self->{related_resultsets} ||= {};
2925 return $self->{related_resultsets}{$rel} ||= do {
2926 my $rsrc = $self->result_source;
2927 my $rel_info = $rsrc->relationship_info($rel);
2929 $self->throw_exception(
2930 "search_related: result source '" . $rsrc->source_name .
2931 "' has no such relationship $rel")
2934 my $attrs = $self->_chain_relationship($rel);
2936 my $join_count = $attrs->{seen_join}{$rel};
2938 my $alias = $self->result_source->storage
2939 ->relname_to_table_alias($rel, $join_count);
2941 # since this is search_related, and we already slid the select window inwards
2942 # (the select/as attrs were deleted in the beginning), we need to flip all
2943 # left joins to inner, so we get the expected results
2944 # read the comment on top of the actual function to see what this does
2945 $attrs->{from} = $rsrc->schema->storage->_inner_join_to_node ($attrs->{from}, $alias);
2948 #XXX - temp fix for result_class bug. There likely is a more elegant fix -groditi
2949 delete @{$attrs}{qw(result_class alias)};
2953 if (my $cache = $self->get_cache) {
2954 if ($cache->[0] && $cache->[0]->related_resultset($rel)->get_cache) {
2955 $new_cache = [ map { @{$_->related_resultset($rel)->get_cache} }
2960 my $rel_source = $rsrc->related_source($rel);
2964 # The reason we do this now instead of passing the alias to the
2965 # search_rs below is that if you wrap/overload resultset on the
2966 # source you need to know what alias it's -going- to have for things
2967 # to work sanely (e.g. RestrictWithObject wants to be able to add
2968 # extra query restrictions, and these may need to be $alias.)
2970 my $rel_attrs = $rel_source->resultset_attributes;
2971 local $rel_attrs->{alias} = $alias;
2973 $rel_source->resultset
2977 where => $attrs->{where},
2980 $new->set_cache($new_cache) if $new_cache;
2985 =head2 current_source_alias
2989 =item Arguments: none
2991 =item Return Value: $source_alias
2995 Returns the current table alias for the result source this resultset is built
2996 on, that will be used in the SQL query. Usually it is C<me>.
2998 Currently the source alias that refers to the result set returned by a
2999 L</search>/L</find> family method depends on how you got to the resultset: it's
3000 C<me> by default, but eg. L</search_related> aliases it to the related result
3001 source name (and keeps C<me> referring to the original result set). The long
3002 term goal is to make L<DBIx::Class> always alias the current resultset as C<me>
3003 (and make this method unnecessary).
3005 Thus it's currently necessary to use this method in predefined queries (see
3006 L<DBIx::Class::Manual::Cookbook/Predefined searches>) when referring to the
3007 source alias of the current result set:
3009 # in a result set class
3011 my ($self, $user) = @_;
3013 my $me = $self->current_source_alias;
3015 return $self->search(
3016 "$me.modified" => $user->id,
3022 sub current_source_alias {
3025 return ($self->{attrs} || {})->{alias} || 'me';
3028 =head2 as_subselect_rs
3032 =item Arguments: none
3034 =item Return Value: $resultset
3038 Act as a barrier to SQL symbols. The resultset provided will be made into a
3039 "virtual view" by including it as a subquery within the from clause. From this
3040 point on, any joined tables are inaccessible to ->search on the resultset (as if
3041 it were simply where-filtered without joins). For example:
3043 my $rs = $schema->resultset('Bar')->search({'x.name' => 'abc'},{ join => 'x' });
3045 # 'x' now pollutes the query namespace
3047 # So the following works as expected
3048 my $ok_rs = $rs->search({'x.other' => 1});
3050 # But this doesn't: instead of finding a 'Bar' related to two x rows (abc and
3051 # def) we look for one row with contradictory terms and join in another table
3052 # (aliased 'x_2') which we never use
3053 my $broken_rs = $rs->search({'x.name' => 'def'});
3055 my $rs2 = $rs->as_subselect_rs;
3057 # doesn't work - 'x' is no longer accessible in $rs2, having been sealed away
3058 my $not_joined_rs = $rs2->search({'x.other' => 1});
3060 # works as expected: finds a 'table' row related to two x rows (abc and def)
3061 my $correctly_joined_rs = $rs2->search({'x.name' => 'def'});
3063 Another example of when one might use this would be to select a subset of
3064 columns in a group by clause:
3066 my $rs = $schema->resultset('Bar')->search(undef, {
3067 group_by => [qw{ id foo_id baz_id }],
3068 })->as_subselect_rs->search(undef, {
3069 columns => [qw{ id foo_id }]
3072 In the above example normally columns would have to be equal to the group by,
3073 but because we isolated the group by into a subselect the above works.
3077 sub as_subselect_rs {
3080 my $attrs = $self->_resolved_attrs;
3082 my $fresh_rs = (ref $self)->new (
3083 $self->result_source
3086 # these pieces will be locked in the subquery
3087 delete $fresh_rs->{cond};
3088 delete @{$fresh_rs->{attrs}}{qw/where bind/};
3090 return $fresh_rs->search( {}, {
3092 $attrs->{alias} => $self->as_query,
3093 -alias => $attrs->{alias},
3094 -source_handle => $self->result_source->handle,
3096 alias => $attrs->{alias},
3100 # This code is called by search_related, and makes sure there
3101 # is clear separation between the joins before, during, and
3102 # after the relationship. This information is needed later
3103 # in order to properly resolve prefetch aliases (any alias
3104 # with a relation_chain_depth less than the depth of the
3105 # current prefetch is not considered)
3107 # The increments happen twice per join. An even number means a
3108 # relationship specified via a search_related, whereas an odd
3109 # number indicates a join/prefetch added via attributes
3111 # Also this code will wrap the current resultset (the one we
3112 # chain to) in a subselect IFF it contains limiting attributes
3113 sub _chain_relationship {
3114 my ($self, $rel) = @_;
3115 my $source = $self->result_source;
3116 my $attrs = { %{$self->{attrs}||{}} };
3118 # we need to take the prefetch the attrs into account before we
3119 # ->_resolve_join as otherwise they get lost - captainL
3120 my $join = $self->_merge_joinpref_attr( $attrs->{join}, $attrs->{prefetch} );
3122 delete @{$attrs}{qw/join prefetch collapse group_by distinct select as columns +select +as +columns/};
3124 my $seen = { %{ (delete $attrs->{seen_join}) || {} } };
3127 my @force_subq_attrs = qw/offset rows group_by having/;
3130 ($attrs->{from} && ref $attrs->{from} ne 'ARRAY')
3132 $self->_has_resolved_attr (@force_subq_attrs)
3134 # Nuke the prefetch (if any) before the new $rs attrs
3135 # are resolved (prefetch is useless - we are wrapping
3136 # a subquery anyway).
3137 my $rs_copy = $self->search;
3138 $rs_copy->{attrs}{join} = $self->_merge_joinpref_attr (
3139 $rs_copy->{attrs}{join},
3140 delete $rs_copy->{attrs}{prefetch},
3144 -source_handle => $source->handle,
3145 -alias => $attrs->{alias},
3146 $attrs->{alias} => $rs_copy->as_query,
3148 delete @{$attrs}{@force_subq_attrs, qw/where bind/};
3149 $seen->{-relation_chain_depth} = 0;
3151 elsif ($attrs->{from}) { #shallow copy suffices
3152 $from = [ @{$attrs->{from}} ];
3156 -source_handle => $source->handle,
3157 -alias => $attrs->{alias},
3158 $attrs->{alias} => $source->from,
3162 my $jpath = ($seen->{-relation_chain_depth})
3163 ? $from->[-1][0]{-join_path}
3166 my @requested_joins = $source->_resolve_join(
3173 push @$from, @requested_joins;
3175 $seen->{-relation_chain_depth}++;
3177 # if $self already had a join/prefetch specified on it, the requested
3178 # $rel might very well be already included. What we do in this case
3179 # is effectively a no-op (except that we bump up the chain_depth on
3180 # the join in question so we could tell it *is* the search_related)
3183 # we consider the last one thus reverse
3184 for my $j (reverse @requested_joins) {
3185 my ($last_j) = keys %{$j->[0]{-join_path}[-1]};
3186 if ($rel eq $last_j) {
3187 $j->[0]{-relation_chain_depth}++;
3193 unless ($already_joined) {
3194 push @$from, $source->_resolve_join(
3202 $seen->{-relation_chain_depth}++;
3204 return {%$attrs, from => $from, seen_join => $seen};
3207 # too many times we have to do $attrs = { %{$self->_resolved_attrs} }
3208 sub _resolved_attrs_copy {
3210 return { %{$self->_resolved_attrs (@_)} };
3213 sub _resolved_attrs {
3215 return $self->{_attrs} if $self->{_attrs};
3217 my $attrs = { %{ $self->{attrs} || {} } };
3218 my $source = $self->result_source;
3219 my $alias = $attrs->{alias};
3221 # one last pass of normalization
3222 $self->_normalize_selection($attrs);
3224 # default selection list
3225 $attrs->{columns} = [ $source->columns ]
3226 unless List::Util::first { exists $attrs->{$_} } qw/columns cols select as _trailing_select/;
3228 # merge selectors together
3229 for (qw/columns select as _trailing_select/) {
3230 $attrs->{$_} = $self->_merge_attr($attrs->{$_}, $attrs->{"+$_"})
3231 if $attrs->{$_} or $attrs->{"+$_"};
3234 # disassemble columns
3236 if (my $cols = delete $attrs->{columns}) {
3237 for my $c (ref $cols eq 'ARRAY' ? @$cols : $cols) {
3238 if (ref $c eq 'HASH') {
3239 for my $as (keys %$c) {
3240 push @sel, $c->{$as};
3251 # when trying to weed off duplicates later do not go past this point -
3252 # everything added from here on is unbalanced "anyone's guess" stuff
3253 my $dedup_stop_idx = $#as;
3255 push @as, @{ ref $attrs->{as} eq 'ARRAY' ? $attrs->{as} : [ $attrs->{as} ] }
3257 push @sel, @{ ref $attrs->{select} eq 'ARRAY' ? $attrs->{select} : [ $attrs->{select} ] }
3258 if $attrs->{select};
3260 # assume all unqualified selectors to apply to the current alias (legacy stuff)
3262 $_ = (ref $_ or $_ =~ /\./) ? $_ : "$alias.$_";
3265 # disqualify all $alias.col as-bits (collapser mandated)
3267 $_ = ($_ =~ /^\Q$alias.\E(.+)$/) ? $1 : $_;
3270 # de-duplicate the result (remove *identical* select/as pairs)
3271 # and also die on duplicate {as} pointing to different {select}s
3272 # not using a c-style for as the condition is prone to shrinkage
3275 while ($i <= $dedup_stop_idx) {
3276 if ($seen->{"$sel[$i] \x00\x00 $as[$i]"}++) {
3281 elsif ($seen->{$as[$i]}++) {
3282 $self->throw_exception(
3283 "inflate_result() alias '$as[$i]' specified twice with different SQL-side {select}-ors"
3291 $attrs->{select} = \@sel;
3292 $attrs->{as} = \@as;
3294 $attrs->{from} ||= [{
3295 -source_handle => $source->handle,
3296 -alias => $self->{attrs}{alias},
3297 $self->{attrs}{alias} => $source->from,
3300 if ( $attrs->{join} || $attrs->{prefetch} ) {
3302 $self->throw_exception ('join/prefetch can not be used with a custom {from}')
3303 if ref $attrs->{from} ne 'ARRAY';
3305 my $join = (delete $attrs->{join}) || {};
3307 if ( defined $attrs->{prefetch} ) {
3308 $join = $self->_merge_joinpref_attr( $join, $attrs->{prefetch} );
3311 $attrs->{from} = # have to copy here to avoid corrupting the original
3313 @{ $attrs->{from} },
3314 $source->_resolve_join(
3317 { %{ $attrs->{seen_join} || {} } },
3318 ( $attrs->{seen_join} && keys %{$attrs->{seen_join}})
3319 ? $attrs->{from}[-1][0]{-join_path}
3326 if ( defined $attrs->{order_by} ) {
3327 $attrs->{order_by} = (
3328 ref( $attrs->{order_by} ) eq 'ARRAY'
3329 ? [ @{ $attrs->{order_by} } ]
3330 : [ $attrs->{order_by} || () ]
3334 if ($attrs->{group_by} and ref $attrs->{group_by} ne 'ARRAY') {
3335 $attrs->{group_by} = [ $attrs->{group_by} ];
3338 # generate the distinct induced group_by early, as prefetch will be carried via a
3339 # subquery (since a group_by is present)
3340 if (delete $attrs->{distinct}) {
3341 if ($attrs->{group_by}) {
3342 carp ("Useless use of distinct on a grouped resultset ('distinct' is ignored when a 'group_by' is present)");
3345 # distinct affects only the main selection part, not what prefetch may
3346 # add below. However trailing is not yet a part of the selection as
3347 # prefetch must insert before it
3348 $attrs->{group_by} = $source->storage->_group_over_selection (
3350 [ @{$attrs->{select}||[]}, @{$attrs->{_trailing_select}||[]} ],
3356 $attrs->{collapse} ||= {};
3357 if ($attrs->{prefetch}) {
3358 my $prefetch = $self->_merge_joinpref_attr( {}, delete $attrs->{prefetch} );
3360 my $prefetch_ordering = [];
3362 # this is a separate structure (we don't look in {from} directly)
3363 # as the resolver needs to shift things off the lists to work
3364 # properly (identical-prefetches on different branches)
3366 if (ref $attrs->{from} eq 'ARRAY') {
3368 my $start_depth = $attrs->{seen_join}{-relation_chain_depth} || 0;
3370 for my $j ( @{$attrs->{from}}[1 .. $#{$attrs->{from}} ] ) {
3371 next unless $j->[0]{-alias};
3372 next unless $j->[0]{-join_path};
3373 next if ($j->[0]{-relation_chain_depth} || 0) < $start_depth;
3375 my @jpath = map { keys %$_ } @{$j->[0]{-join_path}};
3378 $p = $p->{$_} ||= {} for @jpath[ ($start_depth/2) .. $#jpath]; #only even depths are actual jpath boundaries
3379 push @{$p->{-join_aliases} }, $j->[0]{-alias};
3384 $source->_resolve_prefetch( $prefetch, $alias, $join_map, $prefetch_ordering, $attrs->{collapse} );
3386 # we need to somehow mark which columns came from prefetch
3388 my $sel_end = $#{$attrs->{select}};
3389 $attrs->{_prefetch_selector_range} = [ $sel_end + 1, $sel_end + @prefetch ];
3392 push @{ $attrs->{select} }, (map { $_->[0] } @prefetch);
3393 push @{ $attrs->{as} }, (map { $_->[1] } @prefetch);
3395 push( @{$attrs->{order_by}}, @$prefetch_ordering );
3396 $attrs->{_collapse_order_by} = \@$prefetch_ordering;
3400 push @{ $attrs->{select} }, @{$attrs->{_trailing_select}}
3401 if $attrs->{_trailing_select};
3403 # if both page and offset are specified, produce a combined offset
3404 # even though it doesn't make much sense, this is what pre 081xx has
3406 if (my $page = delete $attrs->{page}) {
3408 ($attrs->{rows} * ($page - 1))
3410 ($attrs->{offset} || 0)
3414 return $self->{_attrs} = $attrs;
3418 my ($self, $attr) = @_;
3420 if (ref $attr eq 'HASH') {
3421 return $self->_rollout_hash($attr);
3422 } elsif (ref $attr eq 'ARRAY') {
3423 return $self->_rollout_array($attr);
3429 sub _rollout_array {
3430 my ($self, $attr) = @_;
3433 foreach my $element (@{$attr}) {
3434 if (ref $element eq 'HASH') {
3435 push( @rolled_array, @{ $self->_rollout_hash( $element ) } );
3436 } elsif (ref $element eq 'ARRAY') {
3437 # XXX - should probably recurse here
3438 push( @rolled_array, @{$self->_rollout_array($element)} );
3440 push( @rolled_array, $element );
3443 return \@rolled_array;
3447 my ($self, $attr) = @_;
3450 foreach my $key (keys %{$attr}) {
3451 push( @rolled_array, { $key => $attr->{$key} } );
3453 return \@rolled_array;
3456 sub _calculate_score {
3457 my ($self, $a, $b) = @_;
3459 if (defined $a xor defined $b) {
3462 elsif (not defined $a) {
3466 if (ref $b eq 'HASH') {
3467 my ($b_key) = keys %{$b};
3468 if (ref $a eq 'HASH') {
3469 my ($a_key) = keys %{$a};
3470 if ($a_key eq $b_key) {
3471 return (1 + $self->_calculate_score( $a->{$a_key}, $b->{$b_key} ));
3476 return ($a eq $b_key) ? 1 : 0;
3479 if (ref $a eq 'HASH') {
3480 my ($a_key) = keys %{$a};
3481 return ($b eq $a_key) ? 1 : 0;
3483 return ($b eq $a) ? 1 : 0;
3488 sub _merge_joinpref_attr {
3489 my ($self, $orig, $import) = @_;
3491 return $import unless defined($orig);
3492 return $orig unless defined($import);
3494 $orig = $self->_rollout_attr($orig);
3495 $import = $self->_rollout_attr($import);
3498 foreach my $import_element ( @{$import} ) {
3499 # find best candidate from $orig to merge $b_element into
3500 my $best_candidate = { position => undef, score => 0 }; my $position = 0;
3501 foreach my $orig_element ( @{$orig} ) {
3502 my $score = $self->_calculate_score( $orig_element, $import_element );
3503 if ($score > $best_candidate->{score}) {
3504 $best_candidate->{position} = $position;
3505 $best_candidate->{score} = $score;
3509 my ($import_key) = ( ref $import_element eq 'HASH' ) ? keys %{$import_element} : ($import_element);
3511 if ($best_candidate->{score} == 0 || exists $seen_keys->{$import_key}) {
3512 push( @{$orig}, $import_element );
3514 my $orig_best = $orig->[$best_candidate->{position}];
3515 # merge orig_best and b_element together and replace original with merged
3516 if (ref $orig_best ne 'HASH') {
3517 $orig->[$best_candidate->{position}] = $import_element;
3518 } elsif (ref $import_element eq 'HASH') {
3519 my ($key) = keys %{$orig_best};
3520 $orig->[$best_candidate->{position}] = { $key => $self->_merge_joinpref_attr($orig_best->{$key}, $import_element->{$key}) };
3523 $seen_keys->{$import_key} = 1; # don't merge the same key twice
3534 my $hm = Hash::Merge->new;
3536 $hm->specify_behavior({
3539 my ($defl, $defr) = map { defined $_ } (@_[0,1]);
3541 if ($defl xor $defr) {
3542 return [ $defl ? $_[0] : $_[1] ];
3547 elsif (__HM_DEDUP and $_[0] eq $_[1]) {
3551 return [$_[0], $_[1]];
3555 return $_[1] if !defined $_[0];
3556 return $_[1] if __HM_DEDUP and List::Util::first { $_ eq $_[0] } @{$_[1]};
3557 return [$_[0], @{$_[1]}]
3560 return [] if !defined $_[0] and !keys %{$_[1]};
3561 return [ $_[1] ] if !defined $_[0];
3562 return [ $_[0] ] if !keys %{$_[1]};
3563 return [$_[0], $_[1]]
3568 return $_[0] if !defined $_[1];
3569 return $_[0] if __HM_DEDUP and List::Util::first { $_ eq $_[1] } @{$_[0]};
3570 return [@{$_[0]}, $_[1]]
3573 my @ret = @{$_[0]} or return $_[1];
3574 return [ @ret, @{$_[1]} ] unless __HM_DEDUP;
3575 my %idx = map { $_ => 1 } @ret;
3576 push @ret, grep { ! defined $idx{$_} } (@{$_[1]});
3580 return [ $_[1] ] if ! @{$_[0]};
3581 return $_[0] if !keys %{$_[1]};
3582 return $_[0] if __HM_DEDUP and List::Util::first { $_ eq $_[1] } @{$_[0]};
3583 return [ @{$_[0]}, $_[1] ];
3588 return [] if !keys %{$_[0]} and !defined $_[1];
3589 return [ $_[0] ] if !defined $_[1];
3590 return [ $_[1] ] if !keys %{$_[0]};
3591 return [$_[0], $_[1]]
3594 return [] if !keys %{$_[0]} and !@{$_[1]};
3595 return [ $_[0] ] if !@{$_[1]};
3596 return $_[1] if !keys %{$_[0]};
3597 return $_[1] if __HM_DEDUP and List::Util::first { $_ eq $_[0] } @{$_[1]};
3598 return [ $_[0], @{$_[1]} ];
3601 return [] if !keys %{$_[0]} and !keys %{$_[1]};
3602 return [ $_[0] ] if !keys %{$_[1]};
3603 return [ $_[1] ] if !keys %{$_[0]};
3604 return [ $_[0] ] if $_[0] eq $_[1];
3605 return [ $_[0], $_[1] ];
3608 } => 'DBIC_RS_ATTR_MERGER');
3612 return $hm->merge ($_[1], $_[2]);
3616 sub STORABLE_freeze {
3617 my ($self, $cloning) = @_;
3618 my $to_serialize = { %$self };
3620 # A cursor in progress can't be serialized (and would make little sense anyway)
3621 delete $to_serialize->{cursor};
3623 return nfreeze($to_serialize);
3626 # need this hook for symmetry
3628 my ($self, $cloning, $serialized) = @_;
3630 %$self = %{ thaw($serialized) };
3636 =head2 throw_exception
3638 See L<DBIx::Class::Schema/throw_exception> for details.
3642 sub throw_exception {
3645 if (ref $self and my $rsrc = $self->result_source) {
3646 $rsrc->throw_exception(@_)
3649 DBIx::Class::Exception->throw(@_);
3653 # XXX: FIXME: Attributes docs need clearing up
3657 Attributes are used to refine a ResultSet in various ways when
3658 searching for data. They can be passed to any method which takes an
3659 C<\%attrs> argument. See L</search>, L</search_rs>, L</find>,
3662 These are in no particular order:
3668 =item Value: ( $order_by | \@order_by | \%order_by )
3672 Which column(s) to order the results by.
3674 [The full list of suitable values is documented in
3675 L<SQL::Abstract/"ORDER BY CLAUSES">; the following is a summary of
3678 If a single column name, or an arrayref of names is supplied, the
3679 argument is passed through directly to SQL. The hashref syntax allows
3680 for connection-agnostic specification of ordering direction:
3682 For descending order:
3684 order_by => { -desc => [qw/col1 col2 col3/] }
3686 For explicit ascending order:
3688 order_by => { -asc => 'col' }
3690 The old scalarref syntax (i.e. order_by => \'year DESC') is still
3691 supported, although you are strongly encouraged to use the hashref
3692 syntax as outlined above.
3698 =item Value: \@columns
3702 Shortcut to request a particular set of columns to be retrieved. Each
3703 column spec may be a string (a table column name), or a hash (in which
3704 case the key is the C<as> value, and the value is used as the C<select>
3705 expression). Adds C<me.> onto the start of any column without a C<.> in
3706 it and sets C<select> from that, then auto-populates C<as> from
3707 C<select> as normal. (You may also use the C<cols> attribute, as in
3708 earlier versions of DBIC.)
3710 Essentially C<columns> does the same as L</select> and L</as>.
3712 columns => [ 'foo', { bar => 'baz' } ]
3716 select => [qw/foo baz/],
3723 =item Value: \@columns
3727 Indicates additional columns to be selected from storage. Works the same
3728 as L</columns> but adds columns to the selection. (You may also use the
3729 C<include_columns> attribute, as in earlier versions of DBIC). For
3732 $schema->resultset('CD')->search(undef, {
3733 '+columns' => ['artist.name'],
3737 would return all CDs and include a 'name' column to the information
3738 passed to object inflation. Note that the 'artist' is the name of the
3739 column (or relationship) accessor, and 'name' is the name of the column
3740 accessor in the related table.
3742 =head2 include_columns
3746 =item Value: \@columns
3750 Deprecated. Acts as a synonym for L</+columns> for backward compatibility.
3756 =item Value: \@select_columns
3760 Indicates which columns should be selected from the storage. You can use
3761 column names, or in the case of RDBMS back ends, function or stored procedure
3764 $rs = $schema->resultset('Employee')->search(undef, {
3767 { count => 'employeeid' },
3768 { max => { length => 'name' }, -as => 'longest_name' }
3773 SELECT name, COUNT( employeeid ), MAX( LENGTH( name ) ) AS longest_name FROM employee
3775 B<NOTE:> You will almost always need a corresponding L</as> attribute when you
3776 use L</select>, to instruct DBIx::Class how to store the result of the column.
3777 Also note that the L</as> attribute has nothing to do with the SQL-side 'AS'
3778 identifier aliasing. You can however alias a function, so you can use it in
3779 e.g. an C<ORDER BY> clause. This is done via the C<-as> B<select function
3780 attribute> supplied as shown in the example above.
3786 Indicates additional columns to be selected from storage. Works the same as
3787 L</select> but adds columns to the default selection, instead of specifying
3796 Indicates additional column names for those added via L</+select>. See L</as>.
3804 =item Value: \@inflation_names
3808 Indicates column names for object inflation. That is L</as> indicates the
3809 slot name in which the column value will be stored within the
3810 L<Row|DBIx::Class::Row> object. The value will then be accessible via this
3811 identifier by the C<get_column> method (or via the object accessor B<if one
3812 with the same name already exists>) as shown below. The L</as> attribute has
3813 B<nothing to do> with the SQL-side C<AS>. See L</select> for details.
3815 $rs = $schema->resultset('Employee')->search(undef, {
3818 { count => 'employeeid' },
3819 { max => { length => 'name' }, -as => 'longest_name' }
3828 If the object against which the search is performed already has an accessor
3829 matching a column name specified in C<as>, the value can be retrieved using
3830 the accessor as normal:
3832 my $name = $employee->name();
3834 If on the other hand an accessor does not exist in the object, you need to
3835 use C<get_column> instead:
3837 my $employee_count = $employee->get_column('employee_count');
3839 You can create your own accessors if required - see
3840 L<DBIx::Class::Manual::Cookbook> for details.
3846 =item Value: ($rel_name | \@rel_names | \%rel_names)
3850 Contains a list of relationships that should be joined for this query. For
3853 # Get CDs by Nine Inch Nails
3854 my $rs = $schema->resultset('CD')->search(
3855 { 'artist.name' => 'Nine Inch Nails' },
3856 { join => 'artist' }
3859 Can also contain a hash reference to refer to the other relation's relations.
3862 package MyApp::Schema::Track;
3863 use base qw/DBIx::Class/;
3864 __PACKAGE__->table('track');
3865 __PACKAGE__->add_columns(qw/trackid cd position title/);
3866 __PACKAGE__->set_primary_key('trackid');
3867 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
3870 # In your application
3871 my $rs = $schema->resultset('Artist')->search(
3872 { 'track.title' => 'Teardrop' },
3874 join => { cd => 'track' },
3875 order_by => 'artist.name',
3879 You need to use the relationship (not the table) name in conditions,
3880 because they are aliased as such. The current table is aliased as "me", so
3881 you need to use me.column_name in order to avoid ambiguity. For example:
3883 # Get CDs from 1984 with a 'Foo' track
3884 my $rs = $schema->resultset('CD')->search(
3887 'tracks.name' => 'Foo'
3889 { join => 'tracks' }
3892 If the same join is supplied twice, it will be aliased to <rel>_2 (and
3893 similarly for a third time). For e.g.
3895 my $rs = $schema->resultset('Artist')->search({
3896 'cds.title' => 'Down to Earth',
3897 'cds_2.title' => 'Popular',
3899 join => [ qw/cds cds/ ],
3902 will return a set of all artists that have both a cd with title 'Down
3903 to Earth' and a cd with title 'Popular'.
3905 If you want to fetch related objects from other tables as well, see C<prefetch>
3908 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
3914 =item Value: ($rel_name | \@rel_names | \%rel_names)
3918 Contains one or more relationships that should be fetched along with
3919 the main query (when they are accessed afterwards the data will
3920 already be available, without extra queries to the database). This is
3921 useful for when you know you will need the related objects, because it
3922 saves at least one query:
3924 my $rs = $schema->resultset('Tag')->search(
3933 The initial search results in SQL like the following:
3935 SELECT tag.*, cd.*, artist.* FROM tag
3936 JOIN cd ON tag.cd = cd.cdid
3937 JOIN artist ON cd.artist = artist.artistid
3939 L<DBIx::Class> has no need to go back to the database when we access the
3940 C<cd> or C<artist> relationships, which saves us two SQL statements in this
3943 Simple prefetches will be joined automatically, so there is no need
3944 for a C<join> attribute in the above search.
3946 C<prefetch> can be used with the following relationship types: C<belongs_to>,
3947 C<has_one> (or if you're using C<add_relationship>, any relationship declared
3948 with an accessor type of 'single' or 'filter'). A more complex example that
3949 prefetches an artists cds, the tracks on those cds, and the tags associated
3950 with that artist is given below (assuming many-to-many from artists to tags):
3952 my $rs = $schema->resultset('Artist')->search(
3956 { cds => 'tracks' },
3957 { artist_tags => 'tags' }
3963 B<NOTE:> If you specify a C<prefetch> attribute, the C<join> and C<select>
3964 attributes will be ignored.
3966 B<CAVEATs>: Prefetch does a lot of deep magic. As such, it may not behave
3967 exactly as you might expect.
3973 Prefetch uses the L</cache> to populate the prefetched relationships. This
3974 may or may not be what you want.
3978 If you specify a condition on a prefetched relationship, ONLY those
3979 rows that match the prefetched condition will be fetched into that relationship.
3980 This means that adding prefetch to a search() B<may alter> what is returned by
3981 traversing a relationship. So, if you have C<< Artist->has_many(CDs) >> and you do
3983 my $artist_rs = $schema->resultset('Artist')->search({
3989 my $count = $artist_rs->first->cds->count;
3991 my $artist_rs_prefetch = $artist_rs->search( {}, { prefetch => 'cds' } );
3993 my $prefetch_count = $artist_rs_prefetch->first->cds->count;
3995 cmp_ok( $count, '==', $prefetch_count, "Counts should be the same" );
3997 that cmp_ok() may or may not pass depending on the datasets involved. This
3998 behavior may or may not survive the 0.09 transition.
4010 Makes the resultset paged and specifies the page to retrieve. Effectively
4011 identical to creating a non-pages resultset and then calling ->page($page)
4014 If L<rows> attribute is not specified it defaults to 10 rows per page.
4016 When you have a paged resultset, L</count> will only return the number
4017 of rows in the page. To get the total, use the L</pager> and call
4018 C<total_entries> on it.
4028 Specifies the maximum number of rows for direct retrieval or the number of
4029 rows per page if the page attribute or method is used.
4035 =item Value: $offset
4039 Specifies the (zero-based) row number for the first row to be returned, or the
4040 of the first row of the first page if paging is used.
4046 =item Value: \@columns
4050 A arrayref of columns to group by. Can include columns of joined tables.
4052 group_by => [qw/ column1 column2 ... /]
4058 =item Value: $condition
4062 HAVING is a select statement attribute that is applied between GROUP BY and
4063 ORDER BY. It is applied to the after the grouping calculations have been
4066 having => { 'count_employee' => { '>=', 100 } }
4068 or with an in-place function in which case literal SQL is required:
4070 having => \[ 'count(employee) >= ?', [ count => 100 ] ]
4076 =item Value: (0 | 1)
4080 Set to 1 to group by all columns. If the resultset already has a group_by
4081 attribute, this setting is ignored and an appropriate warning is issued.
4087 Adds to the WHERE clause.
4089 # only return rows WHERE deleted IS NULL for all searches
4090 __PACKAGE__->resultset_attributes({ where => { deleted => undef } }); )
4092 Can be overridden by passing C<< { where => undef } >> as an attribute
4099 Set to 1 to cache search results. This prevents extra SQL queries if you
4100 revisit rows in your ResultSet:
4102 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
4104 while( my $artist = $resultset->next ) {
4108 $rs->first; # without cache, this would issue a query
4110 By default, searches are not cached.
4112 For more examples of using these attributes, see
4113 L<DBIx::Class::Manual::Cookbook>.
4119 =item Value: ( 'update' | 'shared' )
4123 Set to 'update' for a SELECT ... FOR UPDATE or 'shared' for a SELECT