1 package DBIx::Class::ResultSet;
5 use base qw/DBIx::Class/;
7 use DBIx::Class::Exception;
8 use DBIx::Class::ResultSetColumn;
9 use Scalar::Util qw/blessed weaken/;
11 use Data::Compare (); # no imports!!! guard against insane architecture
13 # not importing first() as it will clash with our own method
17 # De-duplication in _merge_attr() is disabled, but left in for reference
18 # (the merger is used for other things that ought not to be de-duped)
19 *__HM_DEDUP = sub () { 0 };
29 __PACKAGE__->mk_group_accessors('simple' => qw/_result_class result_source/);
33 DBIx::Class::ResultSet - Represents a query used for fetching a set of results.
37 my $users_rs = $schema->resultset('User');
38 while( $user = $users_rs->next) {
39 print $user->username;
42 my $registered_users_rs = $schema->resultset('User')->search({ registered => 1 });
43 my @cds_in_2005 = $schema->resultset('CD')->search({ year => 2005 })->all();
47 A ResultSet is an object which stores a set of conditions representing
48 a query. It is the backbone of DBIx::Class (i.e. the really
49 important/useful bit).
51 No SQL is executed on the database when a ResultSet is created, it
52 just stores all the conditions needed to create the query.
54 A basic ResultSet representing the data of an entire table is returned
55 by calling C<resultset> on a L<DBIx::Class::Schema> and passing in a
56 L<Source|DBIx::Class::Manual::Glossary/Source> name.
58 my $users_rs = $schema->resultset('User');
60 A new ResultSet is returned from calling L</search> on an existing
61 ResultSet. The new one will contain all the conditions of the
62 original, plus any new conditions added in the C<search> call.
64 A ResultSet also incorporates an implicit iterator. L</next> and L</reset>
65 can be used to walk through all the L<DBIx::Class::Row>s the ResultSet
68 The query that the ResultSet represents is B<only> executed against
69 the database when these methods are called:
70 L</find>, L</next>, L</all>, L</first>, L</single>, L</count>.
72 If a resultset is used in a numeric context it returns the L</count>.
73 However, if it is used in a boolean context it is B<always> true. So if
74 you want to check if a resultset has any results, you must use C<if $rs
77 =head1 CUSTOM ResultSet CLASSES THAT USE Moose
79 If you want to make your custom ResultSet classes with L<Moose>, use a template
82 package MyApp::Schema::ResultSet::User;
85 use namespace::autoclean;
87 extends 'DBIx::Class::ResultSet';
89 sub BUILDARGS { $_[2] }
93 __PACKAGE__->meta->make_immutable;
97 The L<MooseX::NonMoose> is necessary so that the L<Moose> constructor does not
98 clash with the regular ResultSet constructor. Alternatively, you can use:
100 __PACKAGE__->meta->make_immutable(inline_constructor => 0);
102 The L<BUILDARGS|Moose::Manual::Construction/BUILDARGS> is necessary because the
103 signature of the ResultSet C<new> is C<< ->new($source, \%args) >>.
107 =head2 Chaining resultsets
109 Let's say you've got a query that needs to be run to return some data
110 to the user. But, you have an authorization system in place that
111 prevents certain users from seeing certain information. So, you want
112 to construct the basic query in one method, but add constraints to it in
117 my $request = $self->get_request; # Get a request object somehow.
118 my $schema = $self->result_source->schema;
120 my $cd_rs = $schema->resultset('CD')->search({
121 title => $request->param('title'),
122 year => $request->param('year'),
125 $cd_rs = $self->apply_security_policy( $cd_rs );
127 return $cd_rs->all();
130 sub apply_security_policy {
139 =head3 Resolving conditions and attributes
141 When a resultset is chained from another resultset, conditions and
142 attributes with the same keys need resolving.
144 L</join>, L</prefetch>, L</+select>, L</+as> attributes are merged
145 into the existing ones from the original resultset.
147 The L</where> and L</having> attributes, and any search conditions, are
148 merged with an SQL C<AND> to the existing condition from the original
151 All other attributes are overridden by any new ones supplied in the
154 =head2 Multiple queries
156 Since a resultset just defines a query, you can do all sorts of
157 things with it with the same object.
159 # Don't hit the DB yet.
160 my $cd_rs = $schema->resultset('CD')->search({
161 title => 'something',
165 # Each of these hits the DB individually.
166 my $count = $cd_rs->count;
167 my $most_recent = $cd_rs->get_column('date_released')->max();
168 my @records = $cd_rs->all;
170 And it's not just limited to SELECT statements.
176 $cd_rs->create({ artist => 'Fred' });
178 Which is the same as:
180 $schema->resultset('CD')->create({
181 title => 'something',
186 See: L</search>, L</count>, L</get_column>, L</all>, L</create>.
194 =item Arguments: L<$source|DBIx::Class::ResultSource>, L<\%attrs?|/ATTRIBUTES>
196 =item Return Value: L<$resultset|/search>
200 The resultset constructor. Takes a source object (usually a
201 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
202 L</ATTRIBUTES> below). Does not perform any queries -- these are
203 executed as needed by the other methods.
205 Generally you never construct a resultset manually. Instead you get one
207 C<< $schema->L<resultset|DBIx::Class::Schema/resultset>('$source_name') >>
208 or C<< $another_resultset->L<search|/search>(...) >> (the later called in
211 my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
217 If called on an object, proxies to L</new_result> instead, so
219 my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
221 will return a CD object, not a ResultSet, and is equivalent to:
223 my $cd = $schema->resultset('CD')->new_result({ title => 'Spoon' });
225 Please also keep in mind that many internals call L</new_result> directly,
226 so overloading this method with the idea of intercepting new result object
227 creation B<will not work>. See also warning pertaining to L</create>.
235 return $class->new_result(@_) if ref $class;
237 my ($source, $attrs) = @_;
238 $source = $source->resolve
239 if $source->isa('DBIx::Class::ResultSourceHandle');
240 $attrs = { %{$attrs||{}} };
242 if ($attrs->{page}) {
243 $attrs->{rows} ||= 10;
246 $attrs->{alias} ||= 'me';
249 result_source => $source,
250 cond => $attrs->{where},
255 # if there is a dark selector, this means we are already in a
256 # chain and the cleanup/sanification was taken care of by
258 $self->_normalize_selection($attrs)
259 unless $attrs->{_dark_selector};
262 $attrs->{result_class} || $source->result_class
272 =item Arguments: L<$cond|DBIx::Class::SQLMaker> | undef, L<\%attrs?|/ATTRIBUTES>
274 =item Return Value: $resultset (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
278 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
279 my $new_rs = $cd_rs->search({ year => 2005 });
281 my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
282 # year = 2005 OR year = 2004
284 In list context, C<< ->all() >> is called implicitly on the resultset, thus
285 returning a list of L<result|DBIx::Class::Manual::ResultClass> objects instead.
286 To avoid that, use L</search_rs>.
288 If you need to pass in additional attributes but no additional condition,
289 call it as C<search(undef, \%attrs)>.
291 # "SELECT name, artistid FROM $artist_table"
292 my @all_artists = $schema->resultset('Artist')->search(undef, {
293 columns => [qw/name artistid/],
296 For a list of attributes that can be passed to C<search>, see
297 L</ATTRIBUTES>. For more examples of using this function, see
298 L<Searching|DBIx::Class::Manual::Cookbook/Searching>. For a complete
299 documentation for the first argument, see L<SQL::Abstract>
300 and its extension L<DBIx::Class::SQLMaker>.
302 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
306 Note that L</search> does not process/deflate any of the values passed in the
307 L<SQL::Abstract>-compatible search condition structure. This is unlike other
308 condition-bound methods L</new_result>, L</create> and L</find>. The user must ensure
309 manually that any value passed to this method will stringify to something the
310 RDBMS knows how to deal with. A notable example is the handling of L<DateTime>
311 objects, for more info see:
312 L<DBIx::Class::Manual::Cookbook/Formatting DateTime objects in queries>.
318 my $rs = $self->search_rs( @_ );
323 elsif (defined wantarray) {
327 # we can be called by a relationship helper, which in
328 # turn may be called in void context due to some braindead
329 # overload or whatever else the user decided to be clever
330 # at this particular day. Thus limit the exception to
331 # external code calls only
332 $self->throw_exception ('->search is *not* a mutator, calling it in void context makes no sense')
333 if (caller)[0] !~ /^\QDBIx::Class::/;
343 =item Arguments: L<$cond|DBIx::Class::SQLMaker>, L<\%attrs?|/ATTRIBUTES>
345 =item Return Value: L<$resultset|/search>
349 This method does the same exact thing as search() except it will
350 always return a resultset, even in list context.
357 # Special-case handling for (undef, undef).
358 if ( @_ == 2 && !defined $_[1] && !defined $_[0] ) {
364 if (ref $_[-1] eq 'HASH') {
365 # copy for _normalize_selection
366 $call_attrs = { %{ pop @_ } };
368 elsif (! defined $_[-1] ) {
369 pop @_; # search({}, undef)
373 # see if we can keep the cache (no $rs changes)
375 my %safe = (alias => 1, cache => 1);
376 if ( ! List::Util::first { !$safe{$_} } keys %$call_attrs and (
379 ref $_[0] eq 'HASH' && ! keys %{$_[0]}
381 ref $_[0] eq 'ARRAY' && ! @{$_[0]}
383 $cache = $self->get_cache;
386 my $rsrc = $self->result_source;
388 my $old_attrs = { %{$self->{attrs}} };
389 my $old_having = delete $old_attrs->{having};
390 my $old_where = delete $old_attrs->{where};
392 my $new_attrs = { %$old_attrs };
394 # take care of call attrs (only if anything is changing)
395 if (keys %$call_attrs) {
397 my @selector_attrs = qw/select as columns cols +select +as +columns include_columns/;
399 # reset the current selector list if new selectors are supplied
400 if (List::Util::first { exists $call_attrs->{$_} } qw/columns cols select as/) {
401 delete @{$old_attrs}{(@selector_attrs, '_dark_selector')};
404 # Normalize the new selector list (operates on the passed-in attr structure)
405 # Need to do it on every chain instead of only once on _resolved_attrs, in
406 # order to allow detection of empty vs partial 'as'
407 $call_attrs->{_dark_selector} = $old_attrs->{_dark_selector}
408 if $old_attrs->{_dark_selector};
409 $self->_normalize_selection ($call_attrs);
411 # start with blind overwriting merge, exclude selector attrs
412 $new_attrs = { %{$old_attrs}, %{$call_attrs} };
413 delete @{$new_attrs}{@selector_attrs};
415 for (@selector_attrs) {
416 $new_attrs->{$_} = $self->_merge_attr($old_attrs->{$_}, $call_attrs->{$_})
417 if ( exists $old_attrs->{$_} or exists $call_attrs->{$_} );
420 # older deprecated name, use only if {columns} is not there
421 if (my $c = delete $new_attrs->{cols}) {
422 if ($new_attrs->{columns}) {
423 carp "Resultset specifies both the 'columns' and the legacy 'cols' attributes - ignoring 'cols'";
426 $new_attrs->{columns} = $c;
431 # join/prefetch use their own crazy merging heuristics
432 foreach my $key (qw/join prefetch/) {
433 $new_attrs->{$key} = $self->_merge_joinpref_attr($old_attrs->{$key}, $call_attrs->{$key})
434 if exists $call_attrs->{$key};
437 # stack binds together
438 $new_attrs->{bind} = [ @{ $old_attrs->{bind} || [] }, @{ $call_attrs->{bind} || [] } ];
442 # rip apart the rest of @_, parse a condition
445 if (ref $_[0] eq 'HASH') {
446 (keys %{$_[0]}) ? $_[0] : undef
452 $self->throw_exception('Odd number of arguments to search')
460 if( @_ > 1 and ! $rsrc->result_class->isa('DBIx::Class::CDBICompat') ) {
461 carp_unique 'search( %condition ) is deprecated, use search( \%condition ) instead';
464 for ($old_where, $call_cond) {
466 $new_attrs->{where} = $self->_stack_cond (
467 $_, $new_attrs->{where}
472 if (defined $old_having) {
473 $new_attrs->{having} = $self->_stack_cond (
474 $old_having, $new_attrs->{having}
478 my $rs = (ref $self)->new($rsrc, $new_attrs);
480 $rs->set_cache($cache) if ($cache);
486 sub _normalize_selection {
487 my ($self, $attrs) = @_;
490 $attrs->{'+columns'} = $self->_merge_attr($attrs->{'+columns'}, delete $attrs->{include_columns})
491 if exists $attrs->{include_columns};
493 # columns are always placed first, however
495 # Keep the X vs +X separation until _resolved_attrs time - this allows to
496 # delay the decision on whether to use a default select list ($rsrc->columns)
497 # allowing stuff like the remove_columns helper to work
499 # select/as +select/+as pairs need special handling - the amount of select/as
500 # elements in each pair does *not* have to be equal (think multicolumn
501 # selectors like distinct(foo, bar) ). If the selector is bare (no 'as'
502 # supplied at all) - try to infer the alias, either from the -as parameter
503 # of the selector spec, or use the parameter whole if it looks like a column
504 # name (ugly legacy heuristic). If all fails - leave the selector bare (which
505 # is ok as well), but make sure no more additions to the 'as' chain take place
506 for my $pref ('', '+') {
508 my ($sel, $as) = map {
509 my $key = "${pref}${_}";
511 my $val = [ ref $attrs->{$key} eq 'ARRAY'
513 : $attrs->{$key} || ()
515 delete $attrs->{$key};
519 if (! @$as and ! @$sel ) {
522 elsif (@$as and ! @$sel) {
523 $self->throw_exception(
524 "Unable to handle ${pref}as specification (@$as) without a corresponding ${pref}select"
528 # no as part supplied at all - try to deduce (unless explicit end of named selection is declared)
529 # if any @$as has been supplied we assume the user knows what (s)he is doing
530 # and blindly keep stacking up pieces
531 unless ($attrs->{_dark_selector}) {
534 if ( ref $_ eq 'HASH' and exists $_->{-as} ) {
535 push @$as, $_->{-as};
537 # assume any plain no-space, no-parenthesis string to be a column spec
538 # FIXME - this is retarded but is necessary to support shit like 'count(foo)'
539 elsif ( ! ref $_ and $_ =~ /^ [^\s\(\)]+ $/x) {
542 # if all else fails - raise a flag that no more aliasing will be allowed
544 $attrs->{_dark_selector} = {
546 string => ($dark_sel_dumper ||= do {
547 require Data::Dumper::Concise;
548 Data::Dumper::Concise::DumperObject()->Indent(0);
549 })->Values([$_])->Dump
557 elsif (@$as < @$sel) {
558 $self->throw_exception(
559 "Unable to handle an ${pref}as specification (@$as) with less elements than the corresponding ${pref}select"
562 elsif ($pref and $attrs->{_dark_selector}) {
563 $self->throw_exception(
564 "Unable to process named '+select', resultset contains an unnamed selector $attrs->{_dark_selector}{string}"
570 $attrs->{"${pref}select"} = $self->_merge_attr($attrs->{"${pref}select"}, $sel);
571 $attrs->{"${pref}as"} = $self->_merge_attr($attrs->{"${pref}as"}, $as);
576 my ($self, $left, $right) = @_;
578 # collapse single element top-level conditions
579 # (single pass only, unlikely to need recursion)
580 for ($left, $right) {
581 if (ref $_ eq 'ARRAY') {
589 elsif (ref $_ eq 'HASH') {
590 my ($first, $more) = keys %$_;
593 if (! defined $first) {
597 elsif (! defined $more) {
598 if ($first eq '-and' and ref $_->{'-and'} eq 'HASH') {
601 elsif ($first eq '-or' and ref $_->{'-or'} eq 'ARRAY') {
608 # merge hashes with weeding out of duplicates (simple cases only)
609 if (ref $left eq 'HASH' and ref $right eq 'HASH') {
611 # shallow copy to destroy
612 $right = { %$right };
613 for (grep { exists $right->{$_} } keys %$left) {
614 # the use of eq_deeply here is justified - the rhs of an
615 # expression can contain a lot of twisted weird stuff
616 delete $right->{$_} if Data::Compare::Compare( $left->{$_}, $right->{$_} );
619 $right = undef unless keys %$right;
623 if (defined $left xor defined $right) {
624 return defined $left ? $left : $right;
626 elsif (! defined $left) {
630 return { -and => [ $left, $right ] };
634 =head2 search_literal
636 B<CAVEAT>: C<search_literal> is provided for Class::DBI compatibility and
637 should only be used in that context. C<search_literal> is a convenience
638 method. It is equivalent to calling C<< $schema->search(\[]) >>, but if you
639 want to ensure columns are bound correctly, use L</search>.
641 See L<DBIx::Class::Manual::Cookbook/Searching> and
642 L<DBIx::Class::Manual::FAQ/Searching> for searching techniques that do not
643 require C<search_literal>.
647 =item Arguments: $sql_fragment, @standalone_bind_values
649 =item Return Value: L<$resultset|/search> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
653 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
654 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
656 Pass a literal chunk of SQL to be added to the conditional part of the
659 Example of how to use C<search> instead of C<search_literal>
661 my @cds = $cd_rs->search_literal('cdid = ? AND (artist = ? OR artist = ?)', (2, 1, 2));
662 my @cds = $cd_rs->search(\[ 'cdid = ? AND (artist = ? OR artist = ?)', [ 'cdid', 2 ], [ 'artist', 1 ], [ 'artist', 2 ] ]);
667 my ($self, $sql, @bind) = @_;
669 if ( @bind && ref($bind[-1]) eq 'HASH' ) {
672 return $self->search(\[ $sql, map [ {} => $_ ], @bind ], ($attr || () ));
679 =item Arguments: \%columns_values | @pk_values, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
681 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
685 Finds and returns a single row based on supplied criteria. Takes either a
686 hashref with the same format as L</create> (including inference of foreign
687 keys from related objects), or a list of primary key values in the same
688 order as the L<primary columns|DBIx::Class::ResultSource/primary_columns>
689 declaration on the L</result_source>.
691 In either case an attempt is made to combine conditions already existing on
692 the resultset with the condition passed to this method.
694 To aid with preparing the correct query for the storage you may supply the
695 C<key> attribute, which is the name of a
696 L<unique constraint|DBIx::Class::ResultSource/add_unique_constraint> (the
697 unique constraint corresponding to the
698 L<primary columns|DBIx::Class::ResultSource/primary_columns> is always named
699 C<primary>). If the C<key> attribute has been supplied, and DBIC is unable
700 to construct a query that satisfies the named unique constraint fully (
701 non-NULL values for each column member of the constraint) an exception is
704 If no C<key> is specified, the search is carried over all unique constraints
705 which are fully defined by the available condition.
707 If no such constraint is found, C<find> currently defaults to a simple
708 C<< search->(\%column_values) >> which may or may not do what you expect.
709 Note that this fallback behavior may be deprecated in further versions. If
710 you need to search with arbitrary conditions - use L</search>. If the query
711 resulting from this fallback produces more than one row, a warning to the
712 effect is issued, though only the first row is constructed and returned as
715 In addition to C<key>, L</find> recognizes and applies standard
716 L<resultset attributes|/ATTRIBUTES> in the same way as L</search> does.
718 Note that if you have extra concerns about the correctness of the resulting
719 query you need to specify the C<key> attribute and supply the entire condition
720 as an argument to find (since it is not always possible to perform the
721 combination of the resultset condition with the supplied one, especially if
722 the resultset condition contains literal sql).
724 For example, to find a row by its primary key:
726 my $cd = $schema->resultset('CD')->find(5);
728 You can also find a row by a specific unique constraint:
730 my $cd = $schema->resultset('CD')->find(
732 artist => 'Massive Attack',
733 title => 'Mezzanine',
735 { key => 'cd_artist_title' }
738 See also L</find_or_create> and L</update_or_create>.
744 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
746 my $rsrc = $self->result_source;
749 if (exists $attrs->{key}) {
750 $constraint_name = defined $attrs->{key}
752 : $self->throw_exception("An undefined 'key' resultset attribute makes no sense")
756 # Parse out the condition from input
759 if (ref $_[0] eq 'HASH') {
760 $call_cond = { %{$_[0]} };
763 # if only values are supplied we need to default to 'primary'
764 $constraint_name = 'primary' unless defined $constraint_name;
766 my @c_cols = $rsrc->unique_constraint_columns($constraint_name);
768 $self->throw_exception(
769 "No constraint columns, maybe a malformed '$constraint_name' constraint?"
772 $self->throw_exception (
773 'find() expects either a column/value hashref, or a list of values '
774 . "corresponding to the columns of the specified unique constraint '$constraint_name'"
775 ) unless @c_cols == @_;
778 @{$call_cond}{@c_cols} = @_;
782 for my $key (keys %$call_cond) {
784 my $keyref = ref($call_cond->{$key})
786 my $relinfo = $rsrc->relationship_info($key)
788 my $val = delete $call_cond->{$key};
790 next if $keyref eq 'ARRAY'; # has_many for multi_create
792 my $rel_q = $rsrc->_resolve_condition(
793 $relinfo->{cond}, $val, $key, $key
795 die "Can't handle complex relationship conditions in find" if ref($rel_q) ne 'HASH';
796 @related{keys %$rel_q} = values %$rel_q;
800 # relationship conditions take precedence (?)
801 @{$call_cond}{keys %related} = values %related;
803 my $alias = exists $attrs->{alias} ? $attrs->{alias} : $self->{attrs}{alias};
805 if (defined $constraint_name) {
806 $final_cond = $self->_qualify_cond_columns (
808 $self->_build_unique_cond (
816 elsif ($self->{attrs}{accessor} and $self->{attrs}{accessor} eq 'single') {
817 # This means that we got here after a merger of relationship conditions
818 # in ::Relationship::Base::search_related (the row method), and furthermore
819 # the relationship is of the 'single' type. This means that the condition
820 # provided by the relationship (already attached to $self) is sufficient,
821 # as there can be only one row in the database that would satisfy the
825 # no key was specified - fall down to heuristics mode:
826 # run through all unique queries registered on the resultset, and
827 # 'OR' all qualifying queries together
828 my (@unique_queries, %seen_column_combinations);
829 for my $c_name ($rsrc->unique_constraint_names) {
830 next if $seen_column_combinations{
831 join "\x00", sort $rsrc->unique_constraint_columns($c_name)
834 push @unique_queries, try {
835 $self->_build_unique_cond ($c_name, $call_cond, 'croak_on_nulls')
839 $final_cond = @unique_queries
840 ? [ map { $self->_qualify_cond_columns($_, $alias) } @unique_queries ]
841 : $self->_non_unique_find_fallback ($call_cond, $attrs)
845 # Run the query, passing the result_class since it should propagate for find
846 my $rs = $self->search ($final_cond, {result_class => $self->result_class, %$attrs});
847 if (keys %{$rs->_resolved_attrs->{collapse}}) {
849 carp "Query returned more than one row" if $rs->next;
857 # This is a stop-gap method as agreed during the discussion on find() cleanup:
858 # http://lists.scsys.co.uk/pipermail/dbix-class/2010-October/009535.html
860 # It is invoked when find() is called in legacy-mode with insufficiently-unique
861 # condition. It is provided for overrides until a saner way forward is devised
863 # *NOTE* This is not a public method, and it's *GUARANTEED* to disappear down
864 # the road. Please adjust your tests accordingly to catch this situation early
865 # DBIx::Class::ResultSet->can('_non_unique_find_fallback') is reasonable
867 # The method will not be removed without an adequately complete replacement
868 # for strict-mode enforcement
869 sub _non_unique_find_fallback {
870 my ($self, $cond, $attrs) = @_;
872 return $self->_qualify_cond_columns(
874 exists $attrs->{alias}
876 : $self->{attrs}{alias}
881 sub _qualify_cond_columns {
882 my ($self, $cond, $alias) = @_;
884 my %aliased = %$cond;
885 for (keys %aliased) {
886 $aliased{"$alias.$_"} = delete $aliased{$_}
893 sub _build_unique_cond {
894 my ($self, $constraint_name, $extra_cond, $croak_on_null) = @_;
896 my @c_cols = $self->result_source->unique_constraint_columns($constraint_name);
898 # combination may fail if $self->{cond} is non-trivial
899 my ($final_cond) = try {
900 $self->_merge_with_rscond ($extra_cond)
905 # trim out everything not in $columns
906 $final_cond = { map {
907 exists $final_cond->{$_}
908 ? ( $_ => $final_cond->{$_} )
912 if (my @missing = grep
913 { ! ($croak_on_null ? defined $final_cond->{$_} : exists $final_cond->{$_}) }
916 $self->throw_exception( sprintf ( "Unable to satisfy requested constraint '%s', no values for column(s): %s",
918 join (', ', map { "'$_'" } @missing),
925 !$ENV{DBIC_NULLABLE_KEY_NOWARN}
927 my @undefs = sort grep { ! defined $final_cond->{$_} } (keys %$final_cond)
929 carp_unique ( sprintf (
930 "NULL/undef values supplied for requested unique constraint '%s' (NULL "
931 . 'values in column(s): %s). This is almost certainly not what you wanted, '
932 . 'though you can set DBIC_NULLABLE_KEY_NOWARN to disable this warning.',
934 join (', ', map { "'$_'" } @undefs),
941 =head2 search_related
945 =item Arguments: $rel_name, $cond?, L<\%attrs?|/ATTRIBUTES>
947 =item Return Value: L<$resultset|/search> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
951 $new_rs = $cd_rs->search_related('artist', {
955 Searches the specified relationship, optionally specifying a condition and
956 attributes for matching records. See L</ATTRIBUTES> for more information.
958 In list context, C<< ->all() >> is called implicitly on the resultset, thus
959 returning a list of result objects instead. To avoid that, use L</search_related_rs>.
961 See also L</search_related_rs>.
966 return shift->related_resultset(shift)->search(@_);
969 =head2 search_related_rs
971 This method works exactly the same as search_related, except that
972 it guarantees a resultset, even in list context.
976 sub search_related_rs {
977 return shift->related_resultset(shift)->search_rs(@_);
984 =item Arguments: none
986 =item Return Value: L<$cursor|DBIx::Class::Cursor>
990 Returns a storage-driven cursor to the given resultset. See
991 L<DBIx::Class::Cursor> for more information.
998 my $attrs = $self->_resolved_attrs_copy;
1000 return $self->{cursor}
1001 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
1002 $attrs->{where},$attrs);
1009 =item Arguments: L<$cond?|DBIx::Class::SQLMaker>
1011 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
1015 my $cd = $schema->resultset('CD')->single({ year => 2001 });
1017 Inflates the first result without creating a cursor if the resultset has
1018 any records in it; if not returns C<undef>. Used by L</find> as a lean version
1021 While this method can take an optional search condition (just like L</search>)
1022 being a fast-code-path it does not recognize search attributes. If you need to
1023 add extra joins or similar, call L</search> and then chain-call L</single> on the
1024 L<DBIx::Class::ResultSet> returned.
1030 As of 0.08100, this method enforces the assumption that the preceding
1031 query returns only one row. If more than one row is returned, you will receive
1034 Query returned more than one row
1036 In this case, you should be using L</next> or L</find> instead, or if you really
1037 know what you are doing, use the L</rows> attribute to explicitly limit the size
1040 This method will also throw an exception if it is called on a resultset prefetching
1041 has_many, as such a prefetch implies fetching multiple rows from the database in
1042 order to assemble the resulting object.
1049 my ($self, $where) = @_;
1051 $self->throw_exception('single() only takes search conditions, no attributes. You want ->search( $cond, $attrs )->single()');
1054 my $attrs = $self->_resolved_attrs_copy;
1056 if (keys %{$attrs->{collapse}}) {
1057 $self->throw_exception(
1058 'single() can not be used on resultsets prefetching has_many. Use find( \%cond ) or next() instead'
1063 if (defined $attrs->{where}) {
1066 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
1067 $where, delete $attrs->{where} ]
1070 $attrs->{where} = $where;
1074 my @data = $self->result_source->storage->select_single(
1075 $attrs->{from}, $attrs->{select},
1076 $attrs->{where}, $attrs
1079 return (@data ? ($self->_construct_object(@data))[0] : undef);
1085 # Recursively collapse the query, accumulating values for each column.
1087 sub _collapse_query {
1088 my ($self, $query, $collapsed) = @_;
1092 if (ref $query eq 'ARRAY') {
1093 foreach my $subquery (@$query) {
1094 next unless ref $subquery; # -or
1095 $collapsed = $self->_collapse_query($subquery, $collapsed);
1098 elsif (ref $query eq 'HASH') {
1099 if (keys %$query and (keys %$query)[0] eq '-and') {
1100 foreach my $subquery (@{$query->{-and}}) {
1101 $collapsed = $self->_collapse_query($subquery, $collapsed);
1105 foreach my $col (keys %$query) {
1106 my $value = $query->{$col};
1107 $collapsed->{$col}{$value}++;
1119 =item Arguments: L<$cond?|DBIx::Class::SQLMaker>
1121 =item Return Value: L<$resultsetcolumn|DBIx::Class::ResultSetColumn>
1125 my $max_length = $rs->get_column('length')->max;
1127 Returns a L<DBIx::Class::ResultSetColumn> instance for a column of the ResultSet.
1132 my ($self, $column) = @_;
1133 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
1141 =item Arguments: L<$cond|DBIx::Class::SQLMaker>, L<\%attrs?|/ATTRIBUTES>
1143 =item Return Value: L<$resultset|/search> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
1147 # WHERE title LIKE '%blue%'
1148 $cd_rs = $rs->search_like({ title => '%blue%'});
1150 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
1151 that this is simply a convenience method retained for ex Class::DBI users.
1152 You most likely want to use L</search> with specific operators.
1154 For more information, see L<DBIx::Class::Manual::Cookbook>.
1156 This method is deprecated and will be removed in 0.09. Use L</search()>
1157 instead. An example conversion is:
1159 ->search_like({ foo => 'bar' });
1163 ->search({ foo => { like => 'bar' } });
1170 'search_like() is deprecated and will be removed in DBIC version 0.09.'
1171 .' Instead use ->search({ x => { -like => "y%" } })'
1172 .' (note the outer pair of {}s - they are important!)'
1174 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1175 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
1176 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
1177 return $class->search($query, { %$attrs });
1184 =item Arguments: $first, $last
1186 =item Return Value: L<$resultset|/search> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
1190 Returns a resultset or object list representing a subset of elements from the
1191 resultset slice is called on. Indexes are from 0, i.e., to get the first
1192 three records, call:
1194 my ($one, $two, $three) = $rs->slice(0, 2);
1199 my ($self, $min, $max) = @_;
1200 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
1201 $attrs->{offset} = $self->{attrs}{offset} || 0;
1202 $attrs->{offset} += $min;
1203 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
1204 return $self->search(undef, $attrs);
1205 #my $slice = (ref $self)->new($self->result_source, $attrs);
1206 #return (wantarray ? $slice->all : $slice);
1213 =item Arguments: none
1215 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
1219 Returns the next element in the resultset (C<undef> is there is none).
1221 Can be used to efficiently iterate over records in the resultset:
1223 my $rs = $schema->resultset('CD')->search;
1224 while (my $cd = $rs->next) {
1228 Note that you need to store the resultset object, and call C<next> on it.
1229 Calling C<< resultset('Table')->next >> repeatedly will always return the
1230 first record from the resultset.
1236 if (my $cache = $self->get_cache) {
1237 $self->{all_cache_position} ||= 0;
1238 return $cache->[$self->{all_cache_position}++];
1240 if ($self->{attrs}{cache}) {
1241 delete $self->{pager};
1242 $self->{all_cache_position} = 1;
1243 return ($self->all)[0];
1245 if ($self->{stashed_objects}) {
1246 my $obj = shift(@{$self->{stashed_objects}});
1247 delete $self->{stashed_objects} unless @{$self->{stashed_objects}};
1251 exists $self->{stashed_row}
1252 ? @{delete $self->{stashed_row}}
1253 : $self->cursor->next
1255 return undef unless (@row);
1256 my ($row, @more) = $self->_construct_object(@row);
1257 $self->{stashed_objects} = \@more if @more;
1261 sub _construct_object {
1262 my ($self, @row) = @_;
1264 my $info = $self->_collapse_result($self->{_attrs}{as}, \@row)
1266 my @new = $self->result_class->inflate_result($self->result_source, @$info);
1267 @new = $self->{_attrs}{record_filter}->(@new)
1268 if exists $self->{_attrs}{record_filter};
1272 sub _collapse_result {
1273 my ($self, $as_proto, $row) = @_;
1277 # 'foo' => [ undef, 'foo' ]
1278 # 'foo.bar' => [ 'foo', 'bar' ]
1279 # 'foo.bar.baz' => [ 'foo.bar', 'baz' ]
1281 my @construct_as = map { [ (/^(?:(.*)\.)?([^.]+)$/) ] } @$as_proto;
1283 my %collapse = %{$self->{_attrs}{collapse}||{}};
1287 # if we're doing collapsing (has_many prefetch) we need to grab records
1288 # until the PK changes, so fill @pri_index. if not, we leave it empty so
1289 # we know we don't have to bother.
1291 # the reason for not using the collapse stuff directly is because if you
1292 # had for e.g. two artists in a row with no cds, the collapse info for
1293 # both would be NULL (undef) so you'd lose the second artist
1295 # store just the index so we can check the array positions from the row
1296 # without having to contruct the full hash
1298 if (keys %collapse) {
1299 my %pri = map { ($_ => 1) } $self->result_source->_pri_cols;
1300 foreach my $i (0 .. $#construct_as) {
1301 next if defined($construct_as[$i][0]); # only self table
1302 if (delete $pri{$construct_as[$i][1]}) {
1303 push(@pri_index, $i);
1305 last unless keys %pri; # short circuit (Johnny Five Is Alive!)
1309 # no need to do an if, it'll be empty if @pri_index is empty anyway
1311 my %pri_vals = map { ($_ => $copy[$_]) } @pri_index;
1315 do { # no need to check anything at the front, we always want the first row
1319 foreach my $this_as (@construct_as) {
1320 $const{$this_as->[0]||''}{$this_as->[1]} = shift(@copy);
1323 push(@const_rows, \%const);
1325 } until ( # no pri_index => no collapse => drop straight out
1328 do { # get another row, stash it, drop out if different PK
1330 @copy = $self->cursor->next;
1331 $self->{stashed_row} = \@copy;
1333 # last thing in do block, counts as true if anything doesn't match
1335 # check xor defined first for NULL vs. NOT NULL then if one is
1336 # defined the other must be so check string equality
1339 (defined $pri_vals{$_} ^ defined $copy[$_])
1340 || (defined $pri_vals{$_} && ($pri_vals{$_} ne $copy[$_]))
1345 my $alias = $self->{attrs}{alias};
1352 foreach my $const (@const_rows) {
1353 scalar @const_keys or do {
1354 @const_keys = sort { length($a) <=> length($b) } keys %$const;
1356 foreach my $key (@const_keys) {
1359 my @parts = split(/\./, $key);
1361 my $data = $const->{$key};
1362 foreach my $p (@parts) {
1363 $target = $target->[1]->{$p} ||= [];
1365 if ($cur eq ".${key}" && (my @ckey = @{$collapse{$cur}||[]})) {
1366 # collapsing at this point and on final part
1367 my $pos = $collapse_pos{$cur};
1368 CK: foreach my $ck (@ckey) {
1369 if (!defined $pos->{$ck} || $pos->{$ck} ne $data->{$ck}) {
1370 $collapse_pos{$cur} = $data;
1371 delete @collapse_pos{ # clear all positioning for sub-entries
1372 grep { m/^\Q${cur}.\E/ } keys %collapse_pos
1379 if (exists $collapse{$cur}) {
1380 $target = $target->[-1];
1383 $target->[0] = $data;
1385 $info->[0] = $const->{$key};
1393 =head2 result_source
1397 =item Arguments: L<$result_source?|DBIx::Class::ResultSource>
1399 =item Return Value: L<$result_source|DBIx::Class::ResultSource>
1403 An accessor for the primary ResultSource object from which this ResultSet
1410 =item Arguments: $result_class?
1412 =item Return Value: $result_class
1416 An accessor for the class to use when creating result objects. Defaults to
1417 C<< result_source->result_class >> - which in most cases is the name of the
1418 L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class.
1420 Note that changing the result_class will also remove any components
1421 that were originally loaded in the source class via
1422 L<DBIx::Class::ResultSource/load_components>. Any overloaded methods
1423 in the original source class will not run.
1428 my ($self, $result_class) = @_;
1429 if ($result_class) {
1430 unless (ref $result_class) { # don't fire this for an object
1431 $self->ensure_class_loaded($result_class);
1433 $self->_result_class($result_class);
1434 # THIS LINE WOULD BE A BUG - this accessor specifically exists to
1435 # permit the user to set result class on one result set only; it only
1436 # chains if provided to search()
1437 #$self->{attrs}{result_class} = $result_class if ref $self;
1439 $self->_result_class;
1446 =item Arguments: L<$cond|DBIx::Class::SQLMaker>, L<\%attrs?|/ATTRIBUTES>
1448 =item Return Value: $count
1452 Performs an SQL C<COUNT> with the same query as the resultset was built
1453 with to find the number of elements. Passing arguments is equivalent to
1454 C<< $rs->search ($cond, \%attrs)->count >>
1460 return $self->search(@_)->count if @_ and defined $_[0];
1461 return scalar @{ $self->get_cache } if $self->get_cache;
1463 my $attrs = $self->_resolved_attrs_copy;
1465 # this is a little optimization - it is faster to do the limit
1466 # adjustments in software, instead of a subquery
1467 my $rows = delete $attrs->{rows};
1468 my $offset = delete $attrs->{offset};
1471 if ($self->_has_resolved_attr (qw/collapse group_by/)) {
1472 $crs = $self->_count_subq_rs ($attrs);
1475 $crs = $self->_count_rs ($attrs);
1477 my $count = $crs->next;
1479 $count -= $offset if $offset;
1480 $count = $rows if $rows and $rows < $count;
1481 $count = 0 if ($count < 0);
1490 =item Arguments: L<$cond|DBIx::Class::SQLMaker>, L<\%attrs?|/ATTRIBUTES>
1492 =item Return Value: L<$count_rs|DBIx::Class::ResultSetColumn>
1496 Same as L</count> but returns a L<DBIx::Class::ResultSetColumn> object.
1497 This can be very handy for subqueries:
1499 ->search( { amount => $some_rs->count_rs->as_query } )
1501 As with regular resultsets the SQL query will be executed only after
1502 the resultset is accessed via L</next> or L</all>. That would return
1503 the same single value obtainable via L</count>.
1509 return $self->search(@_)->count_rs if @_;
1511 # this may look like a lack of abstraction (count() does about the same)
1512 # but in fact an _rs *must* use a subquery for the limits, as the
1513 # software based limiting can not be ported if this $rs is to be used
1514 # in a subquery itself (i.e. ->as_query)
1515 if ($self->_has_resolved_attr (qw/collapse group_by offset rows/)) {
1516 return $self->_count_subq_rs;
1519 return $self->_count_rs;
1524 # returns a ResultSetColumn object tied to the count query
1527 my ($self, $attrs) = @_;
1529 my $rsrc = $self->result_source;
1530 $attrs ||= $self->_resolved_attrs;
1532 my $tmp_attrs = { %$attrs };
1533 # take off any limits, record_filter is cdbi, and no point of ordering nor locking a count
1534 delete @{$tmp_attrs}{qw/rows offset order_by record_filter for/};
1536 # overwrite the selector (supplied by the storage)
1537 $tmp_attrs->{select} = $rsrc->storage->_count_select ($rsrc, $attrs);
1538 $tmp_attrs->{as} = 'count';
1539 delete @{$tmp_attrs}{qw/columns/};
1541 my $tmp_rs = $rsrc->resultset_class->new($rsrc, $tmp_attrs)->get_column ('count');
1547 # same as above but uses a subquery
1549 sub _count_subq_rs {
1550 my ($self, $attrs) = @_;
1552 my $rsrc = $self->result_source;
1553 $attrs ||= $self->_resolved_attrs;
1555 my $sub_attrs = { %$attrs };
1556 # extra selectors do not go in the subquery and there is no point of ordering it, nor locking it
1557 delete @{$sub_attrs}{qw/collapse columns as select _prefetch_selector_range order_by for/};
1559 # if we multi-prefetch we group_by something unique, as this is what we would
1560 # get out of the rs via ->next/->all. We *DO WANT* to clobber old group_by regardless
1561 if ( keys %{$attrs->{collapse}} ) {
1562 $sub_attrs->{group_by} = [ map { "$attrs->{alias}.$_" } @{
1563 $rsrc->_identifying_column_set || $self->throw_exception(
1564 'Unable to construct a unique group_by criteria properly collapsing the '
1565 . 'has_many prefetch before count()'
1570 # Calculate subquery selector
1571 if (my $g = $sub_attrs->{group_by}) {
1573 my $sql_maker = $rsrc->storage->sql_maker;
1575 # necessary as the group_by may refer to aliased functions
1577 for my $sel (@{$attrs->{select}}) {
1578 $sel_index->{$sel->{-as}} = $sel
1579 if (ref $sel eq 'HASH' and $sel->{-as});
1582 # anything from the original select mentioned on the group-by needs to make it to the inner selector
1583 # also look for named aggregates referred in the having clause
1584 # having often contains scalarrefs - thus parse it out entirely
1586 if ($attrs->{having}) {
1587 local $sql_maker->{having_bind};
1588 local $sql_maker->{quote_char} = $sql_maker->{quote_char};
1589 local $sql_maker->{name_sep} = $sql_maker->{name_sep};
1590 unless (defined $sql_maker->{quote_char} and length $sql_maker->{quote_char}) {
1591 $sql_maker->{quote_char} = [ "\x00", "\xFF" ];
1592 # if we don't unset it we screw up retarded but unfortunately working
1593 # 'MAX(foo.bar)' => { '>', 3 }
1594 $sql_maker->{name_sep} = '';
1597 my ($lquote, $rquote, $sep) = map { quotemeta $_ } ($sql_maker->_quote_chars, $sql_maker->name_sep);
1599 my $sql = $sql_maker->_parse_rs_attrs ({ having => $attrs->{having} });
1601 # search for both a proper quoted qualified string, for a naive unquoted scalarref
1602 # and if all fails for an utterly naive quoted scalar-with-function
1604 $rquote $sep $lquote (.+?) $rquote
1606 [\s,] \w+ \. (\w+) [\s,]
1608 [\s,] $lquote (.+?) $rquote [\s,]
1610 push @parts, ($1 || $2 || $3); # one of them matched if we got here
1615 my $colpiece = $sel_index->{$_} || $_;
1617 # unqualify join-based group_by's. Arcane but possible query
1618 # also horrible horrible hack to alias a column (not a func.)
1619 # (probably need to introduce SQLA syntax)
1620 if ($colpiece =~ /\./ && $colpiece !~ /^$attrs->{alias}\./) {
1623 $colpiece = \ sprintf ('%s AS %s', map { $sql_maker->_quote ($_) } ($colpiece, $as) );
1625 push @{$sub_attrs->{select}}, $colpiece;
1629 my @pcols = map { "$attrs->{alias}.$_" } ($rsrc->primary_columns);
1630 $sub_attrs->{select} = @pcols ? \@pcols : [ 1 ];
1633 return $rsrc->resultset_class
1634 ->new ($rsrc, $sub_attrs)
1636 ->search ({}, { columns => { count => $rsrc->storage->_count_select ($rsrc, $attrs) } })
1637 ->get_column ('count');
1644 =head2 count_literal
1646 B<CAVEAT>: C<count_literal> is provided for Class::DBI compatibility and
1647 should only be used in that context. See L</search_literal> for further info.
1651 =item Arguments: $sql_fragment, @standalone_bind_values
1653 =item Return Value: $count
1657 Counts the results in a literal query. Equivalent to calling L</search_literal>
1658 with the passed arguments, then L</count>.
1662 sub count_literal { shift->search_literal(@_)->count; }
1668 =item Arguments: none
1670 =item Return Value: L<@result_objs|DBIx::Class::Manual::ResultClass>
1674 Returns all elements in the resultset.
1681 $self->throw_exception("all() doesn't take any arguments, you probably wanted ->search(...)->all()");
1684 return @{ $self->get_cache } if $self->get_cache;
1688 if (keys %{$self->_resolved_attrs->{collapse}}) {
1689 # Using $self->cursor->all is really just an optimisation.
1690 # If we're collapsing has_many prefetches it probably makes
1691 # very little difference, and this is cleaner than hacking
1692 # _construct_object to survive the approach
1693 $self->cursor->reset;
1694 my @row = $self->cursor->next;
1696 push(@obj, $self->_construct_object(@row));
1697 @row = (exists $self->{stashed_row}
1698 ? @{delete $self->{stashed_row}}
1699 : $self->cursor->next);
1702 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
1705 $self->set_cache(\@obj) if $self->{attrs}{cache};
1714 =item Arguments: none
1716 =item Return Value: $self
1720 Resets the resultset's cursor, so you can iterate through the elements again.
1721 Implicitly resets the storage cursor, so a subsequent L</next> will trigger
1728 delete $self->{_attrs} if exists $self->{_attrs};
1729 $self->{all_cache_position} = 0;
1730 $self->cursor->reset;
1738 =item Arguments: none
1740 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
1744 L<Resets|/reset> the resultset (causing a fresh query to storage) and returns
1745 an object for the first result (or C<undef> if the resultset is empty).
1750 return $_[0]->reset->next;
1756 # Determines whether and what type of subquery is required for the $rs operation.
1757 # If grouping is necessary either supplies its own, or verifies the current one
1758 # After all is done delegates to the proper storage method.
1760 sub _rs_update_delete {
1761 my ($self, $op, $values) = @_;
1763 my $cond = $self->{cond};
1764 my $rsrc = $self->result_source;
1765 my $storage = $rsrc->schema->storage;
1767 my $attrs = { %{$self->_resolved_attrs} };
1769 my $existing_group_by = delete $attrs->{group_by};
1770 my $needs_subq = defined $existing_group_by;
1772 # simplify the joinmap and maybe decide if a subquery is necessary
1773 my $relation_classifications = {};
1775 if (ref($attrs->{from}) eq 'ARRAY') {
1776 # if we already know we need a subq, no point of classifying relations
1777 if (!$needs_subq and @{$attrs->{from}} > 1) {
1778 $attrs->{from} = $storage->_prune_unused_joins ($attrs->{from}, $attrs->{select}, $cond, $attrs);
1780 $relation_classifications = $storage->_resolve_aliastypes_from_select_args (
1781 [ @{$attrs->{from}}[1 .. $#{$attrs->{from}}] ],
1789 $needs_subq ||= 1; # if {from} is unparseable assume the worst
1792 # do we need anything like a subquery?
1796 ! keys %{ $relation_classifications->{restricting} || {} }
1798 ! $self->_has_resolved_attr(qw/rows offset/) # limits call for a subq
1800 # Most databases do not allow aliasing of tables in UPDATE/DELETE. Thus
1801 # a condition containing 'me' or other table prefixes will not work
1802 # at all. Tell SQLMaker to dequalify idents via a gross hack.
1804 my $sqla = $rsrc->storage->sql_maker;
1805 local $sqla->{_dequalify_idents} = 1;
1806 \[ $sqla->_recurse_where($self->{cond}) ];
1808 return $rsrc->storage->$op(
1810 $op eq 'update' ? $values : (),
1815 # we got this far - means it is time to wrap a subquery
1816 my $idcols = $rsrc->_identifying_column_set || $self->throw_exception(
1818 "Unable to perform complex resultset %s() without an identifying set of columns on source '%s'",
1824 # make a new $rs selecting only the PKs (that's all we really need for the subq)
1825 delete $attrs->{$_} for qw/collapse _collapse_order_by select _prefetch_selector_range as/;
1826 $attrs->{columns} = [ map { "$attrs->{alias}.$_" } @$idcols ];
1827 $attrs->{group_by} = \ ''; # FIXME - this is an evil hack, it causes the optimiser to kick in and throw away the LEFT joins
1828 my $subrs = (ref $self)->new($rsrc, $attrs);
1830 if (@$idcols == 1) {
1831 return $storage->$op (
1833 $op eq 'update' ? $values : (),
1834 { $idcols->[0] => { -in => $subrs->as_query } },
1837 elsif ($storage->_use_multicolumn_in) {
1838 # This is hideously ugly, but SQLA does not understand multicol IN expressions
1839 my $sql_maker = $storage->sql_maker;
1840 my ($sql, @bind) = @${$subrs->as_query};
1841 $sql = sprintf ('(%s) IN %s', # the as_query already comes with a set of parenthesis
1842 join (', ', map { $sql_maker->_quote ($_) } @$idcols),
1846 return $storage->$op (
1848 $op eq 'update' ? $values : (),
1854 # if all else fails - get all primary keys and operate over a ORed set
1855 # wrap in a transaction for consistency
1856 # this is where the group_by starts to matter
1860 keys %{ $relation_classifications->{multiplying} || {} }
1862 # make sure if there is a supplied group_by it matches the columns compiled above
1863 # perfectly. Anything else can not be sanely executed on most databases so croak
1864 # right then and there
1865 if ($existing_group_by) {
1866 my @current_group_by = map
1867 { $_ =~ /\./ ? $_ : "$attrs->{alias}.$_" }
1872 join ("\x00", sort @current_group_by)
1874 join ("\x00", sort @{$attrs->{columns}} )
1876 $self->throw_exception (
1877 "You have just attempted a $op operation on a resultset which does group_by"
1878 . ' on columns other than the primary keys, while DBIC internally needs to retrieve'
1879 . ' the primary keys in a subselect. All sane RDBMS engines do not support this'
1880 . ' kind of queries. Please retry the operation with a modified group_by or'
1881 . ' without using one at all.'
1886 $subrs = $subrs->search({}, { group_by => $attrs->{columns} });
1889 my $guard = $storage->txn_scope_guard;
1892 for my $row ($subrs->cursor->all) {
1893 push @op_condition, { map
1894 { $idcols->[$_] => $row->[$_] }
1899 my $res = $storage->$op (
1901 $op eq 'update' ? $values : (),
1915 =item Arguments: \%values
1917 =item Return Value: $underlying_storage_rv
1921 Sets the specified columns in the resultset to the supplied values in a
1922 single query. Note that this will not run any accessor/set_column/update
1923 triggers, nor will it update any result object instances derived from this
1924 resultset (this includes the contents of the L<resultset cache|/set_cache>
1925 if any). See L</update_all> if you need to execute any on-update
1926 triggers or cascades defined either by you or a
1927 L<result component|DBIx::Class::Manual::Component/WHAT IS A COMPONENT>.
1929 The return value is a pass through of what the underlying
1930 storage backend returned, and may vary. See L<DBI/execute> for the most
1935 Note that L</update> does not process/deflate any of the values passed in.
1936 This is unlike the corresponding L<DBIx::Class::Row/update>. The user must
1937 ensure manually that any value passed to this method will stringify to
1938 something the RDBMS knows how to deal with. A notable example is the
1939 handling of L<DateTime> objects, for more info see:
1940 L<DBIx::Class::Manual::Cookbook/Formatting DateTime objects in queries>.
1945 my ($self, $values) = @_;
1946 $self->throw_exception('Values for update must be a hash')
1947 unless ref $values eq 'HASH';
1949 return $self->_rs_update_delete ('update', $values);
1956 =item Arguments: \%values
1958 =item Return Value: 1
1962 Fetches all objects and updates them one at a time via
1963 L<DBIx::Class::Row/update>. Note that C<update_all> will run DBIC defined
1964 triggers, while L</update> will not.
1969 my ($self, $values) = @_;
1970 $self->throw_exception('Values for update_all must be a hash')
1971 unless ref $values eq 'HASH';
1973 my $guard = $self->result_source->schema->txn_scope_guard;
1974 $_->update({%$values}) for $self->all; # shallow copy - update will mangle it
1983 =item Arguments: none
1985 =item Return Value: $underlying_storage_rv
1989 Deletes the rows matching this resultset in a single query. Note that this
1990 will not run any delete triggers, nor will it alter the
1991 L<in_storage|DBIx::Class::Row/in_storage> status of any result object instances
1992 derived from this resultset (this includes the contents of the
1993 L<resultset cache|/set_cache> if any). See L</delete_all> if you need to
1994 execute any on-delete triggers or cascades defined either by you or a
1995 L<result component|DBIx::Class::Manual::Component/WHAT IS A COMPONENT>.
1997 The return value is a pass through of what the underlying storage backend
1998 returned, and may vary. See L<DBI/execute> for the most common case.
2004 $self->throw_exception('delete does not accept any arguments')
2007 return $self->_rs_update_delete ('delete');
2014 =item Arguments: none
2016 =item Return Value: 1
2020 Fetches all objects and deletes them one at a time via
2021 L<DBIx::Class::Row/delete>. Note that C<delete_all> will run DBIC defined
2022 triggers, while L</delete> will not.
2028 $self->throw_exception('delete_all does not accept any arguments')
2031 my $guard = $self->result_source->schema->txn_scope_guard;
2032 $_->delete for $self->all;
2041 =item Arguments: [ \@column_list, \@row_values+ ] | [ \%col_data+ ]
2043 =item Return Value: L<\@result_objects|DBIx::Class::Manual::ResultClass> (scalar context) | L<@result_objects|DBIx::Class::Manual::ResultClass> (list context)
2047 Accepts either an arrayref of hashrefs or alternatively an arrayref of
2054 The context of this method call has an important effect on what is
2055 submitted to storage. In void context data is fed directly to fastpath
2056 insertion routines provided by the underlying storage (most often
2057 L<DBI/execute_for_fetch>), bypassing the L<new|DBIx::Class::Row/new> and
2058 L<insert|DBIx::Class::Row/insert> calls on the
2059 L<Result|DBIx::Class::Manual::ResultClass> class, including any
2060 augmentation of these methods provided by components. For example if you
2061 are using something like L<DBIx::Class::UUIDColumns> to create primary
2062 keys for you, you will find that your PKs are empty. In this case you
2063 will have to explicitly force scalar or list context in order to create
2068 In non-void (scalar or list) context, this method is simply a wrapper
2069 for L</create>. Depending on list or scalar context either a list of
2070 L<Result|DBIx::Class::Manual::ResultClass> objects or an arrayref
2071 containing these objects is returned.
2073 When supplying data in "arrayref of arrayrefs" invocation style, the
2074 first element should be a list of column names and each subsequent
2075 element should be a data value in the earlier specified column order.
2078 $Arstist_rs->populate([
2079 [ qw( artistid name ) ],
2080 [ 100, 'A Formally Unknown Singer' ],
2081 [ 101, 'A singer that jumped the shark two albums ago' ],
2082 [ 102, 'An actually cool singer' ],
2085 For the arrayref of hashrefs style each hashref should be a structure
2086 suitable for passing to L</create>. Multi-create is also permitted with
2089 $schema->resultset("Artist")->populate([
2090 { artistid => 4, name => 'Manufactured Crap', cds => [
2091 { title => 'My First CD', year => 2006 },
2092 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
2095 { artistid => 5, name => 'Angsty-Whiny Girl', cds => [
2096 { title => 'My parents sold me to a record company', year => 2005 },
2097 { title => 'Why Am I So Ugly?', year => 2006 },
2098 { title => 'I Got Surgery and am now Popular', year => 2007 }
2103 If you attempt a void-context multi-create as in the example above (each
2104 Artist also has the related list of CDs), and B<do not> supply the
2105 necessary autoinc foreign key information, this method will proxy to the
2106 less efficient L</create>, and then throw the Result objects away. In this
2107 case there are obviously no benefits to using this method over L</create>.
2114 # cruft placed in standalone method
2115 my $data = $self->_normalize_populate_args(@_);
2117 return unless @$data;
2119 if(defined wantarray) {
2121 foreach my $item (@$data) {
2122 push(@created, $self->create($item));
2124 return wantarray ? @created : \@created;
2127 my $first = $data->[0];
2129 # if a column is a registered relationship, and is a non-blessed hash/array, consider
2130 # it relationship data
2131 my (@rels, @columns);
2132 my $rsrc = $self->result_source;
2133 my $rels = { map { $_ => $rsrc->relationship_info($_) } $rsrc->relationships };
2134 for (keys %$first) {
2135 my $ref = ref $first->{$_};
2136 $rels->{$_} && ($ref eq 'ARRAY' or $ref eq 'HASH')
2142 my @pks = $rsrc->primary_columns;
2144 ## do the belongs_to relationships
2145 foreach my $index (0..$#$data) {
2147 # delegate to create() for any dataset without primary keys with specified relationships
2148 if (grep { !defined $data->[$index]->{$_} } @pks ) {
2150 if (grep { ref $data->[$index]{$r} eq $_ } qw/HASH ARRAY/) { # a related set must be a HASH or AoH
2151 my @ret = $self->populate($data);
2157 foreach my $rel (@rels) {
2158 next unless ref $data->[$index]->{$rel} eq "HASH";
2159 my $result = $self->related_resultset($rel)->create($data->[$index]->{$rel});
2160 my ($reverse_relname, $reverse_relinfo) = %{$rsrc->reverse_relationship_info($rel)};
2161 my $related = $result->result_source->_resolve_condition(
2162 $reverse_relinfo->{cond},
2168 delete $data->[$index]->{$rel};
2169 $data->[$index] = {%{$data->[$index]}, %$related};
2171 push @columns, keys %$related if $index == 0;
2175 ## inherit the data locked in the conditions of the resultset
2176 my ($rs_data) = $self->_merge_with_rscond({});
2177 delete @{$rs_data}{@columns};
2178 my @inherit_cols = keys %$rs_data;
2179 my @inherit_data = values %$rs_data;
2181 ## do bulk insert on current row
2182 $rsrc->storage->insert_bulk(
2184 [@columns, @inherit_cols],
2185 [ map { [ @$_{@columns}, @inherit_data ] } @$data ],
2188 ## do the has_many relationships
2189 foreach my $item (@$data) {
2193 foreach my $rel (@rels) {
2194 next unless ref $item->{$rel} eq "ARRAY" && @{ $item->{$rel} };
2196 $main_row ||= $self->new_result({map { $_ => $item->{$_} } @pks});
2198 my $child = $main_row->$rel;
2200 my $related = $child->result_source->_resolve_condition(
2201 $rels->{$rel}{cond},
2207 my @rows_to_add = ref $item->{$rel} eq 'ARRAY' ? @{$item->{$rel}} : ($item->{$rel});
2208 my @populate = map { {%$_, %$related} } @rows_to_add;
2210 $child->populate( \@populate );
2217 # populate() argumnets went over several incarnations
2218 # What we ultimately support is AoH
2219 sub _normalize_populate_args {
2220 my ($self, $arg) = @_;
2222 if (ref $arg eq 'ARRAY') {
2226 elsif (ref $arg->[0] eq 'HASH') {
2229 elsif (ref $arg->[0] eq 'ARRAY') {
2231 my @colnames = @{$arg->[0]};
2232 foreach my $values (@{$arg}[1 .. $#$arg]) {
2233 push @ret, { map { $colnames[$_] => $values->[$_] } (0 .. $#colnames) };
2239 $self->throw_exception('Populate expects an arrayref of hashrefs or arrayref of arrayrefs');
2246 =item Arguments: none
2248 =item Return Value: L<$pager|Data::Page>
2252 Returns a L<Data::Page> object for the current resultset. Only makes
2253 sense for queries with a C<page> attribute.
2255 To get the full count of entries for a paged resultset, call
2256 C<total_entries> on the L<Data::Page> object.
2263 return $self->{pager} if $self->{pager};
2265 my $attrs = $self->{attrs};
2266 if (!defined $attrs->{page}) {
2267 $self->throw_exception("Can't create pager for non-paged rs");
2269 elsif ($attrs->{page} <= 0) {
2270 $self->throw_exception('Invalid page number (page-numbers are 1-based)');
2272 $attrs->{rows} ||= 10;
2274 # throw away the paging flags and re-run the count (possibly
2275 # with a subselect) to get the real total count
2276 my $count_attrs = { %$attrs };
2277 delete $count_attrs->{$_} for qw/rows offset page pager/;
2279 my $total_rs = (ref $self)->new($self->result_source, $count_attrs);
2281 require DBIx::Class::ResultSet::Pager;
2282 return $self->{pager} = DBIx::Class::ResultSet::Pager->new(
2283 sub { $total_rs->count }, #lazy-get the total
2285 $self->{attrs}{page},
2293 =item Arguments: $page_number
2295 =item Return Value: L<$resultset|/search>
2299 Returns a resultset for the $page_number page of the resultset on which page
2300 is called, where each page contains a number of rows equal to the 'rows'
2301 attribute set on the resultset (10 by default).
2306 my ($self, $page) = @_;
2307 return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
2314 =item Arguments: \%col_data
2316 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2320 Creates a new result object in the resultset's result class and returns
2321 it. The row is not inserted into the database at this point, call
2322 L<DBIx::Class::Row/insert> to do that. Calling L<DBIx::Class::Row/in_storage>
2323 will tell you whether the result object has been inserted or not.
2325 Passes the hashref of input on to L<DBIx::Class::Row/new>.
2330 my ($self, $values) = @_;
2332 $self->throw_exception( "new_result takes only one argument - a hashref of values" )
2335 $self->throw_exception( "new_result expects a hashref" )
2336 unless (ref $values eq 'HASH');
2338 my ($merged_cond, $cols_from_relations) = $self->_merge_with_rscond($values);
2342 @$cols_from_relations
2343 ? (-cols_from_relations => $cols_from_relations)
2345 -result_source => $self->result_source, # DO NOT REMOVE THIS, REQUIRED
2348 return $self->result_class->new(\%new);
2351 # _merge_with_rscond
2353 # Takes a simple hash of K/V data and returns its copy merged with the
2354 # condition already present on the resultset. Additionally returns an
2355 # arrayref of value/condition names, which were inferred from related
2356 # objects (this is needed for in-memory related objects)
2357 sub _merge_with_rscond {
2358 my ($self, $data) = @_;
2360 my (%new_data, @cols_from_relations);
2362 my $alias = $self->{attrs}{alias};
2364 if (! defined $self->{cond}) {
2365 # just massage $data below
2367 elsif ($self->{cond} eq $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION) {
2368 %new_data = %{ $self->{attrs}{related_objects} || {} }; # nothing might have been inserted yet
2369 @cols_from_relations = keys %new_data;
2371 elsif (ref $self->{cond} ne 'HASH') {
2372 $self->throw_exception(
2373 "Can't abstract implicit construct, resultset condition not a hash"
2377 # precendence must be given to passed values over values inherited from
2378 # the cond, so the order here is important.
2379 my $collapsed_cond = $self->_collapse_cond($self->{cond});
2380 my %implied = %{$self->_remove_alias($collapsed_cond, $alias)};
2382 while ( my($col, $value) = each %implied ) {
2383 my $vref = ref $value;
2389 (keys %$value)[0] eq '='
2391 $new_data{$col} = $value->{'='};
2393 elsif( !$vref or $vref eq 'SCALAR' or blessed($value) ) {
2394 $new_data{$col} = $value;
2401 %{ $self->_remove_alias($data, $alias) },
2404 return (\%new_data, \@cols_from_relations);
2407 # _has_resolved_attr
2409 # determines if the resultset defines at least one
2410 # of the attributes supplied
2412 # used to determine if a subquery is neccessary
2414 # supports some virtual attributes:
2416 # This will scan for any joins being present on the resultset.
2417 # It is not a mere key-search but a deep inspection of {from}
2420 sub _has_resolved_attr {
2421 my ($self, @attr_names) = @_;
2423 my $attrs = $self->_resolved_attrs;
2427 for my $n (@attr_names) {
2428 if (grep { $n eq $_ } (qw/-join/) ) {
2429 $extra_checks{$n}++;
2433 my $attr = $attrs->{$n};
2435 next if not defined $attr;
2437 if (ref $attr eq 'HASH') {
2438 return 1 if keys %$attr;
2440 elsif (ref $attr eq 'ARRAY') {
2448 # a resolved join is expressed as a multi-level from
2450 $extra_checks{-join}
2452 ref $attrs->{from} eq 'ARRAY'
2454 @{$attrs->{from}} > 1
2462 # Recursively collapse the condition.
2464 sub _collapse_cond {
2465 my ($self, $cond, $collapsed) = @_;
2469 if (ref $cond eq 'ARRAY') {
2470 foreach my $subcond (@$cond) {
2471 next unless ref $subcond; # -or
2472 $collapsed = $self->_collapse_cond($subcond, $collapsed);
2475 elsif (ref $cond eq 'HASH') {
2476 if (keys %$cond and (keys %$cond)[0] eq '-and') {
2477 foreach my $subcond (@{$cond->{-and}}) {
2478 $collapsed = $self->_collapse_cond($subcond, $collapsed);
2482 foreach my $col (keys %$cond) {
2483 my $value = $cond->{$col};
2484 $collapsed->{$col} = $value;
2494 # Remove the specified alias from the specified query hash. A copy is made so
2495 # the original query is not modified.
2498 my ($self, $query, $alias) = @_;
2500 my %orig = %{ $query || {} };
2503 foreach my $key (keys %orig) {
2505 $unaliased{$key} = $orig{$key};
2508 $unaliased{$1} = $orig{$key}
2509 if $key =~ m/^(?:\Q$alias\E\.)?([^.]+)$/;
2519 =item Arguments: none
2521 =item Return Value: \[ $sql, L<@bind_values|/DBIC BIND VALUES> ]
2525 Returns the SQL query and bind vars associated with the invocant.
2527 This is generally used as the RHS for a subquery.
2534 my $attrs = $self->_resolved_attrs_copy;
2539 # my ($sql, \@bind, \%dbi_bind_attrs) = _select_args_to_query (...)
2540 # $sql also has no wrapping parenthesis in list ctx
2542 my $sqlbind = $self->result_source->storage
2543 ->_select_args_to_query ($attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs);
2552 =item Arguments: \%col_data, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
2554 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2558 my $artist = $schema->resultset('Artist')->find_or_new(
2559 { artist => 'fred' }, { key => 'artists' });
2561 $cd->cd_to_producer->find_or_new({ producer => $producer },
2562 { key => 'primary });
2564 Find an existing record from this resultset using L</find>. if none exists,
2565 instantiate a new result object and return it. The object will not be saved
2566 into your storage until you call L<DBIx::Class::Row/insert> on it.
2568 You most likely want this method when looking for existing rows using a unique
2569 constraint that is not the primary key, or looking for related rows.
2571 If you want objects to be saved immediately, use L</find_or_create> instead.
2573 B<Note>: Make sure to read the documentation of L</find> and understand the
2574 significance of the C<key> attribute, as its lack may skew your search, and
2575 subsequently result in spurious new objects.
2577 B<Note>: Take care when using C<find_or_new> with a table having
2578 columns with default values that you intend to be automatically
2579 supplied by the database (e.g. an auto_increment primary key column).
2580 In normal usage, the value of such columns should NOT be included at
2581 all in the call to C<find_or_new>, even when set to C<undef>.
2587 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2588 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
2589 if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2592 return $self->new_result($hash);
2599 =item Arguments: \%col_data
2601 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2605 Attempt to create a single new row or a row with multiple related rows
2606 in the table represented by the resultset (and related tables). This
2607 will not check for duplicate rows before inserting, use
2608 L</find_or_create> to do that.
2610 To create one row for this resultset, pass a hashref of key/value
2611 pairs representing the columns of the table and the values you wish to
2612 store. If the appropriate relationships are set up, foreign key fields
2613 can also be passed an object representing the foreign row, and the
2614 value will be set to its primary key.
2616 To create related objects, pass a hashref of related-object column values
2617 B<keyed on the relationship name>. If the relationship is of type C<multi>
2618 (L<DBIx::Class::Relationship/has_many>) - pass an arrayref of hashrefs.
2619 The process will correctly identify columns holding foreign keys, and will
2620 transparently populate them from the keys of the corresponding relation.
2621 This can be applied recursively, and will work correctly for a structure
2622 with an arbitrary depth and width, as long as the relationships actually
2623 exists and the correct column data has been supplied.
2625 Instead of hashrefs of plain related data (key/value pairs), you may
2626 also pass new or inserted objects. New objects (not inserted yet, see
2627 L</new_result>), will be inserted into their appropriate tables.
2629 Effectively a shortcut for C<< ->new_result(\%col_data)->insert >>.
2631 Example of creating a new row.
2633 $person_rs->create({
2634 name=>"Some Person",
2635 email=>"somebody@someplace.com"
2638 Example of creating a new row and also creating rows in a related C<has_many>
2639 or C<has_one> resultset. Note Arrayref.
2642 { artistid => 4, name => 'Manufactured Crap', cds => [
2643 { title => 'My First CD', year => 2006 },
2644 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
2649 Example of creating a new row and also creating a row in a related
2650 C<belongs_to> resultset. Note Hashref.
2653 title=>"Music for Silly Walks",
2656 name=>"Silly Musician",
2664 When subclassing ResultSet never attempt to override this method. Since
2665 it is a simple shortcut for C<< $self->new_result($attrs)->insert >>, a
2666 lot of the internals simply never call it, so your override will be
2667 bypassed more often than not. Override either L<DBIx::Class::Row/new>
2668 or L<DBIx::Class::Row/insert> depending on how early in the
2669 L</create> process you need to intervene. See also warning pertaining to
2677 my ($self, $attrs) = @_;
2678 $self->throw_exception( "create needs a hashref" )
2679 unless ref $attrs eq 'HASH';
2680 return $self->new_result($attrs)->insert;
2683 =head2 find_or_create
2687 =item Arguments: \%col_data, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
2689 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2693 $cd->cd_to_producer->find_or_create({ producer => $producer },
2694 { key => 'primary' });
2696 Tries to find a record based on its primary key or unique constraints; if none
2697 is found, creates one and returns that instead.
2699 my $cd = $schema->resultset('CD')->find_or_create({
2701 artist => 'Massive Attack',
2702 title => 'Mezzanine',
2706 Also takes an optional C<key> attribute, to search by a specific key or unique
2707 constraint. For example:
2709 my $cd = $schema->resultset('CD')->find_or_create(
2711 artist => 'Massive Attack',
2712 title => 'Mezzanine',
2714 { key => 'cd_artist_title' }
2717 B<Note>: Make sure to read the documentation of L</find> and understand the
2718 significance of the C<key> attribute, as its lack may skew your search, and
2719 subsequently result in spurious row creation.
2721 B<Note>: Because find_or_create() reads from the database and then
2722 possibly inserts based on the result, this method is subject to a race
2723 condition. Another process could create a record in the table after
2724 the find has completed and before the create has started. To avoid
2725 this problem, use find_or_create() inside a transaction.
2727 B<Note>: Take care when using C<find_or_create> with a table having
2728 columns with default values that you intend to be automatically
2729 supplied by the database (e.g. an auto_increment primary key column).
2730 In normal usage, the value of such columns should NOT be included at
2731 all in the call to C<find_or_create>, even when set to C<undef>.
2733 See also L</find> and L</update_or_create>. For information on how to declare
2734 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2736 If you need to know if an existing row was found or a new one created use
2737 L</find_or_new> and L<DBIx::Class::Row/in_storage> instead. Don't forget
2738 to call L<DBIx::Class::Row/insert> to save the newly created row to the
2741 my $cd = $schema->resultset('CD')->find_or_new({
2743 artist => 'Massive Attack',
2744 title => 'Mezzanine',
2748 if( !$cd->in_storage ) {
2755 sub find_or_create {
2757 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2758 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
2759 if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2762 return $self->create($hash);
2765 =head2 update_or_create
2769 =item Arguments: \%col_data, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
2771 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2775 $resultset->update_or_create({ col => $val, ... });
2777 Like L</find_or_create>, but if a row is found it is immediately updated via
2778 C<< $found_row->update (\%col_data) >>.
2781 Takes an optional C<key> attribute to search on a specific unique constraint.
2784 # In your application
2785 my $cd = $schema->resultset('CD')->update_or_create(
2787 artist => 'Massive Attack',
2788 title => 'Mezzanine',
2791 { key => 'cd_artist_title' }
2794 $cd->cd_to_producer->update_or_create({
2795 producer => $producer,
2801 B<Note>: Make sure to read the documentation of L</find> and understand the
2802 significance of the C<key> attribute, as its lack may skew your search, and
2803 subsequently result in spurious row creation.
2805 B<Note>: Take care when using C<update_or_create> with a table having
2806 columns with default values that you intend to be automatically
2807 supplied by the database (e.g. an auto_increment primary key column).
2808 In normal usage, the value of such columns should NOT be included at
2809 all in the call to C<update_or_create>, even when set to C<undef>.
2811 See also L</find> and L</find_or_create>. For information on how to declare
2812 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2814 If you need to know if an existing row was updated or a new one created use
2815 L</update_or_new> and L<DBIx::Class::Row/in_storage> instead. Don't forget
2816 to call L<DBIx::Class::Row/insert> to save the newly created row to the
2821 sub update_or_create {
2823 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2824 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
2826 my $row = $self->find($cond, $attrs);
2828 $row->update($cond);
2832 return $self->create($cond);
2835 =head2 update_or_new
2839 =item Arguments: \%col_data, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
2841 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2845 $resultset->update_or_new({ col => $val, ... });
2847 Like L</find_or_new> but if a row is found it is immediately updated via
2848 C<< $found_row->update (\%col_data) >>.
2852 # In your application
2853 my $cd = $schema->resultset('CD')->update_or_new(
2855 artist => 'Massive Attack',
2856 title => 'Mezzanine',
2859 { key => 'cd_artist_title' }
2862 if ($cd->in_storage) {
2863 # the cd was updated
2866 # the cd is not yet in the database, let's insert it
2870 B<Note>: Make sure to read the documentation of L</find> and understand the
2871 significance of the C<key> attribute, as its lack may skew your search, and
2872 subsequently result in spurious new objects.
2874 B<Note>: Take care when using C<update_or_new> with a table having
2875 columns with default values that you intend to be automatically
2876 supplied by the database (e.g. an auto_increment primary key column).
2877 In normal usage, the value of such columns should NOT be included at
2878 all in the call to C<update_or_new>, even when set to C<undef>.
2880 See also L</find>, L</find_or_create> and L</find_or_new>.
2886 my $attrs = ( @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {} );
2887 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
2889 my $row = $self->find( $cond, $attrs );
2890 if ( defined $row ) {
2891 $row->update($cond);
2895 return $self->new_result($cond);
2902 =item Arguments: none
2904 =item Return Value: L<\@result_objs|DBIx::Class::Manual::ResultClass> | undef
2908 Gets the contents of the cache for the resultset, if the cache is set.
2910 The cache is populated either by using the L</prefetch> attribute to
2911 L</search> or by calling L</set_cache>.
2923 =item Arguments: L<\@result_objs|DBIx::Class::Manual::ResultClass>
2925 =item Return Value: L<\@result_objs|DBIx::Class::Manual::ResultClass>
2929 Sets the contents of the cache for the resultset. Expects an arrayref
2930 of objects of the same class as those produced by the resultset. Note that
2931 if the cache is set, the resultset will return the cached objects rather
2932 than re-querying the database even if the cache attr is not set.
2934 The contents of the cache can also be populated by using the
2935 L</prefetch> attribute to L</search>.
2940 my ( $self, $data ) = @_;
2941 $self->throw_exception("set_cache requires an arrayref")
2942 if defined($data) && (ref $data ne 'ARRAY');
2943 $self->{all_cache} = $data;
2950 =item Arguments: none
2952 =item Return Value: undef
2956 Clears the cache for the resultset.
2961 shift->set_cache(undef);
2968 =item Arguments: none
2970 =item Return Value: true, if the resultset has been paginated
2978 return !!$self->{attrs}{page};
2985 =item Arguments: none
2987 =item Return Value: true, if the resultset has been ordered with C<order_by>.
2995 return scalar $self->result_source->storage->_extract_order_criteria($self->{attrs}{order_by});
2998 =head2 related_resultset
3002 =item Arguments: $rel_name
3004 =item Return Value: L<$resultset|/search>
3008 Returns a related resultset for the supplied relationship name.
3010 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
3014 sub related_resultset {
3015 my ($self, $rel) = @_;
3017 $self->{related_resultsets} ||= {};
3018 return $self->{related_resultsets}{$rel} ||= do {
3019 my $rsrc = $self->result_source;
3020 my $rel_info = $rsrc->relationship_info($rel);
3022 $self->throw_exception(
3023 "search_related: result source '" . $rsrc->source_name .
3024 "' has no such relationship $rel")
3027 my $attrs = $self->_chain_relationship($rel);
3029 my $join_count = $attrs->{seen_join}{$rel};
3031 my $alias = $self->result_source->storage
3032 ->relname_to_table_alias($rel, $join_count);
3034 # since this is search_related, and we already slid the select window inwards
3035 # (the select/as attrs were deleted in the beginning), we need to flip all
3036 # left joins to inner, so we get the expected results
3037 # read the comment on top of the actual function to see what this does
3038 $attrs->{from} = $rsrc->schema->storage->_inner_join_to_node ($attrs->{from}, $alias);
3041 #XXX - temp fix for result_class bug. There likely is a more elegant fix -groditi
3042 delete @{$attrs}{qw(result_class alias)};
3046 if (my $cache = $self->get_cache) {
3047 if ($cache->[0] && $cache->[0]->related_resultset($rel)->get_cache) {
3048 $new_cache = [ map { @{$_->related_resultset($rel)->get_cache} }
3053 my $rel_source = $rsrc->related_source($rel);
3057 # The reason we do this now instead of passing the alias to the
3058 # search_rs below is that if you wrap/overload resultset on the
3059 # source you need to know what alias it's -going- to have for things
3060 # to work sanely (e.g. RestrictWithObject wants to be able to add
3061 # extra query restrictions, and these may need to be $alias.)
3063 my $rel_attrs = $rel_source->resultset_attributes;
3064 local $rel_attrs->{alias} = $alias;
3066 $rel_source->resultset
3070 where => $attrs->{where},
3073 $new->set_cache($new_cache) if $new_cache;
3078 =head2 current_source_alias
3082 =item Arguments: none
3084 =item Return Value: $source_alias
3088 Returns the current table alias for the result source this resultset is built
3089 on, that will be used in the SQL query. Usually it is C<me>.
3091 Currently the source alias that refers to the result set returned by a
3092 L</search>/L</find> family method depends on how you got to the resultset: it's
3093 C<me> by default, but eg. L</search_related> aliases it to the related result
3094 source name (and keeps C<me> referring to the original result set). The long
3095 term goal is to make L<DBIx::Class> always alias the current resultset as C<me>
3096 (and make this method unnecessary).
3098 Thus it's currently necessary to use this method in predefined queries (see
3099 L<DBIx::Class::Manual::Cookbook/Predefined searches>) when referring to the
3100 source alias of the current result set:
3102 # in a result set class
3104 my ($self, $user) = @_;
3106 my $me = $self->current_source_alias;
3108 return $self->search({
3109 "$me.modified" => $user->id,
3115 sub current_source_alias {
3118 return ($self->{attrs} || {})->{alias} || 'me';
3121 =head2 as_subselect_rs
3125 =item Arguments: none
3127 =item Return Value: L<$resultset|/search>
3131 Act as a barrier to SQL symbols. The resultset provided will be made into a
3132 "virtual view" by including it as a subquery within the from clause. From this
3133 point on, any joined tables are inaccessible to ->search on the resultset (as if
3134 it were simply where-filtered without joins). For example:
3136 my $rs = $schema->resultset('Bar')->search({'x.name' => 'abc'},{ join => 'x' });
3138 # 'x' now pollutes the query namespace
3140 # So the following works as expected
3141 my $ok_rs = $rs->search({'x.other' => 1});
3143 # But this doesn't: instead of finding a 'Bar' related to two x rows (abc and
3144 # def) we look for one row with contradictory terms and join in another table
3145 # (aliased 'x_2') which we never use
3146 my $broken_rs = $rs->search({'x.name' => 'def'});
3148 my $rs2 = $rs->as_subselect_rs;
3150 # doesn't work - 'x' is no longer accessible in $rs2, having been sealed away
3151 my $not_joined_rs = $rs2->search({'x.other' => 1});
3153 # works as expected: finds a 'table' row related to two x rows (abc and def)
3154 my $correctly_joined_rs = $rs2->search({'x.name' => 'def'});
3156 Another example of when one might use this would be to select a subset of
3157 columns in a group by clause:
3159 my $rs = $schema->resultset('Bar')->search(undef, {
3160 group_by => [qw{ id foo_id baz_id }],
3161 })->as_subselect_rs->search(undef, {
3162 columns => [qw{ id foo_id }]
3165 In the above example normally columns would have to be equal to the group by,
3166 but because we isolated the group by into a subselect the above works.
3170 sub as_subselect_rs {
3173 my $attrs = $self->_resolved_attrs;
3175 my $fresh_rs = (ref $self)->new (
3176 $self->result_source
3179 # these pieces will be locked in the subquery
3180 delete $fresh_rs->{cond};
3181 delete @{$fresh_rs->{attrs}}{qw/where bind/};
3183 return $fresh_rs->search( {}, {
3185 $attrs->{alias} => $self->as_query,
3186 -alias => $attrs->{alias},
3187 -rsrc => $self->result_source,
3189 alias => $attrs->{alias},
3193 # This code is called by search_related, and makes sure there
3194 # is clear separation between the joins before, during, and
3195 # after the relationship. This information is needed later
3196 # in order to properly resolve prefetch aliases (any alias
3197 # with a relation_chain_depth less than the depth of the
3198 # current prefetch is not considered)
3200 # The increments happen twice per join. An even number means a
3201 # relationship specified via a search_related, whereas an odd
3202 # number indicates a join/prefetch added via attributes
3204 # Also this code will wrap the current resultset (the one we
3205 # chain to) in a subselect IFF it contains limiting attributes
3206 sub _chain_relationship {
3207 my ($self, $rel) = @_;
3208 my $source = $self->result_source;
3209 my $attrs = { %{$self->{attrs}||{}} };
3211 # we need to take the prefetch the attrs into account before we
3212 # ->_resolve_join as otherwise they get lost - captainL
3213 my $join = $self->_merge_joinpref_attr( $attrs->{join}, $attrs->{prefetch} );
3215 delete @{$attrs}{qw/join prefetch collapse group_by distinct select as columns +select +as +columns/};
3217 my $seen = { %{ (delete $attrs->{seen_join}) || {} } };
3220 my @force_subq_attrs = qw/offset rows group_by having/;
3223 ($attrs->{from} && ref $attrs->{from} ne 'ARRAY')
3225 $self->_has_resolved_attr (@force_subq_attrs)
3227 # Nuke the prefetch (if any) before the new $rs attrs
3228 # are resolved (prefetch is useless - we are wrapping
3229 # a subquery anyway).
3230 my $rs_copy = $self->search;
3231 $rs_copy->{attrs}{join} = $self->_merge_joinpref_attr (
3232 $rs_copy->{attrs}{join},
3233 delete $rs_copy->{attrs}{prefetch},
3238 -alias => $attrs->{alias},
3239 $attrs->{alias} => $rs_copy->as_query,
3241 delete @{$attrs}{@force_subq_attrs, qw/where bind/};
3242 $seen->{-relation_chain_depth} = 0;
3244 elsif ($attrs->{from}) { #shallow copy suffices
3245 $from = [ @{$attrs->{from}} ];
3250 -alias => $attrs->{alias},
3251 $attrs->{alias} => $source->from,
3255 my $jpath = ($seen->{-relation_chain_depth})
3256 ? $from->[-1][0]{-join_path}
3259 my @requested_joins = $source->_resolve_join(
3266 push @$from, @requested_joins;
3268 $seen->{-relation_chain_depth}++;
3270 # if $self already had a join/prefetch specified on it, the requested
3271 # $rel might very well be already included. What we do in this case
3272 # is effectively a no-op (except that we bump up the chain_depth on
3273 # the join in question so we could tell it *is* the search_related)
3276 # we consider the last one thus reverse
3277 for my $j (reverse @requested_joins) {
3278 my ($last_j) = keys %{$j->[0]{-join_path}[-1]};
3279 if ($rel eq $last_j) {
3280 $j->[0]{-relation_chain_depth}++;
3286 unless ($already_joined) {
3287 push @$from, $source->_resolve_join(
3295 $seen->{-relation_chain_depth}++;
3297 return {%$attrs, from => $from, seen_join => $seen};
3300 # too many times we have to do $attrs = { %{$self->_resolved_attrs} }
3301 sub _resolved_attrs_copy {
3303 return { %{$self->_resolved_attrs (@_)} };
3306 sub _resolved_attrs {
3308 return $self->{_attrs} if $self->{_attrs};
3310 my $attrs = { %{ $self->{attrs} || {} } };
3311 my $source = $self->result_source;
3312 my $alias = $attrs->{alias};
3314 # default selection list
3315 $attrs->{columns} = [ $source->columns ]
3316 unless List::Util::first { exists $attrs->{$_} } qw/columns cols select as/;
3318 # merge selectors together
3319 for (qw/columns select as/) {
3320 $attrs->{$_} = $self->_merge_attr($attrs->{$_}, delete $attrs->{"+$_"})
3321 if $attrs->{$_} or $attrs->{"+$_"};
3324 # disassemble columns
3326 if (my $cols = delete $attrs->{columns}) {
3327 for my $c (ref $cols eq 'ARRAY' ? @$cols : $cols) {
3328 if (ref $c eq 'HASH') {
3329 for my $as (sort keys %$c) {
3330 push @sel, $c->{$as};
3341 # when trying to weed off duplicates later do not go past this point -
3342 # everything added from here on is unbalanced "anyone's guess" stuff
3343 my $dedup_stop_idx = $#as;
3345 push @as, @{ ref $attrs->{as} eq 'ARRAY' ? $attrs->{as} : [ $attrs->{as} ] }
3347 push @sel, @{ ref $attrs->{select} eq 'ARRAY' ? $attrs->{select} : [ $attrs->{select} ] }
3348 if $attrs->{select};
3350 # assume all unqualified selectors to apply to the current alias (legacy stuff)
3352 $_ = (ref $_ or $_ =~ /\./) ? $_ : "$alias.$_";
3355 # disqualify all $alias.col as-bits (collapser mandated)
3357 $_ = ($_ =~ /^\Q$alias.\E(.+)$/) ? $1 : $_;
3360 # de-duplicate the result (remove *identical* select/as pairs)
3361 # and also die on duplicate {as} pointing to different {select}s
3362 # not using a c-style for as the condition is prone to shrinkage
3365 while ($i <= $dedup_stop_idx) {
3366 if ($seen->{"$sel[$i] \x00\x00 $as[$i]"}++) {
3371 elsif ($seen->{$as[$i]}++) {
3372 $self->throw_exception(
3373 "inflate_result() alias '$as[$i]' specified twice with different SQL-side {select}-ors"
3381 $attrs->{select} = \@sel;
3382 $attrs->{as} = \@as;
3384 $attrs->{from} ||= [{
3386 -alias => $self->{attrs}{alias},
3387 $self->{attrs}{alias} => $source->from,
3390 if ( $attrs->{join} || $attrs->{prefetch} ) {
3392 $self->throw_exception ('join/prefetch can not be used with a custom {from}')
3393 if ref $attrs->{from} ne 'ARRAY';
3395 my $join = (delete $attrs->{join}) || {};
3397 if ( defined $attrs->{prefetch} ) {
3398 $join = $self->_merge_joinpref_attr( $join, $attrs->{prefetch} );
3401 $attrs->{from} = # have to copy here to avoid corrupting the original
3403 @{ $attrs->{from} },
3404 $source->_resolve_join(
3407 { %{ $attrs->{seen_join} || {} } },
3408 ( $attrs->{seen_join} && keys %{$attrs->{seen_join}})
3409 ? $attrs->{from}[-1][0]{-join_path}
3416 if ( defined $attrs->{order_by} ) {
3417 $attrs->{order_by} = (
3418 ref( $attrs->{order_by} ) eq 'ARRAY'
3419 ? [ @{ $attrs->{order_by} } ]
3420 : [ $attrs->{order_by} || () ]
3424 if ($attrs->{group_by} and ref $attrs->{group_by} ne 'ARRAY') {
3425 $attrs->{group_by} = [ $attrs->{group_by} ];
3428 # generate the distinct induced group_by early, as prefetch will be carried via a
3429 # subquery (since a group_by is present)
3430 if (delete $attrs->{distinct}) {
3431 if ($attrs->{group_by}) {
3432 carp_unique ("Useless use of distinct on a grouped resultset ('distinct' is ignored when a 'group_by' is present)");
3435 # distinct affects only the main selection part, not what prefetch may
3437 $attrs->{group_by} = $source->storage->_group_over_selection (
3445 $attrs->{collapse} ||= {};
3446 if ($attrs->{prefetch}) {
3448 $self->throw_exception("Unable to prefetch, resultset contains an unnamed selector $attrs->{_dark_selector}{string}")
3449 if $attrs->{_dark_selector};
3451 my $prefetch = $self->_merge_joinpref_attr( {}, delete $attrs->{prefetch} );
3453 my $prefetch_ordering = [];
3455 # this is a separate structure (we don't look in {from} directly)
3456 # as the resolver needs to shift things off the lists to work
3457 # properly (identical-prefetches on different branches)
3459 if (ref $attrs->{from} eq 'ARRAY') {
3461 my $start_depth = $attrs->{seen_join}{-relation_chain_depth} || 0;
3463 for my $j ( @{$attrs->{from}}[1 .. $#{$attrs->{from}} ] ) {
3464 next unless $j->[0]{-alias};
3465 next unless $j->[0]{-join_path};
3466 next if ($j->[0]{-relation_chain_depth} || 0) < $start_depth;
3468 my @jpath = map { keys %$_ } @{$j->[0]{-join_path}};
3471 $p = $p->{$_} ||= {} for @jpath[ ($start_depth/2) .. $#jpath]; #only even depths are actual jpath boundaries
3472 push @{$p->{-join_aliases} }, $j->[0]{-alias};
3477 $source->_resolve_prefetch( $prefetch, $alias, $join_map, $prefetch_ordering, $attrs->{collapse} );
3479 # we need to somehow mark which columns came from prefetch
3481 my $sel_end = $#{$attrs->{select}};
3482 $attrs->{_prefetch_selector_range} = [ $sel_end + 1, $sel_end + @prefetch ];
3485 push @{ $attrs->{select} }, (map { $_->[0] } @prefetch);
3486 push @{ $attrs->{as} }, (map { $_->[1] } @prefetch);
3488 push( @{$attrs->{order_by}}, @$prefetch_ordering );
3489 $attrs->{_collapse_order_by} = \@$prefetch_ordering;
3492 # if both page and offset are specified, produce a combined offset
3493 # even though it doesn't make much sense, this is what pre 081xx has
3495 if (my $page = delete $attrs->{page}) {
3497 ($attrs->{rows} * ($page - 1))
3499 ($attrs->{offset} || 0)
3503 return $self->{_attrs} = $attrs;
3507 my ($self, $attr) = @_;
3509 if (ref $attr eq 'HASH') {
3510 return $self->_rollout_hash($attr);
3511 } elsif (ref $attr eq 'ARRAY') {
3512 return $self->_rollout_array($attr);
3518 sub _rollout_array {
3519 my ($self, $attr) = @_;
3522 foreach my $element (@{$attr}) {
3523 if (ref $element eq 'HASH') {
3524 push( @rolled_array, @{ $self->_rollout_hash( $element ) } );
3525 } elsif (ref $element eq 'ARRAY') {
3526 # XXX - should probably recurse here
3527 push( @rolled_array, @{$self->_rollout_array($element)} );
3529 push( @rolled_array, $element );
3532 return \@rolled_array;
3536 my ($self, $attr) = @_;
3539 foreach my $key (keys %{$attr}) {
3540 push( @rolled_array, { $key => $attr->{$key} } );
3542 return \@rolled_array;
3545 sub _calculate_score {
3546 my ($self, $a, $b) = @_;
3548 if (defined $a xor defined $b) {
3551 elsif (not defined $a) {
3555 if (ref $b eq 'HASH') {
3556 my ($b_key) = keys %{$b};
3557 if (ref $a eq 'HASH') {
3558 my ($a_key) = keys %{$a};
3559 if ($a_key eq $b_key) {
3560 return (1 + $self->_calculate_score( $a->{$a_key}, $b->{$b_key} ));
3565 return ($a eq $b_key) ? 1 : 0;
3568 if (ref $a eq 'HASH') {
3569 my ($a_key) = keys %{$a};
3570 return ($b eq $a_key) ? 1 : 0;
3572 return ($b eq $a) ? 1 : 0;
3577 sub _merge_joinpref_attr {
3578 my ($self, $orig, $import) = @_;
3580 return $import unless defined($orig);
3581 return $orig unless defined($import);
3583 $orig = $self->_rollout_attr($orig);
3584 $import = $self->_rollout_attr($import);
3587 foreach my $import_element ( @{$import} ) {
3588 # find best candidate from $orig to merge $b_element into
3589 my $best_candidate = { position => undef, score => 0 }; my $position = 0;
3590 foreach my $orig_element ( @{$orig} ) {
3591 my $score = $self->_calculate_score( $orig_element, $import_element );
3592 if ($score > $best_candidate->{score}) {
3593 $best_candidate->{position} = $position;
3594 $best_candidate->{score} = $score;
3598 my ($import_key) = ( ref $import_element eq 'HASH' ) ? keys %{$import_element} : ($import_element);
3599 $import_key = '' if not defined $import_key;
3601 if ($best_candidate->{score} == 0 || exists $seen_keys->{$import_key}) {
3602 push( @{$orig}, $import_element );
3604 my $orig_best = $orig->[$best_candidate->{position}];
3605 # merge orig_best and b_element together and replace original with merged
3606 if (ref $orig_best ne 'HASH') {
3607 $orig->[$best_candidate->{position}] = $import_element;
3608 } elsif (ref $import_element eq 'HASH') {
3609 my ($key) = keys %{$orig_best};
3610 $orig->[$best_candidate->{position}] = { $key => $self->_merge_joinpref_attr($orig_best->{$key}, $import_element->{$key}) };
3613 $seen_keys->{$import_key} = 1; # don't merge the same key twice
3624 require Hash::Merge;
3625 my $hm = Hash::Merge->new;
3627 $hm->specify_behavior({
3630 my ($defl, $defr) = map { defined $_ } (@_[0,1]);
3632 if ($defl xor $defr) {
3633 return [ $defl ? $_[0] : $_[1] ];
3638 elsif (__HM_DEDUP and $_[0] eq $_[1]) {
3642 return [$_[0], $_[1]];
3646 return $_[1] if !defined $_[0];
3647 return $_[1] if __HM_DEDUP and List::Util::first { $_ eq $_[0] } @{$_[1]};
3648 return [$_[0], @{$_[1]}]
3651 return [] if !defined $_[0] and !keys %{$_[1]};
3652 return [ $_[1] ] if !defined $_[0];
3653 return [ $_[0] ] if !keys %{$_[1]};
3654 return [$_[0], $_[1]]
3659 return $_[0] if !defined $_[1];
3660 return $_[0] if __HM_DEDUP and List::Util::first { $_ eq $_[1] } @{$_[0]};
3661 return [@{$_[0]}, $_[1]]
3664 my @ret = @{$_[0]} or return $_[1];
3665 return [ @ret, @{$_[1]} ] unless __HM_DEDUP;
3666 my %idx = map { $_ => 1 } @ret;
3667 push @ret, grep { ! defined $idx{$_} } (@{$_[1]});
3671 return [ $_[1] ] if ! @{$_[0]};
3672 return $_[0] if !keys %{$_[1]};
3673 return $_[0] if __HM_DEDUP and List::Util::first { $_ eq $_[1] } @{$_[0]};
3674 return [ @{$_[0]}, $_[1] ];
3679 return [] if !keys %{$_[0]} and !defined $_[1];
3680 return [ $_[0] ] if !defined $_[1];
3681 return [ $_[1] ] if !keys %{$_[0]};
3682 return [$_[0], $_[1]]
3685 return [] if !keys %{$_[0]} and !@{$_[1]};
3686 return [ $_[0] ] if !@{$_[1]};
3687 return $_[1] if !keys %{$_[0]};
3688 return $_[1] if __HM_DEDUP and List::Util::first { $_ eq $_[0] } @{$_[1]};
3689 return [ $_[0], @{$_[1]} ];
3692 return [] if !keys %{$_[0]} and !keys %{$_[1]};
3693 return [ $_[0] ] if !keys %{$_[1]};
3694 return [ $_[1] ] if !keys %{$_[0]};
3695 return [ $_[0] ] if $_[0] eq $_[1];
3696 return [ $_[0], $_[1] ];
3699 } => 'DBIC_RS_ATTR_MERGER');
3703 return $hm->merge ($_[1], $_[2]);
3707 sub STORABLE_freeze {
3708 my ($self, $cloning) = @_;
3709 my $to_serialize = { %$self };
3711 # A cursor in progress can't be serialized (and would make little sense anyway)
3712 delete $to_serialize->{cursor};
3714 # nor is it sensical to store a not-yet-fired-count pager
3715 if ($to_serialize->{pager} and ref $to_serialize->{pager}{total_entries} eq 'CODE') {
3716 delete $to_serialize->{pager};
3719 Storable::nfreeze($to_serialize);
3722 # need this hook for symmetry
3724 my ($self, $cloning, $serialized) = @_;
3726 %$self = %{ Storable::thaw($serialized) };
3732 =head2 throw_exception
3734 See L<DBIx::Class::Schema/throw_exception> for details.
3738 sub throw_exception {
3741 if (ref $self and my $rsrc = $self->result_source) {
3742 $rsrc->throw_exception(@_)
3745 DBIx::Class::Exception->throw(@_);
3749 # XXX: FIXME: Attributes docs need clearing up
3753 Attributes are used to refine a ResultSet in various ways when
3754 searching for data. They can be passed to any method which takes an
3755 C<\%attrs> argument. See L</search>, L</search_rs>, L</find>,
3758 Default attributes can be set on the result class using
3759 L<DBIx::Class::ResultSource/resultset_attributes>. (Please read
3760 the CAVEATS on that feature before using it!)
3762 These are in no particular order:
3768 =item Value: ( $order_by | \@order_by | \%order_by )
3772 Which column(s) to order the results by.
3774 [The full list of suitable values is documented in
3775 L<SQL::Abstract/"ORDER BY CLAUSES">; the following is a summary of
3778 If a single column name, or an arrayref of names is supplied, the
3779 argument is passed through directly to SQL. The hashref syntax allows
3780 for connection-agnostic specification of ordering direction:
3782 For descending order:
3784 order_by => { -desc => [qw/col1 col2 col3/] }
3786 For explicit ascending order:
3788 order_by => { -asc => 'col' }
3790 The old scalarref syntax (i.e. order_by => \'year DESC') is still
3791 supported, although you are strongly encouraged to use the hashref
3792 syntax as outlined above.
3798 =item Value: \@columns
3802 Shortcut to request a particular set of columns to be retrieved. Each
3803 column spec may be a string (a table column name), or a hash (in which
3804 case the key is the C<as> value, and the value is used as the C<select>
3805 expression). Adds C<me.> onto the start of any column without a C<.> in
3806 it and sets C<select> from that, then auto-populates C<as> from
3807 C<select> as normal. (You may also use the C<cols> attribute, as in
3808 earlier versions of DBIC.)
3810 Essentially C<columns> does the same as L</select> and L</as>.
3812 columns => [ 'foo', { bar => 'baz' } ]
3816 select => [qw/foo baz/],
3823 =item Value: \@columns
3827 Indicates additional columns to be selected from storage. Works the same
3828 as L</columns> but adds columns to the selection. (You may also use the
3829 C<include_columns> attribute, as in earlier versions of DBIC). For
3832 $schema->resultset('CD')->search(undef, {
3833 '+columns' => ['artist.name'],
3837 would return all CDs and include a 'name' column to the information
3838 passed to object inflation. Note that the 'artist' is the name of the
3839 column (or relationship) accessor, and 'name' is the name of the column
3840 accessor in the related table.
3842 B<NOTE:> You need to explicitly quote '+columns' when defining the attribute.
3843 Not doing so causes Perl to incorrectly interpret +columns as a bareword with a
3844 unary plus operator before it.
3846 =head2 include_columns
3850 =item Value: \@columns
3854 Deprecated. Acts as a synonym for L</+columns> for backward compatibility.
3860 =item Value: \@select_columns
3864 Indicates which columns should be selected from the storage. You can use
3865 column names, or in the case of RDBMS back ends, function or stored procedure
3868 $rs = $schema->resultset('Employee')->search(undef, {
3871 { count => 'employeeid' },
3872 { max => { length => 'name' }, -as => 'longest_name' }
3877 SELECT name, COUNT( employeeid ), MAX( LENGTH( name ) ) AS longest_name FROM employee
3879 B<NOTE:> You will almost always need a corresponding L</as> attribute when you
3880 use L</select>, to instruct DBIx::Class how to store the result of the column.
3881 Also note that the L</as> attribute has nothing to do with the SQL-side 'AS'
3882 identifier aliasing. You can however alias a function, so you can use it in
3883 e.g. an C<ORDER BY> clause. This is done via the C<-as> B<select function
3884 attribute> supplied as shown in the example above.
3886 B<NOTE:> You need to explicitly quote '+select'/'+as' when defining the attributes.
3887 Not doing so causes Perl to incorrectly interpret them as a bareword with a
3888 unary plus operator before it.
3894 Indicates additional columns to be selected from storage. Works the same as
3895 L</select> but adds columns to the default selection, instead of specifying
3904 Indicates additional column names for those added via L</+select>. See L</as>.
3912 =item Value: \@inflation_names
3916 Indicates column names for object inflation. That is L</as> indicates the
3917 slot name in which the column value will be stored within the
3918 L<Row|DBIx::Class::Row> object. The value will then be accessible via this
3919 identifier by the C<get_column> method (or via the object accessor B<if one
3920 with the same name already exists>) as shown below. The L</as> attribute has
3921 B<nothing to do> with the SQL-side C<AS>. See L</select> for details.
3923 $rs = $schema->resultset('Employee')->search(undef, {
3926 { count => 'employeeid' },
3927 { max => { length => 'name' }, -as => 'longest_name' }
3936 If the object against which the search is performed already has an accessor
3937 matching a column name specified in C<as>, the value can be retrieved using
3938 the accessor as normal:
3940 my $name = $employee->name();
3942 If on the other hand an accessor does not exist in the object, you need to
3943 use C<get_column> instead:
3945 my $employee_count = $employee->get_column('employee_count');
3947 You can create your own accessors if required - see
3948 L<DBIx::Class::Manual::Cookbook> for details.
3954 =item Value: ($rel_name | \@rel_names | \%rel_names)
3958 Contains a list of relationships that should be joined for this query. For
3961 # Get CDs by Nine Inch Nails
3962 my $rs = $schema->resultset('CD')->search(
3963 { 'artist.name' => 'Nine Inch Nails' },
3964 { join => 'artist' }
3967 Can also contain a hash reference to refer to the other relation's relations.
3970 package MyApp::Schema::Track;
3971 use base qw/DBIx::Class/;
3972 __PACKAGE__->table('track');
3973 __PACKAGE__->add_columns(qw/trackid cd position title/);
3974 __PACKAGE__->set_primary_key('trackid');
3975 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
3978 # In your application
3979 my $rs = $schema->resultset('Artist')->search(
3980 { 'track.title' => 'Teardrop' },
3982 join => { cd => 'track' },
3983 order_by => 'artist.name',
3987 You need to use the relationship (not the table) name in conditions,
3988 because they are aliased as such. The current table is aliased as "me", so
3989 you need to use me.column_name in order to avoid ambiguity. For example:
3991 # Get CDs from 1984 with a 'Foo' track
3992 my $rs = $schema->resultset('CD')->search(
3995 'tracks.name' => 'Foo'
3997 { join => 'tracks' }
4000 If the same join is supplied twice, it will be aliased to <rel>_2 (and
4001 similarly for a third time). For e.g.
4003 my $rs = $schema->resultset('Artist')->search({
4004 'cds.title' => 'Down to Earth',
4005 'cds_2.title' => 'Popular',
4007 join => [ qw/cds cds/ ],
4010 will return a set of all artists that have both a cd with title 'Down
4011 to Earth' and a cd with title 'Popular'.
4013 If you want to fetch related objects from other tables as well, see C<prefetch>
4016 NOTE: An internal join-chain pruner will discard certain joins while
4017 constructing the actual SQL query, as long as the joins in question do not
4018 affect the retrieved result. This for example includes 1:1 left joins
4019 that are not part of the restriction specification (WHERE/HAVING) nor are
4020 a part of the query selection.
4022 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
4028 =item Value: ($rel_name | \@rel_names | \%rel_names)
4032 Contains one or more relationships that should be fetched along with
4033 the main query (when they are accessed afterwards the data will
4034 already be available, without extra queries to the database). This is
4035 useful for when you know you will need the related objects, because it
4036 saves at least one query:
4038 my $rs = $schema->resultset('Tag')->search(
4047 The initial search results in SQL like the following:
4049 SELECT tag.*, cd.*, artist.* FROM tag
4050 JOIN cd ON tag.cd = cd.cdid
4051 JOIN artist ON cd.artist = artist.artistid
4053 L<DBIx::Class> has no need to go back to the database when we access the
4054 C<cd> or C<artist> relationships, which saves us two SQL statements in this
4057 Simple prefetches will be joined automatically, so there is no need
4058 for a C<join> attribute in the above search.
4060 L</prefetch> can be used with the any of the relationship types and
4061 multiple prefetches can be specified together. Below is a more complex
4062 example that prefetches a CD's artist, its liner notes (if present),
4063 the cover image, the tracks on that cd, and the guests on those
4067 My::Schema::CD->belongs_to( artist => 'My::Schema::Artist' );
4068 My::Schema::CD->might_have( liner_note => 'My::Schema::LinerNotes' );
4069 My::Schema::CD->has_one( cover_image => 'My::Schema::Artwork' );
4070 My::Schema::CD->has_many( tracks => 'My::Schema::Track' );
4072 My::Schema::Artist->belongs_to( record_label => 'My::Schema::RecordLabel' );
4074 My::Schema::Track->has_many( guests => 'My::Schema::Guest' );
4077 my $rs = $schema->resultset('CD')->search(
4081 { artist => 'record_label'}, # belongs_to => belongs_to
4082 'liner_note', # might_have
4083 'cover_image', # has_one
4084 { tracks => 'guests' }, # has_many => has_many
4089 This will produce SQL like the following:
4091 SELECT cd.*, artist.*, record_label.*, liner_note.*, cover_image.*,
4095 ON artist.artistid = me.artistid
4096 JOIN record_label record_label
4097 ON record_label.labelid = artist.labelid
4098 LEFT JOIN track tracks
4099 ON tracks.cdid = me.cdid
4100 LEFT JOIN guest guests
4101 ON guests.trackid = track.trackid
4102 LEFT JOIN liner_notes liner_note
4103 ON liner_note.cdid = me.cdid
4104 JOIN cd_artwork cover_image
4105 ON cover_image.cdid = me.cdid
4108 Now the C<artist>, C<record_label>, C<liner_note>, C<cover_image>,
4109 C<tracks>, and C<guests> of the CD will all be available through the
4110 relationship accessors without the need for additional queries to the
4113 However, there is one caveat to be observed: it can be dangerous to
4114 prefetch more than one L<has_many|DBIx::Class::Relationship/has_many>
4115 relationship on a given level. e.g.:
4117 my $rs = $schema->resultset('CD')->search(
4121 'tracks', # has_many
4122 { cd_to_producer => 'producer' }, # has_many => belongs_to (i.e. m2m)
4127 The collapser currently can't identify duplicate tuples for multiple
4128 L<has_many|DBIx::Class::Relationship/has_many> relationships and as a
4129 result the second L<has_many|DBIx::Class::Relationship/has_many>
4130 relation could contain redundant objects.
4132 =head3 Using L</prefetch> with L</join>
4134 L</prefetch> implies a L</join> with the equivalent argument, and is
4135 properly merged with any existing L</join> specification. So the
4138 my $rs = $schema->resultset('CD')->search(
4139 {'record_label.name' => 'Music Product Ltd.'},
4141 join => {artist => 'record_label'},
4142 prefetch => 'artist',
4146 ... will work, searching on the record label's name, but only
4147 prefetching the C<artist>.
4149 =head3 Using L</prefetch> with L</select> / L</+select> / L</as> / L</+as>
4151 L</prefetch> implies a L</+select>/L</+as> with the fields of the
4152 prefetched relations. So given:
4154 my $rs = $schema->resultset('CD')->search(
4157 select => ['cd.title'],
4159 prefetch => 'artist',
4163 The L</select> becomes: C<'cd.title', 'artist.*'> and the L</as>
4164 becomes: C<'cd_title', 'artist.*'>.
4168 Prefetch does a lot of deep magic. As such, it may not behave exactly
4169 as you might expect.
4175 Prefetch uses the L</cache> to populate the prefetched relationships. This
4176 may or may not be what you want.
4180 If you specify a condition on a prefetched relationship, ONLY those
4181 rows that match the prefetched condition will be fetched into that relationship.
4182 This means that adding prefetch to a search() B<may alter> what is returned by
4183 traversing a relationship. So, if you have C<< Artist->has_many(CDs) >> and you do
4185 my $artist_rs = $schema->resultset('Artist')->search({
4191 my $count = $artist_rs->first->cds->count;
4193 my $artist_rs_prefetch = $artist_rs->search( {}, { prefetch => 'cds' } );
4195 my $prefetch_count = $artist_rs_prefetch->first->cds->count;
4197 cmp_ok( $count, '==', $prefetch_count, "Counts should be the same" );
4199 that cmp_ok() may or may not pass depending on the datasets involved. This
4200 behavior may or may not survive the 0.09 transition.
4208 =item Value: $source_alias
4212 Sets the source alias for the query. Normally, this defaults to C<me>, but
4213 nested search queries (sub-SELECTs) might need specific aliases set to
4214 reference inner queries. For example:
4217 ->related_resultset('CDs')
4218 ->related_resultset('Tracks')
4220 'track.id' => { -ident => 'none_search.id' },
4224 my $ids = $self->search({
4227 alias => 'none_search',
4228 group_by => 'none_search.id',
4229 })->get_column('id')->as_query;
4231 $self->search({ id => { -in => $ids } })
4233 This attribute is directly tied to L</current_source_alias>.
4243 Makes the resultset paged and specifies the page to retrieve. Effectively
4244 identical to creating a non-pages resultset and then calling ->page($page)
4247 If L</rows> attribute is not specified it defaults to 10 rows per page.
4249 When you have a paged resultset, L</count> will only return the number
4250 of rows in the page. To get the total, use the L</pager> and call
4251 C<total_entries> on it.
4261 Specifies the maximum number of rows for direct retrieval or the number of
4262 rows per page if the page attribute or method is used.
4268 =item Value: $offset
4272 Specifies the (zero-based) row number for the first row to be returned, or the
4273 of the first row of the first page if paging is used.
4275 =head2 software_limit
4279 =item Value: (0 | 1)
4283 When combined with L</rows> and/or L</offset> the generated SQL will not
4284 include any limit dialect stanzas. Instead the entire result will be selected
4285 as if no limits were specified, and DBIC will perform the limit locally, by
4286 artificially advancing and finishing the resulting L</cursor>.
4288 This is the recommended way of performing resultset limiting when no sane RDBMS
4289 implementation is available (e.g.
4290 L<Sybase ASE|DBIx::Class::Storage::DBI::Sybase::ASE> using the
4291 L<Generic Sub Query|DBIx::Class::SQLMaker::LimitDialects/GenericSubQ> hack)
4297 =item Value: \@columns
4301 A arrayref of columns to group by. Can include columns of joined tables.
4303 group_by => [qw/ column1 column2 ... /]
4309 =item Value: $condition
4313 HAVING is a select statement attribute that is applied between GROUP BY and
4314 ORDER BY. It is applied to the after the grouping calculations have been
4317 having => { 'count_employee' => { '>=', 100 } }
4319 or with an in-place function in which case literal SQL is required:
4321 having => \[ 'count(employee) >= ?', [ count => 100 ] ]
4327 =item Value: (0 | 1)
4331 Set to 1 to group by all columns. If the resultset already has a group_by
4332 attribute, this setting is ignored and an appropriate warning is issued.
4338 Adds to the WHERE clause.
4340 # only return rows WHERE deleted IS NULL for all searches
4341 __PACKAGE__->resultset_attributes({ where => { deleted => undef } });
4343 Can be overridden by passing C<< { where => undef } >> as an attribute
4346 For more complicated where clauses see L<SQL::Abstract/WHERE CLAUSES>.
4352 Set to 1 to cache search results. This prevents extra SQL queries if you
4353 revisit rows in your ResultSet:
4355 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
4357 while( my $artist = $resultset->next ) {
4361 $rs->first; # without cache, this would issue a query
4363 By default, searches are not cached.
4365 For more examples of using these attributes, see
4366 L<DBIx::Class::Manual::Cookbook>.
4372 =item Value: ( 'update' | 'shared' | \$scalar )
4376 Set to 'update' for a SELECT ... FOR UPDATE or 'shared' for a SELECT
4377 ... FOR SHARED. If \$scalar is passed, this is taken directly and embedded in the
4380 =head1 DBIC BIND VALUES
4382 Because DBIC may need more information to bind values than just the column name
4383 and value itself, it uses a special format for both passing and receiving bind
4384 values. Each bind value should be composed of an arrayref of
4385 C<< [ \%args => $val ] >>. The format of C<< \%args >> is currently:
4391 If present (in any form), this is what is being passed directly to bind_param.
4392 Note that different DBD's expect different bind args. (e.g. DBD::SQLite takes
4393 a single numerical type, while DBD::Pg takes a hashref if bind options.)
4395 If this is specified, all other bind options described below are ignored.
4399 If present, this is used to infer the actual bind attribute by passing to
4400 C<< $resolved_storage->bind_attribute_by_data_type() >>. Defaults to the
4401 "data_type" from the L<add_columns column info|DBIx::Class::ResultSource/add_columns>.
4403 Note that the data type is somewhat freeform (hence the sqlt_ prefix);
4404 currently drivers are expected to "Do the Right Thing" when given a common
4405 datatype name. (Not ideal, but that's what we got at this point.)
4409 Currently used to correctly allocate buffers for bind_param_inout().
4410 Defaults to "size" from the L<add_columns column info|DBIx::Class::ResultSource/add_columns>,
4411 or to a sensible value based on the "data_type".
4415 Used to fill in missing sqlt_datatype and sqlt_size attributes (if they are
4416 explicitly specified they are never overriden). Also used by some weird DBDs,
4417 where the column name should be available at bind_param time (e.g. Oracle).
4421 For backwards compatibility and convenience, the following shortcuts are
4424 [ $name => $val ] === [ { dbic_colname => $name }, $val ]
4425 [ \$dt => $val ] === [ { sqlt_datatype => $dt }, $val ]
4426 [ undef, $val ] === [ {}, $val ]
4428 =head1 AUTHOR AND CONTRIBUTORS
4430 See L<AUTHOR|DBIx::Class/AUTHOR> and L<CONTRIBUTORS|DBIx::Class/CONTRIBUTORS> in DBIx::Class
4434 You may distribute this code under the same terms as Perl itself.