1 package DBIx::Class::ResultSet;
5 use base qw/DBIx::Class/;
6 use Carp::Clan qw/^DBIx::Class/;
7 use DBIx::Class::Exception;
10 use DBIx::Class::ResultSetColumn;
11 use DBIx::Class::ResultSourceHandle;
13 use Scalar::Util qw/blessed weaken/;
22 __PACKAGE__->mk_group_accessors('simple' => qw/_result_class _source_handle/);
26 DBIx::Class::ResultSet - Represents a query used for fetching a set of results.
30 my $users_rs = $schema->resultset('User');
31 while( $user = $users_rs->next) {
32 print $user->username;
35 my $registered_users_rs = $schema->resultset('User')->search({ registered => 1 });
36 my @cds_in_2005 = $schema->resultset('CD')->search({ year => 2005 })->all();
40 A ResultSet is an object which stores a set of conditions representing
41 a query. It is the backbone of DBIx::Class (i.e. the really
42 important/useful bit).
44 No SQL is executed on the database when a ResultSet is created, it
45 just stores all the conditions needed to create the query.
47 A basic ResultSet representing the data of an entire table is returned
48 by calling C<resultset> on a L<DBIx::Class::Schema> and passing in a
49 L<Source|DBIx::Class::Manual::Glossary/Source> name.
51 my $users_rs = $schema->resultset('User');
53 A new ResultSet is returned from calling L</search> on an existing
54 ResultSet. The new one will contain all the conditions of the
55 original, plus any new conditions added in the C<search> call.
57 A ResultSet also incorporates an implicit iterator. L</next> and L</reset>
58 can be used to walk through all the L<DBIx::Class::Row>s the ResultSet
61 The query that the ResultSet represents is B<only> executed against
62 the database when these methods are called:
63 L</find>, L</next>, L</all>, L</first>, L</single>, L</count>.
65 If a resultset is used in a numeric context it returns the L</count>.
66 However, if it is used in a boolean context it is B<always> true. So if
67 you want to check if a resultset has any results, you must use C<if $rs
72 =head2 Chaining resultsets
74 Let's say you've got a query that needs to be run to return some data
75 to the user. But, you have an authorization system in place that
76 prevents certain users from seeing certain information. So, you want
77 to construct the basic query in one method, but add constraints to it in
82 my $request = $self->get_request; # Get a request object somehow.
83 my $schema = $self->get_schema; # Get the DBIC schema object somehow.
85 my $cd_rs = $schema->resultset('CD')->search({
86 title => $request->param('title'),
87 year => $request->param('year'),
90 $self->apply_security_policy( $cd_rs );
95 sub apply_security_policy {
104 =head3 Resolving conditions and attributes
106 When a resultset is chained from another resultset, conditions and
107 attributes with the same keys need resolving.
109 L</join>, L</prefetch>, L</+select>, L</+as> attributes are merged
110 into the existing ones from the original resultset.
112 The L</where> and L</having> attributes, and any search conditions, are
113 merged with an SQL C<AND> to the existing condition from the original
116 All other attributes are overridden by any new ones supplied in the
119 =head2 Multiple queries
121 Since a resultset just defines a query, you can do all sorts of
122 things with it with the same object.
124 # Don't hit the DB yet.
125 my $cd_rs = $schema->resultset('CD')->search({
126 title => 'something',
130 # Each of these hits the DB individually.
131 my $count = $cd_rs->count;
132 my $most_recent = $cd_rs->get_column('date_released')->max();
133 my @records = $cd_rs->all;
135 And it's not just limited to SELECT statements.
141 $cd_rs->create({ artist => 'Fred' });
143 Which is the same as:
145 $schema->resultset('CD')->create({
146 title => 'something',
151 See: L</search>, L</count>, L</get_column>, L</all>, L</create>.
159 =item Arguments: $source, \%$attrs
161 =item Return Value: $rs
165 The resultset constructor. Takes a source object (usually a
166 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
167 L</ATTRIBUTES> below). Does not perform any queries -- these are
168 executed as needed by the other methods.
170 Generally you won't need to construct a resultset manually. You'll
171 automatically get one from e.g. a L</search> called in scalar context:
173 my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
175 IMPORTANT: If called on an object, proxies to new_result instead so
177 my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
179 will return a CD object, not a ResultSet.
185 return $class->new_result(@_) if ref $class;
187 my ($source, $attrs) = @_;
188 $source = $source->handle
189 unless $source->isa('DBIx::Class::ResultSourceHandle');
190 $attrs = { %{$attrs||{}} };
192 if ($attrs->{page}) {
193 $attrs->{rows} ||= 10;
196 $attrs->{alias} ||= 'me';
198 # Creation of {} and bless separated to mitigate RH perl bug
199 # see https://bugzilla.redhat.com/show_bug.cgi?id=196836
201 _source_handle => $source,
202 cond => $attrs->{where},
210 $attrs->{result_class} || $source->resolve->result_class
220 =item Arguments: $cond, \%attrs?
222 =item Return Value: $resultset (scalar context), @row_objs (list context)
226 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
227 my $new_rs = $cd_rs->search({ year => 2005 });
229 my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
230 # year = 2005 OR year = 2004
232 If you need to pass in additional attributes but no additional condition,
233 call it as C<search(undef, \%attrs)>.
235 # "SELECT name, artistid FROM $artist_table"
236 my @all_artists = $schema->resultset('Artist')->search(undef, {
237 columns => [qw/name artistid/],
240 For a list of attributes that can be passed to C<search>, see
241 L</ATTRIBUTES>. For more examples of using this function, see
242 L<Searching|DBIx::Class::Manual::Cookbook/Searching>. For a complete
243 documentation for the first argument, see L<SQL::Abstract>.
245 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
251 my $rs = $self->search_rs( @_ );
252 return (wantarray ? $rs->all : $rs);
259 =item Arguments: $cond, \%attrs?
261 =item Return Value: $resultset
265 This method does the same exact thing as search() except it will
266 always return a resultset, even in list context.
273 # Special-case handling for (undef, undef).
274 if ( @_ == 2 && !defined $_[1] && !defined $_[0] ) {
279 $attrs = pop(@_) if @_ > 1 and ref $_[$#_] eq 'HASH';
280 my $our_attrs = { %{$self->{attrs}} };
281 my $having = delete $our_attrs->{having};
282 my $where = delete $our_attrs->{where};
286 my %safe = (alias => 1, cache => 1);
289 (@_ && defined($_[0])) # @_ == () or (undef)
291 (keys %$attrs # empty attrs or only 'safe' attrs
292 && List::Util::first { !$safe{$_} } keys %$attrs)
294 # no search, effectively just a clone
295 $rows = $self->get_cache;
298 # reset the selector list
299 if (List::Util::first { exists $attrs->{$_} } qw{columns select as}) {
300 delete @{$our_attrs}{qw{select as columns +select +as +columns include_columns}};
303 my $new_attrs = { %{$our_attrs}, %{$attrs} };
305 # merge new attrs into inherited
306 foreach my $key (qw/join prefetch +select +as +columns include_columns bind/) {
307 next unless exists $attrs->{$key};
308 $new_attrs->{$key} = $self->_merge_attr($our_attrs->{$key}, $attrs->{$key});
313 (@_ == 1 || ref $_[0] eq "HASH")
315 (ref $_[0] eq 'HASH')
317 (keys %{ $_[0] } > 0)
325 ? $self->throw_exception("Odd number of arguments to search")
332 if (defined $where) {
333 $new_attrs->{where} = (
334 defined $new_attrs->{where}
337 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
338 } $where, $new_attrs->{where}
345 $new_attrs->{where} = (
346 defined $new_attrs->{where}
349 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
350 } $cond, $new_attrs->{where}
356 if (defined $having) {
357 $new_attrs->{having} = (
358 defined $new_attrs->{having}
361 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
362 } $having, $new_attrs->{having}
368 my $rs = (ref $self)->new($self->result_source, $new_attrs);
370 $rs->set_cache($rows) if ($rows);
375 =head2 search_literal
379 =item Arguments: $sql_fragment, @bind_values
381 =item Return Value: $resultset (scalar context), @row_objs (list context)
385 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
386 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
388 Pass a literal chunk of SQL to be added to the conditional part of the
391 CAVEAT: C<search_literal> is provided for Class::DBI compatibility and should
392 only be used in that context. C<search_literal> is a convenience method.
393 It is equivalent to calling $schema->search(\[]), but if you want to ensure
394 columns are bound correctly, use C<search>.
396 Example of how to use C<search> instead of C<search_literal>
398 my @cds = $cd_rs->search_literal('cdid = ? AND (artist = ? OR artist = ?)', (2, 1, 2));
399 my @cds = $cd_rs->search(\[ 'cdid = ? AND (artist = ? OR artist = ?)', [ 'cdid', 2 ], [ 'artist', 1 ], [ 'artist', 2 ] ]);
402 See L<DBIx::Class::Manual::Cookbook/Searching> and
403 L<DBIx::Class::Manual::FAQ/Searching> for searching techniques that do not
404 require C<search_literal>.
409 my ($self, $sql, @bind) = @_;
411 if ( @bind && ref($bind[-1]) eq 'HASH' ) {
414 return $self->search(\[ $sql, map [ __DUMMY__ => $_ ], @bind ], ($attr || () ));
421 =item Arguments: @values | \%cols, \%attrs?
423 =item Return Value: $row_object | undef
427 Finds a row based on its primary key or unique constraint. For example, to find
428 a row by its primary key:
430 my $cd = $schema->resultset('CD')->find(5);
432 You can also find a row by a specific unique constraint using the C<key>
433 attribute. For example:
435 my $cd = $schema->resultset('CD')->find('Massive Attack', 'Mezzanine', {
436 key => 'cd_artist_title'
439 Additionally, you can specify the columns explicitly by name:
441 my $cd = $schema->resultset('CD')->find(
443 artist => 'Massive Attack',
444 title => 'Mezzanine',
446 { key => 'cd_artist_title' }
449 If the C<key> is specified as C<primary>, it searches only on the primary key.
451 If no C<key> is specified, it searches on all unique constraints defined on the
452 source for which column data is provided, including the primary key.
454 If your table does not have a primary key, you B<must> provide a value for the
455 C<key> attribute matching one of the unique constraints on the source.
457 In addition to C<key>, L</find> recognizes and applies standard
458 L<resultset attributes|/ATTRIBUTES> in the same way as L</search> does.
460 Note: If your query does not return only one row, a warning is generated:
462 Query returned more than one row
464 See also L</find_or_create> and L</update_or_create>. For information on how to
465 declare unique constraints, see
466 L<DBIx::Class::ResultSource/add_unique_constraint>.
472 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
474 # Parse out a query from input
476 if (ref $_[0] eq 'HASH') {
477 $input_query = { %{$_[0]} };
480 my $constraint = exists $attrs->{key} ? $attrs->{key} : 'primary';
481 my @c_cols = $self->result_source->unique_constraint_columns($constraint);
483 $self->throw_exception(
484 "No constraint columns, maybe a malformed '$constraint' constraint?"
487 $self->throw_exception (
488 'find() expects either a column/value hashref, or a list of values '
489 . "corresponding to the columns of the specified unique constraint '$constraint'"
490 ) unless @c_cols == @_;
493 @{$input_query}{@c_cols} = @_;
497 for my $key (keys %$input_query) {
499 my $keyref = ref($input_query->{$key})
501 my $relinfo = $self->result_source->relationship_info($key)
503 my $val = delete $input_query->{$key};
505 next if $keyref eq 'ARRAY'; # has_many for multi_create
507 my $rel_q = $self->result_source->_resolve_condition(
508 $relinfo->{cond}, $val, $key
510 die "Can't handle complex relationship conditions in find" if ref($rel_q) ne 'HASH';
511 @related{keys %$rel_q} = values %$rel_q;
515 # relationship conditions take precedence (?)
516 @{$input_query}{keys %related} = values %related;
518 # Build the final query: Default to the disjunction of the unique queries,
519 # but allow the input query in case the ResultSet defines the query or the
520 # user is abusing find
521 my $alias = exists $attrs->{alias} ? $attrs->{alias} : $self->{attrs}{alias};
523 if (exists $attrs->{key}) {
524 my @unique_cols = $self->result_source->unique_constraint_columns($attrs->{key});
525 my $unique_query = $self->_build_unique_query($input_query, \@unique_cols);
526 $query = $self->_add_alias($unique_query, $alias);
528 elsif ($self->{attrs}{accessor} and $self->{attrs}{accessor} eq 'single') {
529 # This means that we got here after a merger of relationship conditions
530 # in ::Relationship::Base::search_related (the row method), and furthermore
531 # the relationship is of the 'single' type. This means that the condition
532 # provided by the relationship (already attached to $self) is sufficient,
533 # as there can be only one row in the database that would satisfy the
537 my @unique_queries = $self->_unique_queries($input_query, $attrs);
538 $query = @unique_queries
539 ? [ map { $self->_add_alias($_, $alias) } @unique_queries ]
540 : $self->_add_alias($input_query, $alias);
543 # Run the query, passing the result_class since it should propagate for find
544 my $rs = $self->search ($query, {result_class => $self->result_class, %$attrs});
545 if (keys %{$rs->_resolved_attrs->{collapse}}) {
547 carp "Query returned more than one row" if $rs->next;
557 # Add the specified alias to the specified query hash. A copy is made so the
558 # original query is not modified.
561 my ($self, $query, $alias) = @_;
563 my %aliased = %$query;
564 foreach my $col (grep { ! m/\./ } keys %aliased) {
565 $aliased{"$alias.$col"} = delete $aliased{$col};
573 # Build a list of queries which satisfy unique constraints.
575 sub _unique_queries {
576 my ($self, $query, $attrs) = @_;
578 my @constraint_names = exists $attrs->{key}
580 : $self->result_source->unique_constraint_names;
582 my $where = $self->_collapse_cond($self->{attrs}{where} || {});
583 my $num_where = scalar keys %$where;
585 my (@unique_queries, %seen_column_combinations);
586 foreach my $name (@constraint_names) {
587 my @constraint_cols = $self->result_source->unique_constraint_columns($name);
589 my $constraint_sig = join "\x00", sort @constraint_cols;
590 next if $seen_column_combinations{$constraint_sig}++;
592 my $unique_query = $self->_build_unique_query($query, \@constraint_cols);
594 my $num_cols = scalar @constraint_cols;
595 my $num_query = scalar keys %$unique_query;
597 my $total = $num_query + $num_where;
598 if ($num_query && ($num_query == $num_cols || $total == $num_cols)) {
599 # The query is either unique on its own or is unique in combination with
600 # the existing where clause
601 push @unique_queries, $unique_query;
605 return @unique_queries;
608 # _build_unique_query
610 # Constrain the specified query hash based on the specified column names.
612 sub _build_unique_query {
613 my ($self, $query, $unique_cols) = @_;
616 map { $_ => $query->{$_} }
617 grep { exists $query->{$_} }
622 =head2 search_related
626 =item Arguments: $rel, $cond, \%attrs?
628 =item Return Value: $new_resultset
632 $new_rs = $cd_rs->search_related('artist', {
636 Searches the specified relationship, optionally specifying a condition and
637 attributes for matching records. See L</ATTRIBUTES> for more information.
642 return shift->related_resultset(shift)->search(@_);
645 =head2 search_related_rs
647 This method works exactly the same as search_related, except that
648 it guarantees a resultset, even in list context.
652 sub search_related_rs {
653 return shift->related_resultset(shift)->search_rs(@_);
660 =item Arguments: none
662 =item Return Value: $cursor
666 Returns a storage-driven cursor to the given resultset. See
667 L<DBIx::Class::Cursor> for more information.
674 my $attrs = $self->_resolved_attrs_copy;
676 return $self->{cursor}
677 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
678 $attrs->{where},$attrs);
685 =item Arguments: $cond?
687 =item Return Value: $row_object | undef
691 my $cd = $schema->resultset('CD')->single({ year => 2001 });
693 Inflates the first result without creating a cursor if the resultset has
694 any records in it; if not returns C<undef>. Used by L</find> as a lean version
697 While this method can take an optional search condition (just like L</search>)
698 being a fast-code-path it does not recognize search attributes. If you need to
699 add extra joins or similar, call L</search> and then chain-call L</single> on the
700 L<DBIx::Class::ResultSet> returned.
706 As of 0.08100, this method enforces the assumption that the preceding
707 query returns only one row. If more than one row is returned, you will receive
710 Query returned more than one row
712 In this case, you should be using L</next> or L</find> instead, or if you really
713 know what you are doing, use the L</rows> attribute to explicitly limit the size
716 This method will also throw an exception if it is called on a resultset prefetching
717 has_many, as such a prefetch implies fetching multiple rows from the database in
718 order to assemble the resulting object.
725 my ($self, $where) = @_;
727 $self->throw_exception('single() only takes search conditions, no attributes. You want ->search( $cond, $attrs )->single()');
730 my $attrs = $self->_resolved_attrs_copy;
732 if (keys %{$attrs->{collapse}}) {
733 $self->throw_exception(
734 'single() can not be used on resultsets prefetching has_many. Use find( \%cond ) or next() instead'
739 if (defined $attrs->{where}) {
742 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
743 $where, delete $attrs->{where} ]
746 $attrs->{where} = $where;
750 my @data = $self->result_source->storage->select_single(
751 $attrs->{from}, $attrs->{select},
752 $attrs->{where}, $attrs
755 return (@data ? ($self->_construct_object(@data))[0] : undef);
761 # Recursively collapse the query, accumulating values for each column.
763 sub _collapse_query {
764 my ($self, $query, $collapsed) = @_;
768 if (ref $query eq 'ARRAY') {
769 foreach my $subquery (@$query) {
770 next unless ref $subquery; # -or
771 $collapsed = $self->_collapse_query($subquery, $collapsed);
774 elsif (ref $query eq 'HASH') {
775 if (keys %$query and (keys %$query)[0] eq '-and') {
776 foreach my $subquery (@{$query->{-and}}) {
777 $collapsed = $self->_collapse_query($subquery, $collapsed);
781 foreach my $col (keys %$query) {
782 my $value = $query->{$col};
783 $collapsed->{$col}{$value}++;
795 =item Arguments: $cond?
797 =item Return Value: $resultsetcolumn
801 my $max_length = $rs->get_column('length')->max;
803 Returns a L<DBIx::Class::ResultSetColumn> instance for a column of the ResultSet.
808 my ($self, $column) = @_;
809 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
817 =item Arguments: $cond, \%attrs?
819 =item Return Value: $resultset (scalar context), @row_objs (list context)
823 # WHERE title LIKE '%blue%'
824 $cd_rs = $rs->search_like({ title => '%blue%'});
826 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
827 that this is simply a convenience method retained for ex Class::DBI users.
828 You most likely want to use L</search> with specific operators.
830 For more information, see L<DBIx::Class::Manual::Cookbook>.
832 This method is deprecated and will be removed in 0.09. Use L</search()>
833 instead. An example conversion is:
835 ->search_like({ foo => 'bar' });
839 ->search({ foo => { like => 'bar' } });
846 'search_like() is deprecated and will be removed in DBIC version 0.09.'
847 .' Instead use ->search({ x => { -like => "y%" } })'
848 .' (note the outer pair of {}s - they are important!)'
850 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
851 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
852 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
853 return $class->search($query, { %$attrs });
860 =item Arguments: $first, $last
862 =item Return Value: $resultset (scalar context), @row_objs (list context)
866 Returns a resultset or object list representing a subset of elements from the
867 resultset slice is called on. Indexes are from 0, i.e., to get the first
870 my ($one, $two, $three) = $rs->slice(0, 2);
875 my ($self, $min, $max) = @_;
876 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
877 $attrs->{offset} = $self->{attrs}{offset} || 0;
878 $attrs->{offset} += $min;
879 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
880 return $self->search(undef, $attrs);
881 #my $slice = (ref $self)->new($self->result_source, $attrs);
882 #return (wantarray ? $slice->all : $slice);
889 =item Arguments: none
891 =item Return Value: $result | undef
895 Returns the next element in the resultset (C<undef> is there is none).
897 Can be used to efficiently iterate over records in the resultset:
899 my $rs = $schema->resultset('CD')->search;
900 while (my $cd = $rs->next) {
904 Note that you need to store the resultset object, and call C<next> on it.
905 Calling C<< resultset('Table')->next >> repeatedly will always return the
906 first record from the resultset.
912 if (my $cache = $self->get_cache) {
913 $self->{all_cache_position} ||= 0;
914 return $cache->[$self->{all_cache_position}++];
916 if ($self->{attrs}{cache}) {
917 delete $self->{pager};
918 $self->{all_cache_position} = 1;
919 return ($self->all)[0];
921 if ($self->{stashed_objects}) {
922 my $obj = shift(@{$self->{stashed_objects}});
923 delete $self->{stashed_objects} unless @{$self->{stashed_objects}};
927 exists $self->{stashed_row}
928 ? @{delete $self->{stashed_row}}
929 : $self->cursor->next
931 return undef unless (@row);
932 my ($row, @more) = $self->_construct_object(@row);
933 $self->{stashed_objects} = \@more if @more;
937 sub _construct_object {
938 my ($self, @row) = @_;
940 my $info = $self->_collapse_result($self->{_attrs}{as}, \@row)
942 my @new = $self->result_class->inflate_result($self->result_source, @$info);
943 @new = $self->{_attrs}{record_filter}->(@new)
944 if exists $self->{_attrs}{record_filter};
948 sub _collapse_result {
949 my ($self, $as_proto, $row) = @_;
953 # 'foo' => [ undef, 'foo' ]
954 # 'foo.bar' => [ 'foo', 'bar' ]
955 # 'foo.bar.baz' => [ 'foo.bar', 'baz' ]
957 my @construct_as = map { [ (/^(?:(.*)\.)?([^.]+)$/) ] } @$as_proto;
959 my %collapse = %{$self->{_attrs}{collapse}||{}};
963 # if we're doing collapsing (has_many prefetch) we need to grab records
964 # until the PK changes, so fill @pri_index. if not, we leave it empty so
965 # we know we don't have to bother.
967 # the reason for not using the collapse stuff directly is because if you
968 # had for e.g. two artists in a row with no cds, the collapse info for
969 # both would be NULL (undef) so you'd lose the second artist
971 # store just the index so we can check the array positions from the row
972 # without having to contruct the full hash
974 if (keys %collapse) {
975 my %pri = map { ($_ => 1) } $self->result_source->_pri_cols;
976 foreach my $i (0 .. $#construct_as) {
977 next if defined($construct_as[$i][0]); # only self table
978 if (delete $pri{$construct_as[$i][1]}) {
979 push(@pri_index, $i);
981 last unless keys %pri; # short circuit (Johnny Five Is Alive!)
985 # no need to do an if, it'll be empty if @pri_index is empty anyway
987 my %pri_vals = map { ($_ => $copy[$_]) } @pri_index;
991 do { # no need to check anything at the front, we always want the first row
995 foreach my $this_as (@construct_as) {
996 $const{$this_as->[0]||''}{$this_as->[1]} = shift(@copy);
999 push(@const_rows, \%const);
1001 } until ( # no pri_index => no collapse => drop straight out
1004 do { # get another row, stash it, drop out if different PK
1006 @copy = $self->cursor->next;
1007 $self->{stashed_row} = \@copy;
1009 # last thing in do block, counts as true if anything doesn't match
1011 # check xor defined first for NULL vs. NOT NULL then if one is
1012 # defined the other must be so check string equality
1015 (defined $pri_vals{$_} ^ defined $copy[$_])
1016 || (defined $pri_vals{$_} && ($pri_vals{$_} ne $copy[$_]))
1021 my $alias = $self->{attrs}{alias};
1028 foreach my $const (@const_rows) {
1029 scalar @const_keys or do {
1030 @const_keys = sort { length($a) <=> length($b) } keys %$const;
1032 foreach my $key (@const_keys) {
1035 my @parts = split(/\./, $key);
1037 my $data = $const->{$key};
1038 foreach my $p (@parts) {
1039 $target = $target->[1]->{$p} ||= [];
1041 if ($cur eq ".${key}" && (my @ckey = @{$collapse{$cur}||[]})) {
1042 # collapsing at this point and on final part
1043 my $pos = $collapse_pos{$cur};
1044 CK: foreach my $ck (@ckey) {
1045 if (!defined $pos->{$ck} || $pos->{$ck} ne $data->{$ck}) {
1046 $collapse_pos{$cur} = $data;
1047 delete @collapse_pos{ # clear all positioning for sub-entries
1048 grep { m/^\Q${cur}.\E/ } keys %collapse_pos
1055 if (exists $collapse{$cur}) {
1056 $target = $target->[-1];
1059 $target->[0] = $data;
1061 $info->[0] = $const->{$key};
1069 =head2 result_source
1073 =item Arguments: $result_source?
1075 =item Return Value: $result_source
1079 An accessor for the primary ResultSource object from which this ResultSet
1086 =item Arguments: $result_class?
1088 =item Return Value: $result_class
1092 An accessor for the class to use when creating row objects. Defaults to
1093 C<< result_source->result_class >> - which in most cases is the name of the
1094 L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class.
1096 Note that changing the result_class will also remove any components
1097 that were originally loaded in the source class via
1098 L<DBIx::Class::ResultSource/load_components>. Any overloaded methods
1099 in the original source class will not run.
1104 my ($self, $result_class) = @_;
1105 if ($result_class) {
1106 unless (ref $result_class) { # don't fire this for an object
1107 $self->ensure_class_loaded($result_class);
1109 $self->_result_class($result_class);
1110 # THIS LINE WOULD BE A BUG - this accessor specifically exists to
1111 # permit the user to set result class on one result set only; it only
1112 # chains if provided to search()
1113 #$self->{attrs}{result_class} = $result_class if ref $self;
1115 $self->_result_class;
1122 =item Arguments: $cond, \%attrs??
1124 =item Return Value: $count
1128 Performs an SQL C<COUNT> with the same query as the resultset was built
1129 with to find the number of elements. Passing arguments is equivalent to
1130 C<< $rs->search ($cond, \%attrs)->count >>
1136 return $self->search(@_)->count if @_ and defined $_[0];
1137 return scalar @{ $self->get_cache } if $self->get_cache;
1139 my $attrs = $self->_resolved_attrs_copy;
1141 # this is a little optimization - it is faster to do the limit
1142 # adjustments in software, instead of a subquery
1143 my $rows = delete $attrs->{rows};
1144 my $offset = delete $attrs->{offset};
1147 if ($self->_has_resolved_attr (qw/collapse group_by/)) {
1148 $crs = $self->_count_subq_rs ($attrs);
1151 $crs = $self->_count_rs ($attrs);
1153 my $count = $crs->next;
1155 $count -= $offset if $offset;
1156 $count = $rows if $rows and $rows < $count;
1157 $count = 0 if ($count < 0);
1166 =item Arguments: $cond, \%attrs??
1168 =item Return Value: $count_rs
1172 Same as L</count> but returns a L<DBIx::Class::ResultSetColumn> object.
1173 This can be very handy for subqueries:
1175 ->search( { amount => $some_rs->count_rs->as_query } )
1177 As with regular resultsets the SQL query will be executed only after
1178 the resultset is accessed via L</next> or L</all>. That would return
1179 the same single value obtainable via L</count>.
1185 return $self->search(@_)->count_rs if @_;
1187 # this may look like a lack of abstraction (count() does about the same)
1188 # but in fact an _rs *must* use a subquery for the limits, as the
1189 # software based limiting can not be ported if this $rs is to be used
1190 # in a subquery itself (i.e. ->as_query)
1191 if ($self->_has_resolved_attr (qw/collapse group_by offset rows/)) {
1192 return $self->_count_subq_rs;
1195 return $self->_count_rs;
1200 # returns a ResultSetColumn object tied to the count query
1203 my ($self, $attrs) = @_;
1205 my $rsrc = $self->result_source;
1206 $attrs ||= $self->_resolved_attrs;
1208 my $tmp_attrs = { %$attrs };
1209 # take off any limits, record_filter is cdbi, and no point of ordering nor locking a count
1210 delete @{$tmp_attrs}{qw/rows offset order_by record_filter for/};
1212 # overwrite the selector (supplied by the storage)
1213 $tmp_attrs->{select} = $rsrc->storage->_count_select ($rsrc, $attrs);
1214 $tmp_attrs->{as} = 'count';
1216 my $tmp_rs = $rsrc->resultset_class->new($rsrc, $tmp_attrs)->get_column ('count');
1222 # same as above but uses a subquery
1224 sub _count_subq_rs {
1225 my ($self, $attrs) = @_;
1227 my $rsrc = $self->result_source;
1228 $attrs ||= $self->_resolved_attrs;
1230 my $sub_attrs = { %$attrs };
1231 # extra selectors do not go in the subquery and there is no point of ordering it, nor locking it
1232 delete @{$sub_attrs}{qw/collapse select _prefetch_select as order_by for/};
1234 # if we multi-prefetch we group_by primary keys only as this is what we would
1235 # get out of the rs via ->next/->all. We *DO WANT* to clobber old group_by regardless
1236 if ( keys %{$attrs->{collapse}} ) {
1237 $sub_attrs->{group_by} = [ map { "$attrs->{alias}.$_" } ($rsrc->_pri_cols) ]
1240 # Calculate subquery selector
1241 if (my $g = $sub_attrs->{group_by}) {
1243 my $sql_maker = $rsrc->storage->sql_maker;
1245 # necessary as the group_by may refer to aliased functions
1247 for my $sel (@{$attrs->{select}}) {
1248 $sel_index->{$sel->{-as}} = $sel
1249 if (ref $sel eq 'HASH' and $sel->{-as});
1252 for my $g_part (@$g) {
1253 my $colpiece = $sel_index->{$g_part} || $g_part;
1255 # disqualify join-based group_by's. Arcane but possible query
1256 # also horrible horrible hack to alias a column (not a func.)
1257 # (probably need to introduce SQLA syntax)
1258 if ($colpiece =~ /\./ && $colpiece !~ /^$attrs->{alias}\./) {
1261 $colpiece = \ sprintf ('%s AS %s', map { $sql_maker->_quote ($_) } ($colpiece, $as) );
1263 push @{$sub_attrs->{select}}, $colpiece;
1267 my @pcols = map { "$attrs->{alias}.$_" } ($rsrc->primary_columns);
1268 $sub_attrs->{select} = @pcols ? \@pcols : [ 1 ];
1271 return $rsrc->resultset_class
1272 ->new ($rsrc, $sub_attrs)
1274 ->search ({}, { columns => { count => $rsrc->storage->_count_select ($rsrc, $attrs) } })
1275 ->get_column ('count');
1282 =head2 count_literal
1286 =item Arguments: $sql_fragment, @bind_values
1288 =item Return Value: $count
1292 Counts the results in a literal query. Equivalent to calling L</search_literal>
1293 with the passed arguments, then L</count>.
1297 sub count_literal { shift->search_literal(@_)->count; }
1303 =item Arguments: none
1305 =item Return Value: @objects
1309 Returns all elements in the resultset. Called implicitly if the resultset
1310 is returned in list context.
1317 $self->throw_exception("all() doesn't take any arguments, you probably wanted ->search(...)->all()");
1320 return @{ $self->get_cache } if $self->get_cache;
1324 if (keys %{$self->_resolved_attrs->{collapse}}) {
1325 # Using $self->cursor->all is really just an optimisation.
1326 # If we're collapsing has_many prefetches it probably makes
1327 # very little difference, and this is cleaner than hacking
1328 # _construct_object to survive the approach
1329 $self->cursor->reset;
1330 my @row = $self->cursor->next;
1332 push(@obj, $self->_construct_object(@row));
1333 @row = (exists $self->{stashed_row}
1334 ? @{delete $self->{stashed_row}}
1335 : $self->cursor->next);
1338 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
1341 $self->set_cache(\@obj) if $self->{attrs}{cache};
1350 =item Arguments: none
1352 =item Return Value: $self
1356 Resets the resultset's cursor, so you can iterate through the elements again.
1357 Implicitly resets the storage cursor, so a subsequent L</next> will trigger
1364 delete $self->{_attrs} if exists $self->{_attrs};
1365 $self->{all_cache_position} = 0;
1366 $self->cursor->reset;
1374 =item Arguments: none
1376 =item Return Value: $object | undef
1380 Resets the resultset and returns an object for the first result (or C<undef>
1381 if the resultset is empty).
1386 return $_[0]->reset->next;
1392 # Determines whether and what type of subquery is required for the $rs operation.
1393 # If grouping is necessary either supplies its own, or verifies the current one
1394 # After all is done delegates to the proper storage method.
1396 sub _rs_update_delete {
1397 my ($self, $op, $values) = @_;
1399 my $rsrc = $self->result_source;
1401 # if a condition exists we need to strip all table qualifiers
1402 # if this is not possible we'll force a subquery below
1403 my $cond = $rsrc->schema->storage->_strip_cond_qualifiers ($self->{cond});
1405 my $needs_group_by_subq = $self->_has_resolved_attr (qw/collapse group_by -join/);
1406 my $needs_subq = $needs_group_by_subq || (not defined $cond) || $self->_has_resolved_attr(qw/rows offset/);
1408 if ($needs_group_by_subq or $needs_subq) {
1410 # make a new $rs selecting only the PKs (that's all we really need)
1411 my $attrs = $self->_resolved_attrs_copy;
1414 delete $attrs->{$_} for qw/collapse _collapse_order_by select _prefetch_select as/;
1415 $attrs->{columns} = [ map { "$attrs->{alias}.$_" } ($self->result_source->_pri_cols) ];
1417 if ($needs_group_by_subq) {
1418 # make sure no group_by was supplied, or if there is one - make sure it matches
1419 # the columns compiled above perfectly. Anything else can not be sanely executed
1420 # on most databases so croak right then and there
1422 if (my $g = $attrs->{group_by}) {
1423 my @current_group_by = map
1424 { $_ =~ /\./ ? $_ : "$attrs->{alias}.$_" }
1429 join ("\x00", sort @current_group_by)
1431 join ("\x00", sort @{$attrs->{columns}} )
1433 $self->throw_exception (
1434 "You have just attempted a $op operation on a resultset which does group_by"
1435 . ' on columns other than the primary keys, while DBIC internally needs to retrieve'
1436 . ' the primary keys in a subselect. All sane RDBMS engines do not support this'
1437 . ' kind of queries. Please retry the operation with a modified group_by or'
1438 . ' without using one at all.'
1443 $attrs->{group_by} = $attrs->{columns};
1447 my $subrs = (ref $self)->new($rsrc, $attrs);
1448 return $self->result_source->storage->_subq_update_delete($subrs, $op, $values);
1451 return $rsrc->storage->$op(
1453 $op eq 'update' ? $values : (),
1463 =item Arguments: \%values
1465 =item Return Value: $storage_rv
1469 Sets the specified columns in the resultset to the supplied values in a
1470 single query. Note that this will not run any accessor/set_column/update
1471 triggers, nor will it update any row object instances derived from this
1472 resultset (this includes the contents of the L<resultset cache|/set_cache>
1473 if any). See L</update_all> if you need to execute any on-update
1474 triggers or cascades defined either by you or a
1475 L<result component|DBIx::Class::Manual::Component/WHAT_IS_A_COMPONENT>.
1477 The return value is a pass through of what the underlying
1478 storage backend returned, and may vary. See L<DBI/execute> for the most
1484 my ($self, $values) = @_;
1485 $self->throw_exception('Values for update must be a hash')
1486 unless ref $values eq 'HASH';
1488 return $self->_rs_update_delete ('update', $values);
1495 =item Arguments: \%values
1497 =item Return Value: 1
1501 Fetches all objects and updates them one at a time via
1502 L<DBIx::Class::Row/update>. Note that C<update_all> will run DBIC defined
1503 triggers, while L</update> will not.
1508 my ($self, $values) = @_;
1509 $self->throw_exception('Values for update_all must be a hash')
1510 unless ref $values eq 'HASH';
1512 my $guard = $self->result_source->schema->txn_scope_guard;
1513 $_->update($values) for $self->all;
1522 =item Arguments: none
1524 =item Return Value: $storage_rv
1528 Deletes the rows matching this resultset in a single query. Note that this
1529 will not run any delete triggers, nor will it alter the
1530 L<in_storage|DBIx::Class::Row/in_storage> status of any row object instances
1531 derived from this resultset (this includes the contents of the
1532 L<resultset cache|/set_cache> if any). See L</delete_all> if you need to
1533 execute any on-delete triggers or cascades defined either by you or a
1534 L<result component|DBIx::Class::Manual::Component/WHAT_IS_A_COMPONENT>.
1536 The return value is a pass through of what the underlying storage backend
1537 returned, and may vary. See L<DBI/execute> for the most common case.
1543 $self->throw_exception('delete does not accept any arguments')
1546 return $self->_rs_update_delete ('delete');
1553 =item Arguments: none
1555 =item Return Value: 1
1559 Fetches all objects and deletes them one at a time via
1560 L<DBIx::Class::Row/delete>. Note that C<delete_all> will run DBIC defined
1561 triggers, while L</delete> will not.
1567 $self->throw_exception('delete_all does not accept any arguments')
1570 my $guard = $self->result_source->schema->txn_scope_guard;
1571 $_->delete for $self->all;
1580 =item Arguments: \@data;
1584 Accepts either an arrayref of hashrefs or alternatively an arrayref of arrayrefs.
1585 For the arrayref of hashrefs style each hashref should be a structure suitable
1586 forsubmitting to a $resultset->create(...) method.
1588 In void context, C<insert_bulk> in L<DBIx::Class::Storage::DBI> is used
1589 to insert the data, as this is a faster method.
1591 Otherwise, each set of data is inserted into the database using
1592 L<DBIx::Class::ResultSet/create>, and the resulting objects are
1593 accumulated into an array. The array itself, or an array reference
1594 is returned depending on scalar or list context.
1596 Example: Assuming an Artist Class that has many CDs Classes relating:
1598 my $Artist_rs = $schema->resultset("Artist");
1600 ## Void Context Example
1601 $Artist_rs->populate([
1602 { artistid => 4, name => 'Manufactured Crap', cds => [
1603 { title => 'My First CD', year => 2006 },
1604 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
1607 { artistid => 5, name => 'Angsty-Whiny Girl', cds => [
1608 { title => 'My parents sold me to a record company', year => 2005 },
1609 { title => 'Why Am I So Ugly?', year => 2006 },
1610 { title => 'I Got Surgery and am now Popular', year => 2007 }
1615 ## Array Context Example
1616 my ($ArtistOne, $ArtistTwo, $ArtistThree) = $Artist_rs->populate([
1617 { name => "Artist One"},
1618 { name => "Artist Two"},
1619 { name => "Artist Three", cds=> [
1620 { title => "First CD", year => 2007},
1621 { title => "Second CD", year => 2008},
1625 print $ArtistOne->name; ## response is 'Artist One'
1626 print $ArtistThree->cds->count ## reponse is '2'
1628 For the arrayref of arrayrefs style, the first element should be a list of the
1629 fieldsnames to which the remaining elements are rows being inserted. For
1632 $Arstist_rs->populate([
1633 [qw/artistid name/],
1634 [100, 'A Formally Unknown Singer'],
1635 [101, 'A singer that jumped the shark two albums ago'],
1636 [102, 'An actually cool singer'],
1639 Please note an important effect on your data when choosing between void and
1640 wantarray context. Since void context goes straight to C<insert_bulk> in
1641 L<DBIx::Class::Storage::DBI> this will skip any component that is overriding
1642 C<insert>. So if you are using something like L<DBIx-Class-UUIDColumns> to
1643 create primary keys for you, you will find that your PKs are empty. In this
1644 case you will have to use the wantarray context in order to create those
1652 # cruft placed in standalone method
1653 my $data = $self->_normalize_populate_args(@_);
1655 if(defined wantarray) {
1657 foreach my $item (@$data) {
1658 push(@created, $self->create($item));
1660 return wantarray ? @created : \@created;
1662 my $first = $data->[0];
1664 # if a column is a registered relationship, and is a non-blessed hash/array, consider
1665 # it relationship data
1666 my (@rels, @columns);
1667 for (keys %$first) {
1668 my $ref = ref $first->{$_};
1669 $self->result_source->has_relationship($_) && ($ref eq 'ARRAY' or $ref eq 'HASH')
1675 my @pks = $self->result_source->primary_columns;
1677 ## do the belongs_to relationships
1678 foreach my $index (0..$#$data) {
1680 # delegate to create() for any dataset without primary keys with specified relationships
1681 if (grep { !defined $data->[$index]->{$_} } @pks ) {
1683 if (grep { ref $data->[$index]{$r} eq $_ } qw/HASH ARRAY/) { # a related set must be a HASH or AoH
1684 my @ret = $self->populate($data);
1690 foreach my $rel (@rels) {
1691 next unless ref $data->[$index]->{$rel} eq "HASH";
1692 my $result = $self->related_resultset($rel)->create($data->[$index]->{$rel});
1693 my ($reverse) = keys %{$self->result_source->reverse_relationship_info($rel)};
1694 my $related = $result->result_source->_resolve_condition(
1695 $result->result_source->relationship_info($reverse)->{cond},
1700 delete $data->[$index]->{$rel};
1701 $data->[$index] = {%{$data->[$index]}, %$related};
1703 push @columns, keys %$related if $index == 0;
1707 ## inherit the data locked in the conditions of the resultset
1708 my ($rs_data) = $self->_merge_cond_with_data({});
1709 delete @{$rs_data}{@columns};
1710 my @inherit_cols = keys %$rs_data;
1711 my @inherit_data = values %$rs_data;
1713 ## do bulk insert on current row
1714 $self->result_source->storage->insert_bulk(
1715 $self->result_source,
1716 [@columns, @inherit_cols],
1717 [ map { [ @$_{@columns}, @inherit_data ] } @$data ],
1720 ## do the has_many relationships
1721 foreach my $item (@$data) {
1723 foreach my $rel (@rels) {
1724 next unless $item->{$rel} && ref $item->{$rel} eq "ARRAY";
1726 my $parent = $self->find({map { $_ => $item->{$_} } @pks})
1727 || $self->throw_exception('Cannot find the relating object.');
1729 my $child = $parent->$rel;
1731 my $related = $child->result_source->_resolve_condition(
1732 $parent->result_source->relationship_info($rel)->{cond},
1737 my @rows_to_add = ref $item->{$rel} eq 'ARRAY' ? @{$item->{$rel}} : ($item->{$rel});
1738 my @populate = map { {%$_, %$related} } @rows_to_add;
1740 $child->populate( \@populate );
1747 # populate() argumnets went over several incarnations
1748 # What we ultimately support is AoH
1749 sub _normalize_populate_args {
1750 my ($self, $arg) = @_;
1752 if (ref $arg eq 'ARRAY') {
1753 if (ref $arg->[0] eq 'HASH') {
1756 elsif (ref $arg->[0] eq 'ARRAY') {
1758 my @colnames = @{$arg->[0]};
1759 foreach my $values (@{$arg}[1 .. $#$arg]) {
1760 push @ret, { map { $colnames[$_] => $values->[$_] } (0 .. $#colnames) };
1766 $self->throw_exception('Populate expects an arrayref of hashrefs or arrayref of arrayrefs');
1773 =item Arguments: none
1775 =item Return Value: $pager
1779 Return Value a L<Data::Page> object for the current resultset. Only makes
1780 sense for queries with a C<page> attribute.
1782 To get the full count of entries for a paged resultset, call
1783 C<total_entries> on the L<Data::Page> object.
1787 # make a wizard good for both a scalar and a hashref
1788 my $mk_lazy_count_wizard = sub {
1789 require Variable::Magic;
1791 my $stash = { total_rs => shift };
1792 my $slot = shift; # only used by the hashref magic
1794 my $magic = Variable::Magic::wizard (
1795 data => sub { $stash },
1801 # set value lazily, and dispell for good
1802 ${$_[0]} = $_[1]{total_rs}->count;
1803 Variable::Magic::dispell (${$_[0]}, $_[1]{magic_selfref});
1807 # an explicit set implies dispell as well
1808 # the unless() is to work around "fun and giggles" below
1809 Variable::Magic::dispell (${$_[0]}, $_[1]{magic_selfref})
1810 unless (caller(2))[3] eq 'DBIx::Class::ResultSet::pager';
1817 if ($_[2] eq $slot and !$_[1]{inactive}) {
1818 my $cnt = $_[1]{total_rs}->count;
1819 $_[0]->{$slot} = $cnt;
1821 # attempting to dispell in a fetch handle (works in store), seems
1822 # to invariable segfault on 5.10, 5.12, 5.13 :(
1823 # so use an inactivator instead
1824 #Variable::Magic::dispell (%{$_[0]}, $_[1]{magic_selfref});
1830 if (! $_[1]{inactive} and $_[2] eq $slot) {
1831 #Variable::Magic::dispell (%{$_[0]}, $_[1]{magic_selfref});
1833 unless (caller(2))[3] eq 'DBIx::Class::ResultSet::pager';
1840 $stash->{magic_selfref} = $magic;
1841 weaken ($stash->{magic_selfref}); # this fails on 5.8.1
1846 # the tie class for 5.8.1
1848 package DBIx::Class::__DBIC_LAZY_RS_COUNT__;
1849 use base qw/Tie::Hash/;
1851 sub FIRSTKEY { my $dummy = scalar keys %{$_[0]{data}}; each %{$_[0]{data}} }
1852 sub NEXTKEY { each %{$_[0]{data}} }
1853 sub EXISTS { exists $_[0]{data}{$_[1]} }
1854 sub DELETE { delete $_[0]{data}{$_[1]} }
1855 sub CLEAR { %{$_[0]{data}} = () }
1856 sub SCALAR { scalar %{$_[0]{data}} }
1859 $_[1]{data} = {%{$_[1]{selfref}}};
1860 %{$_[1]{selfref}} = ();
1861 Scalar::Util::weaken ($_[1]{selfref});
1862 return bless ($_[1], $_[0]);
1866 if ($_[1] eq $_[0]{slot}) {
1867 my $cnt = $_[0]{data}{$_[1]} = $_[0]{total_rs}->count;
1868 untie %{$_[0]{selfref}};
1869 %{$_[0]{selfref}} = %{$_[0]{data}};
1878 $_[0]{data}{$_[1]} = $_[2];
1879 if ($_[1] eq $_[0]{slot}) {
1880 untie %{$_[0]{selfref}};
1881 %{$_[0]{selfref}} = %{$_[0]{data}};
1890 return $self->{pager} if $self->{pager};
1892 if ($self->get_cache) {
1893 $self->throw_exception ('Pagers on cached resultsets are not supported');
1896 my $attrs = $self->{attrs};
1897 $self->throw_exception("Can't create pager for non-paged rs")
1898 unless $self->{attrs}{page};
1899 $attrs->{rows} ||= 10;
1901 # throw away the paging flags and re-run the count (possibly
1902 # with a subselect) to get the real total count
1903 my $count_attrs = { %$attrs };
1904 delete $count_attrs->{$_} for qw/rows offset page pager/;
1905 my $total_rs = (ref $self)->new($self->result_source, $count_attrs);
1908 ### the following may seem awkward and dirty, but it's a thought-experiment
1909 ### necessary for future development of DBIx::DS. Do *NOT* change this code
1910 ### before talking to ribasushi/mst
1912 my $pager = Data::Page->new(
1913 0, #start with an empty set
1915 $self->{attrs}{page},
1918 my $data_slot = 'total_entries';
1920 # Since we are interested in a cached value (once it's set - it's set), every
1921 # technique will detach from the magic-host once the time comes to fire the
1922 # ->count (or in the segfaulting case of >= 5.10 it will deactivate itself)
1924 if ($] < 5.008003) {
1925 # 5.8.1 throws 'Modification of a read-only value attempted' when one tries
1926 # to weakref the magic container :(
1928 tie (%$pager, 'DBIx::Class::__DBIC_LAZY_RS_COUNT__',
1929 { slot => $data_slot, total_rs => $total_rs, selfref => $pager }
1932 elsif ($] < 5.010) {
1933 # We can use magic on the hash value slot. It's interesting that the magic is
1934 # attached to the hash-slot, and does *not* stop working once I do the dummy
1935 # assignments after the cast()
1936 # tested on 5.8.3 and 5.8.9
1937 my $magic = $mk_lazy_count_wizard->($total_rs);
1938 Variable::Magic::cast ( $pager->{$data_slot}, $magic );
1940 # this is for fun and giggles
1941 $pager->{$data_slot} = -1;
1942 $pager->{$data_slot} = 0;
1944 # this does not work for scalars, but works with
1946 #my %vals = %$pager;
1951 # And the uvar magic
1952 # works on 5.10.1, 5.12.1 and 5.13.4 in its current form,
1953 # however see the wizard maker for more notes
1954 my $magic = $mk_lazy_count_wizard->($total_rs, $data_slot);
1955 Variable::Magic::cast ( %$pager, $magic );
1958 $pager->{$data_slot} = -1;
1959 $pager->{$data_slot} = 0;
1967 return $self->{pager} = $pager;
1974 =item Arguments: $page_number
1976 =item Return Value: $rs
1980 Returns a resultset for the $page_number page of the resultset on which page
1981 is called, where each page contains a number of rows equal to the 'rows'
1982 attribute set on the resultset (10 by default).
1987 my ($self, $page) = @_;
1988 return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
1995 =item Arguments: \%vals
1997 =item Return Value: $rowobject
2001 Creates a new row object in the resultset's result class and returns
2002 it. The row is not inserted into the database at this point, call
2003 L<DBIx::Class::Row/insert> to do that. Calling L<DBIx::Class::Row/in_storage>
2004 will tell you whether the row object has been inserted or not.
2006 Passes the hashref of input on to L<DBIx::Class::Row/new>.
2011 my ($self, $values) = @_;
2012 $self->throw_exception( "new_result needs a hash" )
2013 unless (ref $values eq 'HASH');
2015 my ($merged_cond, $cols_from_relations) = $self->_merge_cond_with_data($values);
2019 @$cols_from_relations
2020 ? (-cols_from_relations => $cols_from_relations)
2022 -source_handle => $self->_source_handle,
2023 -result_source => $self->result_source, # DO NOT REMOVE THIS, REQUIRED
2026 return $self->result_class->new(\%new);
2029 # _merge_cond_with_data
2031 # Takes a simple hash of K/V data and returns its copy merged with the
2032 # condition already present on the resultset. Additionally returns an
2033 # arrayref of value/condition names, which were inferred from related
2034 # objects (this is needed for in-memory related objects)
2035 sub _merge_cond_with_data {
2036 my ($self, $data) = @_;
2038 my (%new_data, @cols_from_relations);
2040 my $alias = $self->{attrs}{alias};
2042 if (! defined $self->{cond}) {
2043 # just massage $data below
2045 elsif ($self->{cond} eq $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION) {
2046 %new_data = %{ $self->{attrs}{related_objects} || {} }; # nothing might have been inserted yet
2047 @cols_from_relations = keys %new_data;
2049 elsif (ref $self->{cond} ne 'HASH') {
2050 $self->throw_exception(
2051 "Can't abstract implicit construct, resultset condition not a hash"
2055 # precendence must be given to passed values over values inherited from
2056 # the cond, so the order here is important.
2057 my $collapsed_cond = $self->_collapse_cond($self->{cond});
2058 my %implied = %{$self->_remove_alias($collapsed_cond, $alias)};
2060 while ( my($col, $value) = each %implied ) {
2061 if (ref($value) eq 'HASH' && keys(%$value) && (keys %$value)[0] eq '=') {
2062 $new_data{$col} = $value->{'='};
2065 $new_data{$col} = $value if $self->_is_deterministic_value($value);
2071 %{ $self->_remove_alias($data, $alias) },
2074 return (\%new_data, \@cols_from_relations);
2077 # _is_deterministic_value
2079 # Make an effor to strip non-deterministic values from the condition,
2080 # to make sure new_result chokes less
2082 sub _is_deterministic_value {
2085 my $ref_type = ref $value;
2086 return 1 if $ref_type eq '' || $ref_type eq 'SCALAR';
2087 return 1 if blessed $value;
2091 # _has_resolved_attr
2093 # determines if the resultset defines at least one
2094 # of the attributes supplied
2096 # used to determine if a subquery is neccessary
2098 # supports some virtual attributes:
2100 # This will scan for any joins being present on the resultset.
2101 # It is not a mere key-search but a deep inspection of {from}
2104 sub _has_resolved_attr {
2105 my ($self, @attr_names) = @_;
2107 my $attrs = $self->_resolved_attrs;
2111 for my $n (@attr_names) {
2112 if (grep { $n eq $_ } (qw/-join/) ) {
2113 $extra_checks{$n}++;
2117 my $attr = $attrs->{$n};
2119 next if not defined $attr;
2121 if (ref $attr eq 'HASH') {
2122 return 1 if keys %$attr;
2124 elsif (ref $attr eq 'ARRAY') {
2132 # a resolved join is expressed as a multi-level from
2134 $extra_checks{-join}
2136 ref $attrs->{from} eq 'ARRAY'
2138 @{$attrs->{from}} > 1
2146 # Recursively collapse the condition.
2148 sub _collapse_cond {
2149 my ($self, $cond, $collapsed) = @_;
2153 if (ref $cond eq 'ARRAY') {
2154 foreach my $subcond (@$cond) {
2155 next unless ref $subcond; # -or
2156 $collapsed = $self->_collapse_cond($subcond, $collapsed);
2159 elsif (ref $cond eq 'HASH') {
2160 if (keys %$cond and (keys %$cond)[0] eq '-and') {
2161 foreach my $subcond (@{$cond->{-and}}) {
2162 $collapsed = $self->_collapse_cond($subcond, $collapsed);
2166 foreach my $col (keys %$cond) {
2167 my $value = $cond->{$col};
2168 $collapsed->{$col} = $value;
2178 # Remove the specified alias from the specified query hash. A copy is made so
2179 # the original query is not modified.
2182 my ($self, $query, $alias) = @_;
2184 my %orig = %{ $query || {} };
2187 foreach my $key (keys %orig) {
2189 $unaliased{$key} = $orig{$key};
2192 $unaliased{$1} = $orig{$key}
2193 if $key =~ m/^(?:\Q$alias\E\.)?([^.]+)$/;
2203 =item Arguments: none
2205 =item Return Value: \[ $sql, @bind ]
2209 Returns the SQL query and bind vars associated with the invocant.
2211 This is generally used as the RHS for a subquery.
2218 my $attrs = $self->_resolved_attrs_copy;
2223 # my ($sql, \@bind, \%dbi_bind_attrs) = _select_args_to_query (...)
2224 # $sql also has no wrapping parenthesis in list ctx
2226 my $sqlbind = $self->result_source->storage
2227 ->_select_args_to_query ($attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs);
2236 =item Arguments: \%vals, \%attrs?
2238 =item Return Value: $rowobject
2242 my $artist = $schema->resultset('Artist')->find_or_new(
2243 { artist => 'fred' }, { key => 'artists' });
2245 $cd->cd_to_producer->find_or_new({ producer => $producer },
2246 { key => 'primary });
2248 Find an existing record from this resultset, based on its primary
2249 key, or a unique constraint. If none exists, instantiate a new result
2250 object and return it. The object will not be saved into your storage
2251 until you call L<DBIx::Class::Row/insert> on it.
2253 You most likely want this method when looking for existing rows using
2254 a unique constraint that is not the primary key, or looking for
2257 If you want objects to be saved immediately, use L</find_or_create>
2260 B<Note>: Take care when using C<find_or_new> with a table having
2261 columns with default values that you intend to be automatically
2262 supplied by the database (e.g. an auto_increment primary key column).
2263 In normal usage, the value of such columns should NOT be included at
2264 all in the call to C<find_or_new>, even when set to C<undef>.
2270 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2271 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
2272 if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2275 return $self->new_result($hash);
2282 =item Arguments: \%vals
2284 =item Return Value: a L<DBIx::Class::Row> $object
2288 Attempt to create a single new row or a row with multiple related rows
2289 in the table represented by the resultset (and related tables). This
2290 will not check for duplicate rows before inserting, use
2291 L</find_or_create> to do that.
2293 To create one row for this resultset, pass a hashref of key/value
2294 pairs representing the columns of the table and the values you wish to
2295 store. If the appropriate relationships are set up, foreign key fields
2296 can also be passed an object representing the foreign row, and the
2297 value will be set to its primary key.
2299 To create related objects, pass a hashref of related-object column values
2300 B<keyed on the relationship name>. If the relationship is of type C<multi>
2301 (L<DBIx::Class::Relationship/has_many>) - pass an arrayref of hashrefs.
2302 The process will correctly identify columns holding foreign keys, and will
2303 transparently populate them from the keys of the corresponding relation.
2304 This can be applied recursively, and will work correctly for a structure
2305 with an arbitrary depth and width, as long as the relationships actually
2306 exists and the correct column data has been supplied.
2309 Instead of hashrefs of plain related data (key/value pairs), you may
2310 also pass new or inserted objects. New objects (not inserted yet, see
2311 L</new>), will be inserted into their appropriate tables.
2313 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
2315 Example of creating a new row.
2317 $person_rs->create({
2318 name=>"Some Person",
2319 email=>"somebody@someplace.com"
2322 Example of creating a new row and also creating rows in a related C<has_many>
2323 or C<has_one> resultset. Note Arrayref.
2326 { artistid => 4, name => 'Manufactured Crap', cds => [
2327 { title => 'My First CD', year => 2006 },
2328 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
2333 Example of creating a new row and also creating a row in a related
2334 C<belongs_to> resultset. Note Hashref.
2337 title=>"Music for Silly Walks",
2340 name=>"Silly Musician",
2348 When subclassing ResultSet never attempt to override this method. Since
2349 it is a simple shortcut for C<< $self->new_result($attrs)->insert >>, a
2350 lot of the internals simply never call it, so your override will be
2351 bypassed more often than not. Override either L<new|DBIx::Class::Row/new>
2352 or L<insert|DBIx::Class::Row/insert> depending on how early in the
2353 L</create> process you need to intervene.
2360 my ($self, $attrs) = @_;
2361 $self->throw_exception( "create needs a hashref" )
2362 unless ref $attrs eq 'HASH';
2363 return $self->new_result($attrs)->insert;
2366 =head2 find_or_create
2370 =item Arguments: \%vals, \%attrs?
2372 =item Return Value: $rowobject
2376 $cd->cd_to_producer->find_or_create({ producer => $producer },
2377 { key => 'primary' });
2379 Tries to find a record based on its primary key or unique constraints; if none
2380 is found, creates one and returns that instead.
2382 my $cd = $schema->resultset('CD')->find_or_create({
2384 artist => 'Massive Attack',
2385 title => 'Mezzanine',
2389 Also takes an optional C<key> attribute, to search by a specific key or unique
2390 constraint. For example:
2392 my $cd = $schema->resultset('CD')->find_or_create(
2394 artist => 'Massive Attack',
2395 title => 'Mezzanine',
2397 { key => 'cd_artist_title' }
2400 B<Note>: Because find_or_create() reads from the database and then
2401 possibly inserts based on the result, this method is subject to a race
2402 condition. Another process could create a record in the table after
2403 the find has completed and before the create has started. To avoid
2404 this problem, use find_or_create() inside a transaction.
2406 B<Note>: Take care when using C<find_or_create> with a table having
2407 columns with default values that you intend to be automatically
2408 supplied by the database (e.g. an auto_increment primary key column).
2409 In normal usage, the value of such columns should NOT be included at
2410 all in the call to C<find_or_create>, even when set to C<undef>.
2412 See also L</find> and L</update_or_create>. For information on how to declare
2413 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2417 sub find_or_create {
2419 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2420 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
2421 if (keys %$hash and my $row = $self->find($hash, $attrs) ) {
2424 return $self->create($hash);
2427 =head2 update_or_create
2431 =item Arguments: \%col_values, { key => $unique_constraint }?
2433 =item Return Value: $rowobject
2437 $resultset->update_or_create({ col => $val, ... });
2439 First, searches for an existing row matching one of the unique constraints
2440 (including the primary key) on the source of this resultset. If a row is
2441 found, updates it with the other given column values. Otherwise, creates a new
2444 Takes an optional C<key> attribute to search on a specific unique constraint.
2447 # In your application
2448 my $cd = $schema->resultset('CD')->update_or_create(
2450 artist => 'Massive Attack',
2451 title => 'Mezzanine',
2454 { key => 'cd_artist_title' }
2457 $cd->cd_to_producer->update_or_create({
2458 producer => $producer,
2465 If no C<key> is specified, it searches on all unique constraints defined on the
2466 source, including the primary key.
2468 If the C<key> is specified as C<primary>, it searches only on the primary key.
2470 See also L</find> and L</find_or_create>. For information on how to declare
2471 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
2473 B<Note>: Take care when using C<update_or_create> with a table having
2474 columns with default values that you intend to be automatically
2475 supplied by the database (e.g. an auto_increment primary key column).
2476 In normal usage, the value of such columns should NOT be included at
2477 all in the call to C<update_or_create>, even when set to C<undef>.
2481 sub update_or_create {
2483 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
2484 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
2486 my $row = $self->find($cond, $attrs);
2488 $row->update($cond);
2492 return $self->create($cond);
2495 =head2 update_or_new
2499 =item Arguments: \%col_values, { key => $unique_constraint }?
2501 =item Return Value: $rowobject
2505 $resultset->update_or_new({ col => $val, ... });
2507 First, searches for an existing row matching one of the unique constraints
2508 (including the primary key) on the source of this resultset. If a row is
2509 found, updates it with the other given column values. Otherwise, instantiate
2510 a new result object and return it. The object will not be saved into your storage
2511 until you call L<DBIx::Class::Row/insert> on it.
2513 Takes an optional C<key> attribute to search on a specific unique constraint.
2516 # In your application
2517 my $cd = $schema->resultset('CD')->update_or_new(
2519 artist => 'Massive Attack',
2520 title => 'Mezzanine',
2523 { key => 'cd_artist_title' }
2526 if ($cd->in_storage) {
2527 # the cd was updated
2530 # the cd is not yet in the database, let's insert it
2534 B<Note>: Take care when using C<update_or_new> with a table having
2535 columns with default values that you intend to be automatically
2536 supplied by the database (e.g. an auto_increment primary key column).
2537 In normal usage, the value of such columns should NOT be included at
2538 all in the call to C<update_or_new>, even when set to C<undef>.
2540 See also L</find>, L</find_or_create> and L</find_or_new>.
2546 my $attrs = ( @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {} );
2547 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
2549 my $row = $self->find( $cond, $attrs );
2550 if ( defined $row ) {
2551 $row->update($cond);
2555 return $self->new_result($cond);
2562 =item Arguments: none
2564 =item Return Value: \@cache_objects | undef
2568 Gets the contents of the cache for the resultset, if the cache is set.
2570 The cache is populated either by using the L</prefetch> attribute to
2571 L</search> or by calling L</set_cache>.
2583 =item Arguments: \@cache_objects
2585 =item Return Value: \@cache_objects
2589 Sets the contents of the cache for the resultset. Expects an arrayref
2590 of objects of the same class as those produced by the resultset. Note that
2591 if the cache is set the resultset will return the cached objects rather
2592 than re-querying the database even if the cache attr is not set.
2594 The contents of the cache can also be populated by using the
2595 L</prefetch> attribute to L</search>.
2600 my ( $self, $data ) = @_;
2601 $self->throw_exception("set_cache requires an arrayref")
2602 if defined($data) && (ref $data ne 'ARRAY');
2603 $self->{all_cache} = $data;
2610 =item Arguments: none
2612 =item Return Value: undef
2616 Clears the cache for the resultset.
2621 shift->set_cache(undef);
2628 =item Arguments: none
2630 =item Return Value: true, if the resultset has been paginated
2638 return !!$self->{attrs}{page};
2645 =item Arguments: none
2647 =item Return Value: true, if the resultset has been ordered with C<order_by>.
2655 return scalar $self->result_source->storage->_extract_order_columns($self->{attrs}{order_by});
2658 =head2 related_resultset
2662 =item Arguments: $relationship_name
2664 =item Return Value: $resultset
2668 Returns a related resultset for the supplied relationship name.
2670 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
2674 sub related_resultset {
2675 my ($self, $rel) = @_;
2677 $self->{related_resultsets} ||= {};
2678 return $self->{related_resultsets}{$rel} ||= do {
2679 my $rsrc = $self->result_source;
2680 my $rel_info = $rsrc->relationship_info($rel);
2682 $self->throw_exception(
2683 "search_related: result source '" . $rsrc->source_name .
2684 "' has no such relationship $rel")
2687 my $attrs = $self->_chain_relationship($rel);
2689 my $join_count = $attrs->{seen_join}{$rel};
2691 my $alias = $self->result_source->storage
2692 ->relname_to_table_alias($rel, $join_count);
2694 # since this is search_related, and we already slid the select window inwards
2695 # (the select/as attrs were deleted in the beginning), we need to flip all
2696 # left joins to inner, so we get the expected results
2697 # read the comment on top of the actual function to see what this does
2698 $attrs->{from} = $rsrc->schema->storage->_inner_join_to_node ($attrs->{from}, $alias);
2701 #XXX - temp fix for result_class bug. There likely is a more elegant fix -groditi
2702 delete @{$attrs}{qw(result_class alias)};
2706 if (my $cache = $self->get_cache) {
2707 if ($cache->[0] && $cache->[0]->related_resultset($rel)->get_cache) {
2708 $new_cache = [ map { @{$_->related_resultset($rel)->get_cache} }
2713 my $rel_source = $rsrc->related_source($rel);
2717 # The reason we do this now instead of passing the alias to the
2718 # search_rs below is that if you wrap/overload resultset on the
2719 # source you need to know what alias it's -going- to have for things
2720 # to work sanely (e.g. RestrictWithObject wants to be able to add
2721 # extra query restrictions, and these may need to be $alias.)
2723 my $rel_attrs = $rel_source->resultset_attributes;
2724 local $rel_attrs->{alias} = $alias;
2726 $rel_source->resultset
2730 where => $attrs->{where},
2733 $new->set_cache($new_cache) if $new_cache;
2738 =head2 current_source_alias
2742 =item Arguments: none
2744 =item Return Value: $source_alias
2748 Returns the current table alias for the result source this resultset is built
2749 on, that will be used in the SQL query. Usually it is C<me>.
2751 Currently the source alias that refers to the result set returned by a
2752 L</search>/L</find> family method depends on how you got to the resultset: it's
2753 C<me> by default, but eg. L</search_related> aliases it to the related result
2754 source name (and keeps C<me> referring to the original result set). The long
2755 term goal is to make L<DBIx::Class> always alias the current resultset as C<me>
2756 (and make this method unnecessary).
2758 Thus it's currently necessary to use this method in predefined queries (see
2759 L<DBIx::Class::Manual::Cookbook/Predefined searches>) when referring to the
2760 source alias of the current result set:
2762 # in a result set class
2764 my ($self, $user) = @_;
2766 my $me = $self->current_source_alias;
2768 return $self->search(
2769 "$me.modified" => $user->id,
2775 sub current_source_alias {
2778 return ($self->{attrs} || {})->{alias} || 'me';
2781 =head2 as_subselect_rs
2785 =item Arguments: none
2787 =item Return Value: $resultset
2791 Act as a barrier to SQL symbols. The resultset provided will be made into a
2792 "virtual view" by including it as a subquery within the from clause. From this
2793 point on, any joined tables are inaccessible to ->search on the resultset (as if
2794 it were simply where-filtered without joins). For example:
2796 my $rs = $schema->resultset('Bar')->search({'x.name' => 'abc'},{ join => 'x' });
2798 # 'x' now pollutes the query namespace
2800 # So the following works as expected
2801 my $ok_rs = $rs->search({'x.other' => 1});
2803 # But this doesn't: instead of finding a 'Bar' related to two x rows (abc and
2804 # def) we look for one row with contradictory terms and join in another table
2805 # (aliased 'x_2') which we never use
2806 my $broken_rs = $rs->search({'x.name' => 'def'});
2808 my $rs2 = $rs->as_subselect_rs;
2810 # doesn't work - 'x' is no longer accessible in $rs2, having been sealed away
2811 my $not_joined_rs = $rs2->search({'x.other' => 1});
2813 # works as expected: finds a 'table' row related to two x rows (abc and def)
2814 my $correctly_joined_rs = $rs2->search({'x.name' => 'def'});
2816 Another example of when one might use this would be to select a subset of
2817 columns in a group by clause:
2819 my $rs = $schema->resultset('Bar')->search(undef, {
2820 group_by => [qw{ id foo_id baz_id }],
2821 })->as_subselect_rs->search(undef, {
2822 columns => [qw{ id foo_id }]
2825 In the above example normally columns would have to be equal to the group by,
2826 but because we isolated the group by into a subselect the above works.
2830 sub as_subselect_rs {
2833 my $attrs = $self->_resolved_attrs;
2835 my $fresh_rs = (ref $self)->new (
2836 $self->result_source
2839 # these pieces will be locked in the subquery
2840 delete $fresh_rs->{cond};
2841 delete @{$fresh_rs->{attrs}}{qw/where bind/};
2843 return $fresh_rs->search( {}, {
2845 $attrs->{alias} => $self->as_query,
2846 -alias => $attrs->{alias},
2847 -source_handle => $self->result_source->handle,
2849 alias => $attrs->{alias},
2853 # This code is called by search_related, and makes sure there
2854 # is clear separation between the joins before, during, and
2855 # after the relationship. This information is needed later
2856 # in order to properly resolve prefetch aliases (any alias
2857 # with a relation_chain_depth less than the depth of the
2858 # current prefetch is not considered)
2860 # The increments happen twice per join. An even number means a
2861 # relationship specified via a search_related, whereas an odd
2862 # number indicates a join/prefetch added via attributes
2864 # Also this code will wrap the current resultset (the one we
2865 # chain to) in a subselect IFF it contains limiting attributes
2866 sub _chain_relationship {
2867 my ($self, $rel) = @_;
2868 my $source = $self->result_source;
2869 my $attrs = { %{$self->{attrs}||{}} };
2871 # we need to take the prefetch the attrs into account before we
2872 # ->_resolve_join as otherwise they get lost - captainL
2873 my $join = $self->_merge_attr( $attrs->{join}, $attrs->{prefetch} );
2875 delete @{$attrs}{qw/join prefetch collapse group_by distinct select as columns +select +as +columns/};
2877 my $seen = { %{ (delete $attrs->{seen_join}) || {} } };
2880 my @force_subq_attrs = qw/offset rows group_by having/;
2883 ($attrs->{from} && ref $attrs->{from} ne 'ARRAY')
2885 $self->_has_resolved_attr (@force_subq_attrs)
2887 # Nuke the prefetch (if any) before the new $rs attrs
2888 # are resolved (prefetch is useless - we are wrapping
2889 # a subquery anyway).
2890 my $rs_copy = $self->search;
2891 $rs_copy->{attrs}{join} = $self->_merge_attr (
2892 $rs_copy->{attrs}{join},
2893 delete $rs_copy->{attrs}{prefetch},
2897 -source_handle => $source->handle,
2898 -alias => $attrs->{alias},
2899 $attrs->{alias} => $rs_copy->as_query,
2901 delete @{$attrs}{@force_subq_attrs, qw/where bind/};
2902 $seen->{-relation_chain_depth} = 0;
2904 elsif ($attrs->{from}) { #shallow copy suffices
2905 $from = [ @{$attrs->{from}} ];
2909 -source_handle => $source->handle,
2910 -alias => $attrs->{alias},
2911 $attrs->{alias} => $source->from,
2915 my $jpath = ($seen->{-relation_chain_depth})
2916 ? $from->[-1][0]{-join_path}
2919 my @requested_joins = $source->_resolve_join(
2926 push @$from, @requested_joins;
2928 $seen->{-relation_chain_depth}++;
2930 # if $self already had a join/prefetch specified on it, the requested
2931 # $rel might very well be already included. What we do in this case
2932 # is effectively a no-op (except that we bump up the chain_depth on
2933 # the join in question so we could tell it *is* the search_related)
2936 # we consider the last one thus reverse
2937 for my $j (reverse @requested_joins) {
2938 my ($last_j) = keys %{$j->[0]{-join_path}[-1]};
2939 if ($rel eq $last_j) {
2940 $j->[0]{-relation_chain_depth}++;
2946 unless ($already_joined) {
2947 push @$from, $source->_resolve_join(
2955 $seen->{-relation_chain_depth}++;
2957 return {%$attrs, from => $from, seen_join => $seen};
2960 # too many times we have to do $attrs = { %{$self->_resolved_attrs} }
2961 sub _resolved_attrs_copy {
2963 return { %{$self->_resolved_attrs (@_)} };
2966 sub _resolved_attrs {
2968 return $self->{_attrs} if $self->{_attrs};
2970 my $attrs = { %{ $self->{attrs} || {} } };
2971 my $source = $self->result_source;
2972 my $alias = $attrs->{alias};
2974 $attrs->{columns} ||= delete $attrs->{cols} if exists $attrs->{cols};
2977 # build columns (as long as select isn't set) into a set of as/select hashes
2978 unless ( $attrs->{select} ) {
2981 if ( ref $attrs->{columns} eq 'ARRAY' ) {
2982 @cols = @{ delete $attrs->{columns}}
2983 } elsif ( defined $attrs->{columns} ) {
2984 @cols = delete $attrs->{columns}
2986 @cols = $source->columns
2990 if ( ref $_ eq 'HASH' ) {
2993 my $key = /^\Q${alias}.\E(.+)$/
2999 push @colbits, { $key => $value };
3004 # add the additional columns on
3005 foreach (qw{include_columns +columns}) {
3006 if ( $attrs->{$_} ) {
3007 my @list = ( ref($attrs->{$_}) eq 'ARRAY' )
3008 ? @{ delete $attrs->{$_} }
3009 : delete $attrs->{$_};
3011 if ( ref($_) eq 'HASH' ) {
3014 my $key = ( split /\./, $_ )[-1];
3015 my $value = ( /\./ ? $_ : "$alias.$_" );
3016 push @colbits, { $key => $value };
3022 # start with initial select items
3023 if ( $attrs->{select} ) {
3025 ( ref $attrs->{select} eq 'ARRAY' )
3026 ? [ @{ $attrs->{select} } ]
3027 : [ $attrs->{select} ];
3029 if ( $attrs->{as} ) {
3032 ref $attrs->{as} eq 'ARRAY'
3033 ? [ @{ $attrs->{as} } ]
3037 $attrs->{as} = [ map {
3038 m/^\Q${alias}.\E(.+)$/
3041 } @{ $attrs->{select} }
3047 # otherwise we intialise select & as to empty
3048 $attrs->{select} = [];
3052 # now add colbits to select/as
3053 push @{ $attrs->{select} }, map values %{$_}, @colbits;
3054 push @{ $attrs->{as} }, map keys %{$_}, @colbits;
3056 if ( my $adds = delete $attrs->{'+select'} ) {
3057 $adds = [$adds] unless ref $adds eq 'ARRAY';
3058 push @{ $attrs->{select} },
3059 map { /\./ || ref $_ ? $_ : "$alias.$_" } @$adds;
3061 if ( my $adds = delete $attrs->{'+as'} ) {
3062 $adds = [$adds] unless ref $adds eq 'ARRAY';
3063 push @{ $attrs->{as} }, @$adds;
3066 $attrs->{from} ||= [{
3067 -source_handle => $source->handle,
3068 -alias => $self->{attrs}{alias},
3069 $self->{attrs}{alias} => $source->from,
3072 if ( $attrs->{join} || $attrs->{prefetch} ) {
3074 $self->throw_exception ('join/prefetch can not be used with a custom {from}')
3075 if ref $attrs->{from} ne 'ARRAY';
3077 my $join = delete $attrs->{join} || {};
3079 if ( defined $attrs->{prefetch} ) {
3080 $join = $self->_merge_attr( $join, $attrs->{prefetch} );
3083 $attrs->{from} = # have to copy here to avoid corrupting the original
3085 @{ $attrs->{from} },
3086 $source->_resolve_join(
3089 { %{ $attrs->{seen_join} || {} } },
3090 ( $attrs->{seen_join} && keys %{$attrs->{seen_join}})
3091 ? $attrs->{from}[-1][0]{-join_path}
3098 if ( defined $attrs->{order_by} ) {
3099 $attrs->{order_by} = (
3100 ref( $attrs->{order_by} ) eq 'ARRAY'
3101 ? [ @{ $attrs->{order_by} } ]
3102 : [ $attrs->{order_by} || () ]
3106 if ($attrs->{group_by} and ref $attrs->{group_by} ne 'ARRAY') {
3107 $attrs->{group_by} = [ $attrs->{group_by} ];
3110 # generate the distinct induced group_by early, as prefetch will be carried via a
3111 # subquery (since a group_by is present)
3112 if (delete $attrs->{distinct}) {
3113 if ($attrs->{group_by}) {
3114 carp ("Useless use of distinct on a grouped resultset ('distinct' is ignored when a 'group_by' is present)");
3117 my $storage = $self->result_source->schema->storage;
3118 my $rs_column_list = $storage->_resolve_column_info ($attrs->{from});
3120 my $group_spec = $attrs->{group_by} = [];
3123 for (@{$attrs->{select}}) {
3124 if (! ref($_) or ref ($_) ne 'HASH' ) {
3125 push @$group_spec, $_;
3127 if ($rs_column_list->{$_} and $_ !~ /\./ ) {
3128 # add a fully qualified version as well
3129 $group_index{"$rs_column_list->{$_}{-source_alias}.$_"}++;
3133 # add any order_by parts that are not already present in the group_by
3134 # we need to be careful not to add any named functions/aggregates
3135 # i.e. select => [ ... { count => 'foo', -as 'foocount' } ... ]
3136 for my $chunk ($storage->_extract_order_columns($attrs->{order_by})) {
3138 # only consider real columns (for functions the user got to do an explicit group_by)
3139 my $colinfo = $rs_column_list->{$chunk}
3142 $chunk = "$colinfo->{-source_alias}.$chunk" if $chunk !~ /\./;
3143 push @$group_spec, $chunk unless $group_index{$chunk}++;
3148 $attrs->{collapse} ||= {};
3149 if ( my $prefetch = delete $attrs->{prefetch} ) {
3150 $prefetch = $self->_merge_attr( {}, $prefetch );
3152 my $prefetch_ordering = [];
3154 # this is a separate structure (we don't look in {from} directly)
3155 # as the resolver needs to shift things off the lists to work
3156 # properly (identical-prefetches on different branches)
3158 if (ref $attrs->{from} eq 'ARRAY') {
3160 my $start_depth = $attrs->{seen_join}{-relation_chain_depth} || 0;
3162 for my $j ( @{$attrs->{from}}[1 .. $#{$attrs->{from}} ] ) {
3163 next unless $j->[0]{-alias};
3164 next unless $j->[0]{-join_path};
3165 next if ($j->[0]{-relation_chain_depth} || 0) < $start_depth;
3167 my @jpath = map { keys %$_ } @{$j->[0]{-join_path}};
3170 $p = $p->{$_} ||= {} for @jpath[ ($start_depth/2) .. $#jpath]; #only even depths are actual jpath boundaries
3171 push @{$p->{-join_aliases} }, $j->[0]{-alias};
3176 $source->_resolve_prefetch( $prefetch, $alias, $join_map, $prefetch_ordering, $attrs->{collapse} );
3178 # we need to somehow mark which columns came from prefetch
3179 $attrs->{_prefetch_select} = [ map { $_->[0] } @prefetch ];
3181 push @{ $attrs->{select} }, @{$attrs->{_prefetch_select}};
3182 push @{ $attrs->{as} }, (map { $_->[1] } @prefetch);
3184 push( @{$attrs->{order_by}}, @$prefetch_ordering );
3185 $attrs->{_collapse_order_by} = \@$prefetch_ordering;
3188 # if both page and offset are specified, produce a combined offset
3189 # even though it doesn't make much sense, this is what pre 081xx has
3191 if (my $page = delete $attrs->{page}) {
3193 ($attrs->{rows} * ($page - 1))
3195 ($attrs->{offset} || 0)
3199 return $self->{_attrs} = $attrs;
3203 my ($self, $attr) = @_;
3205 if (ref $attr eq 'HASH') {
3206 return $self->_rollout_hash($attr);
3207 } elsif (ref $attr eq 'ARRAY') {
3208 return $self->_rollout_array($attr);
3214 sub _rollout_array {
3215 my ($self, $attr) = @_;
3218 foreach my $element (@{$attr}) {
3219 if (ref $element eq 'HASH') {
3220 push( @rolled_array, @{ $self->_rollout_hash( $element ) } );
3221 } elsif (ref $element eq 'ARRAY') {
3222 # XXX - should probably recurse here
3223 push( @rolled_array, @{$self->_rollout_array($element)} );
3225 push( @rolled_array, $element );
3228 return \@rolled_array;
3232 my ($self, $attr) = @_;
3235 foreach my $key (keys %{$attr}) {
3236 push( @rolled_array, { $key => $attr->{$key} } );
3238 return \@rolled_array;
3241 sub _calculate_score {
3242 my ($self, $a, $b) = @_;
3244 if (defined $a xor defined $b) {
3247 elsif (not defined $a) {
3251 if (ref $b eq 'HASH') {
3252 my ($b_key) = keys %{$b};
3253 if (ref $a eq 'HASH') {
3254 my ($a_key) = keys %{$a};
3255 if ($a_key eq $b_key) {
3256 return (1 + $self->_calculate_score( $a->{$a_key}, $b->{$b_key} ));
3261 return ($a eq $b_key) ? 1 : 0;
3264 if (ref $a eq 'HASH') {
3265 my ($a_key) = keys %{$a};
3266 return ($b eq $a_key) ? 1 : 0;
3268 return ($b eq $a) ? 1 : 0;
3274 my ($self, $orig, $import) = @_;
3276 return $import unless defined($orig);
3277 return $orig unless defined($import);
3279 $orig = $self->_rollout_attr($orig);
3280 $import = $self->_rollout_attr($import);
3283 foreach my $import_element ( @{$import} ) {
3284 # find best candidate from $orig to merge $b_element into
3285 my $best_candidate = { position => undef, score => 0 }; my $position = 0;
3286 foreach my $orig_element ( @{$orig} ) {
3287 my $score = $self->_calculate_score( $orig_element, $import_element );
3288 if ($score > $best_candidate->{score}) {
3289 $best_candidate->{position} = $position;
3290 $best_candidate->{score} = $score;
3294 my ($import_key) = ( ref $import_element eq 'HASH' ) ? keys %{$import_element} : ($import_element);
3296 if ($best_candidate->{score} == 0 || exists $seen_keys->{$import_key}) {
3297 push( @{$orig}, $import_element );
3299 my $orig_best = $orig->[$best_candidate->{position}];
3300 # merge orig_best and b_element together and replace original with merged
3301 if (ref $orig_best ne 'HASH') {
3302 $orig->[$best_candidate->{position}] = $import_element;
3303 } elsif (ref $import_element eq 'HASH') {
3304 my ($key) = keys %{$orig_best};
3305 $orig->[$best_candidate->{position}] = { $key => $self->_merge_attr($orig_best->{$key}, $import_element->{$key}) };
3308 $seen_keys->{$import_key} = 1; # don't merge the same key twice
3318 $self->_source_handle($_[0]->handle);
3320 $self->_source_handle->resolve;
3324 =head2 throw_exception
3326 See L<DBIx::Class::Schema/throw_exception> for details.
3330 sub throw_exception {
3333 if (ref $self && $self->_source_handle->schema) {
3334 $self->_source_handle->schema->throw_exception(@_)
3337 DBIx::Class::Exception->throw(@_);
3341 # XXX: FIXME: Attributes docs need clearing up
3345 Attributes are used to refine a ResultSet in various ways when
3346 searching for data. They can be passed to any method which takes an
3347 C<\%attrs> argument. See L</search>, L</search_rs>, L</find>,
3350 These are in no particular order:
3356 =item Value: ( $order_by | \@order_by | \%order_by )
3360 Which column(s) to order the results by.
3362 [The full list of suitable values is documented in
3363 L<SQL::Abstract/"ORDER BY CLAUSES">; the following is a summary of
3366 If a single column name, or an arrayref of names is supplied, the
3367 argument is passed through directly to SQL. The hashref syntax allows
3368 for connection-agnostic specification of ordering direction:
3370 For descending order:
3372 order_by => { -desc => [qw/col1 col2 col3/] }
3374 For explicit ascending order:
3376 order_by => { -asc => 'col' }
3378 The old scalarref syntax (i.e. order_by => \'year DESC') is still
3379 supported, although you are strongly encouraged to use the hashref
3380 syntax as outlined above.
3386 =item Value: \@columns
3390 Shortcut to request a particular set of columns to be retrieved. Each
3391 column spec may be a string (a table column name), or a hash (in which
3392 case the key is the C<as> value, and the value is used as the C<select>
3393 expression). Adds C<me.> onto the start of any column without a C<.> in
3394 it and sets C<select> from that, then auto-populates C<as> from
3395 C<select> as normal. (You may also use the C<cols> attribute, as in
3396 earlier versions of DBIC.)
3398 Essentially C<columns> does the same as L</select> and L</as>.
3400 columns => [ 'foo', { bar => 'baz' } ]
3404 select => [qw/foo baz/],
3411 =item Value: \@columns
3415 Indicates additional columns to be selected from storage. Works the same
3416 as L</columns> but adds columns to the selection. (You may also use the
3417 C<include_columns> attribute, as in earlier versions of DBIC). For
3420 $schema->resultset('CD')->search(undef, {
3421 '+columns' => ['artist.name'],
3425 would return all CDs and include a 'name' column to the information
3426 passed to object inflation. Note that the 'artist' is the name of the
3427 column (or relationship) accessor, and 'name' is the name of the column
3428 accessor in the related table.
3430 =head2 include_columns
3434 =item Value: \@columns
3438 Deprecated. Acts as a synonym for L</+columns> for backward compatibility.
3444 =item Value: \@select_columns
3448 Indicates which columns should be selected from the storage. You can use
3449 column names, or in the case of RDBMS back ends, function or stored procedure
3452 $rs = $schema->resultset('Employee')->search(undef, {
3455 { count => 'employeeid' },
3456 { max => { length => 'name' }, -as => 'longest_name' }
3461 SELECT name, COUNT( employeeid ), MAX( LENGTH( name ) ) AS longest_name FROM employee
3463 B<NOTE:> You will almost always need a corresponding L</as> attribute when you
3464 use L</select>, to instruct DBIx::Class how to store the result of the column.
3465 Also note that the L</as> attribute has nothing to do with the SQL-side 'AS'
3466 identifier aliasing. You can however alias a function, so you can use it in
3467 e.g. an C<ORDER BY> clause. This is done via the C<-as> B<select function
3468 attribute> supplied as shown in the example above.
3474 Indicates additional columns to be selected from storage. Works the same as
3475 L</select> but adds columns to the default selection, instead of specifying
3484 Indicates additional column names for those added via L</+select>. See L</as>.
3492 =item Value: \@inflation_names
3496 Indicates column names for object inflation. That is L</as> indicates the
3497 slot name in which the column value will be stored within the
3498 L<Row|DBIx::Class::Row> object. The value will then be accessible via this
3499 identifier by the C<get_column> method (or via the object accessor B<if one
3500 with the same name already exists>) as shown below. The L</as> attribute has
3501 B<nothing to do> with the SQL-side C<AS>. See L</select> for details.
3503 $rs = $schema->resultset('Employee')->search(undef, {
3506 { count => 'employeeid' },
3507 { max => { length => 'name' }, -as => 'longest_name' }
3516 If the object against which the search is performed already has an accessor
3517 matching a column name specified in C<as>, the value can be retrieved using
3518 the accessor as normal:
3520 my $name = $employee->name();
3522 If on the other hand an accessor does not exist in the object, you need to
3523 use C<get_column> instead:
3525 my $employee_count = $employee->get_column('employee_count');
3527 You can create your own accessors if required - see
3528 L<DBIx::Class::Manual::Cookbook> for details.
3534 =item Value: ($rel_name | \@rel_names | \%rel_names)
3538 Contains a list of relationships that should be joined for this query. For
3541 # Get CDs by Nine Inch Nails
3542 my $rs = $schema->resultset('CD')->search(
3543 { 'artist.name' => 'Nine Inch Nails' },
3544 { join => 'artist' }
3547 Can also contain a hash reference to refer to the other relation's relations.
3550 package MyApp::Schema::Track;
3551 use base qw/DBIx::Class/;
3552 __PACKAGE__->table('track');
3553 __PACKAGE__->add_columns(qw/trackid cd position title/);
3554 __PACKAGE__->set_primary_key('trackid');
3555 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
3558 # In your application
3559 my $rs = $schema->resultset('Artist')->search(
3560 { 'track.title' => 'Teardrop' },
3562 join => { cd => 'track' },
3563 order_by => 'artist.name',
3567 You need to use the relationship (not the table) name in conditions,
3568 because they are aliased as such. The current table is aliased as "me", so
3569 you need to use me.column_name in order to avoid ambiguity. For example:
3571 # Get CDs from 1984 with a 'Foo' track
3572 my $rs = $schema->resultset('CD')->search(
3575 'tracks.name' => 'Foo'
3577 { join => 'tracks' }
3580 If the same join is supplied twice, it will be aliased to <rel>_2 (and
3581 similarly for a third time). For e.g.
3583 my $rs = $schema->resultset('Artist')->search({
3584 'cds.title' => 'Down to Earth',
3585 'cds_2.title' => 'Popular',
3587 join => [ qw/cds cds/ ],
3590 will return a set of all artists that have both a cd with title 'Down
3591 to Earth' and a cd with title 'Popular'.
3593 If you want to fetch related objects from other tables as well, see C<prefetch>
3596 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
3602 =item Value: ($rel_name | \@rel_names | \%rel_names)
3606 Contains one or more relationships that should be fetched along with
3607 the main query (when they are accessed afterwards the data will
3608 already be available, without extra queries to the database). This is
3609 useful for when you know you will need the related objects, because it
3610 saves at least one query:
3612 my $rs = $schema->resultset('Tag')->search(
3621 The initial search results in SQL like the following:
3623 SELECT tag.*, cd.*, artist.* FROM tag
3624 JOIN cd ON tag.cd = cd.cdid
3625 JOIN artist ON cd.artist = artist.artistid
3627 L<DBIx::Class> has no need to go back to the database when we access the
3628 C<cd> or C<artist> relationships, which saves us two SQL statements in this
3631 Simple prefetches will be joined automatically, so there is no need
3632 for a C<join> attribute in the above search.
3634 C<prefetch> can be used with the following relationship types: C<belongs_to>,
3635 C<has_one> (or if you're using C<add_relationship>, any relationship declared
3636 with an accessor type of 'single' or 'filter'). A more complex example that
3637 prefetches an artists cds, the tracks on those cds, and the tags associated
3638 with that artist is given below (assuming many-to-many from artists to tags):
3640 my $rs = $schema->resultset('Artist')->search(
3644 { cds => 'tracks' },
3645 { artist_tags => 'tags' }
3651 B<NOTE:> If you specify a C<prefetch> attribute, the C<join> and C<select>
3652 attributes will be ignored.
3654 B<CAVEATs>: Prefetch does a lot of deep magic. As such, it may not behave
3655 exactly as you might expect.
3661 Prefetch uses the L</cache> to populate the prefetched relationships. This
3662 may or may not be what you want.
3666 If you specify a condition on a prefetched relationship, ONLY those
3667 rows that match the prefetched condition will be fetched into that relationship.
3668 This means that adding prefetch to a search() B<may alter> what is returned by
3669 traversing a relationship. So, if you have C<< Artist->has_many(CDs) >> and you do
3671 my $artist_rs = $schema->resultset('Artist')->search({
3677 my $count = $artist_rs->first->cds->count;
3679 my $artist_rs_prefetch = $artist_rs->search( {}, { prefetch => 'cds' } );
3681 my $prefetch_count = $artist_rs_prefetch->first->cds->count;
3683 cmp_ok( $count, '==', $prefetch_count, "Counts should be the same" );
3685 that cmp_ok() may or may not pass depending on the datasets involved. This
3686 behavior may or may not survive the 0.09 transition.
3698 Makes the resultset paged and specifies the page to retrieve. Effectively
3699 identical to creating a non-pages resultset and then calling ->page($page)
3702 If L<rows> attribute is not specified it defaults to 10 rows per page.
3704 When you have a paged resultset, L</count> will only return the number
3705 of rows in the page. To get the total, use the L</pager> and call
3706 C<total_entries> on it.
3716 Specifies the maximum number of rows for direct retrieval or the number of
3717 rows per page if the page attribute or method is used.
3723 =item Value: $offset
3727 Specifies the (zero-based) row number for the first row to be returned, or the
3728 of the first row of the first page if paging is used.
3734 =item Value: \@columns
3738 A arrayref of columns to group by. Can include columns of joined tables.
3740 group_by => [qw/ column1 column2 ... /]
3746 =item Value: $condition
3750 HAVING is a select statement attribute that is applied between GROUP BY and
3751 ORDER BY. It is applied to the after the grouping calculations have been
3754 having => { 'count(employee)' => { '>=', 100 } }
3760 =item Value: (0 | 1)
3764 Set to 1 to group by all columns. If the resultset already has a group_by
3765 attribute, this setting is ignored and an appropriate warning is issued.
3771 Adds to the WHERE clause.
3773 # only return rows WHERE deleted IS NULL for all searches
3774 __PACKAGE__->resultset_attributes({ where => { deleted => undef } }); )
3776 Can be overridden by passing C<< { where => undef } >> as an attribute
3783 Set to 1 to cache search results. This prevents extra SQL queries if you
3784 revisit rows in your ResultSet:
3786 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
3788 while( my $artist = $resultset->next ) {
3792 $rs->first; # without cache, this would issue a query
3794 By default, searches are not cached.
3796 For more examples of using these attributes, see
3797 L<DBIx::Class::Manual::Cookbook>.
3803 =item Value: ( 'update' | 'shared' )
3807 Set to 'update' for a SELECT ... FOR UPDATE or 'shared' for a SELECT