1 package DBIx::Class::ResultSet;
9 use Carp::Clan qw/^DBIx::Class/;
12 use DBIx::Class::ResultSetColumn;
13 use DBIx::Class::ResultSourceHandle;
15 use base qw/DBIx::Class/;
17 __PACKAGE__->mk_group_accessors('simple' => qw/result_class _source_handle/);
21 DBIx::Class::ResultSet - Responsible for fetching and creating resultset.
25 my $rs = $schema->resultset('User')->search(registered => 1);
26 my @rows = $schema->resultset('CD')->search(year => 2005);
30 The resultset is also known as an iterator. It is responsible for handling
31 queries that may return an arbitrary number of rows, e.g. via L</search>
32 or a C<has_many> relationship.
34 In the examples below, the following table classes are used:
36 package MyApp::Schema::Artist;
37 use base qw/DBIx::Class/;
38 __PACKAGE__->load_components(qw/Core/);
39 __PACKAGE__->table('artist');
40 __PACKAGE__->add_columns(qw/artistid name/);
41 __PACKAGE__->set_primary_key('artistid');
42 __PACKAGE__->has_many(cds => 'MyApp::Schema::CD');
45 package MyApp::Schema::CD;
46 use base qw/DBIx::Class/;
47 __PACKAGE__->load_components(qw/Core/);
48 __PACKAGE__->table('cd');
49 __PACKAGE__->add_columns(qw/cdid artist title year/);
50 __PACKAGE__->set_primary_key('cdid');
51 __PACKAGE__->belongs_to(artist => 'MyApp::Schema::Artist');
60 =item Arguments: $source, \%$attrs
62 =item Return Value: $rs
66 The resultset constructor. Takes a source object (usually a
67 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
68 L</ATTRIBUTES> below). Does not perform any queries -- these are
69 executed as needed by the other methods.
71 Generally you won't need to construct a resultset manually. You'll
72 automatically get one from e.g. a L</search> called in scalar context:
74 my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
76 IMPORTANT: If called on an object, proxies to new_result instead so
78 my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
80 will return a CD object, not a ResultSet.
86 return $class->new_result(@_) if ref $class;
88 my ($source, $attrs) = @_;
89 $source = $source->handle
90 unless $source->isa('DBIx::Class::ResultSourceHandle');
91 $attrs = { %{$attrs||{}} };
94 $attrs->{rows} ||= 10;
97 $attrs->{alias} ||= 'me';
99 # Creation of {} and bless separated to mitigate RH perl bug
100 # see https://bugzilla.redhat.com/show_bug.cgi?id=196836
102 _source_handle => $source,
103 result_class => $attrs->{result_class} || $source->resolve->result_class,
104 cond => $attrs->{where},
119 =item Arguments: $cond, \%attrs?
121 =item Return Value: $resultset (scalar context), @row_objs (list context)
125 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
126 my $new_rs = $cd_rs->search({ year => 2005 });
128 my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
129 # year = 2005 OR year = 2004
131 If you need to pass in additional attributes but no additional condition,
132 call it as C<search(undef, \%attrs)>.
134 # "SELECT name, artistid FROM $artist_table"
135 my @all_artists = $schema->resultset('Artist')->search(undef, {
136 columns => [qw/name artistid/],
139 For a list of attributes that can be passed to C<search>, see
140 L</ATTRIBUTES>. For more examples of using this function, see
141 L<Searching|DBIx::Class::Manual::Cookbook/Searching>. For a complete
142 documentation for the first argument, see L<SQL::Abstract>.
144 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
150 my $rs = $self->search_rs( @_ );
151 return (wantarray ? $rs->all : $rs);
158 =item Arguments: $cond, \%attrs?
160 =item Return Value: $resultset
164 This method does the same exact thing as search() except it will
165 always return a resultset, even in list context.
173 $attrs = pop(@_) if @_ > 1 and ref $_[$#_] eq 'HASH';
174 my $our_attrs = { %{$self->{attrs}} };
175 my $having = delete $our_attrs->{having};
176 my $where = delete $our_attrs->{where};
180 my %safe = (alias => 1, cache => 1);
183 (@_ && defined($_[0])) # @_ == () or (undef)
185 (keys %$attrs # empty attrs or only 'safe' attrs
186 && List::Util::first { !$safe{$_} } keys %$attrs)
188 # no search, effectively just a clone
189 $rows = $self->get_cache;
192 my $new_attrs = { %{$our_attrs}, %{$attrs} };
194 # merge new attrs into inherited
195 foreach my $key (qw/join prefetch/) {
196 next unless exists $attrs->{$key};
197 $new_attrs->{$key} = $self->_merge_attr($our_attrs->{$key}, $attrs->{$key});
202 (@_ == 1 || ref $_[0] eq "HASH")
204 (ref $_[0] eq 'HASH')
206 (keys %{ $_[0] } > 0)
214 ? $self->throw_exception("Odd number of arguments to search")
221 if (defined $where) {
222 $new_attrs->{where} = (
223 defined $new_attrs->{where}
226 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
227 } $where, $new_attrs->{where}
234 $new_attrs->{where} = (
235 defined $new_attrs->{where}
238 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
239 } $cond, $new_attrs->{where}
245 if (defined $having) {
246 $new_attrs->{having} = (
247 defined $new_attrs->{having}
250 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
251 } $having, $new_attrs->{having}
257 my $rs = (ref $self)->new($self->result_source, $new_attrs);
259 $rs->set_cache($rows);
264 =head2 search_literal
268 =item Arguments: $sql_fragment, @bind_values
270 =item Return Value: $resultset (scalar context), @row_objs (list context)
274 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
275 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
277 Pass a literal chunk of SQL to be added to the conditional part of the
280 CAVEAT: C<search_literal> is provided for Class::DBI compatibility and should
281 only be used in that context. There are known problems using C<search_literal>
282 in chained queries; it can result in bind values in the wrong order. See
283 L<DBIx::Class::Manual::Cookbook/Searching> and
284 L<DBIx::Class::Manual::FAQ/Searching> for searching techniques that do not
285 require C<search_literal>.
290 my ($self, $cond, @vals) = @_;
291 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
292 $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
293 return $self->search(\$cond, $attrs);
300 =item Arguments: @values | \%cols, \%attrs?
302 =item Return Value: $row_object
306 Finds a row based on its primary key or unique constraint. For example, to find
307 a row by its primary key:
309 my $cd = $schema->resultset('CD')->find(5);
311 You can also find a row by a specific unique constraint using the C<key>
312 attribute. For example:
314 my $cd = $schema->resultset('CD')->find('Massive Attack', 'Mezzanine', {
315 key => 'cd_artist_title'
318 Additionally, you can specify the columns explicitly by name:
320 my $cd = $schema->resultset('CD')->find(
322 artist => 'Massive Attack',
323 title => 'Mezzanine',
325 { key => 'cd_artist_title' }
328 If the C<key> is specified as C<primary>, it searches only on the primary key.
330 If no C<key> is specified, it searches on all unique constraints defined on the
331 source, including the primary key.
333 If your table does not have a primary key, you B<must> provide a value for the
334 C<key> attribute matching one of the unique constraints on the source.
336 See also L</find_or_create> and L</update_or_create>. For information on how to
337 declare unique constraints, see
338 L<DBIx::Class::ResultSource/add_unique_constraint>.
344 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
346 # Default to the primary key, but allow a specific key
347 my @cols = exists $attrs->{key}
348 ? $self->result_source->unique_constraint_columns($attrs->{key})
349 : $self->result_source->primary_columns;
350 $self->throw_exception(
351 "Can't find unless a primary key is defined or unique constraint is specified"
354 # Parse out a hashref from input
356 if (ref $_[0] eq 'HASH') {
357 $input_query = { %{$_[0]} };
359 elsif (@_ == @cols) {
361 @{$input_query}{@cols} = @_;
364 # Compatibility: Allow e.g. find(id => $value)
365 carp "Find by key => value deprecated; please use a hashref instead";
369 my (%related, $info);
371 KEY: foreach my $key (keys %$input_query) {
372 if (ref($input_query->{$key})
373 && ($info = $self->result_source->relationship_info($key))) {
374 my $val = delete $input_query->{$key};
375 next KEY if (ref($val) eq 'ARRAY'); # has_many for multi_create
376 my $rel_q = $self->result_source->resolve_condition(
377 $info->{cond}, $val, $key
379 die "Can't handle OR join condition in find" if ref($rel_q) eq 'ARRAY';
380 @related{keys %$rel_q} = values %$rel_q;
383 if (my @keys = keys %related) {
384 @{$input_query}{@keys} = values %related;
387 my @unique_queries = $self->_unique_queries($input_query, $attrs);
389 # Build the final query: Default to the disjunction of the unique queries,
390 # but allow the input query in case the ResultSet defines the query or the
391 # user is abusing find
392 my $alias = exists $attrs->{alias} ? $attrs->{alias} : $self->{attrs}{alias};
393 my $query = @unique_queries
394 ? [ map { $self->_add_alias($_, $alias) } @unique_queries ]
395 : $self->_add_alias($input_query, $alias);
399 my $rs = $self->search($query, $attrs);
400 return keys %{$rs->_resolved_attrs->{collapse}} ? $rs->next : $rs->single;
403 return keys %{$self->_resolved_attrs->{collapse}}
404 ? $self->search($query)->next
405 : $self->single($query);
411 # Add the specified alias to the specified query hash. A copy is made so the
412 # original query is not modified.
415 my ($self, $query, $alias) = @_;
417 my %aliased = %$query;
418 foreach my $col (grep { ! m/\./ } keys %aliased) {
419 $aliased{"$alias.$col"} = delete $aliased{$col};
427 # Build a list of queries which satisfy unique constraints.
429 sub _unique_queries {
430 my ($self, $query, $attrs) = @_;
432 my @constraint_names = exists $attrs->{key}
434 : $self->result_source->unique_constraint_names;
436 my $where = $self->_collapse_cond($self->{attrs}{where} || {});
437 my $num_where = scalar keys %$where;
440 foreach my $name (@constraint_names) {
441 my @unique_cols = $self->result_source->unique_constraint_columns($name);
442 my $unique_query = $self->_build_unique_query($query, \@unique_cols);
444 my $num_cols = scalar @unique_cols;
445 my $num_query = scalar keys %$unique_query;
447 my $total = $num_query + $num_where;
448 if ($num_query && ($num_query == $num_cols || $total == $num_cols)) {
449 # The query is either unique on its own or is unique in combination with
450 # the existing where clause
451 push @unique_queries, $unique_query;
455 return @unique_queries;
458 # _build_unique_query
460 # Constrain the specified query hash based on the specified column names.
462 sub _build_unique_query {
463 my ($self, $query, $unique_cols) = @_;
466 map { $_ => $query->{$_} }
467 grep { exists $query->{$_} }
472 =head2 search_related
476 =item Arguments: $rel, $cond, \%attrs?
478 =item Return Value: $new_resultset
482 $new_rs = $cd_rs->search_related('artist', {
486 Searches the specified relationship, optionally specifying a condition and
487 attributes for matching records. See L</ATTRIBUTES> for more information.
492 return shift->related_resultset(shift)->search(@_);
499 =item Arguments: none
501 =item Return Value: $cursor
505 Returns a storage-driven cursor to the given resultset. See
506 L<DBIx::Class::Cursor> for more information.
513 my $attrs = { %{$self->_resolved_attrs} };
514 return $self->{cursor}
515 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
516 $attrs->{where},$attrs);
523 =item Arguments: $cond?
525 =item Return Value: $row_object?
529 my $cd = $schema->resultset('CD')->single({ year => 2001 });
531 Inflates the first result without creating a cursor if the resultset has
532 any records in it; if not returns nothing. Used by L</find> as an optimisation.
534 Can optionally take an additional condition *only* - this is a fast-code-path
535 method; if you need to add extra joins or similar call ->search and then
536 ->single without a condition on the $rs returned from that.
541 my ($self, $where) = @_;
542 my $attrs = { %{$self->_resolved_attrs} };
544 if (defined $attrs->{where}) {
547 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
548 $where, delete $attrs->{where} ]
551 $attrs->{where} = $where;
555 # XXX: Disabled since it doesn't infer uniqueness in all cases
556 # unless ($self->_is_unique_query($attrs->{where})) {
557 # carp "Query not guaranteed to return a single row"
558 # . "; please declare your unique constraints or use search instead";
561 my @data = $self->result_source->storage->select_single(
562 $attrs->{from}, $attrs->{select},
563 $attrs->{where}, $attrs
566 return (@data ? ($self->_construct_object(@data))[0] : undef);
571 # Try to determine if the specified query is guaranteed to be unique, based on
572 # the declared unique constraints.
574 sub _is_unique_query {
575 my ($self, $query) = @_;
577 my $collapsed = $self->_collapse_query($query);
578 my $alias = $self->{attrs}{alias};
580 foreach my $name ($self->result_source->unique_constraint_names) {
581 my @unique_cols = map {
583 } $self->result_source->unique_constraint_columns($name);
585 # Count the values for each unique column
586 my %seen = map { $_ => 0 } @unique_cols;
588 foreach my $key (keys %$collapsed) {
589 my $aliased = $key =~ /\./ ? $key : "$alias.$key";
590 next unless exists $seen{$aliased}; # Additional constraints are okay
591 $seen{$aliased} = scalar keys %{ $collapsed->{$key} };
594 # If we get 0 or more than 1 value for a column, it's not necessarily unique
595 return 1 unless grep { $_ != 1 } values %seen;
603 # Recursively collapse the query, accumulating values for each column.
605 sub _collapse_query {
606 my ($self, $query, $collapsed) = @_;
610 if (ref $query eq 'ARRAY') {
611 foreach my $subquery (@$query) {
612 next unless ref $subquery; # -or
613 # warn "ARRAY: " . Dumper $subquery;
614 $collapsed = $self->_collapse_query($subquery, $collapsed);
617 elsif (ref $query eq 'HASH') {
618 if (keys %$query and (keys %$query)[0] eq '-and') {
619 foreach my $subquery (@{$query->{-and}}) {
620 # warn "HASH: " . Dumper $subquery;
621 $collapsed = $self->_collapse_query($subquery, $collapsed);
625 # warn "LEAF: " . Dumper $query;
626 foreach my $col (keys %$query) {
627 my $value = $query->{$col};
628 $collapsed->{$col}{$value}++;
640 =item Arguments: $cond?
642 =item Return Value: $resultsetcolumn
646 my $max_length = $rs->get_column('length')->max;
648 Returns a L<DBIx::Class::ResultSetColumn> instance for a column of the ResultSet.
653 my ($self, $column) = @_;
654 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
662 =item Arguments: $cond, \%attrs?
664 =item Return Value: $resultset (scalar context), @row_objs (list context)
668 # WHERE title LIKE '%blue%'
669 $cd_rs = $rs->search_like({ title => '%blue%'});
671 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
672 that this is simply a convenience method. You most likely want to use
673 L</search> with specific operators.
675 For more information, see L<DBIx::Class::Manual::Cookbook>.
681 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
682 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
683 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
684 return $class->search($query, { %$attrs });
691 =item Arguments: $first, $last
693 =item Return Value: $resultset (scalar context), @row_objs (list context)
697 Returns a resultset or object list representing a subset of elements from the
698 resultset slice is called on. Indexes are from 0, i.e., to get the first
701 my ($one, $two, $three) = $rs->slice(0, 2);
706 my ($self, $min, $max) = @_;
707 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
708 $attrs->{offset} = $self->{attrs}{offset} || 0;
709 $attrs->{offset} += $min;
710 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
711 return $self->search(undef(), $attrs);
712 #my $slice = (ref $self)->new($self->result_source, $attrs);
713 #return (wantarray ? $slice->all : $slice);
720 =item Arguments: none
722 =item Return Value: $result?
726 Returns the next element in the resultset (C<undef> is there is none).
728 Can be used to efficiently iterate over records in the resultset:
730 my $rs = $schema->resultset('CD')->search;
731 while (my $cd = $rs->next) {
735 Note that you need to store the resultset object, and call C<next> on it.
736 Calling C<< resultset('Table')->next >> repeatedly will always return the
737 first record from the resultset.
743 if (my $cache = $self->get_cache) {
744 $self->{all_cache_position} ||= 0;
745 return $cache->[$self->{all_cache_position}++];
747 if ($self->{attrs}{cache}) {
748 $self->{all_cache_position} = 1;
749 return ($self->all)[0];
751 if ($self->{stashed_objects}) {
752 my $obj = shift(@{$self->{stashed_objects}});
753 delete $self->{stashed_objects} unless @{$self->{stashed_objects}};
757 exists $self->{stashed_row}
758 ? @{delete $self->{stashed_row}}
759 : $self->cursor->next
761 return undef unless (@row);
762 my ($row, @more) = $self->_construct_object(@row);
763 $self->{stashed_objects} = \@more if @more;
767 sub _construct_object {
768 my ($self, @row) = @_;
769 my $info = $self->_collapse_result($self->{_attrs}{as}, \@row);
770 my @new = $self->result_class->inflate_result($self->result_source, @$info);
771 @new = $self->{_attrs}{record_filter}->(@new)
772 if exists $self->{_attrs}{record_filter};
776 sub _collapse_result {
777 my ($self, $as_proto, $row) = @_;
781 # 'foo' => [ undef, 'foo' ]
782 # 'foo.bar' => [ 'foo', 'bar' ]
783 # 'foo.bar.baz' => [ 'foo.bar', 'baz' ]
785 my @construct_as = map { [ (/^(?:(.*)\.)?([^.]+)$/) ] } @$as_proto;
787 my %collapse = %{$self->{_attrs}{collapse}||{}};
791 # if we're doing collapsing (has_many prefetch) we need to grab records
792 # until the PK changes, so fill @pri_index. if not, we leave it empty so
793 # we know we don't have to bother.
795 # the reason for not using the collapse stuff directly is because if you
796 # had for e.g. two artists in a row with no cds, the collapse info for
797 # both would be NULL (undef) so you'd lose the second artist
799 # store just the index so we can check the array positions from the row
800 # without having to contruct the full hash
802 if (keys %collapse) {
803 my %pri = map { ($_ => 1) } $self->result_source->primary_columns;
804 foreach my $i (0 .. $#construct_as) {
805 next if defined($construct_as[$i][0]); # only self table
806 if (delete $pri{$construct_as[$i][1]}) {
807 push(@pri_index, $i);
809 last unless keys %pri; # short circuit (Johnny Five Is Alive!)
813 # no need to do an if, it'll be empty if @pri_index is empty anyway
815 my %pri_vals = map { ($_ => $copy[$_]) } @pri_index;
819 do { # no need to check anything at the front, we always want the first row
823 foreach my $this_as (@construct_as) {
824 $const{$this_as->[0]||''}{$this_as->[1]} = shift(@copy);
827 push(@const_rows, \%const);
829 } until ( # no pri_index => no collapse => drop straight out
832 do { # get another row, stash it, drop out if different PK
834 @copy = $self->cursor->next;
835 $self->{stashed_row} = \@copy;
837 # last thing in do block, counts as true if anything doesn't match
839 # check xor defined first for NULL vs. NOT NULL then if one is
840 # defined the other must be so check string equality
843 (defined $pri_vals{$_} ^ defined $copy[$_])
844 || (defined $pri_vals{$_} && ($pri_vals{$_} ne $copy[$_]))
849 my $alias = $self->{attrs}{alias};
856 foreach my $const (@const_rows) {
857 scalar @const_keys or do {
858 @const_keys = sort { length($a) <=> length($b) } keys %$const;
860 foreach my $key (@const_keys) {
863 my @parts = split(/\./, $key);
865 my $data = $const->{$key};
866 foreach my $p (@parts) {
867 $target = $target->[1]->{$p} ||= [];
869 if ($cur eq ".${key}" && (my @ckey = @{$collapse{$cur}||[]})) {
870 # collapsing at this point and on final part
871 my $pos = $collapse_pos{$cur};
872 CK: foreach my $ck (@ckey) {
873 if (!defined $pos->{$ck} || $pos->{$ck} ne $data->{$ck}) {
874 $collapse_pos{$cur} = $data;
875 delete @collapse_pos{ # clear all positioning for sub-entries
876 grep { m/^\Q${cur}.\E/ } keys %collapse_pos
883 if (exists $collapse{$cur}) {
884 $target = $target->[-1];
887 $target->[0] = $data;
889 $info->[0] = $const->{$key};
901 =item Arguments: $result_source?
903 =item Return Value: $result_source
907 An accessor for the primary ResultSource object from which this ResultSet
914 =item Arguments: $result_class?
916 =item Return Value: $result_class
920 An accessor for the class to use when creating row objects. Defaults to
921 C<< result_source->result_class >> - which in most cases is the name of the
922 L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class.
931 =item Arguments: $cond, \%attrs??
933 =item Return Value: $count
937 Performs an SQL C<COUNT> with the same query as the resultset was built
938 with to find the number of elements. If passed arguments, does a search
939 on the resultset and counts the results of that.
941 Note: When using C<count> with C<group_by>, L<DBIx::Class> emulates C<GROUP BY>
942 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
943 not support C<DISTINCT> with multiple columns. If you are using such a
944 database, you should only use columns from the main table in your C<group_by>
951 return $self->search(@_)->count if @_ and defined $_[0];
952 return scalar @{ $self->get_cache } if $self->get_cache;
953 my $count = $self->_count;
954 return 0 unless $count;
956 # need to take offset from resolved attrs
958 $count -= $self->{_attrs}{offset} if $self->{_attrs}{offset};
959 $count = $self->{attrs}{rows} if
960 $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
961 $count = 0 if ($count < 0);
965 sub _count { # Separated out so pager can get the full count
967 my $select = { count => '*' };
969 my $attrs = { %{$self->_resolved_attrs} };
970 if (my $group_by = delete $attrs->{group_by}) {
971 delete $attrs->{having};
972 my @distinct = (ref $group_by ? @$group_by : ($group_by));
973 # todo: try CONCAT for multi-column pk
974 my @pk = $self->result_source->primary_columns;
976 my $alias = $attrs->{alias};
977 foreach my $column (@distinct) {
978 if ($column =~ qr/^(?:\Q${alias}.\E)?$pk[0]$/) {
979 @distinct = ($column);
985 $select = { count => { distinct => \@distinct } };
988 $attrs->{select} = $select;
989 $attrs->{as} = [qw/count/];
991 # offset, order by and page are not needed to count. record_filter is cdbi
992 delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
994 my $tmp_rs = (ref $self)->new($self->result_source, $attrs);
995 my ($count) = $tmp_rs->cursor->next;
1003 =item Arguments: $sql_fragment, @bind_values
1005 =item Return Value: $count
1009 Counts the results in a literal query. Equivalent to calling L</search_literal>
1010 with the passed arguments, then L</count>.
1014 sub count_literal { shift->search_literal(@_)->count; }
1020 =item Arguments: none
1022 =item Return Value: @objects
1026 Returns all elements in the resultset. Called implicitly if the resultset
1027 is returned in list context.
1033 return @{ $self->get_cache } if $self->get_cache;
1037 # TODO: don't call resolve here
1038 if (keys %{$self->_resolved_attrs->{collapse}}) {
1039 # if ($self->{attrs}{prefetch}) {
1040 # Using $self->cursor->all is really just an optimisation.
1041 # If we're collapsing has_many prefetches it probably makes
1042 # very little difference, and this is cleaner than hacking
1043 # _construct_object to survive the approach
1044 my @row = $self->cursor->next;
1046 push(@obj, $self->_construct_object(@row));
1047 @row = (exists $self->{stashed_row}
1048 ? @{delete $self->{stashed_row}}
1049 : $self->cursor->next);
1052 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
1055 $self->set_cache(\@obj) if $self->{attrs}{cache};
1063 =item Arguments: none
1065 =item Return Value: $self
1069 Resets the resultset's cursor, so you can iterate through the elements again.
1075 delete $self->{_attrs} if exists $self->{_attrs};
1076 $self->{all_cache_position} = 0;
1077 $self->cursor->reset;
1085 =item Arguments: none
1087 =item Return Value: $object?
1091 Resets the resultset and returns an object for the first result (if the
1092 resultset returns anything).
1097 return $_[0]->reset->next;
1100 # _cond_for_update_delete
1102 # update/delete require the condition to be modified to handle
1103 # the differing SQL syntax available. This transforms the $self->{cond}
1104 # appropriately, returning the new condition.
1106 sub _cond_for_update_delete {
1107 my ($self, $full_cond) = @_;
1110 $full_cond ||= $self->{cond};
1111 # No-op. No condition, we're updating/deleting everything
1112 return $cond unless ref $full_cond;
1114 if (ref $full_cond eq 'ARRAY') {
1118 foreach my $key (keys %{$_}) {
1120 $hash{$1} = $_->{$key};
1126 elsif (ref $full_cond eq 'HASH') {
1127 if ((keys %{$full_cond})[0] eq '-and') {
1130 my @cond = @{$full_cond->{-and}};
1131 for (my $i = 0; $i < @cond; $i++) {
1132 my $entry = $cond[$i];
1135 if (ref $entry eq 'HASH') {
1136 $hash = $self->_cond_for_update_delete($entry);
1139 $entry =~ /([^.]+)$/;
1140 $hash->{$1} = $cond[++$i];
1143 push @{$cond->{-and}}, $hash;
1147 foreach my $key (keys %{$full_cond}) {
1149 $cond->{$1} = $full_cond->{$key};
1154 $self->throw_exception(
1155 "Can't update/delete on resultset with condition unless hash or array"
1167 =item Arguments: \%values
1169 =item Return Value: $storage_rv
1173 Sets the specified columns in the resultset to the supplied values in a
1174 single query. Return value will be true if the update succeeded or false
1175 if no records were updated; exact type of success value is storage-dependent.
1180 my ($self, $values) = @_;
1181 $self->throw_exception("Values for update must be a hash")
1182 unless ref $values eq 'HASH';
1184 my $cond = $self->_cond_for_update_delete;
1186 return $self->result_source->storage->update(
1187 $self->result_source, $values, $cond
1195 =item Arguments: \%values
1197 =item Return Value: 1
1201 Fetches all objects and updates them one at a time. Note that C<update_all>
1202 will run DBIC cascade triggers, while L</update> will not.
1207 my ($self, $values) = @_;
1208 $self->throw_exception("Values for update must be a hash")
1209 unless ref $values eq 'HASH';
1210 foreach my $obj ($self->all) {
1211 $obj->set_columns($values)->update;
1220 =item Arguments: none
1222 =item Return Value: 1
1226 Deletes the contents of the resultset from its result source. Note that this
1227 will not run DBIC cascade triggers. See L</delete_all> if you need triggers
1228 to run. See also L<DBIx::Class::Row/delete>.
1235 my $cond = $self->_cond_for_update_delete;
1237 $self->result_source->storage->delete($self->result_source, $cond);
1245 =item Arguments: none
1247 =item Return Value: 1
1251 Fetches all objects and deletes them one at a time. Note that C<delete_all>
1252 will run DBIC cascade triggers, while L</delete> will not.
1258 $_->delete for $self->all;
1266 =item Arguments: \@data;
1270 Pass an arrayref of hashrefs. Each hashref should be a structure suitable for
1271 submitting to a $resultset->create(...) method.
1273 In void context, C<insert_bulk> in L<DBIx::Class::Storage::DBI> is used
1274 to insert the data, as this is a faster method.
1276 Otherwise, each set of data is inserted into the database using
1277 L<DBIx::Class::ResultSet/create>, and a arrayref of the resulting row
1278 objects is returned.
1280 Example: Assuming an Artist Class that has many CDs Classes relating:
1282 my $Artist_rs = $schema->resultset("Artist");
1284 ## Void Context Example
1285 $Artist_rs->populate([
1286 { artistid => 4, name => 'Manufactured Crap', cds => [
1287 { title => 'My First CD', year => 2006 },
1288 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
1291 { artistid => 5, name => 'Angsty-Whiny Girl', cds => [
1292 { title => 'My parents sold me to a record company' ,year => 2005 },
1293 { title => 'Why Am I So Ugly?', year => 2006 },
1294 { title => 'I Got Surgery and am now Popular', year => 2007 }
1299 ## Array Context Example
1300 my ($ArtistOne, $ArtistTwo, $ArtistThree) = $Artist_rs->populate([
1301 { name => "Artist One"},
1302 { name => "Artist Two"},
1303 { name => "Artist Three", cds=> [
1304 { title => "First CD", year => 2007},
1305 { title => "Second CD", year => 2008},
1309 print $ArtistOne->name; ## response is 'Artist One'
1310 print $ArtistThree->cds->count ## reponse is '2'
1312 Please note an important effect on your data when choosing between void and
1313 wantarray context. Since void context goes straight to C<insert_bulk> in
1314 L<DBIx::Class::Storage::DBI> this will skip any component that is overriding
1315 c<insert>. So if you are using something like L<DBIx-Class-UUIDColumns> to
1316 create primary keys for you, you will find that your PKs are empty. In this
1317 case you will have to use the wantarray context in order to create those
1323 my ($self, $data) = @_;
1325 if(defined wantarray) {
1327 foreach my $item (@$data) {
1328 push(@created, $self->create($item));
1332 my ($first, @rest) = @$data;
1334 my @names = grep {!ref $first->{$_}} keys %$first;
1335 my @rels = grep { $self->result_source->has_relationship($_) } keys %$first;
1336 my @pks = $self->result_source->primary_columns;
1338 ## do the belongs_to relationships
1339 foreach my $index (0..$#$data) {
1340 if( grep { !defined $data->[$index]->{$_} } @pks ) {
1341 my @ret = $self->populate($data);
1345 foreach my $rel (@rels) {
1346 next unless $data->[$index]->{$rel} && ref $data->[$index]->{$rel} eq "HASH";
1347 my $result = $self->related_resultset($rel)->create($data->[$index]->{$rel});
1348 my ($reverse) = keys %{$self->result_source->reverse_relationship_info($rel)};
1349 my $related = $result->result_source->resolve_condition(
1350 $result->result_source->relationship_info($reverse)->{cond},
1355 delete $data->[$index]->{$rel};
1356 $data->[$index] = {%{$data->[$index]}, %$related};
1358 push @names, keys %$related if $index == 0;
1362 ## do bulk insert on current row
1363 my @values = map { [ @$_{@names} ] } @$data;
1365 $self->result_source->storage->insert_bulk(
1366 $self->result_source,
1371 ## do the has_many relationships
1372 foreach my $item (@$data) {
1374 foreach my $rel (@rels) {
1375 next unless $item->{$rel} && ref $item->{$rel} eq "ARRAY";
1377 my $parent = $self->find(map {{$_=>$item->{$_}} } @pks)
1378 || $self->throw_exception('Cannot find the relating object.');
1380 my $child = $parent->$rel;
1382 my $related = $child->result_source->resolve_condition(
1383 $parent->result_source->relationship_info($rel)->{cond},
1388 my @rows_to_add = ref $item->{$rel} eq 'ARRAY' ? @{$item->{$rel}} : ($item->{$rel});
1389 my @populate = map { {%$_, %$related} } @rows_to_add;
1391 $child->populate( \@populate );
1401 =item Arguments: none
1403 =item Return Value: $pager
1407 Return Value a L<Data::Page> object for the current resultset. Only makes
1408 sense for queries with a C<page> attribute.
1414 my $attrs = $self->{attrs};
1415 $self->throw_exception("Can't create pager for non-paged rs")
1416 unless $self->{attrs}{page};
1417 $attrs->{rows} ||= 10;
1418 return $self->{pager} ||= Data::Page->new(
1419 $self->_count, $attrs->{rows}, $self->{attrs}{page});
1426 =item Arguments: $page_number
1428 =item Return Value: $rs
1432 Returns a resultset for the $page_number page of the resultset on which page
1433 is called, where each page contains a number of rows equal to the 'rows'
1434 attribute set on the resultset (10 by default).
1439 my ($self, $page) = @_;
1440 return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
1447 =item Arguments: \%vals
1449 =item Return Value: $object
1453 Creates a new row object in the resultset's result class and returns
1454 it. The row is not inserted into the database at this point, call
1455 L<DBIx::Class::Row/insert> to do that. Calling L<DBIx::Class::Row/in_storage>
1456 will tell you whether the row object has been inserted or not.
1458 Passes the hashref of input on to L<DBIx::Class::Row/new>.
1463 my ($self, $values) = @_;
1464 $self->throw_exception( "new_result needs a hash" )
1465 unless (ref $values eq 'HASH');
1466 $self->throw_exception(
1467 "Can't abstract implicit construct, condition not a hash"
1468 ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
1470 my $alias = $self->{attrs}{alias};
1471 my $collapsed_cond = $self->{cond} ? $self->_collapse_cond($self->{cond}) : {};
1473 # precendence must be given to passed values over values inherited from the cond,
1474 # so the order here is important.
1476 %{ $self->_remove_alias($collapsed_cond, $alias) },
1477 %{ $self->_remove_alias($values, $alias) },
1478 -source_handle => $self->_source_handle,
1479 -result_source => $self->result_source, # DO NOT REMOVE THIS, REQUIRED
1482 return $self->result_class->new(\%new);
1487 # Recursively collapse the condition.
1489 sub _collapse_cond {
1490 my ($self, $cond, $collapsed) = @_;
1494 if (ref $cond eq 'ARRAY') {
1495 foreach my $subcond (@$cond) {
1496 next unless ref $subcond; # -or
1497 # warn "ARRAY: " . Dumper $subcond;
1498 $collapsed = $self->_collapse_cond($subcond, $collapsed);
1501 elsif (ref $cond eq 'HASH') {
1502 if (keys %$cond and (keys %$cond)[0] eq '-and') {
1503 foreach my $subcond (@{$cond->{-and}}) {
1504 # warn "HASH: " . Dumper $subcond;
1505 $collapsed = $self->_collapse_cond($subcond, $collapsed);
1509 # warn "LEAF: " . Dumper $cond;
1510 foreach my $col (keys %$cond) {
1511 my $value = $cond->{$col};
1512 $collapsed->{$col} = $value;
1522 # Remove the specified alias from the specified query hash. A copy is made so
1523 # the original query is not modified.
1526 my ($self, $query, $alias) = @_;
1528 my %orig = %{ $query || {} };
1531 foreach my $key (keys %orig) {
1533 $unaliased{$key} = $orig{$key};
1536 $unaliased{$1} = $orig{$key}
1537 if $key =~ m/^(?:\Q$alias\E\.)?([^.]+)$/;
1547 =item Arguments: \%vals, \%attrs?
1549 =item Return Value: $object
1553 Find an existing record from this resultset. If none exists, instantiate a new
1554 result object and return it. The object will not be saved into your storage
1555 until you call L<DBIx::Class::Row/insert> on it.
1557 If you want objects to be saved immediately, use L</find_or_create> instead.
1563 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1564 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1565 my $exists = $self->find($hash, $attrs);
1566 return defined $exists ? $exists : $self->new_result($hash);
1573 =item Arguments: \%vals
1575 =item Return Value: a L<DBIx::Class::Row> $object
1579 Attempt to create a single new row or a row with multiple related rows
1580 in the table represented by the resultset (and related tables). This
1581 will not check for duplicate rows before inserting, use
1582 L</find_or_create> to do that.
1584 To create one row for this resultset, pass a hashref of key/value
1585 pairs representing the columns of the table and the values you wish to
1586 store. If the appropriate relationships are set up, foreign key fields
1587 can also be passed an object representing the foreign row, and the
1588 value will be set to it's primary key.
1590 To create related objects, pass a hashref for the value if the related
1591 item is a foreign key relationship (L<DBIx::Class::Relationship/belongs_to>),
1592 and use the name of the relationship as the key. (NOT the name of the field,
1593 necessarily). For C<has_many> and C<has_one> relationships, pass an arrayref
1594 of hashrefs containing the data for each of the rows to create in the foreign
1595 tables, again using the relationship name as the key.
1597 Instead of hashrefs of plain related data (key/value pairs), you may
1598 also pass new or inserted objects. New objects (not inserted yet, see
1599 L</new>), will be inserted into their appropriate tables.
1601 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
1603 Example of creating a new row.
1605 $person_rs->create({
1606 name=>"Some Person",
1607 email=>"somebody@someplace.com"
1610 Example of creating a new row and also creating rows in a related C<has_many>
1611 or C<has_one> resultset. Note Arrayref.
1614 { artistid => 4, name => 'Manufactured Crap', cds => [
1615 { title => 'My First CD', year => 2006 },
1616 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
1621 Example of creating a new row and also creating a row in a related
1622 C<belongs_to>resultset. Note Hashref.
1625 title=>"Music for Silly Walks",
1628 name=>"Silly Musician",
1635 my ($self, $attrs) = @_;
1636 $self->throw_exception( "create needs a hashref" )
1637 unless ref $attrs eq 'HASH';
1638 return $self->new_result($attrs)->insert;
1641 =head2 find_or_create
1645 =item Arguments: \%vals, \%attrs?
1647 =item Return Value: $object
1651 $class->find_or_create({ key => $val, ... });
1653 Tries to find a record based on its primary key or unique constraint; if none
1654 is found, creates one and returns that instead.
1656 my $cd = $schema->resultset('CD')->find_or_create({
1658 artist => 'Massive Attack',
1659 title => 'Mezzanine',
1663 Also takes an optional C<key> attribute, to search by a specific key or unique
1664 constraint. For example:
1666 my $cd = $schema->resultset('CD')->find_or_create(
1668 artist => 'Massive Attack',
1669 title => 'Mezzanine',
1671 { key => 'cd_artist_title' }
1674 See also L</find> and L</update_or_create>. For information on how to declare
1675 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1679 sub find_or_create {
1681 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1682 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1683 my $exists = $self->find($hash, $attrs);
1684 return defined $exists ? $exists : $self->create($hash);
1687 =head2 update_or_create
1691 =item Arguments: \%col_values, { key => $unique_constraint }?
1693 =item Return Value: $object
1697 $class->update_or_create({ col => $val, ... });
1699 First, searches for an existing row matching one of the unique constraints
1700 (including the primary key) on the source of this resultset. If a row is
1701 found, updates it with the other given column values. Otherwise, creates a new
1704 Takes an optional C<key> attribute to search on a specific unique constraint.
1707 # In your application
1708 my $cd = $schema->resultset('CD')->update_or_create(
1710 artist => 'Massive Attack',
1711 title => 'Mezzanine',
1714 { key => 'cd_artist_title' }
1717 If no C<key> is specified, it searches on all unique constraints defined on the
1718 source, including the primary key.
1720 If the C<key> is specified as C<primary>, it searches only on the primary key.
1722 See also L</find> and L</find_or_create>. For information on how to declare
1723 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1727 sub update_or_create {
1729 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1730 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
1732 my $row = $self->find($cond, $attrs);
1734 $row->update($cond);
1738 return $self->create($cond);
1745 =item Arguments: none
1747 =item Return Value: \@cache_objects?
1751 Gets the contents of the cache for the resultset, if the cache is set.
1763 =item Arguments: \@cache_objects
1765 =item Return Value: \@cache_objects
1769 Sets the contents of the cache for the resultset. Expects an arrayref
1770 of objects of the same class as those produced by the resultset. Note that
1771 if the cache is set the resultset will return the cached objects rather
1772 than re-querying the database even if the cache attr is not set.
1777 my ( $self, $data ) = @_;
1778 $self->throw_exception("set_cache requires an arrayref")
1779 if defined($data) && (ref $data ne 'ARRAY');
1780 $self->{all_cache} = $data;
1787 =item Arguments: none
1789 =item Return Value: []
1793 Clears the cache for the resultset.
1798 shift->set_cache(undef);
1801 =head2 related_resultset
1805 =item Arguments: $relationship_name
1807 =item Return Value: $resultset
1811 Returns a related resultset for the supplied relationship name.
1813 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1817 sub related_resultset {
1818 my ($self, $rel) = @_;
1820 $self->{related_resultsets} ||= {};
1821 return $self->{related_resultsets}{$rel} ||= do {
1822 my $rel_obj = $self->result_source->relationship_info($rel);
1824 $self->throw_exception(
1825 "search_related: result source '" . $self->result_source->source_name .
1826 "' has no such relationship $rel")
1829 my ($from,$seen) = $self->_resolve_from($rel);
1831 my $join_count = $seen->{$rel};
1832 my $alias = ($join_count > 1 ? join('_', $rel, $join_count) : $rel);
1834 #XXX - temp fix for result_class bug. There likely is a more elegant fix -groditi
1835 my %attrs = %{$self->{attrs}||{}};
1836 delete @attrs{qw(result_class alias)};
1840 if (my $cache = $self->get_cache) {
1841 if ($cache->[0] && $cache->[0]->related_resultset($rel)->get_cache) {
1842 $new_cache = [ map { @{$_->related_resultset($rel)->get_cache} }
1847 my $rel_source = $self->result_source->related_source($rel);
1851 # The reason we do this now instead of passing the alias to the
1852 # search_rs below is that if you wrap/overload resultset on the
1853 # source you need to know what alias it's -going- to have for things
1854 # to work sanely (e.g. RestrictWithObject wants to be able to add
1855 # extra query restrictions, and these may need to be $alias.)
1857 my $attrs = $rel_source->resultset_attributes;
1858 local $attrs->{alias} = $alias;
1860 $rel_source->resultset
1868 where => $self->{cond},
1873 $new->set_cache($new_cache) if $new_cache;
1879 my ($self, $extra_join) = @_;
1880 my $source = $self->result_source;
1881 my $attrs = $self->{attrs};
1883 my $from = $attrs->{from}
1884 || [ { $attrs->{alias} => $source->from } ];
1886 my $seen = { %{$attrs->{seen_join}||{}} };
1888 my $join = ($attrs->{join}
1889 ? [ $attrs->{join}, $extra_join ]
1892 # we need to take the prefetch the attrs into account before we
1893 # ->resolve_join as otherwise they get lost - captainL
1894 my $merged = $self->_merge_attr( $join, $attrs->{prefetch} );
1898 ($join ? $source->resolve_join($merged, $attrs->{alias}, $seen) : ()),
1901 return ($from,$seen);
1904 sub _resolved_attrs {
1906 return $self->{_attrs} if $self->{_attrs};
1908 my $attrs = { %{$self->{attrs}||{}} };
1909 my $source = $self->result_source;
1910 my $alias = $attrs->{alias};
1912 $attrs->{columns} ||= delete $attrs->{cols} if exists $attrs->{cols};
1913 if ($attrs->{columns}) {
1914 delete $attrs->{as};
1915 } elsif (!$attrs->{select}) {
1916 $attrs->{columns} = [ $source->columns ];
1921 ? (ref $attrs->{select} eq 'ARRAY'
1922 ? [ @{$attrs->{select}} ]
1923 : [ $attrs->{select} ])
1924 : [ map { m/\./ ? $_ : "${alias}.$_" } @{delete $attrs->{columns}} ]
1928 ? (ref $attrs->{as} eq 'ARRAY'
1929 ? [ @{$attrs->{as}} ]
1931 : [ map { m/^\Q${alias}.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}} ]
1935 if ($adds = delete $attrs->{include_columns}) {
1936 $adds = [$adds] unless ref $adds eq 'ARRAY';
1937 push(@{$attrs->{select}}, @$adds);
1938 push(@{$attrs->{as}}, map { m/([^.]+)$/; $1 } @$adds);
1940 if ($adds = delete $attrs->{'+select'}) {
1941 $adds = [$adds] unless ref $adds eq 'ARRAY';
1942 push(@{$attrs->{select}},
1943 map { /\./ || ref $_ ? $_ : "${alias}.$_" } @$adds);
1945 if (my $adds = delete $attrs->{'+as'}) {
1946 $adds = [$adds] unless ref $adds eq 'ARRAY';
1947 push(@{$attrs->{as}}, @$adds);
1950 $attrs->{from} ||= [ { 'me' => $source->from } ];
1952 if (exists $attrs->{join} || exists $attrs->{prefetch}) {
1953 my $join = delete $attrs->{join} || {};
1955 if (defined $attrs->{prefetch}) {
1956 $join = $self->_merge_attr(
1957 $join, $attrs->{prefetch}
1962 $attrs->{from} = # have to copy here to avoid corrupting the original
1965 $source->resolve_join($join, $alias, { %{$attrs->{seen_join}||{}} })
1970 $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
1971 if ($attrs->{order_by}) {
1972 $attrs->{order_by} = (ref($attrs->{order_by}) eq 'ARRAY'
1973 ? [ @{$attrs->{order_by}} ]
1974 : [ $attrs->{order_by} ]);
1976 $attrs->{order_by} = [];
1979 my $collapse = $attrs->{collapse} || {};
1980 if (my $prefetch = delete $attrs->{prefetch}) {
1981 $prefetch = $self->_merge_attr({}, $prefetch);
1983 my $seen = $attrs->{seen_join} || {};
1984 foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
1985 # bring joins back to level of current class
1986 my @prefetch = $source->resolve_prefetch(
1987 $p, $alias, $seen, \@pre_order, $collapse
1989 push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
1990 push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
1992 push(@{$attrs->{order_by}}, @pre_order);
1994 $attrs->{collapse} = $collapse;
1996 if ($attrs->{page}) {
1997 $attrs->{offset} ||= 0;
1998 $attrs->{offset} += ($attrs->{rows} * ($attrs->{page} - 1));
2001 return $self->{_attrs} = $attrs;
2005 my ($self, $attr) = @_;
2007 if (ref $attr eq 'HASH') {
2008 return $self->_rollout_hash($attr);
2009 } elsif (ref $attr eq 'ARRAY') {
2010 return $self->_rollout_array($attr);
2016 sub _rollout_array {
2017 my ($self, $attr) = @_;
2020 foreach my $element (@{$attr}) {
2021 if (ref $element eq 'HASH') {
2022 push( @rolled_array, @{ $self->_rollout_hash( $element ) } );
2023 } elsif (ref $element eq 'ARRAY') {
2024 # XXX - should probably recurse here
2025 push( @rolled_array, @{$self->_rollout_array($element)} );
2027 push( @rolled_array, $element );
2030 return \@rolled_array;
2034 my ($self, $attr) = @_;
2037 foreach my $key (keys %{$attr}) {
2038 push( @rolled_array, { $key => $attr->{$key} } );
2040 return \@rolled_array;
2043 sub _calculate_score {
2044 my ($self, $a, $b) = @_;
2046 if (ref $b eq 'HASH') {
2047 my ($b_key) = keys %{$b};
2048 if (ref $a eq 'HASH') {
2049 my ($a_key) = keys %{$a};
2050 if ($a_key eq $b_key) {
2051 return (1 + $self->_calculate_score( $a->{$a_key}, $b->{$b_key} ));
2056 return ($a eq $b_key) ? 1 : 0;
2059 if (ref $a eq 'HASH') {
2060 my ($a_key) = keys %{$a};
2061 return ($b eq $a_key) ? 1 : 0;
2063 return ($b eq $a) ? 1 : 0;
2069 my ($self, $a, $b) = @_;
2071 return $b unless defined($a);
2072 return $a unless defined($b);
2074 $a = $self->_rollout_attr($a);
2075 $b = $self->_rollout_attr($b);
2078 foreach my $b_element ( @{$b} ) {
2079 # find best candidate from $a to merge $b_element into
2080 my $best_candidate = { position => undef, score => 0 }; my $position = 0;
2081 foreach my $a_element ( @{$a} ) {
2082 my $score = $self->_calculate_score( $a_element, $b_element );
2083 if ($score > $best_candidate->{score}) {
2084 $best_candidate->{position} = $position;
2085 $best_candidate->{score} = $score;
2089 my ($b_key) = ( ref $b_element eq 'HASH' ) ? keys %{$b_element} : ($b_element);
2091 if ($best_candidate->{score} == 0 || exists $seen_keys->{$b_key}) {
2092 push( @{$a}, $b_element );
2094 my $a_best = $a->[$best_candidate->{position}];
2095 # merge a_best and b_element together and replace original with merged
2096 if (ref $a_best ne 'HASH') {
2097 $a->[$best_candidate->{position}] = $b_element;
2098 } elsif (ref $b_element eq 'HASH') {
2099 my ($key) = keys %{$a_best};
2100 $a->[$best_candidate->{position}] = { $key => $self->_merge_attr($a_best->{$key}, $b_element->{$key}) };
2103 $seen_keys->{$b_key} = 1; # don't merge the same key twice
2113 $self->_source_handle($_[0]->handle);
2115 $self->_source_handle->resolve;
2119 =head2 throw_exception
2121 See L<DBIx::Class::Schema/throw_exception> for details.
2125 sub throw_exception {
2127 $self->_source_handle->schema->throw_exception(@_);
2130 # XXX: FIXME: Attributes docs need clearing up
2134 The resultset takes various attributes that modify its behavior. Here's an
2141 =item Value: ($order_by | \@order_by)
2145 Which column(s) to order the results by. This is currently passed
2146 through directly to SQL, so you can give e.g. C<year DESC> for a
2147 descending order on the column `year'.
2149 Please note that if you have C<quote_char> enabled (see
2150 L<DBIx::Class::Storage::DBI/connect_info>) you will need to do C<\'year DESC' > to
2151 specify an order. (The scalar ref causes it to be passed as raw sql to the DB,
2152 so you will need to manually quote things as appropriate.)
2158 =item Value: \@columns
2162 Shortcut to request a particular set of columns to be retrieved. Adds
2163 C<me.> onto the start of any column without a C<.> in it and sets C<select>
2164 from that, then auto-populates C<as> from C<select> as normal. (You may also
2165 use the C<cols> attribute, as in earlier versions of DBIC.)
2167 =head2 include_columns
2171 =item Value: \@columns
2175 Shortcut to include additional columns in the returned results - for example
2177 $schema->resultset('CD')->search(undef, {
2178 include_columns => ['artist.name'],
2182 would return all CDs and include a 'name' column to the information
2183 passed to object inflation. Note that the 'artist' is the name of the
2184 column (or relationship) accessor, and 'name' is the name of the column
2185 accessor in the related table.
2191 =item Value: \@select_columns
2195 Indicates which columns should be selected from the storage. You can use
2196 column names, or in the case of RDBMS back ends, function or stored procedure
2199 $rs = $schema->resultset('Employee')->search(undef, {
2202 { count => 'employeeid' },
2207 When you use function/stored procedure names and do not supply an C<as>
2208 attribute, the column names returned are storage-dependent. E.g. MySQL would
2209 return a column named C<count(employeeid)> in the above example.
2215 Indicates additional columns to be selected from storage. Works the same as
2216 L</select> but adds columns to the selection.
2224 Indicates additional column names for those added via L</+select>.
2232 =item Value: \@inflation_names
2236 Indicates column names for object inflation. That is, C<as>
2237 indicates the name that the column can be accessed as via the
2238 C<get_column> method (or via the object accessor, B<if one already
2239 exists>). It has nothing to do with the SQL code C<SELECT foo AS bar>.
2241 The C<as> attribute is used in conjunction with C<select>,
2242 usually when C<select> contains one or more function or stored
2245 $rs = $schema->resultset('Employee')->search(undef, {
2248 { count => 'employeeid' }
2250 as => ['name', 'employee_count'],
2253 my $employee = $rs->first(); # get the first Employee
2255 If the object against which the search is performed already has an accessor
2256 matching a column name specified in C<as>, the value can be retrieved using
2257 the accessor as normal:
2259 my $name = $employee->name();
2261 If on the other hand an accessor does not exist in the object, you need to
2262 use C<get_column> instead:
2264 my $employee_count = $employee->get_column('employee_count');
2266 You can create your own accessors if required - see
2267 L<DBIx::Class::Manual::Cookbook> for details.
2269 Please note: This will NOT insert an C<AS employee_count> into the SQL
2270 statement produced, it is used for internal access only. Thus
2271 attempting to use the accessor in an C<order_by> clause or similar
2272 will fail miserably.
2274 To get around this limitation, you can supply literal SQL to your
2275 C<select> attibute that contains the C<AS alias> text, eg:
2277 select => [\'myfield AS alias']
2283 =item Value: ($rel_name | \@rel_names | \%rel_names)
2287 Contains a list of relationships that should be joined for this query. For
2290 # Get CDs by Nine Inch Nails
2291 my $rs = $schema->resultset('CD')->search(
2292 { 'artist.name' => 'Nine Inch Nails' },
2293 { join => 'artist' }
2296 Can also contain a hash reference to refer to the other relation's relations.
2299 package MyApp::Schema::Track;
2300 use base qw/DBIx::Class/;
2301 __PACKAGE__->table('track');
2302 __PACKAGE__->add_columns(qw/trackid cd position title/);
2303 __PACKAGE__->set_primary_key('trackid');
2304 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
2307 # In your application
2308 my $rs = $schema->resultset('Artist')->search(
2309 { 'track.title' => 'Teardrop' },
2311 join => { cd => 'track' },
2312 order_by => 'artist.name',
2316 You need to use the relationship (not the table) name in conditions,
2317 because they are aliased as such. The current table is aliased as "me", so
2318 you need to use me.column_name in order to avoid ambiguity. For example:
2320 # Get CDs from 1984 with a 'Foo' track
2321 my $rs = $schema->resultset('CD')->search(
2324 'tracks.name' => 'Foo'
2326 { join => 'tracks' }
2329 If the same join is supplied twice, it will be aliased to <rel>_2 (and
2330 similarly for a third time). For e.g.
2332 my $rs = $schema->resultset('Artist')->search({
2333 'cds.title' => 'Down to Earth',
2334 'cds_2.title' => 'Popular',
2336 join => [ qw/cds cds/ ],
2339 will return a set of all artists that have both a cd with title 'Down
2340 to Earth' and a cd with title 'Popular'.
2342 If you want to fetch related objects from other tables as well, see C<prefetch>
2345 For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
2351 =item Value: ($rel_name | \@rel_names | \%rel_names)
2355 Contains one or more relationships that should be fetched along with
2356 the main query (when they are accessed afterwards the data will
2357 already be available, without extra queries to the database). This is
2358 useful for when you know you will need the related objects, because it
2359 saves at least one query:
2361 my $rs = $schema->resultset('Tag')->search(
2370 The initial search results in SQL like the following:
2372 SELECT tag.*, cd.*, artist.* FROM tag
2373 JOIN cd ON tag.cd = cd.cdid
2374 JOIN artist ON cd.artist = artist.artistid
2376 L<DBIx::Class> has no need to go back to the database when we access the
2377 C<cd> or C<artist> relationships, which saves us two SQL statements in this
2380 Simple prefetches will be joined automatically, so there is no need
2381 for a C<join> attribute in the above search. If you're prefetching to
2382 depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
2383 specify the join as well.
2385 C<prefetch> can be used with the following relationship types: C<belongs_to>,
2386 C<has_one> (or if you're using C<add_relationship>, any relationship declared
2387 with an accessor type of 'single' or 'filter').
2397 Makes the resultset paged and specifies the page to retrieve. Effectively
2398 identical to creating a non-pages resultset and then calling ->page($page)
2401 If L<rows> attribute is not specified it defualts to 10 rows per page.
2411 Specifes the maximum number of rows for direct retrieval or the number of
2412 rows per page if the page attribute or method is used.
2418 =item Value: $offset
2422 Specifies the (zero-based) row number for the first row to be returned, or the
2423 of the first row of the first page if paging is used.
2429 =item Value: \@columns
2433 A arrayref of columns to group by. Can include columns of joined tables.
2435 group_by => [qw/ column1 column2 ... /]
2441 =item Value: $condition
2445 HAVING is a select statement attribute that is applied between GROUP BY and
2446 ORDER BY. It is applied to the after the grouping calculations have been
2449 having => { 'count(employee)' => { '>=', 100 } }
2455 =item Value: (0 | 1)
2459 Set to 1 to group by all columns.
2465 Adds to the WHERE clause.
2467 # only return rows WHERE deleted IS NULL for all searches
2468 __PACKAGE__->resultset_attributes({ where => { deleted => undef } }); )
2470 Can be overridden by passing C<{ where => undef }> as an attribute
2477 Set to 1 to cache search results. This prevents extra SQL queries if you
2478 revisit rows in your ResultSet:
2480 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
2482 while( my $artist = $resultset->next ) {
2486 $rs->first; # without cache, this would issue a query
2488 By default, searches are not cached.
2490 For more examples of using these attributes, see
2491 L<DBIx::Class::Manual::Cookbook>.
2497 =item Value: \@from_clause
2501 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
2502 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
2505 NOTE: Use this on your own risk. This allows you to shoot off your foot!
2507 C<join> will usually do what you need and it is strongly recommended that you
2508 avoid using C<from> unless you cannot achieve the desired result using C<join>.
2509 And we really do mean "cannot", not just tried and failed. Attempting to use
2510 this because you're having problems with C<join> is like trying to use x86
2511 ASM because you've got a syntax error in your C. Trust us on this.
2513 Now, if you're still really, really sure you need to use this (and if you're
2514 not 100% sure, ask the mailing list first), here's an explanation of how this
2517 The syntax is as follows -
2520 { <alias1> => <table1> },
2522 { <alias2> => <table2>, -join_type => 'inner|left|right' },
2523 [], # nested JOIN (optional)
2524 { <table1.column1> => <table2.column2>, ... (more conditions) },
2526 # More of the above [ ] may follow for additional joins
2533 ON <table1.column1> = <table2.column2>
2534 <more joins may follow>
2536 An easy way to follow the examples below is to remember the following:
2538 Anything inside "[]" is a JOIN
2539 Anything inside "{}" is a condition for the enclosing JOIN
2541 The following examples utilize a "person" table in a family tree application.
2542 In order to express parent->child relationships, this table is self-joined:
2544 # Person->belongs_to('father' => 'Person');
2545 # Person->belongs_to('mother' => 'Person');
2547 C<from> can be used to nest joins. Here we return all children with a father,
2548 then search against all mothers of those children:
2550 $rs = $schema->resultset('Person')->search(
2553 alias => 'mother', # alias columns in accordance with "from"
2555 { mother => 'person' },
2558 { child => 'person' },
2560 { father => 'person' },
2561 { 'father.person_id' => 'child.father_id' }
2564 { 'mother.person_id' => 'child.mother_id' }
2571 # SELECT mother.* FROM person mother
2574 # JOIN person father
2575 # ON ( father.person_id = child.father_id )
2577 # ON ( mother.person_id = child.mother_id )
2579 The type of any join can be controlled manually. To search against only people
2580 with a father in the person table, we could explicitly use C<INNER JOIN>:
2582 $rs = $schema->resultset('Person')->search(
2585 alias => 'child', # alias columns in accordance with "from"
2587 { child => 'person' },
2589 { father => 'person', -join_type => 'inner' },
2590 { 'father.id' => 'child.father_id' }
2597 # SELECT child.* FROM person child
2598 # INNER JOIN person father ON child.father_id = father.id