1 package DBIx::Class::ResultSet;
6 use base 'DBIx::Class';
9 use DBIx::Class::ResultSetColumn;
10 use DBIx::Class::ResultClass::HashRefInflator;
11 use Scalar::Util qw( blessed reftype );
12 use SQL::Abstract 'is_literal_value';
13 use DBIx::Class::_Util qw(
14 dbic_internal_try dbic_internal_catch dump_value emit_loud_diag
15 fail_on_internal_wantarray fail_on_internal_call
16 UNRESOLVABLE_CONDITION DUMMY_ALIASPAIR
18 use DBIx::Class::SQLMaker::Util qw( normalize_sqla_condition extract_equality_conditions );
19 use DBIx::Class::ResultSource::FromSpec::Util 'find_join_path_to_alias';
22 # De-duplication in _merge_attr() is disabled, but left in for reference
23 # (the merger is used for other things that ought not to be de-duped)
24 *__HM_DEDUP = sub () { 0 };
34 # this is real - CDBICompat overrides it with insanity
35 # yes, prototype won't matter, but that's for now ;)
38 __PACKAGE__->mk_group_accessors('simple' => qw/_result_class result_source/);
42 DBIx::Class::ResultSet - Represents a query used for fetching a set of results.
46 my $users_rs = $schema->resultset('User');
47 while( $user = $users_rs->next) {
48 print $user->username;
51 my $registered_users_rs = $schema->resultset('User')->search({ registered => 1 });
52 my @cds_in_2005 = $schema->resultset('CD')->search({ year => 2005 })->all();
56 A ResultSet is an object which stores a set of conditions representing
57 a query. It is the backbone of DBIx::Class (i.e. the really
58 important/useful bit).
60 No SQL is executed on the database when a ResultSet is created, it
61 just stores all the conditions needed to create the query.
63 A basic ResultSet representing the data of an entire table is returned
64 by calling C<resultset> on a L<DBIx::Class::Schema> and passing in a
65 L<Source|DBIx::Class::Manual::Glossary/ResultSource> name.
67 my $users_rs = $schema->resultset('User');
69 A new ResultSet is returned from calling L</search> on an existing
70 ResultSet. The new one will contain all the conditions of the
71 original, plus any new conditions added in the C<search> call.
73 A ResultSet also incorporates an implicit iterator. L</next> and L</reset>
74 can be used to walk through all the L<DBIx::Class::Row>s the ResultSet
77 The query that the ResultSet represents is B<only> executed against
78 the database when these methods are called:
79 L</find>, L</next>, L</all>, L</first>, L</single>, L</count>.
81 If a resultset is used in a numeric context it returns the L</count>.
82 However, if it is used in a boolean context it is B<always> true. So if
83 you want to check if a resultset has any results, you must use C<if $rs
88 =head2 Chaining resultsets
90 Let's say you've got a query that needs to be run to return some data
91 to the user. But, you have an authorization system in place that
92 prevents certain users from seeing certain information. So, you want
93 to construct the basic query in one method, but add constraints to it in
98 my $request = $self->get_request; # Get a request object somehow.
99 my $schema = $self->result_source->schema;
101 my $cd_rs = $schema->resultset('CD')->search({
102 title => $request->param('title'),
103 year => $request->param('year'),
106 $cd_rs = $self->apply_security_policy( $cd_rs );
108 return $cd_rs->all();
111 sub apply_security_policy {
120 =head3 Resolving conditions and attributes
122 When a resultset is chained from another resultset (e.g.:
123 C<< my $new_rs = $old_rs->search(\%extra_cond, \%attrs) >>), conditions
124 and attributes with the same keys need resolving.
126 If any of L</columns>, L</select>, L</as> are present, they reset the
127 original selection, and start the selection "clean".
129 The L</join>, L</prefetch>, L</+columns>, L</+select>, L</+as> attributes
130 are merged into the existing ones from the original resultset.
132 The L</where> and L</having> attributes, and any search conditions, are
133 merged with an SQL C<AND> to the existing condition from the original
136 All other attributes are overridden by any new ones supplied in the
139 =head2 Multiple queries
141 Since a resultset just defines a query, you can do all sorts of
142 things with it with the same object.
144 # Don't hit the DB yet.
145 my $cd_rs = $schema->resultset('CD')->search({
146 title => 'something',
150 # Each of these hits the DB individually.
151 my $count = $cd_rs->count;
152 my $most_recent = $cd_rs->get_column('date_released')->max();
153 my @records = $cd_rs->all;
155 And it's not just limited to SELECT statements.
161 $cd_rs->create({ artist => 'Fred' });
163 Which is the same as:
165 $schema->resultset('CD')->create({
166 title => 'something',
171 See: L</search>, L</count>, L</get_column>, L</all>, L</create>.
173 =head2 Custom ResultSet classes
175 To add methods to your resultsets, you can subclass L<DBIx::Class::ResultSet>, similar to:
177 package MyApp::Schema::ResultSet::User;
182 use base 'DBIx::Class::ResultSet';
186 $self->search({ $self->current_source_alias . '.active' => 1 });
191 $self->search({ $self->current_source_alias . '.verified' => 0 });
194 sub created_n_days_ago {
195 my ($self, $days_ago) = @_;
197 $self->current_source_alias . '.create_date' => {
199 $self->result_source->schema->storage->datetime_parser->format_datetime(
200 DateTime->now( time_zone => 'UTC' )->subtract( days => $days_ago )
205 sub users_to_warn { shift->active->unverified->created_n_days_ago(7) }
209 See L<DBIx::Class::Schema/load_namespaces> on how DBIC can discover and
210 automatically attach L<Result|DBIx::Class::Manual::ResultClass>-specific
211 L<ResulSet|DBIx::Class::ResultSet> classes.
213 =head3 ResultSet subclassing with Moose and similar constructor-providers
215 Using L<Moose> or L<Moo> in your ResultSet classes is usually overkill, but
216 you may find it useful if your ResultSets contain a lot of business logic
217 (e.g. C<has xml_parser>, C<has json>, etc) or if you just prefer to organize
220 In order to write custom ResultSet classes with L<Moo> you need to use the
221 following template. The L<BUILDARGS|Moo/BUILDARGS> is necessary due to the
222 unusual signature of the L<constructor provided by DBIC
223 |DBIx::Class::ResultSet/new> C<< ->new($source, \%args) >>.
226 extends 'DBIx::Class::ResultSet';
227 sub BUILDARGS { $_[2] } # ::RS::new() expects my ($class, $rsrc, $args) = @_
233 If you want to build your custom ResultSet classes with L<Moose>, you need
234 a similar, though a little more elaborate template in order to interface the
235 inlining of the L<Moose>-provided
236 L<object constructor|Moose::Manual::Construction/WHERE'S THE CONSTRUCTOR?>,
239 package MyApp::Schema::ResultSet::User;
242 use MooseX::NonMoose;
243 extends 'DBIx::Class::ResultSet';
245 sub BUILDARGS { $_[2] } # ::RS::new() expects my ($class, $rsrc, $args) = @_
249 __PACKAGE__->meta->make_immutable;
253 The L<MooseX::NonMoose> is necessary so that the L<Moose> constructor does not
254 entirely overwrite the DBIC one (in contrast L<Moo> does this automatically).
255 Alternatively, you can skip L<MooseX::NonMoose> and get by with just L<Moose>
258 __PACKAGE__->meta->make_immutable(inline_constructor => 0);
266 =item Arguments: L<$source|DBIx::Class::ResultSource>, L<\%attrs?|/ATTRIBUTES>
268 =item Return Value: L<$resultset|/search>
272 The resultset constructor. Takes a source object (usually a
273 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
274 L</ATTRIBUTES> below). Does not perform any queries -- these are
275 executed as needed by the other methods.
277 Generally you never construct a resultset manually. Instead you get one
279 C<< $schema->L<resultset|DBIx::Class::Schema/resultset>('$source_name') >>
280 or C<< $another_resultset->L<search|/search>(...) >> (the later called in
283 my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
289 If called on an object, proxies to L</new_result> instead, so
291 my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
293 will return a CD object, not a ResultSet, and is equivalent to:
295 my $cd = $schema->resultset('CD')->new_result({ title => 'Spoon' });
297 Please also keep in mind that many internals call L</new_result> directly,
298 so overloading this method with the idea of intercepting new result object
299 creation B<will not work>. See also warning pertaining to L</create>.
309 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
310 return $class->new_result(@_);
313 my ($source, $attrs) = @_;
314 $source = $source->resolve
315 if $source->isa('DBIx::Class::ResultSourceHandle');
317 $attrs = { %{$attrs||{}} };
318 delete @{$attrs}{qw(_last_sqlmaker_alias_map _simple_passthrough_construction)};
320 if ($attrs->{page}) {
321 $attrs->{rows} ||= 10;
324 $attrs->{alias} ||= 'me';
327 result_source => $source,
328 cond => $attrs->{where},
333 # if there is a dark selector, this means we are already in a
334 # chain and the cleanup/sanification was taken care of by
336 $self->_normalize_selection($attrs)
337 unless $attrs->{_dark_selector};
340 $attrs->{result_class} || $source->result_class
350 =item Arguments: L<$cond|DBIx::Class::SQLMaker> | undef, L<\%attrs?|/ATTRIBUTES>
352 =item Return Value: $resultset (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
356 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
357 my $new_rs = $cd_rs->search({ year => 2005 });
359 my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
360 # year = 2005 OR year = 2004
362 In list context, C<< ->all() >> is called implicitly on the resultset, thus
363 returning a list of L<result|DBIx::Class::Manual::ResultClass> objects instead.
364 To avoid that, use L</search_rs>.
366 If you need to pass in additional attributes but no additional condition,
367 call it as C<search(undef, \%attrs)>.
369 # "SELECT name, artistid FROM $artist_table"
370 my @all_artists = $schema->resultset('Artist')->search(undef, {
371 columns => [qw/name artistid/],
374 For a list of attributes that can be passed to C<search>, see
375 L</ATTRIBUTES>. For more examples of using this function, see
376 L<Searching|DBIx::Class::Manual::Cookbook/SEARCHING>. For a complete
377 documentation for the first argument, see L<SQL::Abstract/"WHERE CLAUSES">
378 and its extension L<DBIx::Class::SQLMaker>.
380 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
384 Note that L</search> does not process/deflate any of the values passed in the
385 L<SQL::Abstract>-compatible search condition structure. This is unlike other
386 condition-bound methods L</new_result>, L</create> and L</find>. The user must ensure
387 manually that any value passed to this method will stringify to something the
388 RDBMS knows how to deal with. A notable example is the handling of L<DateTime>
389 objects, for more info see:
390 L<DBIx::Class::Manual::Cookbook/Formatting DateTime objects in queries>.
396 my $rs = $self->search_rs( @_ );
399 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_WANTARRAY and my $sog = fail_on_internal_wantarray;
402 elsif (defined wantarray) {
406 # we can be called by a relationship helper, which in
407 # turn may be called in void context due to some braindead
408 # overload or whatever else the user decided to be clever
409 # at this particular day. Thus limit the exception to
410 # external code calls only
411 $self->throw_exception ('->search is *not* a mutator, calling it in void context makes no sense')
412 if (caller)[0] !~ /^\QDBIx::Class::/;
422 =item Arguments: L<$cond|DBIx::Class::SQLMaker>, L<\%attrs?|/ATTRIBUTES>
424 =item Return Value: L<$resultset|/search>
428 This method does the same exact thing as search() except it will
429 always return a resultset, even in list context.
436 my $rsrc = $self->result_source;
437 my ($call_cond, $call_attrs);
439 # Special-case handling for (undef, undef) or (undef)
440 # Note that (foo => undef) is valid deprecated syntax
441 @_ = () if not scalar grep { defined $_ } @_;
447 # fish out attrs in the ($condref, $attr) case
448 elsif (@_ == 2 and ( ! defined $_[0] or length ref $_[0] ) ) {
449 ($call_cond, $call_attrs) = @_;
452 $self->throw_exception('Odd number of arguments to search')
456 carp_unique 'search( %condition ) is deprecated, use search( \%condition ) instead'
457 unless $rsrc->result_class->isa('DBIx::Class::CDBICompat');
459 for my $i (0 .. $#_) {
461 $self->throw_exception ('All keys in condition key/value pairs must be plain scalars')
462 if (! defined $_[$i] or length ref $_[$i] );
468 # see if we can keep the cache (no $rs changes)
470 my %safe = (alias => 1, cache => 1);
471 if ( ! grep { !$safe{$_} } keys %$call_attrs and (
474 ref $call_cond eq 'HASH' && ! keys %$call_cond
476 ref $call_cond eq 'ARRAY' && ! @$call_cond
478 $cache = $self->get_cache;
481 my $old_attrs = { %{$self->{attrs}} };
482 my ($old_having, $old_where) = delete @{$old_attrs}{qw(having where)};
484 my $new_attrs = { %$old_attrs };
486 # take care of call attrs (only if anything is changing)
487 if ($call_attrs and keys %$call_attrs) {
489 # copy for _normalize_selection
490 $call_attrs = { %$call_attrs };
492 my @selector_attrs = qw/select as columns cols +select +as +columns include_columns/;
494 # reset the current selector list if new selectors are supplied
495 delete @{$old_attrs}{(@selector_attrs, '_dark_selector')}
496 if grep { exists $call_attrs->{$_} } qw(columns cols select as);
498 # Normalize the new selector list (operates on the passed-in attr structure)
499 # Need to do it on every chain instead of only once on _resolved_attrs, in
500 # order to allow detection of empty vs partial 'as'
501 $call_attrs->{_dark_selector} = $old_attrs->{_dark_selector}
502 if $old_attrs->{_dark_selector};
503 $self->_normalize_selection ($call_attrs);
505 # start with blind overwriting merge, exclude selector attrs
506 $new_attrs = { %{$old_attrs}, %{$call_attrs} };
507 delete @{$new_attrs}{@selector_attrs};
509 for (@selector_attrs) {
510 $new_attrs->{$_} = $self->_merge_attr($old_attrs->{$_}, $call_attrs->{$_})
511 if ( exists $old_attrs->{$_} or exists $call_attrs->{$_} );
514 # older deprecated name, use only if {columns} is not there
515 if (my $c = delete $new_attrs->{cols}) {
516 carp_unique( "Resultset attribute 'cols' is deprecated, use 'columns' instead" );
517 if ($new_attrs->{columns}) {
518 carp "Resultset specifies both the 'columns' and the legacy 'cols' attributes - ignoring 'cols'";
521 $new_attrs->{columns} = $c;
526 # join/prefetch use their own crazy merging heuristics
527 foreach my $key (qw/join prefetch/) {
528 $new_attrs->{$key} = $self->_merge_joinpref_attr($old_attrs->{$key}, $call_attrs->{$key})
529 if exists $call_attrs->{$key};
532 # stack binds together
533 $new_attrs->{bind} = [ @{ $old_attrs->{bind} || [] }, @{ $call_attrs->{bind} || [] } ];
537 for ($old_where, $call_cond) {
539 $new_attrs->{where} = $self->_stack_cond (
540 $_, $new_attrs->{where}
545 if (defined $old_having) {
546 $new_attrs->{having} = $self->_stack_cond (
547 $old_having, $new_attrs->{having}
551 my $rs = (ref $self)->new($rsrc, $new_attrs);
553 $rs->set_cache($cache) if ($cache);
558 sub _normalize_selection {
559 my ($self, $attrs) = @_;
562 if ( exists $attrs->{include_columns} ) {
563 carp_unique( "Resultset attribute 'include_columns' is deprecated, use '+columns' instead" );
564 $attrs->{'+columns'} = $self->_merge_attr(
565 $attrs->{'+columns'}, delete $attrs->{include_columns}
569 # columns are always placed first, however
571 # Keep the X vs +X separation until _resolved_attrs time - this allows to
572 # delay the decision on whether to use a default select list ($rsrc->columns)
573 # allowing stuff like the remove_columns helper to work
575 # select/as +select/+as pairs need special handling - the amount of select/as
576 # elements in each pair does *not* have to be equal (think multicolumn
577 # selectors like distinct(foo, bar) ). If the selector is bare (no 'as'
578 # supplied at all) - try to infer the alias, either from the -as parameter
579 # of the selector spec, or use the parameter whole if it looks like a column
580 # name (ugly legacy heuristic). If all fails - leave the selector bare (which
581 # is ok as well), but make sure no more additions to the 'as' chain take place
582 for my $pref ('', '+') {
584 my ($sel, $as) = map {
585 my $key = "${pref}${_}";
587 my $val = [ ref $attrs->{$key} eq 'ARRAY'
589 : $attrs->{$key} || ()
591 delete $attrs->{$key};
595 if (! @$as and ! @$sel ) {
598 elsif (@$as and ! @$sel) {
599 $self->throw_exception(
600 "Unable to handle ${pref}as specification (@$as) without a corresponding ${pref}select"
604 # no as part supplied at all - try to deduce (unless explicit end of named selection is declared)
605 # if any @$as has been supplied we assume the user knows what (s)he is doing
606 # and blindly keep stacking up pieces
607 unless ($attrs->{_dark_selector}) {
610 if ( ref $_ eq 'HASH' and exists $_->{-as} ) {
611 push @$as, $_->{-as};
613 # assume any plain no-space, no-parenthesis string to be a column spec
614 # FIXME - this is retarded but is necessary to support shit like 'count(foo)'
615 elsif ( ! ref $_ and $_ =~ /^ [^\s\(\)]+ $/x) {
618 # if all else fails - raise a flag that no more aliasing will be allowed
620 $attrs->{_dark_selector} = {
623 local $Data::Dumper::Indent = 0;
632 elsif (@$as < @$sel) {
633 $self->throw_exception(
634 "Unable to handle an ${pref}as specification (@$as) with less elements than the corresponding ${pref}select"
637 elsif ($pref and $attrs->{_dark_selector}) {
638 $self->throw_exception(
639 "Unable to process named '+select', resultset contains an unnamed selector $attrs->{_dark_selector}{string}"
645 $attrs->{"${pref}select"} = $self->_merge_attr($attrs->{"${pref}select"}, $sel);
646 $attrs->{"${pref}as"} = $self->_merge_attr($attrs->{"${pref}as"}, $as);
651 my ($self, $left, $right) = @_;
654 (ref $_ eq 'ARRAY' and !@$_)
656 (ref $_ eq 'HASH' and ! keys %$_)
657 ) and $_ = undef for ($left, $right);
660 # either one of the two undef
661 ( (defined $left) xor (defined $right) ) ? ( defined $left ? $left : $right )
664 : ( ! defined $left ) ? undef
666 : { -and => [$left, $right] }
670 =head2 search_literal
672 B<CAVEAT>: C<search_literal> is provided for Class::DBI compatibility and
673 should only be used in that context. C<search_literal> is a convenience
674 method. It is equivalent to calling C<< $schema->search(\[]) >>, but if you
675 want to ensure columns are bound correctly, use L</search>.
677 See L<DBIx::Class::Manual::Cookbook/SEARCHING> and
678 L<DBIx::Class::Manual::FAQ/Searching> for searching techniques that do not
679 require C<search_literal>.
683 =item Arguments: $sql_fragment, @standalone_bind_values
685 =item Return Value: L<$resultset|/search> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
689 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
690 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
692 Pass a literal chunk of SQL to be added to the conditional part of the
695 Example of how to use C<search> instead of C<search_literal>
697 my @cds = $cd_rs->search_literal('cdid = ? AND (artist = ? OR artist = ?)', (2, 1, 2));
698 my @cds = $cd_rs->search(\[ 'cdid = ? AND (artist = ? OR artist = ?)', [ 'cdid', 2 ], [ 'artist', 1 ], [ 'artist', 2 ] ]);
703 my ($self, $sql, @bind) = @_;
705 if ( @bind && ref($bind[-1]) eq 'HASH' ) {
708 return $self->search(\[ $sql, map [ {} => $_ ], @bind ], ($attr || () ));
715 =item Arguments: \%columns_values | @pk_values, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
717 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
721 Finds and returns a single row based on supplied criteria. Takes either a
722 hashref with the same format as L</create> (including inference of foreign
723 keys from related objects), or a list of primary key values in the same
724 order as the L<primary columns|DBIx::Class::ResultSource/primary_columns>
725 declaration on the L</result_source>.
727 In either case an attempt is made to combine conditions already existing on
728 the resultset with the condition passed to this method.
730 To aid with preparing the correct query for the storage you may supply the
731 C<key> attribute, which is the name of a
732 L<unique constraint|DBIx::Class::ResultSource/add_unique_constraint> (the
733 unique constraint corresponding to the
734 L<primary columns|DBIx::Class::ResultSource/primary_columns> is always named
735 C<primary>). If the C<key> attribute has been supplied, and DBIC is unable
736 to construct a query that satisfies the named unique constraint fully (
737 non-NULL values for each column member of the constraint) an exception is
740 If no C<key> is specified, the search is carried over all unique constraints
741 which are fully defined by the available condition.
743 If no such constraint is found, C<find> currently defaults to a simple
744 C<< search->(\%column_values) >> which may or may not do what you expect.
745 Note that this fallback behavior may be deprecated in further versions. If
746 you need to search with arbitrary conditions - use L</search>. If the query
747 resulting from this fallback produces more than one row, a warning to the
748 effect is issued, though only the first row is constructed and returned as
751 In addition to C<key>, L</find> recognizes and applies standard
752 L<resultset attributes|/ATTRIBUTES> in the same way as L</search> does.
754 Note that if you have extra concerns about the correctness of the resulting
755 query you need to specify the C<key> attribute and supply the entire condition
756 as an argument to find (since it is not always possible to perform the
757 combination of the resultset condition with the supplied one, especially if
758 the resultset condition contains literal sql).
760 For example, to find a row by its primary key:
762 my $cd = $schema->resultset('CD')->find(5);
764 You can also find a row by a specific unique constraint:
766 my $cd = $schema->resultset('CD')->find(
768 artist => 'Massive Attack',
769 title => 'Mezzanine',
771 { key => 'cd_artist_title' }
774 See also L</find_or_create> and L</update_or_create>.
780 my $attrs = (@_ > 1 && ref $_[-1] eq 'HASH' ? pop(@_) : {});
784 if (exists $attrs->{key}) {
785 $constraint_name = defined $attrs->{key}
787 : $self->throw_exception("An undefined 'key' resultset attribute makes no sense")
791 # Parse out the condition from input
794 my $rsrc = $self->result_source;
796 if (ref $_[0] eq 'HASH') {
797 $call_cond = { %{$_[0]} };
800 # if only values are supplied we need to default to 'primary'
801 $constraint_name = 'primary' unless defined $constraint_name;
803 my @c_cols = $rsrc->unique_constraint_columns($constraint_name);
805 $self->throw_exception(
806 "No constraint columns, maybe a malformed '$constraint_name' constraint?"
809 $self->throw_exception (
810 'find() expects either a column/value hashref, or a list of values '
811 . "corresponding to the columns of the specified unique constraint '$constraint_name'"
812 ) unless @c_cols == @_;
814 @{$call_cond}{@c_cols} = @_;
817 # process relationship data if any
820 for my $key (keys %$call_cond) {
822 # either a structure or a result-ish object
823 length ref($call_cond->{$key})
825 ( $rel_list ||= { map { $_ => 1 } $rsrc->relationships } )
828 ! is_literal_value( $call_cond->{$key} )
830 # implicitly skip has_many's (likely MC), via the delete()
831 ( ref( my $foreign_val = delete $call_cond->{$key} ) ne 'ARRAY' )
834 # FIXME: it seems wrong that relationship conditions take precedence...?
838 %{ $rsrc->_resolve_relationship_condition(
841 (! defined blessed $foreign_val) ? $foreign_val : do {
843 my $f_result_class = $rsrc->related_source($key)->result_class;
845 unless( $foreign_val->isa($f_result_class) ) {
847 $self->throw_exception(
848 'Objects supplied to find() must inherit from '
849 . "'$DBIx::Class::ResultSource::__expected_result_class_isa'"
850 ) unless $foreign_val->isa(
851 $DBIx::Class::ResultSource::__expected_result_class_isa
855 "Objects supplied to find() via '$key' usually should inherit from "
856 . "the related ResultClass ('$f_result_class'), perhaps you've made "
861 +{ $foreign_val->get_columns };
864 infer_values_based_on => {},
866 # an API where these are optional would be too cumbersome,
867 # instead always pass in some dummy values
869 )->{inferred_values} },
874 my $alias = exists $attrs->{alias} ? $attrs->{alias} : $self->{attrs}{alias};
876 if (defined $constraint_name) {
877 $final_cond = $self->_qualify_cond_columns (
879 $rsrc->_minimal_valueset_satisfying_constraint(
880 constraint_name => $constraint_name,
881 values => ($self->_merge_with_rscond($call_cond))[0],
888 elsif ($self->{attrs}{accessor} and $self->{attrs}{accessor} eq 'single') {
889 # This means that we got here after a merger of relationship conditions
890 # in ::Relationship::Base::search_related (the row method), and furthermore
891 # the relationship is of the 'single' type. This means that the condition
892 # provided by the relationship (already attached to $self) is sufficient,
893 # as there can be only one row in the database that would satisfy the
897 my (@unique_queries, %seen_column_combinations, $ci, @fc_exceptions);
899 # no key was specified - fall down to heuristics mode:
900 # run through all unique queries registered on the resultset, and
901 # 'OR' all qualifying queries together
903 # always start from 'primary' if it exists at all
904 for my $c_name ( sort {
906 : $b eq 'primary' ? 1
908 } $rsrc->unique_constraint_names) {
910 next if $seen_column_combinations{
911 join "\x00", sort $rsrc->unique_constraint_columns($c_name)
915 push @unique_queries, $self->_qualify_cond_columns(
916 $rsrc->_minimal_valueset_satisfying_constraint(
917 constraint_name => $c_name,
918 values => ($self->_merge_with_rscond($call_cond))[0],
919 columns_info => ($ci ||= $rsrc->columns_info),
924 dbic_internal_catch {
925 push @fc_exceptions, $_ if $_ =~ /\bFilterColumn\b/;
930 @unique_queries ? \@unique_queries
931 : @fc_exceptions ? $self->throw_exception(join "; ", map { $_ =~ /(.*) at .+ line \d+$/s } @fc_exceptions )
932 : $self->_non_unique_find_fallback ($call_cond, $attrs)
936 # Run the query, passing the result_class since it should propagate for find
937 my $rs = $self->search ($final_cond, {result_class => $self->result_class, %$attrs});
938 if ($rs->_resolved_attrs->{collapse}) {
940 carp "Query returned more than one row" if $rs->next;
948 # This is a stop-gap method as agreed during the discussion on find() cleanup:
949 # http://lists.scsys.co.uk/pipermail/dbix-class/2010-October/009535.html
951 # It is invoked when find() is called in legacy-mode with insufficiently-unique
952 # condition. It is provided for overrides until a saner way forward is devised
954 # *NOTE* This is not a public method, and it's *GUARANTEED* to disappear down
955 # the road. Please adjust your tests accordingly to catch this situation early
956 # DBIx::Class::ResultSet->can('_non_unique_find_fallback') is reasonable
958 # The method will not be removed without an adequately complete replacement
959 # for strict-mode enforcement
960 sub _non_unique_find_fallback {
961 my ($self, $cond, $attrs) = @_;
963 return $self->_qualify_cond_columns(
965 exists $attrs->{alias}
967 : $self->{attrs}{alias}
972 sub _qualify_cond_columns {
973 my ($self, $cond, $alias) = @_;
975 my %aliased = %$cond;
976 for (keys %aliased) {
977 $aliased{"$alias.$_"} = delete $aliased{$_}
984 sub _build_unique_cond {
986 '_build_unique_cond is a private method, and moreover is about to go '
987 . 'away. Please contact the development team at %s if you believe you '
988 . 'have a genuine use for this method, in order to discuss alternatives.',
989 DBIx::Class::_ENV_::HELP_URL,
992 my ($self, $constraint_name, $cond, $croak_on_null) = @_;
994 $self->result_source->_minimal_valueset_satisfying_constraint(
995 constraint_name => $constraint_name,
997 carp_on_nulls => !$croak_on_null
1001 =head2 search_related
1005 =item Arguments: $rel_name, $cond?, L<\%attrs?|/ATTRIBUTES>
1007 =item Return Value: L<$resultset|/search> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
1011 $new_rs = $cd_rs->search_related('artist', {
1015 Searches the specified relationship, optionally specifying a condition and
1016 attributes for matching records. See L</ATTRIBUTES> for more information.
1018 In list context, C<< ->all() >> is called implicitly on the resultset, thus
1019 returning a list of result objects instead. To avoid that, use L</search_related_rs>.
1021 See also L</search_related_rs>.
1025 sub search_related :DBIC_method_is_indirect_sugar {
1026 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
1027 return shift->related_resultset(shift)->search(@_);
1030 =head2 search_related_rs
1032 This method works exactly the same as search_related, except that
1033 it guarantees a resultset, even in list context.
1037 sub search_related_rs :DBIC_method_is_indirect_sugar {
1038 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
1039 return shift->related_resultset(shift)->search_rs(@_);
1046 =item Arguments: none
1048 =item Return Value: L<$cursor|DBIx::Class::Cursor>
1052 Returns a storage-driven cursor to the given resultset. See
1053 L<DBIx::Class::Cursor> for more information.
1060 return $self->{cursor} ||= do {
1061 my $attrs = $self->_resolved_attrs;
1062 $self->result_source->schema->storage->select(
1063 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
1072 =item Arguments: L<$cond?|DBIx::Class::SQLMaker>
1074 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
1078 my $cd = $schema->resultset('CD')->single({ year => 2001 });
1080 Inflates the first result without creating a cursor if the resultset has
1081 any records in it; if not returns C<undef>. Used by L</find> as a lean version
1084 While this method can take an optional search condition (just like L</search>)
1085 being a fast-code-path it does not recognize search attributes. If you need to
1086 add extra joins or similar, call L</search> and then chain-call L</single> on the
1087 L<DBIx::Class::ResultSet> returned.
1093 As of 0.08100, this method enforces the assumption that the preceding
1094 query returns only one row. If more than one row is returned, you will receive
1097 Query returned more than one row
1099 In this case, you should be using L</next> or L</find> instead, or if you really
1100 know what you are doing, use the L</rows> attribute to explicitly limit the size
1103 This method will also throw an exception if it is called on a resultset prefetching
1104 has_many, as such a prefetch implies fetching multiple rows from the database in
1105 order to assemble the resulting object.
1112 my ($self, $where) = @_;
1114 $self->throw_exception('single() only takes search conditions, no attributes. You want ->search( $cond, $attrs )->single()');
1117 my $attrs = { %{$self->_resolved_attrs} };
1119 $self->throw_exception(
1120 'single() can not be used on resultsets collapsing a has_many. Use find( \%cond ) or next() instead'
1121 ) if $attrs->{collapse};
1124 if (defined $attrs->{where}) {
1127 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
1128 $where, delete $attrs->{where} ]
1131 $attrs->{where} = $where;
1135 my $data = [ $self->result_source->schema->storage->select_single(
1136 $attrs->{from}, $attrs->{select},
1137 $attrs->{where}, $attrs
1140 return undef unless @$data;
1141 $self->{_stashed_rows} = [ $data ];
1142 $self->_construct_results->[0];
1149 =item Arguments: L<$cond?|DBIx::Class::SQLMaker>
1151 =item Return Value: L<$resultsetcolumn|DBIx::Class::ResultSetColumn>
1155 my $max_length = $rs->get_column('length')->max;
1157 Returns a L<DBIx::Class::ResultSetColumn> instance for a column of the ResultSet.
1162 DBIx::Class::ResultSetColumn->new(@_);
1169 =item Arguments: L<$cond|DBIx::Class::SQLMaker>, L<\%attrs?|/ATTRIBUTES>
1171 =item Return Value: L<$resultset|/search> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
1175 # WHERE title LIKE '%blue%'
1176 $cd_rs = $rs->search_like({ title => '%blue%'});
1178 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
1179 that this is simply a convenience method retained for ex Class::DBI users.
1180 You most likely want to use L</search> with specific operators.
1182 For more information, see L<DBIx::Class::Manual::Cookbook>.
1184 This method is deprecated and will be removed in 0.09. Use L<search()|/search>
1185 instead. An example conversion is:
1187 ->search_like({ foo => 'bar' });
1191 ->search({ foo => { like => 'bar' } });
1198 'search_like() is deprecated and will be removed in DBIC version 0.09.'
1199 .' Instead use ->search({ x => { -like => "y%" } })'
1200 .' (note the outer pair of {}s - they are important!)'
1202 my $attrs = (@_ > 1 && ref $_[-1] eq 'HASH' ? pop(@_) : {});
1203 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
1204 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
1205 return $class->search($query, { %$attrs });
1212 =item Arguments: $first, $last
1214 =item Return Value: L<$resultset|/search> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
1218 Returns a resultset or object list representing a subset of elements from the
1219 resultset slice is called on. Indexes are from 0, i.e., to get the first
1220 three records, call:
1222 my ($one, $two, $three) = $rs->slice(0, 2);
1227 my ($self, $min, $max) = @_;
1228 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
1229 $attrs->{offset} = $self->{attrs}{offset} || 0;
1230 $attrs->{offset} += $min;
1231 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
1232 return $self->search(undef, $attrs);
1239 =item Arguments: none
1241 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
1245 Returns the next element in the resultset (C<undef> is there is none).
1247 Can be used to efficiently iterate over records in the resultset:
1249 my $rs = $schema->resultset('CD')->search;
1250 while (my $cd = $rs->next) {
1254 Note that you need to store the resultset object, and call C<next> on it.
1255 Calling C<< resultset('Table')->next >> repeatedly will always return the
1256 first record from the resultset.
1263 if (my $cache = $self->get_cache) {
1264 $self->{all_cache_position} ||= 0;
1265 return $cache->[$self->{all_cache_position}++];
1268 if ($self->{attrs}{cache}) {
1269 delete $self->{pager};
1270 $self->{all_cache_position} = 1;
1271 return ($self->all)[0];
1274 return shift(@{$self->{_stashed_results}}) if @{ $self->{_stashed_results}||[] };
1276 $self->{_stashed_results} = $self->_construct_results
1279 return shift @{$self->{_stashed_results}};
1282 # Constructs as many results as it can in one pass while respecting
1283 # cursor laziness. Several modes of operation:
1285 # * Always builds everything present in @{$self->{_stashed_rows}}
1286 # * If called with $fetch_all true - pulls everything off the cursor and
1287 # builds all result structures (or objects) in one pass
1288 # * If $self->_resolved_attrs->{collapse} is true, checks the order_by
1289 # and if the resultset is ordered properly by the left side:
1290 # * Fetches stuff off the cursor until the "master object" changes,
1291 # and saves the last extra row (if any) in @{$self->{_stashed_rows}}
1293 # * Just fetches, and collapses/constructs everything as if $fetch_all
1294 # was requested (there is no other way to collapse except for an
1296 # * If no collapse is requested - just get the next row, construct and
1298 sub _construct_results {
1299 my ($self, $fetch_all) = @_;
1301 my $rsrc = $self->result_source;
1302 my $attrs = $self->_resolved_attrs;
1307 ! $attrs->{order_by}
1311 my @pcols = $rsrc->primary_columns
1313 # default order for collapsing unless the user asked for something
1314 $attrs->{order_by} = [ map { join '.', $attrs->{alias}, $_} @pcols ];
1315 $attrs->{_ordered_for_collapse} = 1;
1316 $attrs->{_order_is_artificial} = 1;
1319 # this will be used as both initial raw-row collector AND as a RV of
1320 # _construct_results. Not regrowing the array twice matters a lot...
1321 # a surprising amount actually
1322 my $rows = delete $self->{_stashed_rows};
1324 my $cursor; # we may not need one at all
1326 my $did_fetch_all = $fetch_all;
1329 # FIXME SUBOPTIMAL - we can do better, cursor->next/all (well diff. methods) should return a ref
1330 $rows = [ ($rows ? @$rows : ()), $self->cursor->all ];
1332 elsif( $attrs->{collapse} ) {
1334 # a cursor will need to be closed over in case of collapse
1335 $cursor = $self->cursor;
1337 $attrs->{_ordered_for_collapse} = (
1343 ->_extract_colinfo_of_stable_main_source_order_by_portion($attrs)
1345 ) unless defined $attrs->{_ordered_for_collapse};
1347 if (! $attrs->{_ordered_for_collapse}) {
1350 # instead of looping over ->next, use ->all in stealth mode
1351 # *without* calling a ->reset afterwards
1352 # FIXME ENCAPSULATION - encapsulation breach, cursor method additions pending
1353 if (! $cursor->{_done}) {
1354 $rows = [ ($rows ? @$rows : ()), $cursor->all ];
1355 $cursor->{_done} = 1;
1360 if (! $did_fetch_all and ! @{$rows||[]} ) {
1361 # FIXME SUBOPTIMAL - we can do better, cursor->next/all (well diff. methods) should return a ref
1362 $cursor ||= $self->cursor;
1363 if (scalar (my @r = $cursor->next) ) {
1368 return undef unless @{$rows||[]};
1370 # sanity check - people are too clever for their own good
1371 if ($attrs->{collapse} and my $aliastypes = $attrs->{_last_sqlmaker_alias_map} ) {
1373 my $multiplied_selectors;
1374 for my $sel_alias ( grep { $_ ne $attrs->{alias} } keys %{ $aliastypes->{selecting} } ) {
1376 $aliastypes->{multiplying}{$sel_alias}
1378 $aliastypes->{premultiplied}{$sel_alias}
1380 $multiplied_selectors->{$_} = 1 for values %{$aliastypes->{selecting}{$sel_alias}{-seen_columns}}
1384 for my $i (0 .. $#{$attrs->{as}} ) {
1385 my $sel = $attrs->{select}[$i];
1387 if (ref $sel eq 'SCALAR') {
1390 elsif( ref $sel eq 'REF' and ref $$sel eq 'ARRAY' ) {
1394 $self->throw_exception(
1395 'Result collapse not possible - selection from a has_many source redirected to the main object'
1396 ) if ($multiplied_selectors->{$sel} and $attrs->{as}[$i] !~ /\./);
1400 # hotspot - skip the setter
1401 my $res_class = $self->_result_class;
1403 my $inflator_cref = $self->{_result_inflator}{cref} ||= do {
1404 $res_class->can ('inflate_result')
1405 or $self->throw_exception("Inflator $res_class does not provide an inflate_result() method");
1408 my $infmap = $attrs->{as};
1410 $self->{_result_inflator}{is_core_row} = ( (
1413 ( \&DBIx::Class::Row::inflate_result || die "No ::Row::inflate_result() - can't happen" )
1414 ) ? 1 : 0 ) unless defined $self->{_result_inflator}{is_core_row};
1416 $self->{_result_inflator}{is_hri} = ( (
1417 ! $self->{_result_inflator}{is_core_row}
1419 $inflator_cref == \&DBIx::Class::ResultClass::HashRefInflator::inflate_result
1420 ) ? 1 : 0 ) unless defined $self->{_result_inflator}{is_hri};
1423 if ($attrs->{_simple_passthrough_construction}) {
1424 # construct a much simpler array->hash folder for the one-table HRI cases right here
1425 if ($self->{_result_inflator}{is_hri}) {
1426 for my $r (@$rows) {
1427 $r = { map { $infmap->[$_] => $r->[$_] } 0..$#$infmap };
1430 # FIXME SUBOPTIMAL this is a very very very hot spot
1431 # while rather optimal we can *still* do much better, by
1432 # building a smarter Row::inflate_result(), and
1433 # switch to feeding it data via a much leaner interface
1435 # crude unscientific benchmarking indicated the shortcut eval is not worth it for
1436 # this particular resultset size
1437 elsif ( $self->{_result_inflator}{is_core_row} and @$rows < 60 ) {
1438 for my $r (@$rows) {
1439 $r = $inflator_cref->($res_class, $rsrc, { map { $infmap->[$_] => $r->[$_] } (0..$#$infmap) } );
1444 ( $self->{_result_inflator}{is_core_row}
1445 ? '$_ = $inflator_cref->($res_class, $rsrc, { %s }) for @$rows'
1446 # a custom inflator may be a multiplier/reductor - put it in direct list ctx
1447 : '@$rows = map { $inflator_cref->($res_class, $rsrc, { %s } ) } @$rows'
1449 ( join (', ', map { "\$infmap->[$_] => \$_->[$_]" } 0..$#$infmap ) )
1455 $self->{_result_inflator}{is_hri} ? 'hri'
1456 : $self->{_result_inflator}{is_core_row} ? 'classic_pruning'
1457 : 'classic_nonpruning'
1460 unless( $self->{_row_parser}{$parser_type}{cref} ) {
1462 # $args and $attrs to _mk_row_parser are separated to delineate what is
1463 # core collapser stuff and what is dbic $rs specific
1464 $self->{_row_parser}{$parser_type}{src} = $rsrc->_mk_row_parser({
1465 inflate_map => $infmap,
1466 collapse => $attrs->{collapse},
1467 premultiplied => $attrs->{_main_source_premultiplied},
1468 hri_style => $self->{_result_inflator}{is_hri},
1469 prune_null_branches => $self->{_result_inflator}{is_hri} || $self->{_result_inflator}{is_core_row},
1472 $self->{_row_parser}{$parser_type}{cref} = do {
1473 package # hide form PAUSE
1474 DBIx::Class::__GENERATED_ROW_PARSER__;
1476 eval $self->{_row_parser}{$parser_type}{src};
1480 # this needs to close over the *current* cursor, hence why it is not cached above
1481 my $next_cref = ($did_fetch_all or ! $attrs->{collapse})
1484 # FIXME SUBOPTIMAL - we can do better, cursor->next/all (well diff. methods) should return a ref
1485 my @r = $cursor->next or return;
1490 $self->{_row_parser}{$parser_type}{cref}->(
1493 ( $self->{_stashed_rows} = [] ),
1494 ( my $null_violations = {} ),
1497 $self->throw_exception(
1498 'Collapse aborted - the following columns are declared (or defaulted to) '
1499 . 'non-nullable within DBIC but NULLs were retrieved from storage: '
1500 . join( ', ', map { "'$infmap->[$_]'" } sort { $a <=> $b } keys %$null_violations )
1501 . ' within data row ' . dump_value({
1504 ( ! defined $self->{_stashed_rows}[0][$_] or length $self->{_stashed_rows}[0][$_] < 50 )
1505 ? $self->{_stashed_rows}[0][$_]
1506 : substr( $self->{_stashed_rows}[0][$_], 0, 50 ) . '...'
1507 } 0 .. $#{$self->{_stashed_rows}[0]}
1509 ) if keys %$null_violations;
1511 # simple in-place substitution, does not regrow $rows
1512 if ($self->{_result_inflator}{is_core_row}) {
1513 $_ = $inflator_cref->($res_class, $rsrc, @$_) for @$rows
1515 # Special-case multi-object HRI - there is no $inflator_cref pass at all
1516 elsif ( ! $self->{_result_inflator}{is_hri} ) {
1517 # the inflator may be a multiplier/reductor - put it in list ctx
1518 @$rows = map { $inflator_cref->($res_class, $rsrc, @$_) } @$rows;
1522 # The @$rows check seems odd at first - why wouldn't we want to warn
1523 # regardless? The issue is things like find() etc, where the user
1524 # *knows* only one result will come back. In these cases the ->all
1525 # is not a pessimization, but rather something we actually want
1527 'Unable to properly collapse has_many results in iterator mode due '
1528 . 'to order criteria - performed an eager cursor slurp underneath. '
1529 . 'Consider using ->all() instead'
1530 ) if ( ! $fetch_all and @$rows > 1 );
1535 =head2 result_source
1539 =item Arguments: L<$result_source?|DBIx::Class::ResultSource>
1541 =item Return Value: L<$result_source|DBIx::Class::ResultSource>
1545 An accessor for the primary ResultSource object from which this ResultSet
1552 =item Arguments: $result_class?
1554 =item Return Value: $result_class
1558 An accessor for the class to use when creating result objects. Defaults to
1559 C<< result_source->result_class >> - which in most cases is the name of the
1560 L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class.
1562 Note that changing the result_class will also remove any components
1563 that were originally loaded in the source class via
1564 L<load_components|Class::C3::Componentised/load_components( @comps )>.
1565 Any overloaded methods in the original source class will not run.
1570 my ($self, $result_class) = @_;
1571 if ($result_class) {
1573 # don't fire this for an object
1574 $self->ensure_class_loaded($result_class)
1575 unless ref($result_class);
1577 if ($self->get_cache) {
1578 carp_unique('Changing the result_class of a ResultSet instance with cached results is a noop - the cache contents will not be altered');
1580 # FIXME ENCAPSULATION - encapsulation breach, cursor method additions pending
1581 elsif ($self->{cursor} && $self->{cursor}{_pos}) {
1582 $self->throw_exception('Changing the result_class of a ResultSet instance with an active cursor is not supported');
1585 $self->_result_class($result_class);
1587 delete $self->{_result_inflator};
1589 $self->_result_class;
1596 =item Arguments: L<$cond|DBIx::Class::SQLMaker>, L<\%attrs?|/ATTRIBUTES>
1598 =item Return Value: $count
1602 Performs an SQL C<COUNT> with the same query as the resultset was built
1603 with to find the number of elements. Passing arguments is equivalent to
1604 C<< $rs->search ($cond, \%attrs)->count >>
1610 return $self->search(@_)->count if @_ and defined $_[0];
1611 return scalar @{ $self->get_cache } if $self->get_cache;
1613 my $attrs = { %{ $self->_resolved_attrs } };
1615 # this is a little optimization - it is faster to do the limit
1616 # adjustments in software, instead of a subquery
1617 my ($rows, $offset) = delete @{$attrs}{qw/rows offset/};
1620 if ($self->_has_resolved_attr (qw/collapse group_by/)) {
1621 $crs = $self->_count_subq_rs ($attrs);
1624 $crs = $self->_count_rs ($attrs);
1626 my $count = $crs->next;
1628 $count -= $offset if $offset;
1629 $count = $rows if $rows and $rows < $count;
1630 $count = 0 if ($count < 0);
1639 =item Arguments: L<$cond|DBIx::Class::SQLMaker>, L<\%attrs?|/ATTRIBUTES>
1641 =item Return Value: L<$count_rs|DBIx::Class::ResultSetColumn>
1645 Same as L</count> but returns a L<DBIx::Class::ResultSetColumn> object.
1646 This can be very handy for subqueries:
1648 ->search( { amount => $some_rs->count_rs->as_query } )
1650 As with regular resultsets the SQL query will be executed only after
1651 the resultset is accessed via L</next> or L</all>. That would return
1652 the same single value obtainable via L</count>.
1658 return $self->search(@_)->count_rs if @_;
1660 # this may look like a lack of abstraction (count() does about the same)
1661 # but in fact an _rs *must* use a subquery for the limits, as the
1662 # software based limiting can not be ported if this $rs is to be used
1663 # in a subquery itself (i.e. ->as_query)
1664 if ($self->_has_resolved_attr (qw/collapse group_by offset rows/)) {
1665 return $self->_count_subq_rs($self->{_attrs});
1668 return $self->_count_rs($self->{_attrs});
1673 # returns a ResultSetColumn object tied to the count query
1676 my ($self, $attrs) = @_;
1678 my $rsrc = $self->result_source;
1680 my $tmp_attrs = { %$attrs };
1681 # take off any limits, record_filter is cdbi, and no point of ordering nor locking a count
1682 delete @{$tmp_attrs}{qw/rows offset order_by record_filter for/};
1684 # overwrite the selector (supplied by the storage)
1685 $rsrc->resultset_class->new($rsrc, {
1687 select => $rsrc->schema->storage->_count_select ($rsrc, $attrs),
1689 })->get_column ('count');
1693 # same as above but uses a subquery
1695 sub _count_subq_rs {
1696 my ($self, $attrs) = @_;
1698 my $rsrc = $self->result_source;
1700 my $sub_attrs = { %$attrs };
1701 # extra selectors do not go in the subquery and there is no point of ordering it, nor locking it
1702 delete @{$sub_attrs}{qw/collapse columns as select order_by for/};
1704 # if we multi-prefetch we group_by something unique, as this is what we would
1705 # get out of the rs via ->next/->all. We *DO WANT* to clobber old group_by regardless
1706 if ( $attrs->{collapse} ) {
1707 $sub_attrs->{group_by} = [ map { "$attrs->{alias}.$_" } @{
1708 $rsrc->_identifying_column_set || $self->throw_exception(
1709 'Unable to construct a unique group_by criteria properly collapsing the '
1710 . 'has_many prefetch before count()'
1715 # Calculate subquery selector
1716 if (my $g = $sub_attrs->{group_by}) {
1718 my $sql_maker = $rsrc->schema->storage->sql_maker;
1720 # necessary as the group_by may refer to aliased functions
1722 for my $sel (@{$attrs->{select}}) {
1723 $sel_index->{$sel->{-as}} = $sel
1724 if (ref $sel eq 'HASH' and $sel->{-as});
1727 # anything from the original select mentioned on the group-by needs to make it to the inner selector
1728 # also look for named aggregates referred in the having clause
1729 # having often contains scalarrefs - thus parse it out entirely
1731 if ($attrs->{having}) {
1732 local $sql_maker->{having_bind};
1733 local $sql_maker->{quote_char} = $sql_maker->{quote_char};
1734 local $sql_maker->{name_sep} = $sql_maker->{name_sep};
1735 unless (defined $sql_maker->{quote_char} and length $sql_maker->{quote_char}) {
1736 $sql_maker->{quote_char} = [ "\x00", "\xFF" ];
1737 # if we don't unset it we screw up retarded but unfortunately working
1738 # 'MAX(foo.bar)' => { '>', 3 }
1739 $sql_maker->{name_sep} = '';
1742 my ($lquote, $rquote, $sep) = map { quotemeta $_ } ($sql_maker->_quote_chars, $sql_maker->name_sep);
1744 my $having_sql = $sql_maker->_parse_rs_attrs ({ having => $attrs->{having} });
1747 # search for both a proper quoted qualified string, for a naive unquoted scalarref
1748 # and if all fails for an utterly naive quoted scalar-with-function
1749 while ($having_sql =~ /
1750 $rquote $sep $lquote (.+?) $rquote
1752 [\s,] \w+ \. (\w+) [\s,]
1754 [\s,] $lquote (.+?) $rquote [\s,]
1756 my $part = $1 || $2 || $3; # one of them matched if we got here
1757 unless ($seen_having{$part}++) {
1764 my $colpiece = $sel_index->{$_} || $_;
1766 # unqualify join-based group_by's. Arcane but possible query
1767 # also horrible horrible hack to alias a column (not a func.)
1768 # (probably need to introduce SQLA syntax)
1769 if ($colpiece =~ /\./ && $colpiece !~ /^$attrs->{alias}\./) {
1772 $colpiece = \ sprintf ('%s AS %s', map { $sql_maker->_quote ($_) } ($colpiece, $as) );
1774 push @{$sub_attrs->{select}}, $colpiece;
1778 my @pcols = map { "$attrs->{alias}.$_" } ($rsrc->primary_columns);
1779 $sub_attrs->{select} = @pcols ? \@pcols : [ 1 ];
1782 return $rsrc->resultset_class
1783 ->new ($rsrc, $sub_attrs)
1785 ->search ({}, { columns => { count => $rsrc->schema->storage->_count_select ($rsrc, $attrs) } })
1786 ->get_column ('count');
1790 =head2 count_literal
1792 B<CAVEAT>: C<count_literal> is provided for Class::DBI compatibility and
1793 should only be used in that context. See L</search_literal> for further info.
1797 =item Arguments: $sql_fragment, @standalone_bind_values
1799 =item Return Value: $count
1803 Counts the results in a literal query. Equivalent to calling L</search_literal>
1804 with the passed arguments, then L</count>.
1808 sub count_literal :DBIC_method_is_indirect_sugar {
1809 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
1810 shift->search_literal(@_)->count
1817 =item Arguments: none
1819 =item Return Value: L<@result_objs|DBIx::Class::Manual::ResultClass>
1823 Returns all elements in the resultset.
1830 $self->throw_exception("all() doesn't take any arguments, you probably wanted ->search(...)->all()");
1833 delete @{$self}{qw/_stashed_rows _stashed_results/};
1835 if (my $c = $self->get_cache) {
1839 $self->cursor->reset;
1841 my $objs = $self->_construct_results('fetch_all') || [];
1843 $self->set_cache($objs) if $self->{attrs}{cache};
1852 =item Arguments: none
1854 =item Return Value: $self
1858 Resets the resultset's cursor, so you can iterate through the elements again.
1859 Implicitly resets the storage cursor, so a subsequent L</next> will trigger
1867 delete @{$self}{qw/_stashed_rows _stashed_results/};
1868 $self->{all_cache_position} = 0;
1869 $self->cursor->reset;
1877 =item Arguments: none
1879 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
1883 L<Resets|/reset> the resultset (causing a fresh query to storage) and returns
1884 an object for the first result (or C<undef> if the resultset is empty).
1888 sub first :DBIC_method_is_indirect_sugar {
1889 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
1890 return $_[0]->reset->next;
1896 # Determines whether and what type of subquery is required for the $rs operation.
1897 # If grouping is necessary either supplies its own, or verifies the current one
1898 # After all is done delegates to the proper storage method.
1900 sub _rs_update_delete {
1901 my ($self, $op, $values) = @_;
1903 my $rsrc = $self->result_source;
1904 my $storage = $rsrc->schema->storage;
1906 my $attrs = { %{$self->_resolved_attrs} };
1908 my $join_classifications;
1909 my ($existing_group_by) = delete @{$attrs}{qw(group_by _grouped_by_distinct)};
1911 # do we need a subquery for any reason?
1913 defined $existing_group_by
1915 # if {from} is unparseable wrap a subq
1916 ref($attrs->{from}) ne 'ARRAY'
1918 # limits call for a subq
1919 $self->_has_resolved_attr(qw/rows offset/)
1922 # simplify the joinmap, so we can further decide if a subq is necessary
1923 if (!$needs_subq and @{$attrs->{from}} > 1) {
1925 ($attrs->{from}, $join_classifications) =
1926 $storage->_prune_unused_joins ($attrs);
1928 # any non-pruneable non-local restricting joins imply subq
1929 $needs_subq = grep { $_ ne $attrs->{alias} } keys %{ $join_classifications->{restricting} || {} };
1932 # check if the head is composite (by now all joins are thrown out unless $needs_subq)
1934 (ref $attrs->{from}[0]) ne 'HASH'
1936 ref $attrs->{from}[0]{ $attrs->{from}[0]{-alias} }
1940 # do we need anything like a subquery?
1941 if (! $needs_subq) {
1942 # Most databases do not allow aliasing of tables in UPDATE/DELETE. Thus
1943 # a condition containing 'me' or other table prefixes will not work
1944 # at all. Tell SQLMaker to dequalify idents via a gross hack.
1946 my $sqla = $rsrc->schema->storage->sql_maker;
1947 local $sqla->{_dequalify_idents} = 1;
1948 \[ $sqla->_recurse_where($self->{cond}) ];
1952 # we got this far - means it is time to wrap a subquery
1953 my $idcols = $rsrc->_identifying_column_set || $self->throw_exception(
1955 "Unable to perform complex resultset %s() without an identifying set of columns on source '%s'",
1961 # make a new $rs selecting only the PKs (that's all we really need for the subq)
1962 delete $attrs->{$_} for qw/select as collapse/;
1963 $attrs->{columns} = [ map { "$attrs->{alias}.$_" } @$idcols ];
1965 # this will be consumed by the pruner waaaaay down the stack
1966 $attrs->{_force_prune_multiplying_joins} = 1;
1968 my $subrs = (ref $self)->new($rsrc, $attrs);
1970 if (@$idcols == 1) {
1971 $cond = { $idcols->[0] => { -in => $subrs->as_query } };
1973 elsif ($storage->_use_multicolumn_in) {
1974 # no syntax for calling this properly yet
1975 # !!! EXPERIMENTAL API !!! WILL CHANGE !!!
1976 $cond = $storage->sql_maker->_where_op_multicolumn_in (
1977 $idcols, # how do I convey a list of idents...? can binds reside on lhs?
1982 # if all else fails - get all primary keys and operate over a ORed set
1983 # wrap in a transaction for consistency
1984 # this is where the group_by/multiplication starts to matter
1988 # we do not need to check pre-multipliers, since if the premulti is there, its
1989 # parent (who is multi) will be there too
1990 keys %{ $join_classifications->{multiplying} || {} }
1992 # make sure if there is a supplied group_by it matches the columns compiled above
1993 # perfectly. Anything else can not be sanely executed on most databases so croak
1994 # right then and there
1995 if ($existing_group_by) {
1996 my @current_group_by = map
1997 { $_ =~ /\./ ? $_ : "$attrs->{alias}.$_" }
2002 join ("\x00", sort @current_group_by)
2004 join ("\x00", sort @{$attrs->{columns}} )
2006 $self->throw_exception (
2007 "You have just attempted a $op operation on a resultset which does group_by"
2008 . ' on columns other than the primary keys, while DBIC internally needs to retrieve'
2009 . ' the primary keys in a subselect. All sane RDBMS engines do not support this'
2010 . ' kind of queries. Please retry the operation with a modified group_by or'
2011 . ' without using one at all.'
2016 $subrs = $subrs->search({}, { group_by => $attrs->{columns} });
2019 $guard = $storage->txn_scope_guard;
2021 for my $row ($subrs->cursor->all) {
2023 { $idcols->[$_] => $row->[$_] }
2030 my $res = $cond ? $storage->$op (
2032 $op eq 'update' ? $values : (),
2036 $guard->commit if $guard;
2045 =item Arguments: \%values
2047 =item Return Value: $underlying_storage_rv
2051 Sets the specified columns in the resultset to the supplied values in a
2052 single query. Note that this will not run any accessor/set_column/update
2053 triggers, nor will it update any result object instances derived from this
2054 resultset (this includes the contents of the L<resultset cache|/set_cache>
2055 if any). See L</update_all> if you need to execute any on-update
2056 triggers or cascades defined either by you or a
2057 L<result component|DBIx::Class::Manual::Component/WHAT IS A COMPONENT>.
2059 The return value is a pass through of what the underlying
2060 storage backend returned, and may vary. See L<DBI/execute> for the most
2065 Note that L</update> does not process/deflate any of the values passed in.
2066 This is unlike the corresponding L<DBIx::Class::Row/update>. The user must
2067 ensure manually that any value passed to this method will stringify to
2068 something the RDBMS knows how to deal with. A notable example is the
2069 handling of L<DateTime> objects, for more info see:
2070 L<DBIx::Class::Manual::Cookbook/Formatting DateTime objects in queries>.
2075 my ($self, $values) = @_;
2076 $self->throw_exception('Values for update must be a hash')
2077 unless ref $values eq 'HASH';
2079 return $self->_rs_update_delete ('update', $values);
2086 =item Arguments: \%values
2088 =item Return Value: 1
2092 Fetches all objects and updates them one at a time via
2093 L<DBIx::Class::Row/update>. Note that C<update_all> will run DBIC defined
2094 triggers, while L</update> will not.
2099 my ($self, $values) = @_;
2100 $self->throw_exception('Values for update_all must be a hash')
2101 unless ref $values eq 'HASH';
2103 my $guard = $self->result_source->schema->txn_scope_guard;
2104 $_->update({%$values}) for $self->all; # shallow copy - update will mangle it
2113 =item Arguments: none
2115 =item Return Value: $underlying_storage_rv
2119 Deletes the rows matching this resultset in a single query. Note that this
2120 will not run any delete triggers, nor will it alter the
2121 L<in_storage|DBIx::Class::Row/in_storage> status of any result object instances
2122 derived from this resultset (this includes the contents of the
2123 L<resultset cache|/set_cache> if any). See L</delete_all> if you need to
2124 execute any on-delete triggers or cascades defined either by you or a
2125 L<result component|DBIx::Class::Manual::Component/WHAT IS A COMPONENT>.
2127 The return value is a pass through of what the underlying storage backend
2128 returned, and may vary. See L<DBI/execute> for the most common case.
2134 $self->throw_exception('delete does not accept any arguments')
2137 return $self->_rs_update_delete ('delete');
2144 =item Arguments: none
2146 =item Return Value: 1
2150 Fetches all objects and deletes them one at a time via
2151 L<DBIx::Class::Row/delete>. Note that C<delete_all> will run DBIC defined
2152 triggers, while L</delete> will not.
2158 $self->throw_exception('delete_all does not accept any arguments')
2161 my $guard = $self->result_source->schema->txn_scope_guard;
2162 $_->delete for $self->all;
2171 =item Arguments: [ \@column_list, \@row_values+ ] | [ \%col_data+ ]
2173 =item Return Value: L<\@result_objects|DBIx::Class::Manual::ResultClass> (scalar context) | L<@result_objects|DBIx::Class::Manual::ResultClass> (list context)
2177 Accepts either an arrayref of hashrefs or alternatively an arrayref of
2184 The context of this method call has an important effect on what is
2185 submitted to storage. In void context data is fed directly to fastpath
2186 insertion routines provided by the underlying storage (most often
2187 L<DBI/execute_for_fetch>), bypassing the L<new|DBIx::Class::Row/new> and
2188 L<insert|DBIx::Class::Row/insert> calls on the
2189 L<Result|DBIx::Class::Manual::ResultClass> class, including any
2190 augmentation of these methods provided by components. For example if you
2191 are using something like L<DBIx::Class::UUIDColumns> to create primary
2192 keys for you, you will find that your PKs are empty. In this case you
2193 will have to explicitly force scalar or list context in order to create
2198 In non-void (scalar or list) context, this method is simply a wrapper
2199 for L</create>. Depending on list or scalar context either a list of
2200 L<Result|DBIx::Class::Manual::ResultClass> objects or an arrayref
2201 containing these objects is returned.
2203 When supplying data in "arrayref of arrayrefs" invocation style, the
2204 first element should be a list of column names and each subsequent
2205 element should be a data value in the earlier specified column order.
2208 $schema->resultset("Artist")->populate([
2209 [ qw( artistid name ) ],
2210 [ 100, 'A Formally Unknown Singer' ],
2211 [ 101, 'A singer that jumped the shark two albums ago' ],
2212 [ 102, 'An actually cool singer' ],
2215 For the arrayref of hashrefs style each hashref should be a structure
2216 suitable for passing to L</create>. Multi-create is also permitted with
2219 $schema->resultset("Artist")->populate([
2220 { artistid => 4, name => 'Manufactured Crap', cds => [
2221 { title => 'My First CD', year => 2006 },
2222 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
2225 { artistid => 5, name => 'Angsty-Whiny Girl', cds => [
2226 { title => 'My parents sold me to a record company', year => 2005 },
2227 { title => 'Why Am I So Ugly?', year => 2006 },
2228 { title => 'I Got Surgery and am now Popular', year => 2007 }
2233 If you attempt a void-context multi-create as in the example above (each
2234 Artist also has the related list of CDs), and B<do not> supply the
2235 necessary autoinc foreign key information, this method will proxy to the
2236 less efficient L</create>, and then throw the Result objects away. In this
2237 case there are obviously no benefits to using this method over L</create>.
2244 # this is naive and just a quick check
2245 # the types will need to be checked more thoroughly when the
2246 # multi-source populate gets added
2248 ref $_[0] eq 'ARRAY'
2250 ( @{$_[0]} or return )
2252 ( ref $_[0][0] eq 'HASH' or ref $_[0][0] eq 'ARRAY' )
2255 ) or $self->throw_exception('Populate expects an arrayref of hashrefs or arrayref of arrayrefs');
2257 # FIXME - no cref handling
2258 # At this point assume either hashes or arrays
2260 my $rsrc = $self->result_source;
2261 my $storage = $rsrc->schema->storage;
2263 if(defined wantarray) {
2264 my (@results, $guard);
2266 if (ref $data->[0] eq 'ARRAY') {
2267 # column names only, nothing to do
2268 return if @$data == 1;
2270 $guard = $storage->txn_scope_guard
2274 { my $vals = $_; $self->new_result({ map { $data->[0][$_] => $vals->[$_] } 0..$#{$data->[0]} })->insert }
2275 @{$data}[1 .. $#$data]
2280 $guard = $storage->txn_scope_guard
2283 @results = map { $self->new_result($_)->insert } @$data;
2286 $guard->commit if $guard;
2287 return wantarray ? @results : \@results;
2290 # we have to deal with *possibly incomplete* related data
2291 # this means we have to walk the data structure twice
2292 # whether we want this or not
2293 # jnap, I hate you ;)
2294 my $rel_info = { map { $_ => $rsrc->relationship_info($_) } $rsrc->relationships };
2296 my ($colinfo, $colnames, $slices_with_rels);
2300 for my $i (0 .. $#$data) {
2302 my $current_slice_seen_rel_infos;
2304 ### Determine/Supplement collists
2305 ### BEWARE - This is a hot piece of code, a lot of weird idioms were used
2306 if( ref $data->[$i] eq 'ARRAY' ) {
2308 # positional(!) explicit column list
2310 # column names only, nothing to do
2311 return if @$data == 1;
2313 $colinfo->{$data->[0][$_]} = { pos => $_, name => $data->[0][$_] } and push @$colnames, $data->[0][$_]
2314 for 0 .. $#{$data->[0]};
2321 for (values %$colinfo) {
2322 if ($_->{is_rel} ||= (
2323 $rel_info->{$_->{name}}
2326 ref $data->[$i][$_->{pos}] eq 'ARRAY'
2328 ref $data->[$i][$_->{pos}] eq 'HASH'
2331 defined blessed $data->[$i][$_->{pos}]
2333 $data->[$i][$_->{pos}]->isa(
2334 $DBIx::Class::ResultSource::__expected_result_class_isa
2338 msg => 'Global $DBIx::Class::ResultSource::__expected_result_class_isa unexpectedly unset...'
2347 # moar sanity check... sigh
2348 for ( ref $data->[$i][$_->{pos}] eq 'ARRAY' ? @{$data->[$i][$_->{pos}]} : $data->[$i][$_->{pos}] ) {
2353 $DBIx::Class::ResultSource::__expected_result_class_isa
2357 msg => 'Global $DBIx::Class::ResultSource::__expected_result_class_isa unexpectedly unset...'
2361 carp_unique("Fast-path populate() with supplied related objects is not possible - falling back to regular create()");
2362 return my $throwaway = $self->populate(@_);
2366 push @$current_slice_seen_rel_infos, $rel_info->{$_->{name}};
2371 if ($current_slice_seen_rel_infos) {
2372 push @$slices_with_rels, { map { $colnames->[$_] => $data->[$i][$_] } 0 .. $#$colnames };
2374 # this is needed further down to decide whether or not to fallback to create()
2375 $colinfo->{$colnames->[$_]}{seen_null} ||= ! defined $data->[$i][$_]
2376 for 0 .. $#$colnames;
2379 elsif( ref $data->[$i] eq 'HASH' ) {
2381 for ( sort keys %{$data->[$i]} ) {
2383 $colinfo->{$_} ||= do {
2385 $self->throw_exception("Column '$_' must be present in supplied explicit column list")
2386 if $data_start; # it will be 0 on AoH, 1 on AoA
2388 push @$colnames, $_;
2391 { pos => $#$colnames, name => $_ }
2394 if ($colinfo->{$_}{is_rel} ||= (
2398 ref $data->[$i]{$_} eq 'ARRAY'
2400 ref $data->[$i]{$_} eq 'HASH'
2403 defined blessed $data->[$i]{$_}
2405 $data->[$i]{$_}->isa(
2406 $DBIx::Class::ResultSource::__expected_result_class_isa
2410 msg => 'Global $DBIx::Class::ResultSource::__expected_result_class_isa unexpectedly unset...'
2419 # moar sanity check... sigh
2420 for ( ref $data->[$i]{$_} eq 'ARRAY' ? @{$data->[$i]{$_}} : $data->[$i]{$_} ) {
2425 $DBIx::Class::ResultSource::__expected_result_class_isa
2429 msg => 'Global $DBIx::Class::ResultSource::__expected_result_class_isa unexpectedly unset...'
2433 carp_unique("Fast-path populate() with supplied related objects is not possible - falling back to regular create()");
2434 return my $throwaway = $self->populate(@_);
2438 push @$current_slice_seen_rel_infos, $rel_info->{$_};
2442 if ($current_slice_seen_rel_infos) {
2443 push @$slices_with_rels, $data->[$i];
2445 # this is needed further down to decide whether or not to fallback to create()
2446 $colinfo->{$_}{seen_null} ||= ! defined $data->[$i]{$_}
2447 for keys %{$data->[$i]};
2451 $self->throw_exception('Unexpected populate() data structure member type: ' . ref $data->[$i] );
2455 { $_->{attrs}{is_depends_on} }
2456 @{ $current_slice_seen_rel_infos || [] }
2458 carp_unique("Fast-path populate() of belongs_to relationship data is not possible - falling back to regular create()");
2459 return my $throwaway = $self->populate(@_);
2463 if( $slices_with_rels ) {
2465 # need to exclude the rel "columns"
2466 $colnames = [ grep { ! $colinfo->{$_}{is_rel} } @$colnames ];
2468 # extra sanity check - ensure the main source is in fact identifiable
2469 # the localizing of nullability is insane, but oh well... the use-case is legit
2470 my $ci = $rsrc->columns_info($colnames);
2472 $ci->{$_} = { %{$ci->{$_}}, is_nullable => 0 }
2473 for grep { ! $colinfo->{$_}{seen_null} } keys %$ci;
2475 unless( $rsrc->_identifying_column_set($ci) ) {
2476 carp_unique("Fast-path populate() of non-uniquely identifiable rows with related data is not possible - falling back to regular create()");
2477 return my $throwaway = $self->populate(@_);
2481 ### inherit the data locked in the conditions of the resultset
2482 my ($rs_data) = $self->_merge_with_rscond({});
2483 delete @{$rs_data}{@$colnames}; # passed-in stuff takes precedence
2485 # if anything left - decompose rs_data
2487 if (keys %$rs_data) {
2488 push @$rs_data_vals, $rs_data->{$_}
2489 for sort keys %$rs_data;
2494 $guard = $storage->txn_scope_guard
2495 if $slices_with_rels;
2497 ### main source data
2498 # FIXME - need to switch entirely to a coderef-based thing,
2499 # so that large sets aren't copied several times... I think
2500 $storage->_insert_bulk(
2502 [ @$colnames, sort keys %$rs_data ],
2504 ref $data->[$_] eq 'ARRAY'
2506 $slices_with_rels ? [ @{$data->[$_]}[0..$#$colnames], @{$rs_data_vals||[]} ] # the collist changed
2507 : $rs_data_vals ? [ @{$data->[$_]}, @$rs_data_vals ]
2510 : [ @{$data->[$_]}{@$colnames}, @{$rs_data_vals||[]} ]
2511 } $data_start .. $#$data ],
2514 ### do the children relationships
2515 if ( $slices_with_rels ) {
2516 my @rels = grep { $colinfo->{$_}{is_rel} } keys %$colinfo
2517 or die 'wtf... please report a bug with DBIC_TRACE=1 output (stacktrace)';
2519 for my $sl (@$slices_with_rels) {
2521 my ($main_proto, $main_proto_rs);
2522 for my $rel (@rels) {
2523 next unless defined $sl->{$rel};
2527 (map { $_ => $sl->{$_} } @$colnames),
2530 unless (defined $colinfo->{$rel}{rs}) {
2532 $colinfo->{$rel}{rs} = $rsrc->related_source($rel)->resultset;
2534 $colinfo->{$rel}{fk_map} = { reverse %{ $rsrc->_resolve_relationship_condition(
2537 # an API where these are optional would be too cumbersome,
2538 # instead always pass in some dummy values
2540 )->{identity_map} || {} } };
2544 $colinfo->{$rel}{rs}->search({ map # only so that we inherit them values properly, no actual search
2547 ( $main_proto_rs ||= $rsrc->resultset->search($main_proto) )
2548 ->get_column( $colinfo->{$rel}{fk_map}{$_} )
2552 keys %{$colinfo->{$rel}{fk_map}}
2553 })->populate( ref $sl->{$rel} eq 'ARRAY' ? $sl->{$rel} : [ $sl->{$rel} ] );
2560 $guard->commit if $guard;
2567 =item Arguments: none
2569 =item Return Value: L<$pager|Data::Page>
2573 Returns a L<Data::Page> object for the current resultset. Only makes
2574 sense for queries with a C<page> attribute.
2576 To get the full count of entries for a paged resultset, call
2577 C<total_entries> on the L<Data::Page> object.
2584 return $self->{pager} if $self->{pager};
2586 my $attrs = $self->{attrs};
2587 if (!defined $attrs->{page}) {
2588 $self->throw_exception("Can't create pager for non-paged rs");
2590 elsif ($attrs->{page} <= 0) {
2591 $self->throw_exception('Invalid page number (page-numbers are 1-based)');
2593 $attrs->{rows} ||= 10;
2595 # throw away the paging flags and re-run the count (possibly
2596 # with a subselect) to get the real total count
2597 my $count_attrs = { %$attrs };
2598 delete @{$count_attrs}{qw/rows offset page pager/};
2600 my $total_rs = (ref $self)->new($self->result_source, $count_attrs);
2602 require DBIx::Class::ResultSet::Pager;
2603 return $self->{pager} = DBIx::Class::ResultSet::Pager->new(
2604 sub { $total_rs->count }, #lazy-get the total
2606 $self->{attrs}{page},
2614 =item Arguments: $page_number
2616 =item Return Value: L<$resultset|/search>
2620 Returns a resultset for the $page_number page of the resultset on which page
2621 is called, where each page contains a number of rows equal to the 'rows'
2622 attribute set on the resultset (10 by default).
2627 my ($self, $page) = @_;
2628 return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
2635 =item Arguments: \%col_data
2637 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2641 Creates a new result object in the resultset's result class and returns
2642 it. The row is not inserted into the database at this point, call
2643 L<DBIx::Class::Row/insert> to do that. Calling L<DBIx::Class::Row/in_storage>
2644 will tell you whether the result object has been inserted or not.
2646 Passes the hashref of input on to L<DBIx::Class::Row/new>.
2651 my ($self, $values) = @_;
2653 $self->throw_exception( "Result object instantiation requires a single hashref argument" )
2654 if @_ > 2 or ref $values ne 'HASH';
2656 my ($merged_cond, $cols_from_relations) = $self->_merge_with_rscond($values);
2658 my $new = $self->result_class->new({
2660 ( @$cols_from_relations
2661 ? (-cols_from_relations => $cols_from_relations)
2664 -result_source => $self->result_source, # DO NOT REMOVE THIS, REQUIRED
2668 reftype($new) eq 'HASH'
2674 carp_unique (sprintf (
2675 "%s->new returned a blessed empty hashref - a strong indicator something is wrong with its inheritance chain",
2676 $self->result_class,
2683 # _merge_with_rscond
2685 # Takes a simple hash of K/V data and returns its copy merged with the
2686 # condition already present on the resultset. Additionally returns an
2687 # arrayref of value/condition names, which were inferred from related
2688 # objects (this is needed for in-memory related objects)
2689 sub _merge_with_rscond {
2690 my ($self, $data) = @_;
2692 my ($implied_data, @cols_from_relations);
2694 my $alias = $self->{attrs}{alias};
2696 if (! defined $self->{cond}) {
2697 # just massage $data below
2699 elsif ($self->{cond} eq UNRESOLVABLE_CONDITION) {
2700 $implied_data = $self->{attrs}{related_objects}; # nothing might have been inserted yet
2701 @cols_from_relations = keys %{ $implied_data || {} };
2704 my $eqs = extract_equality_conditions( $self->{cond}, 'consider_nulls' );
2705 $implied_data = { map {
2706 ( ($eqs->{$_}||'') eq UNRESOLVABLE_CONDITION ) ? () : ( $_ => $eqs->{$_} )
2712 { %{ $self->_remove_alias($_, $alias) } }
2713 # precedence must be given to passed values over values inherited from
2714 # the cond, so the order here is important.
2715 ( $implied_data||(), $data)
2717 \@cols_from_relations
2721 # _has_resolved_attr
2723 # determines if the resultset defines at least one
2724 # of the attributes supplied
2726 # used to determine if a subquery is necessary
2728 # supports some virtual attributes:
2730 # This will scan for any joins being present on the resultset.
2731 # It is not a mere key-search but a deep inspection of {from}
2734 sub _has_resolved_attr {
2735 my ($self, @attr_names) = @_;
2737 my $attrs = $self->_resolved_attrs;
2741 for my $n (@attr_names) {
2742 if (grep { $n eq $_ } (qw/-join/) ) {
2743 $extra_checks{$n}++;
2747 my $attr = $attrs->{$n};
2749 next if not defined $attr;
2751 if (ref $attr eq 'HASH') {
2752 return 1 if keys %$attr;
2754 elsif (ref $attr eq 'ARRAY') {
2762 # a resolved join is expressed as a multi-level from
2764 $extra_checks{-join}
2766 ref $attrs->{from} eq 'ARRAY'
2768 @{$attrs->{from}} > 1
2776 # Remove the specified alias from the specified query hash. A copy is made so
2777 # the original query is not modified.
2780 my ($self, $query, $alias) = @_;
2782 my %orig = %{ $query || {} };
2785 foreach my $key (keys %orig) {
2787 $unaliased{$key} = $orig{$key};
2790 $unaliased{$1} = $orig{$key}
2791 if $key =~ m/^(?:\Q$alias\E\.)?([^.]+)$/;
2801 =item Arguments: none
2803 =item Return Value: \[ $sql, L<@bind_values|/DBIC BIND VALUES> ]
2807 Returns the SQL query and bind vars associated with the invocant.
2809 This is generally used as the RHS for a subquery.
2816 my $attrs = { %{ $self->_resolved_attrs } };
2818 my $aq = $self->result_source->schema->storage->_select_args_to_query (
2819 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
2829 =item Arguments: \%col_data, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
2831 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2835 my $artist = $schema->resultset('Artist')->find_or_new(
2836 { artist => 'fred' }, { key => 'artists' });
2838 $cd->cd_to_producer->find_or_new({ producer => $producer },
2839 { key => 'primary' });
2841 Find an existing record from this resultset using L</find>. if none exists,
2842 instantiate a new result object and return it. The object will not be saved
2843 into your storage until you call L<DBIx::Class::Row/insert> on it.
2845 You most likely want this method when looking for existing rows using a unique
2846 constraint that is not the primary key, or looking for related rows.
2848 If you want objects to be saved immediately, use L</find_or_create> instead.
2850 B<Note>: Make sure to read the documentation of L</find> and understand the
2851 significance of the C<key> attribute, as its lack may skew your search, and
2852 subsequently result in spurious new objects.
2854 B<Note>: Take care when using C<find_or_new> with a table having
2855 columns with default values that you intend to be automatically
2856 supplied by the database (e.g. an auto_increment primary key column).
2857 In normal usage, the value of such columns should NOT be included at
2858 all in the call to C<find_or_new>, even when set to C<undef>.
2864 my $attrs = (@_ > 1 && ref $_[-1] eq 'HASH' ? pop(@_) : {});
2865 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
2866 if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2869 return $self->new_result($hash);
2876 =item Arguments: \%col_data
2878 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2882 Attempt to create a single new row or a row with multiple related rows
2883 in the table represented by the resultset (and related tables). This
2884 will not check for duplicate rows before inserting, use
2885 L</find_or_create> to do that.
2887 To create one row for this resultset, pass a hashref of key/value
2888 pairs representing the columns of the table and the values you wish to
2889 store. If the appropriate relationships are set up, foreign key fields
2890 can also be passed an object representing the foreign row, and the
2891 value will be set to its primary key.
2893 To create related objects, pass a hashref of related-object column values
2894 B<keyed on the relationship name>. If the relationship is of type C<multi>
2895 (L<DBIx::Class::Relationship/has_many>) - pass an arrayref of hashrefs.
2896 The process will correctly identify columns holding foreign keys, and will
2897 transparently populate them from the keys of the corresponding relation.
2898 This can be applied recursively, and will work correctly for a structure
2899 with an arbitrary depth and width, as long as the relationships actually
2900 exists and the correct column data has been supplied.
2902 Instead of hashrefs of plain related data (key/value pairs), you may
2903 also pass new or inserted objects. New objects (not inserted yet, see
2904 L</new_result>), will be inserted into their appropriate tables.
2906 Effectively a shortcut for C<< ->new_result(\%col_data)->insert >>.
2908 Example of creating a new row.
2910 $person_rs->create({
2911 name=>"Some Person",
2912 email=>"somebody@someplace.com"
2915 Example of creating a new row and also creating rows in a related C<has_many>
2916 or C<has_one> resultset. Note Arrayref.
2919 { artistid => 4, name => 'Manufactured Crap', cds => [
2920 { title => 'My First CD', year => 2006 },
2921 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
2926 Example of creating a new row and also creating a row in a related
2927 C<belongs_to> resultset. Note Hashref.
2930 title=>"Music for Silly Walks",
2933 name=>"Silly Musician",
2941 When subclassing ResultSet never attempt to override this method. Since
2942 it is a simple shortcut for C<< $self->new_result($attrs)->insert >>, a
2943 lot of the internals simply never call it, so your override will be
2944 bypassed more often than not. Override either L<DBIx::Class::Row/new>
2945 or L<DBIx::Class::Row/insert> depending on how early in the
2946 L</create> process you need to intervene. See also warning pertaining to
2953 sub create :DBIC_method_is_indirect_sugar {
2954 #my ($self, $col_data) = @_;
2955 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
2956 return shift->new_result(shift)->insert;
2959 =head2 find_or_create
2963 =item Arguments: \%col_data, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
2965 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
2969 $cd->cd_to_producer->find_or_create({ producer => $producer },
2970 { key => 'primary' });
2972 Tries to find a record based on its primary key or unique constraints; if none
2973 is found, creates one and returns that instead.
2975 my $cd = $schema->resultset('CD')->find_or_create({
2977 artist => 'Massive Attack',
2978 title => 'Mezzanine',
2982 Also takes an optional C<key> attribute, to search by a specific key or unique
2983 constraint. For example:
2985 my $cd = $schema->resultset('CD')->find_or_create(
2987 artist => 'Massive Attack',
2988 title => 'Mezzanine',
2990 { key => 'cd_artist_title' }
2993 B<Note>: Make sure to read the documentation of L</find> and understand the
2994 significance of the C<key> attribute, as its lack may skew your search, and
2995 subsequently result in spurious row creation.
2997 B<Note>: Because find_or_create() reads from the database and then
2998 possibly inserts based on the result, this method is subject to a race
2999 condition. Another process could create a record in the table after
3000 the find has completed and before the create has started. To avoid
3001 this problem, use find_or_create() inside a transaction.
3003 B<Note>: Take care when using C<find_or_create> with a table having
3004 columns with default values that you intend to be automatically
3005 supplied by the database (e.g. an auto_increment primary key column).
3006 In normal usage, the value of such columns should NOT be included at
3007 all in the call to C<find_or_create>, even when set to C<undef>.
3009 See also L</find> and L</update_or_create>. For information on how to declare
3010 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
3012 If you need to know if an existing row was found or a new one created use
3013 L</find_or_new> and L<DBIx::Class::Row/in_storage> instead. Don't forget
3014 to call L<DBIx::Class::Row/insert> to save the newly created row to the
3017 my $cd = $schema->resultset('CD')->find_or_new({
3019 artist => 'Massive Attack',
3020 title => 'Mezzanine',
3024 if( !$cd->in_storage ) {
3031 sub find_or_create {
3033 my $attrs = (@_ > 1 && ref $_[-1] eq 'HASH' ? pop(@_) : {});
3034 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
3035 if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
3038 return $self->new_result($hash)->insert;
3041 =head2 update_or_create
3045 =item Arguments: \%col_data, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
3047 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
3051 $resultset->update_or_create({ col => $val, ... });
3053 Like L</find_or_create>, but if a row is found it is immediately updated via
3054 C<< $found_row->update (\%col_data) >>.
3057 Takes an optional C<key> attribute to search on a specific unique constraint.
3060 # In your application
3061 my $cd = $schema->resultset('CD')->update_or_create(
3063 artist => 'Massive Attack',
3064 title => 'Mezzanine',
3067 { key => 'cd_artist_title' }
3070 $cd->cd_to_producer->update_or_create({
3071 producer => $producer,
3077 B<Note>: Make sure to read the documentation of L</find> and understand the
3078 significance of the C<key> attribute, as its lack may skew your search, and
3079 subsequently result in spurious row creation.
3081 B<Note>: Take care when using C<update_or_create> with a table having
3082 columns with default values that you intend to be automatically
3083 supplied by the database (e.g. an auto_increment primary key column).
3084 In normal usage, the value of such columns should NOT be included at
3085 all in the call to C<update_or_create>, even when set to C<undef>.
3087 See also L</find> and L</find_or_create>. For information on how to declare
3088 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
3090 If you need to know if an existing row was updated or a new one created use
3091 L</update_or_new> and L<DBIx::Class::Row/in_storage> instead. Don't forget
3092 to call L<DBIx::Class::Row/insert> to save the newly created row to the
3097 sub update_or_create {
3099 my $attrs = (@_ > 1 && ref $_[-1] eq 'HASH' ? pop(@_) : {});
3100 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
3102 my $row = $self->find($cond, $attrs);
3104 $row->update($cond);
3108 return $self->new_result($cond)->insert;
3111 =head2 update_or_new
3115 =item Arguments: \%col_data, { key => $unique_constraint, L<%attrs|/ATTRIBUTES> }?
3117 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
3121 $resultset->update_or_new({ col => $val, ... });
3123 Like L</find_or_new> but if a row is found it is immediately updated via
3124 C<< $found_row->update (\%col_data) >>.
3128 # In your application
3129 my $cd = $schema->resultset('CD')->update_or_new(
3131 artist => 'Massive Attack',
3132 title => 'Mezzanine',
3135 { key => 'cd_artist_title' }
3138 if ($cd->in_storage) {
3139 # the cd was updated
3142 # the cd is not yet in the database, let's insert it
3146 B<Note>: Make sure to read the documentation of L</find> and understand the
3147 significance of the C<key> attribute, as its lack may skew your search, and
3148 subsequently result in spurious new objects.
3150 B<Note>: Take care when using C<update_or_new> with a table having
3151 columns with default values that you intend to be automatically
3152 supplied by the database (e.g. an auto_increment primary key column).
3153 In normal usage, the value of such columns should NOT be included at
3154 all in the call to C<update_or_new>, even when set to C<undef>.
3156 See also L</find>, L</find_or_create> and L</find_or_new>.
3162 my $attrs = ( @_ > 1 && ref $_[-1] eq 'HASH' ? pop(@_) : {} );
3163 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
3165 my $row = $self->find( $cond, $attrs );
3166 if ( defined $row ) {
3167 $row->update($cond);
3171 return $self->new_result($cond);
3178 =item Arguments: none
3180 =item Return Value: L<\@result_objs|DBIx::Class::Manual::ResultClass> | undef
3184 Gets the contents of the cache for the resultset, if the cache is set.
3186 The cache is populated either by using the L</prefetch> attribute to
3187 L</search> or by calling L</set_cache>.
3199 =item Arguments: L<\@result_objs|DBIx::Class::Manual::ResultClass>
3201 =item Return Value: L<\@result_objs|DBIx::Class::Manual::ResultClass>
3205 Sets the contents of the cache for the resultset. Expects an arrayref
3206 of objects of the same class as those produced by the resultset. Note that
3207 if the cache is set, the resultset will return the cached objects rather
3208 than re-querying the database even if the cache attr is not set.
3210 The contents of the cache can also be populated by using the
3211 L</prefetch> attribute to L</search>.
3216 my ( $self, $data ) = @_;
3217 $self->throw_exception("set_cache requires an arrayref")
3218 if defined($data) && (ref $data ne 'ARRAY');
3219 $self->{all_cache} = $data;
3226 =item Arguments: none
3228 =item Return Value: undef
3232 Clears the cache for the resultset.
3237 shift->set_cache(undef);
3244 =item Arguments: none
3246 =item Return Value: true, if the resultset has been paginated
3254 return !!$self->{attrs}{page};
3261 =item Arguments: none
3263 =item Return Value: true, if the resultset has been ordered with C<order_by>.
3271 return scalar $self->result_source->schema->storage->_extract_order_criteria($self->{attrs}{order_by});
3274 =head2 related_resultset
3278 =item Arguments: $rel_name
3280 =item Return Value: L<$resultset|/search>
3284 Returns a related resultset for the supplied relationship name.
3286 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
3290 sub related_resultset {
3291 $_[0]->throw_exception(
3292 'Extra arguments to $rs->related_resultset() were always quietly '
3293 . 'discarded without consideration, you need to switch to '
3294 . '...->related_resultset( $relname )->search_rs( $search, $args ) instead.'
3297 return $_[0]->{related_resultsets}{$_[1]}
3298 if defined $_[0]->{related_resultsets}{$_[1]};
3300 my ($self, $rel) = @_;
3302 return $self->{related_resultsets}{$rel} = do {
3303 my $rsrc = $self->result_source;
3304 my $rel_info = $rsrc->relationship_info($rel);
3306 $self->throw_exception(
3307 "search_related: result source '" . $rsrc->source_name .
3308 "' has no such relationship $rel")
3311 my $attrs = $self->_chain_relationship($rel);
3313 # Previously this atribute was deleted (instead of being set as it is now)
3314 # Doing so seems to be harmless in all available test permutations
3315 # See also 01d59a6a6 and mst's comment below
3317 $attrs->{alias} = $rsrc->schema->storage->relname_to_table_alias(
3319 $attrs->{seen_join}{$rel}
3322 # since this is search_related, and we already slid the select window inwards
3323 # (the select/as attrs were deleted in the beginning), we need to flip all
3324 # left joins to inner, so we get the expected results
3326 # The DBIC relationship chaining implementation is pretty simple - every
3327 # new related_relationship is pushed onto the {from} stack, and the {select}
3328 # window simply slides further in. This means that when we count somewhere
3329 # in the middle, we got to make sure that everything in the join chain is an
3330 # actual inner join, otherwise the count will come back with unpredictable
3331 # results (a resultset may be generated with _some_ rows regardless of if
3332 # the relation which the $rs currently selects has rows or not). E.g.
3333 # $artist_rs->cds->count - normally generates:
3334 # SELECT COUNT( * ) FROM artist me LEFT JOIN cd cds ON cds.artist = me.artistid
3335 # which actually returns the number of artists * (number of cds || 1)
3337 # So what we do here is crawl {from}, determine if the current alias is at
3338 # the top of the stack, and if not - make sure the chain is inner-joined down
3341 my $switch_branch = find_join_path_to_alias(
3346 if ( @{ $switch_branch || [] } ) {
3348 # So it looks like we will have to switch some stuff around.
3349 # local() is useless here as we will be leaving the scope
3350 # anyway, and deep cloning is just too fucking expensive
3351 # So replace the first hashref in the node arrayref manually
3352 my @new_from = $attrs->{from}[0];
3353 my $sw_idx = { map { (values %$_), 1 } @$switch_branch }; #there's one k/v per join-path
3355 for my $j ( @{$attrs->{from}}[ 1 .. $#{$attrs->{from}} ] ) {
3356 my $jalias = $j->[0]{-alias};
3358 if ($sw_idx->{$jalias}) {
3359 my %attrs = %{$j->[0]};
3360 delete $attrs{-join_type};
3371 $attrs->{from} = \@new_from;
3375 #XXX - temp fix for result_class bug. There likely is a more elegant fix -groditi
3376 delete $attrs->{result_class};
3380 # The reason we do this now instead of passing the alias to the
3381 # search_rs below is that if you wrap/overload resultset on the
3382 # source you need to know what alias it's -going- to have for things
3383 # to work sanely (e.g. RestrictWithObject wants to be able to add
3384 # extra query restrictions, and these may need to be $alias.)
3385 # -- mst ~ 2007 (01d59a6a6)
3387 # FIXME - this seems to be no longer neccessary (perhaps due to the
3388 # advances in relcond resolution. Testing DBIC::S::RWO and its only
3389 # dependent (as of Jun 2015 ) does not yield any difference with or
3390 # without this line. Nevertheless keep it as is for now, to minimize
3391 # churn, there is enough potential for breakage in 0.0829xx as it is
3392 # -- ribasushi Jun 2015
3394 my $rel_source = $rsrc->related_source($rel);
3395 local $rel_source->resultset_attributes->{alias} = $attrs->{alias};
3397 $rel_source->resultset->search_rs( undef, $attrs );
3400 if (my $cache = $self->get_cache) {
3401 my @related_cache = map
3402 { $_->related_resultset($rel)->get_cache || () }
3406 $new->set_cache([ map @$_, @related_cache ]) if @related_cache == @$cache;
3413 =head2 current_source_alias
3417 =item Arguments: none
3419 =item Return Value: $source_alias
3423 Returns the current table alias for the result source this resultset is built
3424 on, that will be used in the SQL query. Usually it is C<me>.
3426 Currently the source alias that refers to the result set returned by a
3427 L</search>/L</find> family method depends on how you got to the resultset: it's
3428 C<me> by default, but eg. L</search_related> aliases it to the related result
3429 source name (and keeps C<me> referring to the original result set). The long
3430 term goal is to make L<DBIx::Class> always alias the current resultset as C<me>
3431 (and make this method unnecessary).
3433 Thus it's currently necessary to use this method in predefined queries (see
3434 L<DBIx::Class::Manual::Cookbook/Predefined searches>) when referring to the
3435 source alias of the current result set:
3437 # in a result set class
3439 my ($self, $user) = @_;
3441 my $me = $self->current_source_alias;
3443 return $self->search({
3444 "$me.modified" => $user->id,
3448 The alias of L<newly created resultsets|/search> can be altered by the
3449 L<alias attribute|/alias>.
3453 sub current_source_alias {
3454 return (shift->{attrs} || {})->{alias} || 'me';
3457 =head2 as_subselect_rs
3461 =item Arguments: none
3463 =item Return Value: L<$resultset|/search>
3467 Act as a barrier to SQL symbols. The resultset provided will be made into a
3468 "virtual view" by including it as a subquery within the from clause. From this
3469 point on, any joined tables are inaccessible to ->search on the resultset (as if
3470 it were simply where-filtered without joins). For example:
3472 my $rs = $schema->resultset('Bar')->search({'x.name' => 'abc'},{ join => 'x' });
3474 # 'x' now pollutes the query namespace
3476 # So the following works as expected
3477 my $ok_rs = $rs->search({'x.other' => 1});
3479 # But this doesn't: instead of finding a 'Bar' related to two x rows (abc and
3480 # def) we look for one row with contradictory terms and join in another table
3481 # (aliased 'x_2') which we never use
3482 my $broken_rs = $rs->search({'x.name' => 'def'});
3484 my $rs2 = $rs->as_subselect_rs;
3486 # doesn't work - 'x' is no longer accessible in $rs2, having been sealed away
3487 my $not_joined_rs = $rs2->search({'x.other' => 1});
3489 # works as expected: finds a 'table' row related to two x rows (abc and def)
3490 my $correctly_joined_rs = $rs2->search({'x.name' => 'def'});
3492 Another example of when one might use this would be to select a subset of
3493 columns in a group by clause:
3495 my $rs = $schema->resultset('Bar')->search(undef, {
3496 group_by => [qw{ id foo_id baz_id }],
3497 })->as_subselect_rs->search(undef, {
3498 columns => [qw{ id foo_id }]
3501 In the above example normally columns would have to be equal to the group by,
3502 but because we isolated the group by into a subselect the above works.
3506 sub as_subselect_rs {
3509 my $attrs = $self->_resolved_attrs;
3511 my $fresh_rs = (ref $self)->new (
3512 $self->result_source
3515 # these pieces will be locked in the subquery
3516 delete $fresh_rs->{cond};
3517 delete @{$fresh_rs->{attrs}}{qw/where bind/};
3519 return $fresh_rs->search( {}, {
3521 $attrs->{alias} => $self->as_query,
3522 -alias => $attrs->{alias},
3523 -rsrc => $self->result_source,
3525 alias => $attrs->{alias},
3529 # This code is called by search_related, and makes sure there
3530 # is clear separation between the joins before, during, and
3531 # after the relationship. This information is needed later
3532 # in order to properly resolve prefetch aliases (any alias
3533 # with a relation_chain_depth less than the depth of the
3534 # current prefetch is not considered)
3536 # The increments happen twice per join. An even number means a
3537 # relationship specified via a search_related, whereas an odd
3538 # number indicates a join/prefetch added via attributes
3540 # Also this code will wrap the current resultset (the one we
3541 # chain to) in a subselect IFF it contains limiting attributes
3542 sub _chain_relationship {
3543 my ($self, $rel) = @_;
3544 my $source = $self->result_source;
3545 my $attrs = { %{$self->{attrs}||{}} };
3547 # we need to take the prefetch the attrs into account before we
3548 # ->_resolve_join as otherwise they get lost - captainL
3549 my $join = $self->_merge_joinpref_attr( $attrs->{join}, $attrs->{prefetch} );
3551 delete @{$attrs}{qw/join prefetch collapse group_by distinct _grouped_by_distinct select as columns +select +as +columns/};
3553 my $seen = { %{ (delete $attrs->{seen_join}) || {} } };
3556 my @force_subq_attrs = qw/offset rows group_by having/;
3559 ($attrs->{from} && ref $attrs->{from} ne 'ARRAY')
3561 $self->_has_resolved_attr (@force_subq_attrs)
3563 # Nuke the prefetch (if any) before the new $rs attrs
3564 # are resolved (prefetch is useless - we are wrapping
3565 # a subquery anyway).
3566 my $rs_copy = $self->search;
3567 $rs_copy->{attrs}{join} = $self->_merge_joinpref_attr (
3568 $rs_copy->{attrs}{join},
3569 delete $rs_copy->{attrs}{prefetch},
3574 -alias => $attrs->{alias},
3575 $attrs->{alias} => $rs_copy->as_query,
3577 delete @{$attrs}{@force_subq_attrs, qw/where bind/};
3578 $seen->{-relation_chain_depth} = 0;
3580 elsif ($attrs->{from}) { #shallow copy suffices
3581 $from = [ @{$attrs->{from}} ];
3586 -alias => $attrs->{alias},
3587 $attrs->{alias} => $source->from,
3591 my $jpath = ($seen->{-relation_chain_depth})
3592 ? $from->[-1][0]{-join_path}
3595 my @requested_joins = $source->_resolve_join(
3602 push @$from, @requested_joins;
3604 $seen->{-relation_chain_depth}++;
3606 # if $self already had a join/prefetch specified on it, the requested
3607 # $rel might very well be already included. What we do in this case
3608 # is effectively a no-op (except that we bump up the chain_depth on
3609 # the join in question so we could tell it *is* the search_related)
3612 # we consider the last one thus reverse
3613 for my $j (reverse @requested_joins) {
3614 my ($last_j) = keys %{$j->[0]{-join_path}[-1]};
3615 if ($rel eq $last_j) {
3616 $j->[0]{-relation_chain_depth}++;
3622 unless ($already_joined) {
3623 push @$from, $source->_resolve_join(
3631 $seen->{-relation_chain_depth}++;
3633 return {%$attrs, from => $from, seen_join => $seen};
3636 sub _resolved_attrs {
3638 return $self->{_attrs} if $self->{_attrs};
3640 my $attrs = { %{ $self->{attrs} || {} } };
3641 my $source = $attrs->{result_source} = $self->result_source;
3642 my $alias = $attrs->{alias};
3644 $self->throw_exception("Specifying distinct => 1 in conjunction with collapse => 1 is unsupported")
3645 if $attrs->{collapse} and $attrs->{distinct};
3648 # Sanity check the paging attributes
3649 # SQLMaker does it too, but in case of a software_limit we'll never get there
3650 if (defined $attrs->{offset}) {
3651 $self->throw_exception('A supplied offset attribute must be a non-negative integer')
3652 if ( $attrs->{offset} =~ /[^0-9]/ or $attrs->{offset} < 0 );
3654 if (defined $attrs->{rows}) {
3655 $self->throw_exception("The rows attribute must be a positive integer if present")
3656 if ( $attrs->{rows} =~ /[^0-9]/ or $attrs->{rows} <= 0 );
3659 # normalize where condition
3660 $attrs->{where} = normalize_sqla_condition( $attrs->{where} )
3663 # default selection list
3664 $attrs->{columns} = [ $source->columns ]
3665 unless grep { exists $attrs->{$_} } qw/columns cols select as/;
3667 # merge selectors together
3668 for (qw/columns select as/) {
3669 $attrs->{$_} = $self->_merge_attr($attrs->{$_}, delete $attrs->{"+$_"})
3670 if $attrs->{$_} or $attrs->{"+$_"};
3673 # disassemble columns
3675 if (my $cols = delete $attrs->{columns}) {
3676 for my $c (ref $cols eq 'ARRAY' ? @$cols : $cols) {
3677 if (ref $c eq 'HASH') {
3678 for my $as (sort keys %$c) {
3679 push @sel, $c->{$as};
3690 # when trying to weed off duplicates later do not go past this point -
3691 # everything added from here on is unbalanced "anyone's guess" stuff
3692 my $dedup_stop_idx = $#as;
3694 push @as, @{ ref $attrs->{as} eq 'ARRAY' ? $attrs->{as} : [ $attrs->{as} ] }
3696 push @sel, @{ ref $attrs->{select} eq 'ARRAY' ? $attrs->{select} : [ $attrs->{select} ] }
3697 if $attrs->{select};
3699 # assume all unqualified selectors to apply to the current alias (legacy stuff)
3700 $_ = (ref $_ or $_ =~ /\./) ? $_ : "$alias.$_" for @sel;
3702 # disqualify all $alias.col as-bits (inflate-map mandated)
3703 $_ = ($_ =~ /^\Q$alias.\E(.+)$/) ? $1 : $_ for @as;
3705 # de-duplicate the result (remove *identical* select/as pairs)
3706 # and also die on duplicate {as} pointing to different {select}s
3707 # not using a c-style for as the condition is prone to shrinkage
3710 while ($i <= $dedup_stop_idx) {
3711 if ($seen->{"$sel[$i] \x00\x00 $as[$i]"}++) {
3716 elsif ($seen->{$as[$i]}++) {
3717 $self->throw_exception(
3718 "inflate_result() alias '$as[$i]' specified twice with different SQL-side {select}-ors"
3726 $attrs->{select} = \@sel;
3727 $attrs->{as} = \@as;
3729 $attrs->{from} ||= [{
3731 -alias => $self->{attrs}{alias},
3732 $self->{attrs}{alias} => $source->from,
3735 if ( $attrs->{join} || $attrs->{prefetch} ) {
3737 $self->throw_exception ('join/prefetch can not be used with a custom {from}')
3738 if ref $attrs->{from} ne 'ARRAY';
3740 my $join = (delete $attrs->{join}) || {};
3742 if ( defined $attrs->{prefetch} ) {
3743 $join = $self->_merge_joinpref_attr( $join, $attrs->{prefetch} );
3746 $attrs->{from} = # have to copy here to avoid corrupting the original
3748 @{ $attrs->{from} },
3749 $source->_resolve_join(
3752 { %{ $attrs->{seen_join} || {} } },
3753 ( $attrs->{seen_join} && keys %{$attrs->{seen_join}})
3754 ? $attrs->{from}[-1][0]{-join_path}
3762 for my $attr (qw(order_by group_by)) {
3764 if ( defined $attrs->{$attr} ) {
3766 ref( $attrs->{$attr} ) eq 'ARRAY'
3767 ? [ @{ $attrs->{$attr} } ]
3768 : [ $attrs->{$attr} || () ]
3771 delete $attrs->{$attr} unless @{$attrs->{$attr}};
3776 # set collapse default based on presence of prefetch
3779 defined $attrs->{prefetch}
3781 $prefetch = $self->_merge_joinpref_attr( {}, delete $attrs->{prefetch} )
3783 $self->throw_exception("Specifying prefetch in conjunction with an explicit collapse => 0 is unsupported")
3784 if defined $attrs->{collapse} and ! $attrs->{collapse};
3786 $attrs->{collapse} = 1;
3790 # run through the resulting joinstructure (starting from our current slot)
3791 # and unset collapse if proven unnecessary
3793 # also while we are at it find out if the current root source has
3794 # been premultiplied by previous related_source chaining
3796 # this allows to predict whether a root object with all other relation
3797 # data set to NULL is in fact unique
3798 if ($attrs->{collapse}) {
3800 if (ref $attrs->{from} eq 'ARRAY') {
3802 if (@{$attrs->{from}} == 1) {
3803 # no joins - no collapse
3804 $attrs->{collapse} = 0;
3807 # find where our table-spec starts
3808 my @fromlist = @{$attrs->{from}};
3810 my $t = shift @fromlist;
3813 # me vs join from-spec distinction - a ref means non-root
3814 if (ref $t eq 'ARRAY') {
3816 $is_multi ||= ! $t->{-is_single};
3818 last if ($t->{-alias} && $t->{-alias} eq $alias);
3819 $attrs->{_main_source_premultiplied} ||= $is_multi;
3822 # no non-singles remaining, nor any premultiplication - nothing to collapse
3824 ! $attrs->{_main_source_premultiplied}
3826 ! grep { ! $_->[0]{-is_single} } @fromlist
3828 $attrs->{collapse} = 0;
3834 # if we can not analyze the from - err on the side of safety
3835 $attrs->{_main_source_premultiplied} = 1;
3840 # generate the distinct induced group_by before injecting the prefetched select/as parts
3841 if (delete $attrs->{distinct}) {
3842 if ($attrs->{group_by}) {
3843 carp_unique ("Useless use of distinct on a grouped resultset ('distinct' is ignored when a 'group_by' is present)");
3846 $attrs->{_grouped_by_distinct} = 1;
3847 # distinct affects only the main selection part, not what prefetch may add below
3848 ($attrs->{group_by}, my $new_order) = $source->schema->storage->_group_over_selection($attrs);
3850 # FIXME possibly ignore a rewritten order_by (may turn out to be an issue)
3851 # The thinking is: if we are collapsing the subquerying prefetch engine will
3852 # rip stuff apart for us anyway, and we do not want to have a potentially
3853 # function-converted external order_by
3854 # ( there is an explicit if ( collapse && _grouped_by_distinct ) check in DBIHacks )
3855 $attrs->{order_by} = $new_order unless $attrs->{collapse};
3860 # generate selections based on the prefetch helper
3863 $self->throw_exception("Unable to prefetch, resultset contains an unnamed selector $attrs->{_dark_selector}{string}")
3864 if $attrs->{_dark_selector};
3866 # this is a separate structure (we don't look in {from} directly)
3867 # as the resolver needs to shift things off the lists to work
3868 # properly (identical-prefetches on different branches)
3869 my $joined_node_aliases_map = {};
3870 if (ref $attrs->{from} eq 'ARRAY') {
3872 my $start_depth = $attrs->{seen_join}{-relation_chain_depth} || 0;
3874 for my $j ( @{$attrs->{from}}[1 .. $#{$attrs->{from}} ] ) {
3875 next unless $j->[0]{-alias};
3876 next unless $j->[0]{-join_path};
3877 next if ($j->[0]{-relation_chain_depth} || 0) < $start_depth;
3879 my @jpath = map { keys %$_ } @{$j->[0]{-join_path}};
3881 my $p = $joined_node_aliases_map;
3882 $p = $p->{$_} ||= {} for @jpath[ ($start_depth/2) .. $#jpath]; #only even depths are actual jpath boundaries
3883 push @{$p->{-join_aliases} }, $j->[0]{-alias};
3887 ( push @{$attrs->{select}}, $_->[0] ) and ( push @{$attrs->{as}}, $_->[1] )
3888 for $source->_resolve_selection_from_prefetch( $prefetch, $joined_node_aliases_map );
3892 $attrs->{_simple_passthrough_construction} = !(
3895 grep { $_ =~ /\./ } @{$attrs->{as}}
3899 # if both page and offset are specified, produce a combined offset
3900 # even though it doesn't make much sense, this is what pre 081xx has
3902 if (my $page = delete $attrs->{page}) {
3904 ($attrs->{rows} * ($page - 1))
3906 ($attrs->{offset} || 0)
3910 return $self->{_attrs} = $attrs;
3914 my ($self, $attr) = @_;
3916 if (ref $attr eq 'HASH') {
3917 return $self->_rollout_hash($attr);
3918 } elsif (ref $attr eq 'ARRAY') {
3919 return $self->_rollout_array($attr);
3925 sub _rollout_array {
3926 my ($self, $attr) = @_;
3929 foreach my $element (@{$attr}) {
3930 if (ref $element eq 'HASH') {
3931 push( @rolled_array, @{ $self->_rollout_hash( $element ) } );
3932 } elsif (ref $element eq 'ARRAY') {
3933 # XXX - should probably recurse here
3934 push( @rolled_array, @{$self->_rollout_array($element)} );
3936 push( @rolled_array, $element );
3939 return \@rolled_array;
3943 my ($self, $attr) = @_;
3946 foreach my $key (keys %{$attr}) {
3947 push( @rolled_array, { $key => $attr->{$key} } );
3949 return \@rolled_array;
3952 sub _calculate_score {
3953 my ($self, $a, $b) = @_;
3955 if (defined $a xor defined $b) {
3958 elsif (not defined $a) {
3962 if (ref $b eq 'HASH') {
3963 my ($b_key) = keys %{$b};
3964 $b_key = '' if ! defined $b_key;
3965 if (ref $a eq 'HASH') {
3966 my ($a_key) = keys %{$a};
3967 $a_key = '' if ! defined $a_key;
3968 if ($a_key eq $b_key) {
3969 return (1 + $self->_calculate_score( $a->{$a_key}, $b->{$b_key} ));
3974 return ($a eq $b_key) ? 1 : 0;
3977 if (ref $a eq 'HASH') {
3978 my ($a_key) = keys %{$a};
3979 return ($b eq $a_key) ? 1 : 0;
3981 return ($b eq $a) ? 1 : 0;
3986 sub _merge_joinpref_attr {
3987 my ($self, $orig, $import) = @_;
3989 return $import unless defined($orig);
3990 return $orig unless defined($import);
3992 $orig = $self->_rollout_attr($orig);
3993 $import = $self->_rollout_attr($import);
3996 foreach my $import_element ( @{$import} ) {
3997 # find best candidate from $orig to merge $b_element into
3998 my $best_candidate = { position => undef, score => 0 }; my $position = 0;
3999 foreach my $orig_element ( @{$orig} ) {
4000 my $score = $self->_calculate_score( $orig_element, $import_element );
4001 if ($score > $best_candidate->{score}) {
4002 $best_candidate->{position} = $position;
4003 $best_candidate->{score} = $score;
4007 my ($import_key) = ( ref $import_element eq 'HASH' ) ? keys %{$import_element} : ($import_element);
4008 $import_key = '' if not defined $import_key;
4010 if ($best_candidate->{score} == 0 || exists $seen_keys->{$import_key}) {
4011 push( @{$orig}, $import_element );
4013 my $orig_best = $orig->[$best_candidate->{position}];
4014 # merge orig_best and b_element together and replace original with merged
4015 if (ref $orig_best ne 'HASH') {
4016 $orig->[$best_candidate->{position}] = $import_element;
4017 } elsif (ref $import_element eq 'HASH') {
4018 my ($key) = keys %{$orig_best};
4019 $orig->[$best_candidate->{position}] = { $key => $self->_merge_joinpref_attr($orig_best->{$key}, $import_element->{$key}) };
4022 $seen_keys->{$import_key} = 1; # don't merge the same key twice
4025 return @$orig ? $orig : ();
4033 require Hash::Merge;
4034 my $hm = Hash::Merge->new;
4036 $hm->specify_behavior({
4039 my ($defl, $defr) = map { defined $_ } (@_[0,1]);
4041 if ($defl xor $defr) {
4042 return [ $defl ? $_[0] : $_[1] ];
4047 elsif (__HM_DEDUP and $_[0] eq $_[1]) {
4051 return [$_[0], $_[1]];
4055 return $_[1] if !defined $_[0];
4056 return $_[1] if __HM_DEDUP and grep { $_ eq $_[0] } @{$_[1]};
4057 return [$_[0], @{$_[1]}]
4060 return [] if !defined $_[0] and !keys %{$_[1]};
4061 return [ $_[1] ] if !defined $_[0];
4062 return [ $_[0] ] if !keys %{$_[1]};
4063 return [$_[0], $_[1]]
4068 return $_[0] if !defined $_[1];
4069 return $_[0] if __HM_DEDUP and grep { $_ eq $_[1] } @{$_[0]};
4070 return [@{$_[0]}, $_[1]]
4073 my @ret = @{$_[0]} or return $_[1];
4074 return [ @ret, @{$_[1]} ] unless __HM_DEDUP;
4075 my %idx = map { $_ => 1 } @ret;
4076 push @ret, grep { ! defined $idx{$_} } (@{$_[1]});
4080 return [ $_[1] ] if ! @{$_[0]};
4081 return $_[0] if !keys %{$_[1]};
4082 return $_[0] if __HM_DEDUP and grep { $_ eq $_[1] } @{$_[0]};
4083 return [ @{$_[0]}, $_[1] ];
4088 return [] if !keys %{$_[0]} and !defined $_[1];
4089 return [ $_[0] ] if !defined $_[1];
4090 return [ $_[1] ] if !keys %{$_[0]};
4091 return [$_[0], $_[1]]
4094 return [] if !keys %{$_[0]} and !@{$_[1]};
4095 return [ $_[0] ] if !@{$_[1]};
4096 return $_[1] if !keys %{$_[0]};
4097 return $_[1] if __HM_DEDUP and grep { $_ eq $_[0] } @{$_[1]};
4098 return [ $_[0], @{$_[1]} ];
4101 return [] if !keys %{$_[0]} and !keys %{$_[1]};
4102 return [ $_[0] ] if !keys %{$_[1]};
4103 return [ $_[1] ] if !keys %{$_[0]};
4104 return [ $_[0] ] if $_[0] eq $_[1];
4105 return [ $_[0], $_[1] ];
4108 } => 'DBIC_RS_ATTR_MERGER');
4112 return $hm->merge ($_[1], $_[2]);
4116 sub STORABLE_freeze {
4117 my ($self, $cloning) = @_;
4118 my $to_serialize = { %$self };
4120 # A cursor in progress can't be serialized (and would make little sense anyway)
4121 # the parser can be regenerated (and can't be serialized)
4122 delete @{$to_serialize}{qw/cursor _row_parser _result_inflator/};
4124 # nor is it sensical to store a not-yet-fired-count pager
4125 if ($to_serialize->{pager} and ref $to_serialize->{pager}{total_entries} eq 'CODE') {
4126 delete $to_serialize->{pager};
4129 Storable::nfreeze($to_serialize);
4132 # need this hook for symmetry
4134 my ($self, $cloning, $serialized) = @_;
4136 %$self = %{ Storable::thaw($serialized) };
4142 =head2 throw_exception
4144 See L<DBIx::Class::Schema/throw_exception> for details.
4148 sub throw_exception {
4151 if (ref $self and my $rsrc = $self->result_source) {
4152 $rsrc->throw_exception(@_)
4155 DBIx::Class::Exception->throw(@_);
4163 # XXX: FIXME: Attributes docs need clearing up
4167 Attributes are used to refine a ResultSet in various ways when
4168 searching for data. They can be passed to any method which takes an
4169 C<\%attrs> argument. See L</search>, L</search_rs>, L</find>,
4172 Default attributes can be set on the result class using
4173 L<DBIx::Class::ResultSource/resultset_attributes>. (Please read
4174 the CAVEATS on that feature before using it!)
4176 These are in no particular order:
4182 =item Value: ( $order_by | \@order_by | \%order_by )
4186 Which column(s) to order the results by.
4188 [The full list of suitable values is documented in
4189 L<SQL::Abstract/"ORDER BY CLAUSES">; the following is a summary of
4192 If a single column name, or an arrayref of names is supplied, the
4193 argument is passed through directly to SQL. The hashref syntax allows
4194 for connection-agnostic specification of ordering direction:
4196 For descending order:
4198 order_by => { -desc => [qw/col1 col2 col3/] }
4200 For explicit ascending order:
4202 order_by => { -asc => 'col' }
4204 The old scalarref syntax (i.e. order_by => \'year DESC') is still
4205 supported, although you are strongly encouraged to use the hashref
4206 syntax as outlined above.
4212 =item Value: \@columns | \%columns | $column
4216 Shortcut to request a particular set of columns to be retrieved. Each
4217 column spec may be a string (a table column name), or a hash (in which
4218 case the key is the C<as> value, and the value is used as the C<select>
4219 expression). Adds the L</current_source_alias> onto the start of any column without a C<.> in
4220 it and sets C<select> from that, then auto-populates C<as> from
4221 C<select> as normal. (You may also use the C<cols> attribute, as in
4222 earlier versions of DBIC, but this is deprecated)
4224 Essentially C<columns> does the same as L</select> and L</as>.
4226 columns => [ 'some_column', { dbic_slot => 'another_column' } ]
4230 select => [qw(some_column another_column)],
4231 as => [qw(some_column dbic_slot)]
4233 If you want to individually retrieve related columns (in essence perform
4234 manual L</prefetch>) you have to make sure to specify the correct inflation slot
4235 chain such that it matches existing relationships:
4237 my $rs = $schema->resultset('Artist')->search({}, {
4238 # required to tell DBIC to collapse has_many relationships
4240 join => { cds => 'tracks' },
4242 'cds.cdid' => 'cds.cdid',
4243 'cds.tracks.title' => 'tracks.title',
4247 Like elsewhere, literal SQL or literal values can be included by using a
4248 scalar reference or a literal bind value, and these values will be available
4249 in the result with C<get_column> (see also
4250 L<SQL::Abstract/Literal SQL and value type operators>):
4252 # equivalent SQL: SELECT 1, 'a string', IF(my_column,?,?) ...
4253 # bind values: $true_value, $false_value
4257 bar => \q{'a string'},
4258 baz => \[ 'IF(my_column,?,?)', $true_value, $false_value ],
4264 B<NOTE:> You B<MUST> explicitly quote C<'+columns'> when using this attribute.
4265 Not doing so causes Perl to incorrectly interpret C<+columns> as a bareword
4266 with a unary plus operator before it, which is the same as simply C<columns>.
4270 =item Value: \@extra_columns
4274 Indicates additional columns to be selected from storage. Works the same as
4275 L</columns> but adds columns to the current selection. (You may also use the
4276 C<include_columns> attribute, as in earlier versions of DBIC, but this is
4279 $schema->resultset('CD')->search(undef, {
4280 '+columns' => ['artist.name'],
4284 would return all CDs and include a 'name' column to the information
4285 passed to object inflation. Note that the 'artist' is the name of the
4286 column (or relationship) accessor, and 'name' is the name of the column
4287 accessor in the related table.
4293 =item Value: \@select_columns
4297 Indicates which columns should be selected from the storage. You can use
4298 column names, or in the case of RDBMS back ends, function or stored procedure
4301 $rs = $schema->resultset('Employee')->search(undef, {
4304 { count => 'employeeid' },
4305 { max => { length => 'name' }, -as => 'longest_name' }
4310 SELECT name, COUNT( employeeid ), MAX( LENGTH( name ) ) AS longest_name FROM employee
4312 B<NOTE:> You will almost always need a corresponding L</as> attribute when you
4313 use L</select>, to instruct DBIx::Class how to store the result of the column.
4315 Also note that the L</as> attribute has B<nothing to do> with the SQL-side
4316 C<AS> identifier aliasing. You B<can> alias a function (so you can use it e.g.
4317 in an C<ORDER BY> clause), however this is done via the C<-as> B<select
4318 function attribute> supplied as shown in the example above.
4322 B<NOTE:> You B<MUST> explicitly quote C<'+select'> when using this attribute.
4323 Not doing so causes Perl to incorrectly interpret C<+select> as a bareword
4324 with a unary plus operator before it, which is the same as simply C<select>.
4328 =item Value: \@extra_select_columns
4332 Indicates additional columns to be selected from storage. Works the same as
4333 L</select> but adds columns to the current selection, instead of specifying
4334 a new explicit list.
4340 =item Value: \@inflation_names
4344 Indicates DBIC-side names for object inflation. That is L</as> indicates the
4345 slot name in which the column value will be stored within the
4346 L<Row|DBIx::Class::Row> object. The value will then be accessible via this
4347 identifier by the C<get_column> method (or via the object accessor B<if one
4348 with the same name already exists>) as shown below.
4350 The L</as> attribute has B<nothing to do> with the SQL-side identifier
4351 aliasing C<AS>. See L</select> for details.
4353 $rs = $schema->resultset('Employee')->search(undef, {
4356 { count => 'employeeid' },
4357 { max => { length => 'name' }, -as => 'longest_name' }
4366 If the object against which the search is performed already has an accessor
4367 matching a column name specified in C<as>, the value can be retrieved using
4368 the accessor as normal:
4370 my $name = $employee->name();
4372 If on the other hand an accessor does not exist in the object, you need to
4373 use C<get_column> instead:
4375 my $employee_count = $employee->get_column('employee_count');
4377 You can create your own accessors if required - see
4378 L<DBIx::Class::Manual::Cookbook> for details.
4382 B<NOTE:> You B<MUST> explicitly quote C<'+as'> when using this attribute.
4383 Not doing so causes Perl to incorrectly interpret C<+as> as a bareword
4384 with a unary plus operator before it, which is the same as simply C<as>.
4388 =item Value: \@extra_inflation_names
4392 Indicates additional inflation names for selectors added via L</+select>. See L</as>.
4398 =item Value: ($rel_name | \@rel_names | \%rel_names)
4402 Contains a list of relationships that should be joined for this query. For
4405 # Get CDs by Nine Inch Nails
4406 my $rs = $schema->resultset('CD')->search(
4407 { 'artist.name' => 'Nine Inch Nails' },
4408 { join => 'artist' }
4411 Can also contain a hash reference to refer to the other relation's relations.
4414 package MyApp::Schema::Track;
4415 use base qw/DBIx::Class/;
4416 __PACKAGE__->table('track');
4417 __PACKAGE__->add_columns(qw/trackid cd position title/);
4418 __PACKAGE__->set_primary_key('trackid');
4419 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
4422 # In your application
4423 my $rs = $schema->resultset('Artist')->search(
4424 { 'track.title' => 'Teardrop' },
4426 join => { cd => 'track' },
4427 order_by => 'artist.name',
4431 You need to use the relationship (not the table) name in conditions,
4432 because they are aliased as such. The current table is aliased as "me", so
4433 you need to use me.column_name in order to avoid ambiguity. For example:
4435 # Get CDs from 1984 with a 'Foo' track
4436 my $rs = $schema->resultset('CD')->search(
4439 'tracks.name' => 'Foo'
4441 { join => 'tracks' }
4444 If the same join is supplied twice, it will be aliased to <rel>_2 (and
4445 similarly for a third time). For e.g.
4447 my $rs = $schema->resultset('Artist')->search({
4448 'cds.title' => 'Down to Earth',
4449 'cds_2.title' => 'Popular',
4451 join => [ qw/cds cds/ ],
4454 will return a set of all artists that have both a cd with title 'Down
4455 to Earth' and a cd with title 'Popular'.
4457 If you want to fetch related objects from other tables as well, see L</prefetch>
4460 NOTE: An internal join-chain pruner will discard certain joins while
4461 constructing the actual SQL query, as long as the joins in question do not
4462 affect the retrieved result. This for example includes 1:1 left joins
4463 that are not part of the restriction specification (WHERE/HAVING) nor are
4464 a part of the query selection.
4466 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
4472 =item Value: (0 | 1)
4476 When set to a true value, indicates that any rows fetched from joined has_many
4477 relationships are to be aggregated into the corresponding "parent" object. For
4478 example, the resultset:
4480 my $rs = $schema->resultset('CD')->search({}, {
4481 '+columns' => [ qw/ tracks.title tracks.position / ],
4486 While executing the following query:
4488 SELECT me.*, tracks.title, tracks.position
4490 LEFT JOIN track tracks
4491 ON tracks.cdid = me.cdid
4493 Will return only as many objects as there are rows in the CD source, even
4494 though the result of the query may span many rows. Each of these CD objects
4495 will in turn have multiple "Track" objects hidden behind the has_many
4496 generated accessor C<tracks>. Without C<< collapse => 1 >>, the return values
4497 of this resultset would be as many CD objects as there are tracks (a "Cartesian
4498 product"), with each CD object containing exactly one of all fetched Track data.
4500 When a collapse is requested on a non-ordered resultset, an order by some
4501 unique part of the main source (the left-most table) is inserted automatically.
4502 This is done so that the resultset is allowed to be "lazy" - calling
4503 L<< $rs->next|/next >> will fetch only as many rows as it needs to build the next
4504 object with all of its related data.
4506 If an L</order_by> is already declared, and orders the resultset in a way that
4507 makes collapsing as described above impossible (e.g. C<< ORDER BY
4508 has_many_rel.column >> or C<ORDER BY RANDOM()>), DBIC will automatically
4509 switch to "eager" mode and slurp the entire resultset before constructing the
4510 first object returned by L</next>.
4512 Setting this attribute on a resultset that does not join any has_many
4513 relations is a no-op.
4515 For a more in-depth discussion, see L</PREFETCHING>.
4521 =item Value: ($rel_name | \@rel_names | \%rel_names)
4525 This attribute is a shorthand for specifying a L</join> spec, adding all
4526 columns from the joined related sources as L</+columns> and setting
4527 L</collapse> to a true value. It can be thought of as a rough B<superset>
4528 of the L</join> attribute.
4530 For example, the following two queries are equivalent:
4532 my $rs = $schema->resultset('Artist')->search({}, {
4533 prefetch => { cds => ['genre', 'tracks' ] },
4538 my $rs = $schema->resultset('Artist')->search({}, {
4539 join => { cds => ['genre', 'tracks' ] },
4543 { +{ "cds.$_" => "cds.$_" } }
4544 $schema->source('Artist')->related_source('cds')->columns
4547 { +{ "cds.genre.$_" => "genre.$_" } }
4548 $schema->source('Artist')->related_source('cds')->related_source('genre')->columns
4551 { +{ "cds.tracks.$_" => "tracks.$_" } }
4552 $schema->source('Artist')->related_source('cds')->related_source('tracks')->columns
4557 Both producing the following SQL:
4559 SELECT me.artistid, me.name, me.rank, me.charfield,
4560 cds.cdid, cds.artist, cds.title, cds.year, cds.genreid, cds.single_track,
4561 genre.genreid, genre.name,
4562 tracks.trackid, tracks.cd, tracks.position, tracks.title, tracks.last_updated_on, tracks.last_updated_at
4565 ON cds.artist = me.artistid
4566 LEFT JOIN genre genre
4567 ON genre.genreid = cds.genreid
4568 LEFT JOIN track tracks
4569 ON tracks.cd = cds.cdid
4570 ORDER BY me.artistid
4572 While L</prefetch> implies a L</join>, it is ok to mix the two together, as
4573 the arguments are properly merged and generally do the right thing. For
4574 example, you may want to do the following:
4576 my $artists_and_cds_without_genre = $schema->resultset('Artist')->search(
4577 { 'genre.genreid' => undef },
4579 join => { cds => 'genre' },
4584 Which generates the following SQL:
4586 SELECT me.artistid, me.name, me.rank, me.charfield,
4587 cds.cdid, cds.artist, cds.title, cds.year, cds.genreid, cds.single_track
4590 ON cds.artist = me.artistid
4591 LEFT JOIN genre genre
4592 ON genre.genreid = cds.genreid
4593 WHERE genre.genreid IS NULL
4594 ORDER BY me.artistid
4596 For a more in-depth discussion, see L</PREFETCHING>.
4602 =item Value: $source_alias
4606 Sets the source alias for the query. Normally, this defaults to C<me>, but
4607 nested search queries (sub-SELECTs) might need specific aliases set to
4608 reference inner queries. For example:
4611 ->related_resultset('CDs')
4612 ->related_resultset('Tracks')
4614 'track.id' => { -ident => 'none_search.id' },
4618 my $ids = $self->search({
4621 alias => 'none_search',
4622 group_by => 'none_search.id',
4623 })->get_column('id')->as_query;
4625 $self->search({ id => { -in => $ids } })
4627 This attribute is directly tied to L</current_source_alias>.
4637 Makes the resultset paged and specifies the page to retrieve. Effectively
4638 identical to creating a non-pages resultset and then calling ->page($page)
4641 If L</rows> attribute is not specified it defaults to 10 rows per page.
4643 When you have a paged resultset, L</count> will only return the number
4644 of rows in the page. To get the total, use the L</pager> and call
4645 C<total_entries> on it.
4655 Specifies the maximum number of rows for direct retrieval or the number of
4656 rows per page if the page attribute or method is used.
4662 =item Value: $offset
4666 Specifies the (zero-based) row number for the first row to be returned, or the
4667 of the first row of the first page if paging is used.
4669 =head2 software_limit
4673 =item Value: (0 | 1)
4677 When combined with L</rows> and/or L</offset> the generated SQL will not
4678 include any limit dialect stanzas. Instead the entire result will be selected
4679 as if no limits were specified, and DBIC will perform the limit locally, by
4680 artificially advancing and finishing the resulting L</cursor>.
4682 This is the recommended way of performing resultset limiting when no sane RDBMS
4683 implementation is available (e.g.
4684 L<Sybase ASE|DBIx::Class::Storage::DBI::Sybase::ASE> using the
4685 L<Generic Sub Query|DBIx::Class::SQLMaker::LimitDialects/GenericSubQ> hack)
4691 =item Value: \@columns
4695 A arrayref of columns to group by. Can include columns of joined tables.
4697 group_by => [qw/ column1 column2 ... /]
4703 =item Value: $condition
4707 The HAVING operator specifies a B<secondary> condition applied to the set
4708 after the grouping calculations have been done. In other words it is a
4709 constraint just like L</where> (and accepting the same
4710 L<SQL::Abstract syntax|SQL::Abstract/WHERE CLAUSES>) applied to the data
4711 as it exists after GROUP BY has taken place. Specifying L</having> without
4712 L</group_by> is a logical mistake, and a fatal error on most RDBMS engines.
4716 having => { 'count_employee' => { '>=', 100 } }
4718 or with an in-place function in which case literal SQL is required:
4720 having => \[ 'count(employee) >= ?', 100 ]
4726 =item Value: (0 | 1)
4730 Set to 1 to automatically generate a L</group_by> clause based on the selection
4731 (including intelligent handling of L</order_by> contents). Note that the group
4732 criteria calculation takes place over the B<final> selection. This includes
4733 any L</+columns>, L</+select> or L</order_by> additions in subsequent
4734 L</search> calls, and standalone columns selected via
4735 L<DBIx::Class::ResultSetColumn> (L</get_column>). A notable exception are the
4736 extra selections specified via L</prefetch> - such selections are explicitly
4737 excluded from group criteria calculations.
4739 If the final ResultSet also explicitly defines a L</group_by> attribute, this
4740 setting is ignored and an appropriate warning is issued.
4744 Adds extra conditions to the resultset, combined with the preexisting C<WHERE>
4745 conditions, same as the B<first> argument to the L<search operator|/search>
4747 # only return rows WHERE deleted IS NULL for all searches
4748 __PACKAGE__->resultset_attributes({ where => { deleted => undef } });
4750 Note that the above example is
4751 L<strongly discouraged|DBIx::Class::ResultSource/resultset_attributes>.
4755 Set to 1 to cache search results. This prevents extra SQL queries if you
4756 revisit rows in your ResultSet:
4758 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
4760 while( my $artist = $resultset->next ) {
4764 $resultset->first; # without cache, this would issue a query
4766 By default, searches are not cached.
4768 For more examples of using these attributes, see
4769 L<DBIx::Class::Manual::Cookbook>.
4775 =item Value: ( 'update' | 'shared' | \$scalar )
4779 Set to 'update' for a SELECT ... FOR UPDATE or 'shared' for a SELECT
4780 ... FOR SHARED. If \$scalar is passed, this is taken directly and embedded in the
4785 DBIx::Class supports arbitrary related data prefetching from multiple related
4786 sources. Any combination of relationship types and column sets are supported.
4787 If L<collapsing|/collapse> is requested, there is an additional requirement of
4788 selecting enough data to make every individual object uniquely identifiable.
4790 Here are some more involved examples, based on the following relationship map:
4793 My::Schema::CD->belongs_to( artist => 'My::Schema::Artist' );
4794 My::Schema::CD->might_have( liner_note => 'My::Schema::LinerNotes' );
4795 My::Schema::CD->has_many( tracks => 'My::Schema::Track' );
4797 My::Schema::Artist->belongs_to( record_label => 'My::Schema::RecordLabel' );
4799 My::Schema::Track->has_many( guests => 'My::Schema::Guest' );
4803 my $rs = $schema->resultset('Tag')->search(
4812 The initial search results in SQL like the following:
4814 SELECT tag.*, cd.*, artist.* FROM tag
4815 JOIN cd ON tag.cd = cd.cdid
4816 JOIN artist ON cd.artist = artist.artistid
4818 L<DBIx::Class> has no need to go back to the database when we access the
4819 C<cd> or C<artist> relationships, which saves us two SQL statements in this
4822 Simple prefetches will be joined automatically, so there is no need
4823 for a C<join> attribute in the above search.
4825 The L</prefetch> attribute can be used with any of the relationship types
4826 and multiple prefetches can be specified together. Below is a more complex
4827 example that prefetches a CD's artist, its liner notes (if present),
4828 the cover image, the tracks on that CD, and the guests on those
4831 my $rs = $schema->resultset('CD')->search(
4835 { artist => 'record_label'}, # belongs_to => belongs_to
4836 'liner_note', # might_have
4837 'cover_image', # has_one
4838 { tracks => 'guests' }, # has_many => has_many
4843 This will produce SQL like the following:
4845 SELECT cd.*, artist.*, record_label.*, liner_note.*, cover_image.*,
4849 ON artist.artistid = me.artistid
4850 JOIN record_label record_label
4851 ON record_label.labelid = artist.labelid
4852 LEFT JOIN track tracks
4853 ON tracks.cdid = me.cdid
4854 LEFT JOIN guest guests
4855 ON guests.trackid = track.trackid
4856 LEFT JOIN liner_notes liner_note
4857 ON liner_note.cdid = me.cdid
4858 JOIN cd_artwork cover_image
4859 ON cover_image.cdid = me.cdid
4862 Now the C<artist>, C<record_label>, C<liner_note>, C<cover_image>,
4863 C<tracks>, and C<guests> of the CD will all be available through the
4864 relationship accessors without the need for additional queries to the
4869 Prefetch does a lot of deep magic. As such, it may not behave exactly
4870 as you might expect.
4876 Prefetch uses the L</cache> to populate the prefetched relationships. This
4877 may or may not be what you want.
4881 If you specify a condition on a prefetched relationship, ONLY those
4882 rows that match the prefetched condition will be fetched into that relationship.
4883 This means that adding prefetch to a search() B<may alter> what is returned by
4884 traversing a relationship. So, if you have C<< Artist->has_many(CDs) >> and you do
4886 my $artist_rs = $schema->resultset('Artist')->search({
4892 my $count = $artist_rs->first->cds->count;
4894 my $artist_rs_prefetch = $artist_rs->search( {}, { prefetch => 'cds' } );
4896 my $prefetch_count = $artist_rs_prefetch->first->cds->count;
4898 cmp_ok( $count, '==', $prefetch_count, "Counts should be the same" );
4900 That cmp_ok() may or may not pass depending on the datasets involved. In other
4901 words the C<WHERE> condition would apply to the entire dataset, just like
4902 it would in regular SQL. If you want to add a condition only to the "right side"
4903 of a C<LEFT JOIN> - consider declaring and using a L<relationship with a custom
4904 condition|DBIx::Class::Relationship::Base/condition>
4908 =head1 DBIC BIND VALUES
4910 Because DBIC may need more information to bind values than just the column name
4911 and value itself, it uses a special format for both passing and receiving bind
4912 values. Each bind value should be composed of an arrayref of
4913 C<< [ \%args => $val ] >>. The format of C<< \%args >> is currently:
4919 If present (in any form), this is what is being passed directly to bind_param.
4920 Note that different DBD's expect different bind args. (e.g. DBD::SQLite takes
4921 a single numerical type, while DBD::Pg takes a hashref if bind options.)
4923 If this is specified, all other bind options described below are ignored.
4927 If present, this is used to infer the actual bind attribute by passing to
4928 C<< $resolved_storage->bind_attribute_by_data_type() >>. Defaults to the
4929 "data_type" from the L<add_columns column info|DBIx::Class::ResultSource/add_columns>.
4931 Note that the data type is somewhat freeform (hence the sqlt_ prefix);
4932 currently drivers are expected to "Do the Right Thing" when given a common
4933 datatype name. (Not ideal, but that's what we got at this point.)
4937 Currently used to correctly allocate buffers for bind_param_inout().
4938 Defaults to "size" from the L<add_columns column info|DBIx::Class::ResultSource/add_columns>,
4939 or to a sensible value based on the "data_type".
4943 Used to fill in missing sqlt_datatype and sqlt_size attributes (if they are
4944 explicitly specified they are never overridden). Also used by some weird DBDs,
4945 where the column name should be available at bind_param time (e.g. Oracle).
4949 For backwards compatibility and convenience, the following shortcuts are
4952 [ $name => $val ] === [ { dbic_colname => $name }, $val ]
4953 [ \$dt => $val ] === [ { sqlt_datatype => $dt }, $val ]
4954 [ undef, $val ] === [ {}, $val ]
4955 $val === [ {}, $val ]
4957 =head1 FURTHER QUESTIONS?
4959 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
4961 =head1 COPYRIGHT AND LICENSE
4963 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
4964 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
4965 redistribute it and/or modify it under the same terms as the
4966 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.