1 package DBIx::Class::ResultSet;
9 use Carp::Clan qw/^DBIx::Class/;
12 use DBIx::Class::ResultSetColumn;
13 use DBIx::Class::ResultSourceHandle;
16 use base qw/DBIx::Class/;
18 __PACKAGE__->mk_group_accessors('simple' => qw/result_class _source_handle/);
22 DBIx::Class::ResultSet - Responsible for fetching and creating resultset.
26 my $rs = $schema->resultset('User')->search({ registered => 1 });
27 my @rows = $schema->resultset('CD')->search({ year => 2005 })->all();
31 The resultset is also known as an iterator. It is responsible for handling
32 queries that may return an arbitrary number of rows, e.g. via L</search>
33 or a C<has_many> relationship.
35 In the examples below, the following table classes are used:
37 package MyApp::Schema::Artist;
38 use base qw/DBIx::Class/;
39 __PACKAGE__->load_components(qw/Core/);
40 __PACKAGE__->table('artist');
41 __PACKAGE__->add_columns(qw/artistid name/);
42 __PACKAGE__->set_primary_key('artistid');
43 __PACKAGE__->has_many(cds => 'MyApp::Schema::CD');
46 package MyApp::Schema::CD;
47 use base qw/DBIx::Class/;
48 __PACKAGE__->load_components(qw/Core/);
49 __PACKAGE__->table('cd');
50 __PACKAGE__->add_columns(qw/cdid artist title year/);
51 __PACKAGE__->set_primary_key('cdid');
52 __PACKAGE__->belongs_to(artist => 'MyApp::Schema::Artist');
57 If a resultset is used in a numeric context it returns the L</count>.
58 However, if it is used in a booleand context it is always true. So if
59 you want to check if a resultset has any results use C<if $rs != 0>.
60 C<if $rs> will always be true.
68 =item Arguments: $source, \%$attrs
70 =item Return Value: $rs
74 The resultset constructor. Takes a source object (usually a
75 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
76 L</ATTRIBUTES> below). Does not perform any queries -- these are
77 executed as needed by the other methods.
79 Generally you won't need to construct a resultset manually. You'll
80 automatically get one from e.g. a L</search> called in scalar context:
82 my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
84 IMPORTANT: If called on an object, proxies to new_result instead so
86 my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
88 will return a CD object, not a ResultSet.
94 return $class->new_result(@_) if ref $class;
96 my ($source, $attrs) = @_;
97 $source = $source->handle
98 unless $source->isa('DBIx::Class::ResultSourceHandle');
99 $attrs = { %{$attrs||{}} };
101 if ($attrs->{page}) {
102 $attrs->{rows} ||= 10;
105 $attrs->{alias} ||= 'me';
107 # Creation of {} and bless separated to mitigate RH perl bug
108 # see https://bugzilla.redhat.com/show_bug.cgi?id=196836
110 _source_handle => $source,
111 result_class => $attrs->{result_class} || $source->resolve->result_class,
112 cond => $attrs->{where},
127 =item Arguments: $cond, \%attrs?
129 =item Return Value: $resultset (scalar context), @row_objs (list context)
133 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
134 my $new_rs = $cd_rs->search({ year => 2005 });
136 my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
137 # year = 2005 OR year = 2004
139 If you need to pass in additional attributes but no additional condition,
140 call it as C<search(undef, \%attrs)>.
142 # "SELECT name, artistid FROM $artist_table"
143 my @all_artists = $schema->resultset('Artist')->search(undef, {
144 columns => [qw/name artistid/],
147 For a list of attributes that can be passed to C<search>, see
148 L</ATTRIBUTES>. For more examples of using this function, see
149 L<Searching|DBIx::Class::Manual::Cookbook/Searching>. For a complete
150 documentation for the first argument, see L<SQL::Abstract>.
152 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
158 my $rs = $self->search_rs( @_ );
159 return (wantarray ? $rs->all : $rs);
166 =item Arguments: $cond, \%attrs?
168 =item Return Value: $resultset
172 This method does the same exact thing as search() except it will
173 always return a resultset, even in list context.
181 $attrs = pop(@_) if @_ > 1 and ref $_[$#_] eq 'HASH';
182 my $our_attrs = { %{$self->{attrs}} };
183 my $having = delete $our_attrs->{having};
184 my $where = delete $our_attrs->{where};
188 my %safe = (alias => 1, cache => 1);
191 (@_ && defined($_[0])) # @_ == () or (undef)
193 (keys %$attrs # empty attrs or only 'safe' attrs
194 && List::Util::first { !$safe{$_} } keys %$attrs)
196 # no search, effectively just a clone
197 $rows = $self->get_cache;
200 my $new_attrs = { %{$our_attrs}, %{$attrs} };
202 # merge new attrs into inherited
203 foreach my $key (qw/join prefetch/) {
204 next unless exists $attrs->{$key};
205 $new_attrs->{$key} = $self->_merge_attr($our_attrs->{$key}, $attrs->{$key});
210 (@_ == 1 || ref $_[0] eq "HASH")
212 (ref $_[0] eq 'HASH')
214 (keys %{ $_[0] } > 0)
222 ? $self->throw_exception("Odd number of arguments to search")
229 if (defined $where) {
230 $new_attrs->{where} = (
231 defined $new_attrs->{where}
234 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
235 } $where, $new_attrs->{where}
242 $new_attrs->{where} = (
243 defined $new_attrs->{where}
246 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
247 } $cond, $new_attrs->{where}
253 if (defined $having) {
254 $new_attrs->{having} = (
255 defined $new_attrs->{having}
258 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
259 } $having, $new_attrs->{having}
265 my $rs = (ref $self)->new($self->result_source, $new_attrs);
267 $rs->set_cache($rows);
272 =head2 search_literal
276 =item Arguments: $sql_fragment, @bind_values
278 =item Return Value: $resultset (scalar context), @row_objs (list context)
282 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
283 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
285 Pass a literal chunk of SQL to be added to the conditional part of the
288 CAVEAT: C<search_literal> is provided for Class::DBI compatibility and should
289 only be used in that context. There are known problems using C<search_literal>
290 in chained queries; it can result in bind values in the wrong order. See
291 L<DBIx::Class::Manual::Cookbook/Searching> and
292 L<DBIx::Class::Manual::FAQ/Searching> for searching techniques that do not
293 require C<search_literal>.
298 my ($self, $cond, @vals) = @_;
299 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
300 $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
301 return $self->search(\$cond, $attrs);
308 =item Arguments: @values | \%cols, \%attrs?
310 =item Return Value: $row_object
314 Finds a row based on its primary key or unique constraint. For example, to find
315 a row by its primary key:
317 my $cd = $schema->resultset('CD')->find(5);
319 You can also find a row by a specific unique constraint using the C<key>
320 attribute. For example:
322 my $cd = $schema->resultset('CD')->find('Massive Attack', 'Mezzanine', {
323 key => 'cd_artist_title'
326 Additionally, you can specify the columns explicitly by name:
328 my $cd = $schema->resultset('CD')->find(
330 artist => 'Massive Attack',
331 title => 'Mezzanine',
333 { key => 'cd_artist_title' }
336 If the C<key> is specified as C<primary>, it searches only on the primary key.
338 If no C<key> is specified, it searches on all unique constraints defined on the
339 source for which column data is provided, including the primary key.
341 If your table does not have a primary key, you B<must> provide a value for the
342 C<key> attribute matching one of the unique constraints on the source.
344 Note: If your query does not return only one row, a warning is generated:
346 Query returned more than one row
348 See also L</find_or_create> and L</update_or_create>. For information on how to
349 declare unique constraints, see
350 L<DBIx::Class::ResultSource/add_unique_constraint>.
356 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
358 # Default to the primary key, but allow a specific key
359 my @cols = exists $attrs->{key}
360 ? $self->result_source->unique_constraint_columns($attrs->{key})
361 : $self->result_source->primary_columns;
362 $self->throw_exception(
363 "Can't find unless a primary key is defined or unique constraint is specified"
366 # Parse out a hashref from input
368 if (ref $_[0] eq 'HASH') {
369 $input_query = { %{$_[0]} };
371 elsif (@_ == @cols) {
373 @{$input_query}{@cols} = @_;
376 # Compatibility: Allow e.g. find(id => $value)
377 carp "Find by key => value deprecated; please use a hashref instead";
381 my (%related, $info);
383 KEY: foreach my $key (keys %$input_query) {
384 if (ref($input_query->{$key})
385 && ($info = $self->result_source->relationship_info($key))) {
386 my $val = delete $input_query->{$key};
387 next KEY if (ref($val) eq 'ARRAY'); # has_many for multi_create
388 my $rel_q = $self->result_source->resolve_condition(
389 $info->{cond}, $val, $key
391 die "Can't handle OR join condition in find" if ref($rel_q) eq 'ARRAY';
392 @related{keys %$rel_q} = values %$rel_q;
395 if (my @keys = keys %related) {
396 @{$input_query}{@keys} = values %related;
400 # Build the final query: Default to the disjunction of the unique queries,
401 # but allow the input query in case the ResultSet defines the query or the
402 # user is abusing find
403 my $alias = exists $attrs->{alias} ? $attrs->{alias} : $self->{attrs}{alias};
405 if (exists $attrs->{key}) {
406 my @unique_cols = $self->result_source->unique_constraint_columns($attrs->{key});
407 my $unique_query = $self->_build_unique_query($input_query, \@unique_cols);
408 $query = $self->_add_alias($unique_query, $alias);
411 my @unique_queries = $self->_unique_queries($input_query, $attrs);
412 $query = @unique_queries
413 ? [ map { $self->_add_alias($_, $alias) } @unique_queries ]
414 : $self->_add_alias($input_query, $alias);
419 my $rs = $self->search($query, $attrs);
420 if (keys %{$rs->_resolved_attrs->{collapse}}) {
422 carp "Query returned more than one row" if $rs->next;
430 if (keys %{$self->_resolved_attrs->{collapse}}) {
431 my $rs = $self->search($query);
433 carp "Query returned more than one row" if $rs->next;
437 return $self->single($query);
444 # Add the specified alias to the specified query hash. A copy is made so the
445 # original query is not modified.
448 my ($self, $query, $alias) = @_;
450 my %aliased = %$query;
451 foreach my $col (grep { ! m/\./ } keys %aliased) {
452 $aliased{"$alias.$col"} = delete $aliased{$col};
460 # Build a list of queries which satisfy unique constraints.
462 sub _unique_queries {
463 my ($self, $query, $attrs) = @_;
465 my @constraint_names = exists $attrs->{key}
467 : $self->result_source->unique_constraint_names;
469 my $where = $self->_collapse_cond($self->{attrs}{where} || {});
470 my $num_where = scalar keys %$where;
473 foreach my $name (@constraint_names) {
474 my @unique_cols = $self->result_source->unique_constraint_columns($name);
475 my $unique_query = $self->_build_unique_query($query, \@unique_cols);
477 my $num_cols = scalar @unique_cols;
478 my $num_query = scalar keys %$unique_query;
480 my $total = $num_query + $num_where;
481 if ($num_query && ($num_query == $num_cols || $total == $num_cols)) {
482 # The query is either unique on its own or is unique in combination with
483 # the existing where clause
484 push @unique_queries, $unique_query;
488 return @unique_queries;
491 # _build_unique_query
493 # Constrain the specified query hash based on the specified column names.
495 sub _build_unique_query {
496 my ($self, $query, $unique_cols) = @_;
499 map { $_ => $query->{$_} }
500 grep { exists $query->{$_} }
505 =head2 search_related
509 =item Arguments: $rel, $cond, \%attrs?
511 =item Return Value: $new_resultset
515 $new_rs = $cd_rs->search_related('artist', {
519 Searches the specified relationship, optionally specifying a condition and
520 attributes for matching records. See L</ATTRIBUTES> for more information.
525 return shift->related_resultset(shift)->search(@_);
528 =head2 search_related_rs
530 This method works exactly the same as search_related, except that
531 it guarantees a restultset, even in list context.
535 sub search_related_rs {
536 return shift->related_resultset(shift)->search_rs(@_);
543 =item Arguments: none
545 =item Return Value: $cursor
549 Returns a storage-driven cursor to the given resultset. See
550 L<DBIx::Class::Cursor> for more information.
557 my $attrs = { %{$self->_resolved_attrs} };
558 return $self->{cursor}
559 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
560 $attrs->{where},$attrs);
567 =item Arguments: $cond?
569 =item Return Value: $row_object?
573 my $cd = $schema->resultset('CD')->single({ year => 2001 });
575 Inflates the first result without creating a cursor if the resultset has
576 any records in it; if not returns nothing. Used by L</find> as an optimisation.
578 Can optionally take an additional condition B<only> - this is a fast-code-path
579 method; if you need to add extra joins or similar call L</search> and then
580 L</single> without a condition on the L<DBIx::Class::ResultSet> returned from
583 B<Note>: As of 0.08100, this method assumes that the query returns only one
584 row. If more than one row is returned, you will receive a warning:
586 Query returned more than one row
588 In this case, you should be using L</first> or L</find> instead.
593 my ($self, $where) = @_;
594 my $attrs = { %{$self->_resolved_attrs} };
596 if (defined $attrs->{where}) {
599 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
600 $where, delete $attrs->{where} ]
603 $attrs->{where} = $where;
607 # XXX: Disabled since it doesn't infer uniqueness in all cases
608 # unless ($self->_is_unique_query($attrs->{where})) {
609 # carp "Query not guaranteed to return a single row"
610 # . "; please declare your unique constraints or use search instead";
613 my @data = $self->result_source->storage->select_single(
614 $attrs->{from}, $attrs->{select},
615 $attrs->{where}, $attrs
618 return (@data ? ($self->_construct_object(@data))[0] : undef);
623 # Try to determine if the specified query is guaranteed to be unique, based on
624 # the declared unique constraints.
626 sub _is_unique_query {
627 my ($self, $query) = @_;
629 my $collapsed = $self->_collapse_query($query);
630 my $alias = $self->{attrs}{alias};
632 foreach my $name ($self->result_source->unique_constraint_names) {
633 my @unique_cols = map {
635 } $self->result_source->unique_constraint_columns($name);
637 # Count the values for each unique column
638 my %seen = map { $_ => 0 } @unique_cols;
640 foreach my $key (keys %$collapsed) {
641 my $aliased = $key =~ /\./ ? $key : "$alias.$key";
642 next unless exists $seen{$aliased}; # Additional constraints are okay
643 $seen{$aliased} = scalar keys %{ $collapsed->{$key} };
646 # If we get 0 or more than 1 value for a column, it's not necessarily unique
647 return 1 unless grep { $_ != 1 } values %seen;
655 # Recursively collapse the query, accumulating values for each column.
657 sub _collapse_query {
658 my ($self, $query, $collapsed) = @_;
662 if (ref $query eq 'ARRAY') {
663 foreach my $subquery (@$query) {
664 next unless ref $subquery; # -or
665 # warn "ARRAY: " . Dumper $subquery;
666 $collapsed = $self->_collapse_query($subquery, $collapsed);
669 elsif (ref $query eq 'HASH') {
670 if (keys %$query and (keys %$query)[0] eq '-and') {
671 foreach my $subquery (@{$query->{-and}}) {
672 # warn "HASH: " . Dumper $subquery;
673 $collapsed = $self->_collapse_query($subquery, $collapsed);
677 # warn "LEAF: " . Dumper $query;
678 foreach my $col (keys %$query) {
679 my $value = $query->{$col};
680 $collapsed->{$col}{$value}++;
692 =item Arguments: $cond?
694 =item Return Value: $resultsetcolumn
698 my $max_length = $rs->get_column('length')->max;
700 Returns a L<DBIx::Class::ResultSetColumn> instance for a column of the ResultSet.
705 my ($self, $column) = @_;
706 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
714 =item Arguments: $cond, \%attrs?
716 =item Return Value: $resultset (scalar context), @row_objs (list context)
720 # WHERE title LIKE '%blue%'
721 $cd_rs = $rs->search_like({ title => '%blue%'});
723 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
724 that this is simply a convenience method. You most likely want to use
725 L</search> with specific operators.
727 For more information, see L<DBIx::Class::Manual::Cookbook>.
733 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
734 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
735 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
736 return $class->search($query, { %$attrs });
743 =item Arguments: $first, $last
745 =item Return Value: $resultset (scalar context), @row_objs (list context)
749 Returns a resultset or object list representing a subset of elements from the
750 resultset slice is called on. Indexes are from 0, i.e., to get the first
753 my ($one, $two, $three) = $rs->slice(0, 2);
758 my ($self, $min, $max) = @_;
759 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
760 $attrs->{offset} = $self->{attrs}{offset} || 0;
761 $attrs->{offset} += $min;
762 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
763 return $self->search(undef(), $attrs);
764 #my $slice = (ref $self)->new($self->result_source, $attrs);
765 #return (wantarray ? $slice->all : $slice);
772 =item Arguments: none
774 =item Return Value: $result?
778 Returns the next element in the resultset (C<undef> is there is none).
780 Can be used to efficiently iterate over records in the resultset:
782 my $rs = $schema->resultset('CD')->search;
783 while (my $cd = $rs->next) {
787 Note that you need to store the resultset object, and call C<next> on it.
788 Calling C<< resultset('Table')->next >> repeatedly will always return the
789 first record from the resultset.
795 if (my $cache = $self->get_cache) {
796 $self->{all_cache_position} ||= 0;
797 return $cache->[$self->{all_cache_position}++];
799 if ($self->{attrs}{cache}) {
800 $self->{all_cache_position} = 1;
801 return ($self->all)[0];
803 if ($self->{stashed_objects}) {
804 my $obj = shift(@{$self->{stashed_objects}});
805 delete $self->{stashed_objects} unless @{$self->{stashed_objects}};
809 exists $self->{stashed_row}
810 ? @{delete $self->{stashed_row}}
811 : $self->cursor->next
813 return undef unless (@row);
814 my ($row, @more) = $self->_construct_object(@row);
815 $self->{stashed_objects} = \@more if @more;
819 sub _construct_object {
820 my ($self, @row) = @_;
821 my $info = $self->_collapse_result($self->{_attrs}{as}, \@row);
822 my @new = $self->result_class->inflate_result($self->result_source, @$info);
823 @new = $self->{_attrs}{record_filter}->(@new)
824 if exists $self->{_attrs}{record_filter};
828 sub _collapse_result {
829 my ($self, $as_proto, $row) = @_;
833 # 'foo' => [ undef, 'foo' ]
834 # 'foo.bar' => [ 'foo', 'bar' ]
835 # 'foo.bar.baz' => [ 'foo.bar', 'baz' ]
837 my @construct_as = map { [ (/^(?:(.*)\.)?([^.]+)$/) ] } @$as_proto;
839 my %collapse = %{$self->{_attrs}{collapse}||{}};
843 # if we're doing collapsing (has_many prefetch) we need to grab records
844 # until the PK changes, so fill @pri_index. if not, we leave it empty so
845 # we know we don't have to bother.
847 # the reason for not using the collapse stuff directly is because if you
848 # had for e.g. two artists in a row with no cds, the collapse info for
849 # both would be NULL (undef) so you'd lose the second artist
851 # store just the index so we can check the array positions from the row
852 # without having to contruct the full hash
854 if (keys %collapse) {
855 my %pri = map { ($_ => 1) } $self->result_source->primary_columns;
856 foreach my $i (0 .. $#construct_as) {
857 next if defined($construct_as[$i][0]); # only self table
858 if (delete $pri{$construct_as[$i][1]}) {
859 push(@pri_index, $i);
861 last unless keys %pri; # short circuit (Johnny Five Is Alive!)
865 # no need to do an if, it'll be empty if @pri_index is empty anyway
867 my %pri_vals = map { ($_ => $copy[$_]) } @pri_index;
871 do { # no need to check anything at the front, we always want the first row
875 foreach my $this_as (@construct_as) {
876 $const{$this_as->[0]||''}{$this_as->[1]} = shift(@copy);
879 push(@const_rows, \%const);
881 } until ( # no pri_index => no collapse => drop straight out
884 do { # get another row, stash it, drop out if different PK
886 @copy = $self->cursor->next;
887 $self->{stashed_row} = \@copy;
889 # last thing in do block, counts as true if anything doesn't match
891 # check xor defined first for NULL vs. NOT NULL then if one is
892 # defined the other must be so check string equality
895 (defined $pri_vals{$_} ^ defined $copy[$_])
896 || (defined $pri_vals{$_} && ($pri_vals{$_} ne $copy[$_]))
901 my $alias = $self->{attrs}{alias};
908 foreach my $const (@const_rows) {
909 scalar @const_keys or do {
910 @const_keys = sort { length($a) <=> length($b) } keys %$const;
912 foreach my $key (@const_keys) {
915 my @parts = split(/\./, $key);
917 my $data = $const->{$key};
918 foreach my $p (@parts) {
919 $target = $target->[1]->{$p} ||= [];
921 if ($cur eq ".${key}" && (my @ckey = @{$collapse{$cur}||[]})) {
922 # collapsing at this point and on final part
923 my $pos = $collapse_pos{$cur};
924 CK: foreach my $ck (@ckey) {
925 if (!defined $pos->{$ck} || $pos->{$ck} ne $data->{$ck}) {
926 $collapse_pos{$cur} = $data;
927 delete @collapse_pos{ # clear all positioning for sub-entries
928 grep { m/^\Q${cur}.\E/ } keys %collapse_pos
935 if (exists $collapse{$cur}) {
936 $target = $target->[-1];
939 $target->[0] = $data;
941 $info->[0] = $const->{$key};
953 =item Arguments: $result_source?
955 =item Return Value: $result_source
959 An accessor for the primary ResultSource object from which this ResultSet
966 =item Arguments: $result_class?
968 =item Return Value: $result_class
972 An accessor for the class to use when creating row objects. Defaults to
973 C<< result_source->result_class >> - which in most cases is the name of the
974 L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class.
983 =item Arguments: $cond, \%attrs??
985 =item Return Value: $count
989 Performs an SQL C<COUNT> with the same query as the resultset was built
990 with to find the number of elements. If passed arguments, does a search
991 on the resultset and counts the results of that.
993 Note: When using C<count> with C<group_by>, L<DBIx::Class> emulates C<GROUP BY>
994 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
995 not support C<DISTINCT> with multiple columns. If you are using such a
996 database, you should only use columns from the main table in your C<group_by>
1003 return $self->search(@_)->count if @_ and defined $_[0];
1004 return scalar @{ $self->get_cache } if $self->get_cache;
1005 my $count = $self->_count;
1006 return 0 unless $count;
1008 # need to take offset from resolved attrs
1010 $count -= $self->{_attrs}{offset} if $self->{_attrs}{offset};
1011 $count = $self->{attrs}{rows} if
1012 $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
1013 $count = 0 if ($count < 0);
1017 sub _count { # Separated out so pager can get the full count
1019 my $select = { count => '*' };
1021 my $attrs = { %{$self->_resolved_attrs} };
1022 if (my $group_by = delete $attrs->{group_by}) {
1023 delete $attrs->{having};
1024 my @distinct = (ref $group_by ? @$group_by : ($group_by));
1025 # todo: try CONCAT for multi-column pk
1026 my @pk = $self->result_source->primary_columns;
1028 my $alias = $attrs->{alias};
1029 foreach my $column (@distinct) {
1030 if ($column =~ qr/^(?:\Q${alias}.\E)?$pk[0]$/) {
1031 @distinct = ($column);
1037 $select = { count => { distinct => \@distinct } };
1040 $attrs->{select} = $select;
1041 $attrs->{as} = [qw/count/];
1043 # offset, order by and page are not needed to count. record_filter is cdbi
1044 delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
1046 my $tmp_rs = (ref $self)->new($self->result_source, $attrs);
1047 my ($count) = $tmp_rs->cursor->next;
1055 =head2 count_literal
1059 =item Arguments: $sql_fragment, @bind_values
1061 =item Return Value: $count
1065 Counts the results in a literal query. Equivalent to calling L</search_literal>
1066 with the passed arguments, then L</count>.
1070 sub count_literal { shift->search_literal(@_)->count; }
1076 =item Arguments: none
1078 =item Return Value: @objects
1082 Returns all elements in the resultset. Called implicitly if the resultset
1083 is returned in list context.
1089 return @{ $self->get_cache } if $self->get_cache;
1093 # TODO: don't call resolve here
1094 if (keys %{$self->_resolved_attrs->{collapse}}) {
1095 # if ($self->{attrs}{prefetch}) {
1096 # Using $self->cursor->all is really just an optimisation.
1097 # If we're collapsing has_many prefetches it probably makes
1098 # very little difference, and this is cleaner than hacking
1099 # _construct_object to survive the approach
1100 my @row = $self->cursor->next;
1102 push(@obj, $self->_construct_object(@row));
1103 @row = (exists $self->{stashed_row}
1104 ? @{delete $self->{stashed_row}}
1105 : $self->cursor->next);
1108 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
1111 $self->set_cache(\@obj) if $self->{attrs}{cache};
1119 =item Arguments: none
1121 =item Return Value: $self
1125 Resets the resultset's cursor, so you can iterate through the elements again.
1131 delete $self->{_attrs} if exists $self->{_attrs};
1132 $self->{all_cache_position} = 0;
1133 $self->cursor->reset;
1141 =item Arguments: none
1143 =item Return Value: $object?
1147 Resets the resultset and returns an object for the first result (if the
1148 resultset returns anything).
1153 return $_[0]->reset->next;
1156 # _cond_for_update_delete
1158 # update/delete require the condition to be modified to handle
1159 # the differing SQL syntax available. This transforms the $self->{cond}
1160 # appropriately, returning the new condition.
1162 sub _cond_for_update_delete {
1163 my ($self, $full_cond) = @_;
1166 $full_cond ||= $self->{cond};
1167 # No-op. No condition, we're updating/deleting everything
1168 return $cond unless ref $full_cond;
1170 if (ref $full_cond eq 'ARRAY') {
1174 foreach my $key (keys %{$_}) {
1176 $hash{$1} = $_->{$key};
1182 elsif (ref $full_cond eq 'HASH') {
1183 if ((keys %{$full_cond})[0] eq '-and') {
1186 my @cond = @{$full_cond->{-and}};
1187 for (my $i = 0; $i < @cond; $i++) {
1188 my $entry = $cond[$i];
1191 if (ref $entry eq 'HASH') {
1192 $hash = $self->_cond_for_update_delete($entry);
1195 $entry =~ /([^.]+)$/;
1196 $hash->{$1} = $cond[++$i];
1199 push @{$cond->{-and}}, $hash;
1203 foreach my $key (keys %{$full_cond}) {
1205 $cond->{$1} = $full_cond->{$key};
1210 $self->throw_exception(
1211 "Can't update/delete on resultset with condition unless hash or array"
1223 =item Arguments: \%values
1225 =item Return Value: $storage_rv
1229 Sets the specified columns in the resultset to the supplied values in a
1230 single query. Return value will be true if the update succeeded or false
1231 if no records were updated; exact type of success value is storage-dependent.
1236 my ($self, $values) = @_;
1237 $self->throw_exception("Values for update must be a hash")
1238 unless ref $values eq 'HASH';
1240 my $cond = $self->_cond_for_update_delete;
1242 return $self->result_source->storage->update(
1243 $self->result_source, $values, $cond
1251 =item Arguments: \%values
1253 =item Return Value: 1
1257 Fetches all objects and updates them one at a time. Note that C<update_all>
1258 will run DBIC cascade triggers, while L</update> will not.
1263 my ($self, $values) = @_;
1264 $self->throw_exception("Values for update must be a hash")
1265 unless ref $values eq 'HASH';
1266 foreach my $obj ($self->all) {
1267 $obj->set_columns($values)->update;
1276 =item Arguments: none
1278 =item Return Value: 1
1282 Deletes the contents of the resultset from its result source. Note that this
1283 will not run DBIC cascade triggers. See L</delete_all> if you need triggers
1284 to run. See also L<DBIx::Class::Row/delete>.
1291 my $cond = $self->_cond_for_update_delete;
1293 $self->result_source->storage->delete($self->result_source, $cond);
1301 =item Arguments: none
1303 =item Return Value: 1
1307 Fetches all objects and deletes them one at a time. Note that C<delete_all>
1308 will run DBIC cascade triggers, while L</delete> will not.
1314 $_->delete for $self->all;
1322 =item Arguments: \@data;
1326 Pass an arrayref of hashrefs. Each hashref should be a structure suitable for
1327 submitting to a $resultset->create(...) method.
1329 In void context, C<insert_bulk> in L<DBIx::Class::Storage::DBI> is used
1330 to insert the data, as this is a faster method.
1332 Otherwise, each set of data is inserted into the database using
1333 L<DBIx::Class::ResultSet/create>, and a arrayref of the resulting row
1334 objects is returned.
1336 Example: Assuming an Artist Class that has many CDs Classes relating:
1338 my $Artist_rs = $schema->resultset("Artist");
1340 ## Void Context Example
1341 $Artist_rs->populate([
1342 { artistid => 4, name => 'Manufactured Crap', cds => [
1343 { title => 'My First CD', year => 2006 },
1344 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
1347 { artistid => 5, name => 'Angsty-Whiny Girl', cds => [
1348 { title => 'My parents sold me to a record company' ,year => 2005 },
1349 { title => 'Why Am I So Ugly?', year => 2006 },
1350 { title => 'I Got Surgery and am now Popular', year => 2007 }
1355 ## Array Context Example
1356 my ($ArtistOne, $ArtistTwo, $ArtistThree) = $Artist_rs->populate([
1357 { name => "Artist One"},
1358 { name => "Artist Two"},
1359 { name => "Artist Three", cds=> [
1360 { title => "First CD", year => 2007},
1361 { title => "Second CD", year => 2008},
1365 print $ArtistOne->name; ## response is 'Artist One'
1366 print $ArtistThree->cds->count ## reponse is '2'
1368 Please note an important effect on your data when choosing between void and
1369 wantarray context. Since void context goes straight to C<insert_bulk> in
1370 L<DBIx::Class::Storage::DBI> this will skip any component that is overriding
1371 c<insert>. So if you are using something like L<DBIx-Class-UUIDColumns> to
1372 create primary keys for you, you will find that your PKs are empty. In this
1373 case you will have to use the wantarray context in order to create those
1379 my ($self, $data) = @_;
1381 if(defined wantarray) {
1383 foreach my $item (@$data) {
1384 push(@created, $self->create($item));
1388 my ($first, @rest) = @$data;
1390 my @names = grep {!ref $first->{$_}} keys %$first;
1391 my @rels = grep { $self->result_source->has_relationship($_) } keys %$first;
1392 my @pks = $self->result_source->primary_columns;
1394 ## do the belongs_to relationships
1395 foreach my $index (0..$#$data) {
1396 if( grep { !defined $data->[$index]->{$_} } @pks ) {
1397 my @ret = $self->populate($data);
1401 foreach my $rel (@rels) {
1402 next unless $data->[$index]->{$rel} && ref $data->[$index]->{$rel} eq "HASH";
1403 my $result = $self->related_resultset($rel)->create($data->[$index]->{$rel});
1404 my ($reverse) = keys %{$self->result_source->reverse_relationship_info($rel)};
1405 my $related = $result->result_source->resolve_condition(
1406 $result->result_source->relationship_info($reverse)->{cond},
1411 delete $data->[$index]->{$rel};
1412 $data->[$index] = {%{$data->[$index]}, %$related};
1414 push @names, keys %$related if $index == 0;
1418 ## do bulk insert on current row
1419 my @values = map { [ @$_{@names} ] } @$data;
1421 $self->result_source->storage->insert_bulk(
1422 $self->result_source,
1427 ## do the has_many relationships
1428 foreach my $item (@$data) {
1430 foreach my $rel (@rels) {
1431 next unless $item->{$rel} && ref $item->{$rel} eq "ARRAY";
1433 my $parent = $self->find(map {{$_=>$item->{$_}} } @pks)
1434 || $self->throw_exception('Cannot find the relating object.');
1436 my $child = $parent->$rel;
1438 my $related = $child->result_source->resolve_condition(
1439 $parent->result_source->relationship_info($rel)->{cond},
1444 my @rows_to_add = ref $item->{$rel} eq 'ARRAY' ? @{$item->{$rel}} : ($item->{$rel});
1445 my @populate = map { {%$_, %$related} } @rows_to_add;
1447 $child->populate( \@populate );
1457 =item Arguments: none
1459 =item Return Value: $pager
1463 Return Value a L<Data::Page> object for the current resultset. Only makes
1464 sense for queries with a C<page> attribute.
1470 my $attrs = $self->{attrs};
1471 $self->throw_exception("Can't create pager for non-paged rs")
1472 unless $self->{attrs}{page};
1473 $attrs->{rows} ||= 10;
1474 return $self->{pager} ||= Data::Page->new(
1475 $self->_count, $attrs->{rows}, $self->{attrs}{page});
1482 =item Arguments: $page_number
1484 =item Return Value: $rs
1488 Returns a resultset for the $page_number page of the resultset on which page
1489 is called, where each page contains a number of rows equal to the 'rows'
1490 attribute set on the resultset (10 by default).
1495 my ($self, $page) = @_;
1496 return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
1503 =item Arguments: \%vals
1505 =item Return Value: $object
1509 Creates a new row object in the resultset's result class and returns
1510 it. The row is not inserted into the database at this point, call
1511 L<DBIx::Class::Row/insert> to do that. Calling L<DBIx::Class::Row/in_storage>
1512 will tell you whether the row object has been inserted or not.
1514 Passes the hashref of input on to L<DBIx::Class::Row/new>.
1519 my ($self, $values) = @_;
1520 $self->throw_exception( "new_result needs a hash" )
1521 unless (ref $values eq 'HASH');
1522 $self->throw_exception(
1523 "Implicit construct invalid, condition was not resolveable on parent "
1525 ) if (defined $self->{cond}
1526 && $self->{cond} eq $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION);
1527 $self->throw_exception(
1528 "Can't abstract implicit construct, condition not a hash"
1529 ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
1531 my $alias = $self->{attrs}{alias};
1532 my $collapsed_cond = $self->{cond} ? $self->_collapse_cond($self->{cond}) : {};
1534 # precendence must be given to passed values over values inherited from the cond,
1535 # so the order here is important.
1537 my %implied = %{$self->_remove_alias($collapsed_cond, $alias)};
1538 while( my($col,$value) = each %implied ){
1539 if(ref($value) eq 'HASH' && keys(%$value) && (keys %$value)[0] eq '='){
1540 $new{$col} = $value->{'='};
1543 $new{$col} = $value if $self->_is_deterministic_value($value);
1548 %{ $self->_remove_alias($values, $alias) },
1549 -source_handle => $self->_source_handle,
1550 -result_source => $self->result_source, # DO NOT REMOVE THIS, REQUIRED
1553 return $self->result_class->new(\%new);
1556 # _is_deterministic_value
1558 # Make an effor to strip non-deterministic values from the condition,
1559 # to make sure new_result chokes less
1561 sub _is_deterministic_value {
1564 my $ref_type = ref $value;
1565 return 1 if $ref_type eq '' || $ref_type eq 'SCALAR';
1566 return 1 if Scalar::Util::blessed($value);
1572 # Recursively collapse the condition.
1574 sub _collapse_cond {
1575 my ($self, $cond, $collapsed) = @_;
1579 if (ref $cond eq 'ARRAY') {
1580 foreach my $subcond (@$cond) {
1581 next unless ref $subcond; # -or
1582 # warn "ARRAY: " . Dumper $subcond;
1583 $collapsed = $self->_collapse_cond($subcond, $collapsed);
1586 elsif (ref $cond eq 'HASH') {
1587 if (keys %$cond and (keys %$cond)[0] eq '-and') {
1588 foreach my $subcond (@{$cond->{-and}}) {
1589 # warn "HASH: " . Dumper $subcond;
1590 $collapsed = $self->_collapse_cond($subcond, $collapsed);
1594 # warn "LEAF: " . Dumper $cond;
1595 foreach my $col (keys %$cond) {
1596 my $value = $cond->{$col};
1597 $collapsed->{$col} = $value;
1607 # Remove the specified alias from the specified query hash. A copy is made so
1608 # the original query is not modified.
1611 my ($self, $query, $alias) = @_;
1613 my %orig = %{ $query || {} };
1616 foreach my $key (keys %orig) {
1618 $unaliased{$key} = $orig{$key};
1621 $unaliased{$1} = $orig{$key}
1622 if $key =~ m/^(?:\Q$alias\E\.)?([^.]+)$/;
1632 =item Arguments: \%vals, \%attrs?
1634 =item Return Value: $object
1638 Find an existing record from this resultset. If none exists, instantiate a new
1639 result object and return it. The object will not be saved into your storage
1640 until you call L<DBIx::Class::Row/insert> on it.
1642 If you want objects to be saved immediately, use L</find_or_create> instead.
1648 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1649 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1650 my $exists = $self->find($hash, $attrs);
1651 return defined $exists ? $exists : $self->new_result($hash);
1658 =item Arguments: \%vals
1660 =item Return Value: a L<DBIx::Class::Row> $object
1664 Attempt to create a single new row or a row with multiple related rows
1665 in the table represented by the resultset (and related tables). This
1666 will not check for duplicate rows before inserting, use
1667 L</find_or_create> to do that.
1669 To create one row for this resultset, pass a hashref of key/value
1670 pairs representing the columns of the table and the values you wish to
1671 store. If the appropriate relationships are set up, foreign key fields
1672 can also be passed an object representing the foreign row, and the
1673 value will be set to it's primary key.
1675 To create related objects, pass a hashref for the value if the related
1676 item is a foreign key relationship (L<DBIx::Class::Relationship/belongs_to>),
1677 and use the name of the relationship as the key. (NOT the name of the field,
1678 necessarily). For C<has_many> and C<has_one> relationships, pass an arrayref
1679 of hashrefs containing the data for each of the rows to create in the foreign
1680 tables, again using the relationship name as the key.
1682 Instead of hashrefs of plain related data (key/value pairs), you may
1683 also pass new or inserted objects. New objects (not inserted yet, see
1684 L</new>), will be inserted into their appropriate tables.
1686 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
1688 Example of creating a new row.
1690 $person_rs->create({
1691 name=>"Some Person",
1692 email=>"somebody@someplace.com"
1695 Example of creating a new row and also creating rows in a related C<has_many>
1696 or C<has_one> resultset. Note Arrayref.
1699 { artistid => 4, name => 'Manufactured Crap', cds => [
1700 { title => 'My First CD', year => 2006 },
1701 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
1706 Example of creating a new row and also creating a row in a related
1707 C<belongs_to>resultset. Note Hashref.
1710 title=>"Music for Silly Walks",
1713 name=>"Silly Musician",
1720 my ($self, $attrs) = @_;
1721 $self->throw_exception( "create needs a hashref" )
1722 unless ref $attrs eq 'HASH';
1723 return $self->new_result($attrs)->insert;
1726 =head2 find_or_create
1730 =item Arguments: \%vals, \%attrs?
1732 =item Return Value: $object
1736 $class->find_or_create({ key => $val, ... });
1738 Tries to find a record based on its primary key or unique constraint; if none
1739 is found, creates one and returns that instead.
1741 my $cd = $schema->resultset('CD')->find_or_create({
1743 artist => 'Massive Attack',
1744 title => 'Mezzanine',
1748 Also takes an optional C<key> attribute, to search by a specific key or unique
1749 constraint. For example:
1751 my $cd = $schema->resultset('CD')->find_or_create(
1753 artist => 'Massive Attack',
1754 title => 'Mezzanine',
1756 { key => 'cd_artist_title' }
1759 Note: Because find_or_create() reads from the database and then
1760 possibly inserts based on the result, this method is subject to a race
1761 condition. Another process could create a record in the table after
1762 the find has completed and before the create has started. To avoid
1763 this problem, use find_or_create() inside a transaction.
1765 See also L</find> and L</update_or_create>. For information on how to declare
1766 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1770 sub find_or_create {
1772 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1773 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1774 my $exists = $self->find($hash, $attrs);
1775 return defined $exists ? $exists : $self->create($hash);
1778 =head2 update_or_create
1782 =item Arguments: \%col_values, { key => $unique_constraint }?
1784 =item Return Value: $object
1788 $class->update_or_create({ col => $val, ... });
1790 First, searches for an existing row matching one of the unique constraints
1791 (including the primary key) on the source of this resultset. If a row is
1792 found, updates it with the other given column values. Otherwise, creates a new
1795 Takes an optional C<key> attribute to search on a specific unique constraint.
1798 # In your application
1799 my $cd = $schema->resultset('CD')->update_or_create(
1801 artist => 'Massive Attack',
1802 title => 'Mezzanine',
1805 { key => 'cd_artist_title' }
1808 If no C<key> is specified, it searches on all unique constraints defined on the
1809 source, including the primary key.
1811 If the C<key> is specified as C<primary>, it searches only on the primary key.
1813 See also L</find> and L</find_or_create>. For information on how to declare
1814 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1818 sub update_or_create {
1820 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1821 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
1823 my $row = $self->find($cond, $attrs);
1825 $row->update($cond);
1829 return $self->create($cond);
1836 =item Arguments: none
1838 =item Return Value: \@cache_objects?
1842 Gets the contents of the cache for the resultset, if the cache is set.
1844 The cache is populated either by using the L</prefetch> attribute to
1845 L</search> or by calling L</set_cache>.
1857 =item Arguments: \@cache_objects
1859 =item Return Value: \@cache_objects
1863 Sets the contents of the cache for the resultset. Expects an arrayref
1864 of objects of the same class as those produced by the resultset. Note that
1865 if the cache is set the resultset will return the cached objects rather
1866 than re-querying the database even if the cache attr is not set.
1868 The contents of the cache can also be populated by using the
1869 L</prefetch> attribute to L</search>.
1874 my ( $self, $data ) = @_;
1875 $self->throw_exception("set_cache requires an arrayref")
1876 if defined($data) && (ref $data ne 'ARRAY');
1877 $self->{all_cache} = $data;
1884 =item Arguments: none
1886 =item Return Value: []
1890 Clears the cache for the resultset.
1895 shift->set_cache(undef);
1898 =head2 related_resultset
1902 =item Arguments: $relationship_name
1904 =item Return Value: $resultset
1908 Returns a related resultset for the supplied relationship name.
1910 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1914 sub related_resultset {
1915 my ($self, $rel) = @_;
1917 $self->{related_resultsets} ||= {};
1918 return $self->{related_resultsets}{$rel} ||= do {
1919 my $rel_obj = $self->result_source->relationship_info($rel);
1921 $self->throw_exception(
1922 "search_related: result source '" . $self->result_source->source_name .
1923 "' has no such relationship $rel")
1926 my ($from,$seen) = $self->_resolve_from($rel);
1928 my $join_count = $seen->{$rel};
1929 my $alias = ($join_count > 1 ? join('_', $rel, $join_count) : $rel);
1931 #XXX - temp fix for result_class bug. There likely is a more elegant fix -groditi
1932 my %attrs = %{$self->{attrs}||{}};
1933 delete @attrs{qw(result_class alias)};
1937 if (my $cache = $self->get_cache) {
1938 if ($cache->[0] && $cache->[0]->related_resultset($rel)->get_cache) {
1939 $new_cache = [ map { @{$_->related_resultset($rel)->get_cache} }
1944 my $rel_source = $self->result_source->related_source($rel);
1948 # The reason we do this now instead of passing the alias to the
1949 # search_rs below is that if you wrap/overload resultset on the
1950 # source you need to know what alias it's -going- to have for things
1951 # to work sanely (e.g. RestrictWithObject wants to be able to add
1952 # extra query restrictions, and these may need to be $alias.)
1954 my $attrs = $rel_source->resultset_attributes;
1955 local $attrs->{alias} = $alias;
1957 $rel_source->resultset
1965 where => $self->{cond},
1970 $new->set_cache($new_cache) if $new_cache;
1976 my ($self, $extra_join) = @_;
1977 my $source = $self->result_source;
1978 my $attrs = $self->{attrs};
1980 my $from = $attrs->{from}
1981 || [ { $attrs->{alias} => $source->from } ];
1983 my $seen = { %{$attrs->{seen_join}||{}} };
1985 my $join = ($attrs->{join}
1986 ? [ $attrs->{join}, $extra_join ]
1989 # we need to take the prefetch the attrs into account before we
1990 # ->resolve_join as otherwise they get lost - captainL
1991 my $merged = $self->_merge_attr( $join, $attrs->{prefetch} );
1995 ($join ? $source->resolve_join($merged, $attrs->{alias}, $seen) : ()),
1998 return ($from,$seen);
2001 sub _resolved_attrs {
2003 return $self->{_attrs} if $self->{_attrs};
2005 my $attrs = { %{$self->{attrs}||{}} };
2006 my $source = $self->result_source;
2007 my $alias = $attrs->{alias};
2009 $attrs->{columns} ||= delete $attrs->{cols} if exists $attrs->{cols};
2010 if ($attrs->{columns}) {
2011 delete $attrs->{as};
2012 } elsif (!$attrs->{select}) {
2013 $attrs->{columns} = [ $source->columns ];
2018 ? (ref $attrs->{select} eq 'ARRAY'
2019 ? [ @{$attrs->{select}} ]
2020 : [ $attrs->{select} ])
2021 : [ map { m/\./ ? $_ : "${alias}.$_" } @{delete $attrs->{columns}} ]
2025 ? (ref $attrs->{as} eq 'ARRAY'
2026 ? [ @{$attrs->{as}} ]
2028 : [ map { m/^\Q${alias}.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}} ]
2032 if ($adds = delete $attrs->{include_columns}) {
2033 $adds = [$adds] unless ref $adds eq 'ARRAY';
2034 push(@{$attrs->{select}}, @$adds);
2035 push(@{$attrs->{as}}, map { m/([^.]+)$/; $1 } @$adds);
2037 if ($adds = delete $attrs->{'+select'}) {
2038 $adds = [$adds] unless ref $adds eq 'ARRAY';
2039 push(@{$attrs->{select}},
2040 map { /\./ || ref $_ ? $_ : "${alias}.$_" } @$adds);
2042 if (my $adds = delete $attrs->{'+as'}) {
2043 $adds = [$adds] unless ref $adds eq 'ARRAY';
2044 push(@{$attrs->{as}}, @$adds);
2047 $attrs->{from} ||= [ { 'me' => $source->from } ];
2049 if (exists $attrs->{join} || exists $attrs->{prefetch}) {
2050 my $join = delete $attrs->{join} || {};
2052 if (defined $attrs->{prefetch}) {
2053 $join = $self->_merge_attr(
2054 $join, $attrs->{prefetch}
2059 $attrs->{from} = # have to copy here to avoid corrupting the original
2062 $source->resolve_join($join, $alias, { %{$attrs->{seen_join}||{}} })
2067 $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
2068 if ($attrs->{order_by}) {
2069 $attrs->{order_by} = (ref($attrs->{order_by}) eq 'ARRAY'
2070 ? [ @{$attrs->{order_by}} ]
2071 : [ $attrs->{order_by} ]);
2073 $attrs->{order_by} = [];
2076 my $collapse = $attrs->{collapse} || {};
2077 if (my $prefetch = delete $attrs->{prefetch}) {
2078 $prefetch = $self->_merge_attr({}, $prefetch);
2080 my $seen = $attrs->{seen_join} || {};
2081 foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
2082 # bring joins back to level of current class
2083 my @prefetch = $source->resolve_prefetch(
2084 $p, $alias, $seen, \@pre_order, $collapse
2086 push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
2087 push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
2089 push(@{$attrs->{order_by}}, @pre_order);
2091 $attrs->{collapse} = $collapse;
2093 if ($attrs->{page}) {
2094 $attrs->{offset} ||= 0;
2095 $attrs->{offset} += ($attrs->{rows} * ($attrs->{page} - 1));
2098 return $self->{_attrs} = $attrs;
2102 my ($self, $attr) = @_;
2104 if (ref $attr eq 'HASH') {
2105 return $self->_rollout_hash($attr);
2106 } elsif (ref $attr eq 'ARRAY') {
2107 return $self->_rollout_array($attr);
2113 sub _rollout_array {
2114 my ($self, $attr) = @_;
2117 foreach my $element (@{$attr}) {
2118 if (ref $element eq 'HASH') {
2119 push( @rolled_array, @{ $self->_rollout_hash( $element ) } );
2120 } elsif (ref $element eq 'ARRAY') {
2121 # XXX - should probably recurse here
2122 push( @rolled_array, @{$self->_rollout_array($element)} );
2124 push( @rolled_array, $element );
2127 return \@rolled_array;
2131 my ($self, $attr) = @_;
2134 foreach my $key (keys %{$attr}) {
2135 push( @rolled_array, { $key => $attr->{$key} } );
2137 return \@rolled_array;
2140 sub _calculate_score {
2141 my ($self, $a, $b) = @_;
2143 if (ref $b eq 'HASH') {
2144 my ($b_key) = keys %{$b};
2145 if (ref $a eq 'HASH') {
2146 my ($a_key) = keys %{$a};
2147 if ($a_key eq $b_key) {
2148 return (1 + $self->_calculate_score( $a->{$a_key}, $b->{$b_key} ));
2153 return ($a eq $b_key) ? 1 : 0;
2156 if (ref $a eq 'HASH') {
2157 my ($a_key) = keys %{$a};
2158 return ($b eq $a_key) ? 1 : 0;
2160 return ($b eq $a) ? 1 : 0;
2166 my ($self, $a, $b) = @_;
2168 return $b unless defined($a);
2169 return $a unless defined($b);
2171 $a = $self->_rollout_attr($a);
2172 $b = $self->_rollout_attr($b);
2175 foreach my $b_element ( @{$b} ) {
2176 # find best candidate from $a to merge $b_element into
2177 my $best_candidate = { position => undef, score => 0 }; my $position = 0;
2178 foreach my $a_element ( @{$a} ) {
2179 my $score = $self->_calculate_score( $a_element, $b_element );
2180 if ($score > $best_candidate->{score}) {
2181 $best_candidate->{position} = $position;
2182 $best_candidate->{score} = $score;
2186 my ($b_key) = ( ref $b_element eq 'HASH' ) ? keys %{$b_element} : ($b_element);
2188 if ($best_candidate->{score} == 0 || exists $seen_keys->{$b_key}) {
2189 push( @{$a}, $b_element );
2191 my $a_best = $a->[$best_candidate->{position}];
2192 # merge a_best and b_element together and replace original with merged
2193 if (ref $a_best ne 'HASH') {
2194 $a->[$best_candidate->{position}] = $b_element;
2195 } elsif (ref $b_element eq 'HASH') {
2196 my ($key) = keys %{$a_best};
2197 $a->[$best_candidate->{position}] = { $key => $self->_merge_attr($a_best->{$key}, $b_element->{$key}) };
2200 $seen_keys->{$b_key} = 1; # don't merge the same key twice
2210 $self->_source_handle($_[0]->handle);
2212 $self->_source_handle->resolve;
2216 =head2 throw_exception
2218 See L<DBIx::Class::Schema/throw_exception> for details.
2222 sub throw_exception {
2224 if (ref $self && $self->_source_handle->schema) {
2225 $self->_source_handle->schema->throw_exception(@_)
2232 # XXX: FIXME: Attributes docs need clearing up
2236 The resultset takes various attributes that modify its behavior. Here's an
2243 =item Value: ($order_by | \@order_by)
2247 Which column(s) to order the results by. This is currently passed
2248 through directly to SQL, so you can give e.g. C<year DESC> for a
2249 descending order on the column `year'.
2251 Please note that if you have C<quote_char> enabled (see
2252 L<DBIx::Class::Storage::DBI/connect_info>) you will need to do C<\'year DESC' > to
2253 specify an order. (The scalar ref causes it to be passed as raw sql to the DB,
2254 so you will need to manually quote things as appropriate.)
2260 =item Value: \@columns
2264 Shortcut to request a particular set of columns to be retrieved. Adds
2265 C<me.> onto the start of any column without a C<.> in it and sets C<select>
2266 from that, then auto-populates C<as> from C<select> as normal. (You may also
2267 use the C<cols> attribute, as in earlier versions of DBIC.)
2269 =head2 include_columns
2273 =item Value: \@columns
2277 Shortcut to include additional columns in the returned results - for example
2279 $schema->resultset('CD')->search(undef, {
2280 include_columns => ['artist.name'],
2284 would return all CDs and include a 'name' column to the information
2285 passed to object inflation. Note that the 'artist' is the name of the
2286 column (or relationship) accessor, and 'name' is the name of the column
2287 accessor in the related table.
2293 =item Value: \@select_columns
2297 Indicates which columns should be selected from the storage. You can use
2298 column names, or in the case of RDBMS back ends, function or stored procedure
2301 $rs = $schema->resultset('Employee')->search(undef, {
2304 { count => 'employeeid' },
2309 When you use function/stored procedure names and do not supply an C<as>
2310 attribute, the column names returned are storage-dependent. E.g. MySQL would
2311 return a column named C<count(employeeid)> in the above example.
2317 Indicates additional columns to be selected from storage. Works the same as
2318 L</select> but adds columns to the selection.
2326 Indicates additional column names for those added via L</+select>.
2334 =item Value: \@inflation_names
2338 Indicates column names for object inflation. That is, C<as>
2339 indicates the name that the column can be accessed as via the
2340 C<get_column> method (or via the object accessor, B<if one already
2341 exists>). It has nothing to do with the SQL code C<SELECT foo AS bar>.
2343 The C<as> attribute is used in conjunction with C<select>,
2344 usually when C<select> contains one or more function or stored
2347 $rs = $schema->resultset('Employee')->search(undef, {
2350 { count => 'employeeid' }
2352 as => ['name', 'employee_count'],
2355 my $employee = $rs->first(); # get the first Employee
2357 If the object against which the search is performed already has an accessor
2358 matching a column name specified in C<as>, the value can be retrieved using
2359 the accessor as normal:
2361 my $name = $employee->name();
2363 If on the other hand an accessor does not exist in the object, you need to
2364 use C<get_column> instead:
2366 my $employee_count = $employee->get_column('employee_count');
2368 You can create your own accessors if required - see
2369 L<DBIx::Class::Manual::Cookbook> for details.
2371 Please note: This will NOT insert an C<AS employee_count> into the SQL
2372 statement produced, it is used for internal access only. Thus
2373 attempting to use the accessor in an C<order_by> clause or similar
2374 will fail miserably.
2376 To get around this limitation, you can supply literal SQL to your
2377 C<select> attibute that contains the C<AS alias> text, eg:
2379 select => [\'myfield AS alias']
2385 =item Value: ($rel_name | \@rel_names | \%rel_names)
2389 Contains a list of relationships that should be joined for this query. For
2392 # Get CDs by Nine Inch Nails
2393 my $rs = $schema->resultset('CD')->search(
2394 { 'artist.name' => 'Nine Inch Nails' },
2395 { join => 'artist' }
2398 Can also contain a hash reference to refer to the other relation's relations.
2401 package MyApp::Schema::Track;
2402 use base qw/DBIx::Class/;
2403 __PACKAGE__->table('track');
2404 __PACKAGE__->add_columns(qw/trackid cd position title/);
2405 __PACKAGE__->set_primary_key('trackid');
2406 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
2409 # In your application
2410 my $rs = $schema->resultset('Artist')->search(
2411 { 'track.title' => 'Teardrop' },
2413 join => { cd => 'track' },
2414 order_by => 'artist.name',
2418 You need to use the relationship (not the table) name in conditions,
2419 because they are aliased as such. The current table is aliased as "me", so
2420 you need to use me.column_name in order to avoid ambiguity. For example:
2422 # Get CDs from 1984 with a 'Foo' track
2423 my $rs = $schema->resultset('CD')->search(
2426 'tracks.name' => 'Foo'
2428 { join => 'tracks' }
2431 If the same join is supplied twice, it will be aliased to <rel>_2 (and
2432 similarly for a third time). For e.g.
2434 my $rs = $schema->resultset('Artist')->search({
2435 'cds.title' => 'Down to Earth',
2436 'cds_2.title' => 'Popular',
2438 join => [ qw/cds cds/ ],
2441 will return a set of all artists that have both a cd with title 'Down
2442 to Earth' and a cd with title 'Popular'.
2444 If you want to fetch related objects from other tables as well, see C<prefetch>
2447 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
2453 =item Value: ($rel_name | \@rel_names | \%rel_names)
2457 Contains one or more relationships that should be fetched along with
2458 the main query (when they are accessed afterwards the data will
2459 already be available, without extra queries to the database). This is
2460 useful for when you know you will need the related objects, because it
2461 saves at least one query:
2463 my $rs = $schema->resultset('Tag')->search(
2472 The initial search results in SQL like the following:
2474 SELECT tag.*, cd.*, artist.* FROM tag
2475 JOIN cd ON tag.cd = cd.cdid
2476 JOIN artist ON cd.artist = artist.artistid
2478 L<DBIx::Class> has no need to go back to the database when we access the
2479 C<cd> or C<artist> relationships, which saves us two SQL statements in this
2482 Simple prefetches will be joined automatically, so there is no need
2483 for a C<join> attribute in the above search.
2485 C<prefetch> can be used with the following relationship types: C<belongs_to>,
2486 C<has_one> (or if you're using C<add_relationship>, any relationship declared
2487 with an accessor type of 'single' or 'filter'). A more complex example that
2488 prefetches an artists cds, the tracks on those cds, and the tags associted
2489 with that artist is given below (assuming many-to-many from artists to tags):
2491 my $rs = $schema->resultset('Artist')->search(
2495 { cds => 'tracks' },
2496 { artist_tags => 'tags' }
2502 B<NOTE:> If you specify a C<prefetch> attribute, the C<join> and C<select>
2503 attributes will be ignored.
2513 Makes the resultset paged and specifies the page to retrieve. Effectively
2514 identical to creating a non-pages resultset and then calling ->page($page)
2517 If L<rows> attribute is not specified it defualts to 10 rows per page.
2527 Specifes the maximum number of rows for direct retrieval or the number of
2528 rows per page if the page attribute or method is used.
2534 =item Value: $offset
2538 Specifies the (zero-based) row number for the first row to be returned, or the
2539 of the first row of the first page if paging is used.
2545 =item Value: \@columns
2549 A arrayref of columns to group by. Can include columns of joined tables.
2551 group_by => [qw/ column1 column2 ... /]
2557 =item Value: $condition
2561 HAVING is a select statement attribute that is applied between GROUP BY and
2562 ORDER BY. It is applied to the after the grouping calculations have been
2565 having => { 'count(employee)' => { '>=', 100 } }
2571 =item Value: (0 | 1)
2575 Set to 1 to group by all columns.
2581 Adds to the WHERE clause.
2583 # only return rows WHERE deleted IS NULL for all searches
2584 __PACKAGE__->resultset_attributes({ where => { deleted => undef } }); )
2586 Can be overridden by passing C<{ where => undef }> as an attribute
2593 Set to 1 to cache search results. This prevents extra SQL queries if you
2594 revisit rows in your ResultSet:
2596 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
2598 while( my $artist = $resultset->next ) {
2602 $rs->first; # without cache, this would issue a query
2604 By default, searches are not cached.
2606 For more examples of using these attributes, see
2607 L<DBIx::Class::Manual::Cookbook>.
2613 =item Value: \@from_clause
2617 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
2618 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
2621 NOTE: Use this on your own risk. This allows you to shoot off your foot!
2623 C<join> will usually do what you need and it is strongly recommended that you
2624 avoid using C<from> unless you cannot achieve the desired result using C<join>.
2625 And we really do mean "cannot", not just tried and failed. Attempting to use
2626 this because you're having problems with C<join> is like trying to use x86
2627 ASM because you've got a syntax error in your C. Trust us on this.
2629 Now, if you're still really, really sure you need to use this (and if you're
2630 not 100% sure, ask the mailing list first), here's an explanation of how this
2633 The syntax is as follows -
2636 { <alias1> => <table1> },
2638 { <alias2> => <table2>, -join_type => 'inner|left|right' },
2639 [], # nested JOIN (optional)
2640 { <table1.column1> => <table2.column2>, ... (more conditions) },
2642 # More of the above [ ] may follow for additional joins
2649 ON <table1.column1> = <table2.column2>
2650 <more joins may follow>
2652 An easy way to follow the examples below is to remember the following:
2654 Anything inside "[]" is a JOIN
2655 Anything inside "{}" is a condition for the enclosing JOIN
2657 The following examples utilize a "person" table in a family tree application.
2658 In order to express parent->child relationships, this table is self-joined:
2660 # Person->belongs_to('father' => 'Person');
2661 # Person->belongs_to('mother' => 'Person');
2663 C<from> can be used to nest joins. Here we return all children with a father,
2664 then search against all mothers of those children:
2666 $rs = $schema->resultset('Person')->search(
2669 alias => 'mother', # alias columns in accordance with "from"
2671 { mother => 'person' },
2674 { child => 'person' },
2676 { father => 'person' },
2677 { 'father.person_id' => 'child.father_id' }
2680 { 'mother.person_id' => 'child.mother_id' }
2687 # SELECT mother.* FROM person mother
2690 # JOIN person father
2691 # ON ( father.person_id = child.father_id )
2693 # ON ( mother.person_id = child.mother_id )
2695 The type of any join can be controlled manually. To search against only people
2696 with a father in the person table, we could explicitly use C<INNER JOIN>:
2698 $rs = $schema->resultset('Person')->search(
2701 alias => 'child', # alias columns in accordance with "from"
2703 { child => 'person' },
2705 { father => 'person', -join_type => 'inner' },
2706 { 'father.id' => 'child.father_id' }
2713 # SELECT child.* FROM person child
2714 # INNER JOIN person father ON child.father_id = father.id
2720 =item Value: ( 'update' | 'shared' )
2724 Set to 'update' for a SELECT ... FOR UPDATE or 'shared' for a SELECT