1 package DBIx::Class::ResultSet;
9 use Carp::Clan qw/^DBIx::Class/;
12 use DBIx::Class::ResultSetColumn;
13 use DBIx::Class::ResultSourceHandle;
14 use base qw/DBIx::Class/;
16 __PACKAGE__->mk_group_accessors('simple' => qw/result_class _source_handle/);
20 DBIx::Class::ResultSet - Responsible for fetching and creating resultset.
24 my $rs = $schema->resultset('User')->search(registered => 1);
25 my @rows = $schema->resultset('CD')->search(year => 2005);
29 The resultset is also known as an iterator. It is responsible for handling
30 queries that may return an arbitrary number of rows, e.g. via L</search>
31 or a C<has_many> relationship.
33 In the examples below, the following table classes are used:
35 package MyApp::Schema::Artist;
36 use base qw/DBIx::Class/;
37 __PACKAGE__->load_components(qw/Core/);
38 __PACKAGE__->table('artist');
39 __PACKAGE__->add_columns(qw/artistid name/);
40 __PACKAGE__->set_primary_key('artistid');
41 __PACKAGE__->has_many(cds => 'MyApp::Schema::CD');
44 package MyApp::Schema::CD;
45 use base qw/DBIx::Class/;
46 __PACKAGE__->load_components(qw/Core/);
47 __PACKAGE__->table('cd');
48 __PACKAGE__->add_columns(qw/cdid artist title year/);
49 __PACKAGE__->set_primary_key('cdid');
50 __PACKAGE__->belongs_to(artist => 'MyApp::Schema::Artist');
59 =item Arguments: $source, \%$attrs
61 =item Return Value: $rs
65 The resultset constructor. Takes a source object (usually a
66 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
67 L</ATTRIBUTES> below). Does not perform any queries -- these are
68 executed as needed by the other methods.
70 Generally you won't need to construct a resultset manually. You'll
71 automatically get one from e.g. a L</search> called in scalar context:
73 my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
75 IMPORTANT: If called on an object, proxies to new_result instead so
77 my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });
79 will return a CD object, not a ResultSet.
85 return $class->new_result(@_) if ref $class;
87 my ($source, $attrs) = @_;
88 $source = $source->handle
89 unless $source->isa('DBIx::Class::ResultSourceHandle');
90 $attrs = { %{$attrs||{}} };
93 $attrs->{rows} ||= 10;
96 $attrs->{alias} ||= 'me';
99 _source_handle => $source,
100 result_class => $attrs->{result_class} || $source->resolve->result_class,
101 cond => $attrs->{where},
116 =item Arguments: $cond, \%attrs?
118 =item Return Value: $resultset (scalar context), @row_objs (list context)
122 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
123 my $new_rs = $cd_rs->search({ year => 2005 });
125 my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
126 # year = 2005 OR year = 2004
128 If you need to pass in additional attributes but no additional condition,
129 call it as C<search(undef, \%attrs)>.
131 # "SELECT name, artistid FROM $artist_table"
132 my @all_artists = $schema->resultset('Artist')->search(undef, {
133 columns => [qw/name artistid/],
136 For a list of attributes that can be passed to C<search>, see
137 L</ATTRIBUTES>. For more examples of using this function, see
138 L<Searching|DBIx::Class::Manual::Cookbook/Searching>. For a complete
139 documentation for the first argument, see L<SQL::Abstract>.
145 my $rs = $self->search_rs( @_ );
146 return (wantarray ? $rs->all : $rs);
153 =item Arguments: $cond, \%attrs?
155 =item Return Value: $resultset
159 This method does the same exact thing as search() except it will
160 always return a resultset, even in list context.
169 unless (@_) { # no search, effectively just a clone
170 $rows = $self->get_cache;
174 $attrs = pop(@_) if @_ > 1 and ref $_[$#_] eq 'HASH';
175 my $our_attrs = { %{$self->{attrs}} };
176 my $having = delete $our_attrs->{having};
177 my $where = delete $our_attrs->{where};
179 my $new_attrs = { %{$our_attrs}, %{$attrs} };
181 # merge new attrs into inherited
182 foreach my $key (qw/join prefetch/) {
183 next unless exists $attrs->{$key};
184 $new_attrs->{$key} = $self->_merge_attr($our_attrs->{$key}, $attrs->{$key});
189 (@_ == 1 || ref $_[0] eq "HASH")
191 (ref $_[0] eq 'HASH')
193 (keys %{ $_[0] } > 0)
201 ? $self->throw_exception("Odd number of arguments to search")
208 if (defined $where) {
209 $new_attrs->{where} = (
210 defined $new_attrs->{where}
213 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
214 } $where, $new_attrs->{where}
221 $new_attrs->{where} = (
222 defined $new_attrs->{where}
225 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
226 } $cond, $new_attrs->{where}
232 if (defined $having) {
233 $new_attrs->{having} = (
234 defined $new_attrs->{having}
237 ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_
238 } $having, $new_attrs->{having}
244 my $rs = (ref $self)->new($self->result_source, $new_attrs);
246 $rs->set_cache($rows);
251 =head2 search_literal
255 =item Arguments: $sql_fragment, @bind_values
257 =item Return Value: $resultset (scalar context), @row_objs (list context)
261 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
262 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
264 Pass a literal chunk of SQL to be added to the conditional part of the
267 CAVEAT: C<search_literal> is provided for Class::DBI compatibility and should
268 only be used in that context. There are known problems using C<search_literal>
269 in chained queries; it can result in bind values in the wrong order. See
270 L<DBIx::Class::Manual::Cookbook/Searching> and
271 L<DBIx::Class::Manual::FAQ/Searching> for seaching techniques that do not
272 require C<search_literal>.
277 my ($self, $cond, @vals) = @_;
278 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
279 $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
280 return $self->search(\$cond, $attrs);
287 =item Arguments: @values | \%cols, \%attrs?
289 =item Return Value: $row_object
293 Finds a row based on its primary key or unique constraint. For example, to find
294 a row by its primary key:
296 my $cd = $schema->resultset('CD')->find(5);
298 You can also find a row by a specific unique constraint using the C<key>
299 attribute. For example:
301 my $cd = $schema->resultset('CD')->find('Massive Attack', 'Mezzanine', {
302 key => 'cd_artist_title'
305 Additionally, you can specify the columns explicitly by name:
307 my $cd = $schema->resultset('CD')->find(
309 artist => 'Massive Attack',
310 title => 'Mezzanine',
312 { key => 'cd_artist_title' }
315 If the C<key> is specified as C<primary>, it searches only on the primary key.
317 If no C<key> is specified, it searches on all unique constraints defined on the
318 source, including the primary key.
320 If your table does not have a primary key, you B<must> provide a value for the
321 C<key> attribute matching one of the unique constraints on the source.
323 See also L</find_or_create> and L</update_or_create>. For information on how to
324 declare unique constraints, see
325 L<DBIx::Class::ResultSource/add_unique_constraint>.
331 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
333 # Default to the primary key, but allow a specific key
334 my @cols = exists $attrs->{key}
335 ? $self->result_source->unique_constraint_columns($attrs->{key})
336 : $self->result_source->primary_columns;
337 $self->throw_exception(
338 "Can't find unless a primary key is defined or unique constraint is specified"
341 # Parse out a hashref from input
343 if (ref $_[0] eq 'HASH') {
344 $input_query = { %{$_[0]} };
346 elsif (@_ == @cols) {
348 @{$input_query}{@cols} = @_;
351 # Compatibility: Allow e.g. find(id => $value)
352 carp "Find by key => value deprecated; please use a hashref instead";
356 my (%related, $info);
358 KEY: foreach my $key (keys %$input_query) {
359 if (ref($input_query->{$key})
360 && ($info = $self->result_source->relationship_info($key))) {
361 my $val = delete $input_query->{$key};
362 next KEY if (ref($val) eq 'ARRAY'); # has_many for multi_create
363 my $rel_q = $self->result_source->resolve_condition(
364 $info->{cond}, $val, $key
366 die "Can't handle OR join condition in find" if ref($rel_q) eq 'ARRAY';
367 @related{keys %$rel_q} = values %$rel_q;
370 if (my @keys = keys %related) {
371 @{$input_query}{@keys} = values %related;
374 my @unique_queries = $self->_unique_queries($input_query, $attrs);
376 # Build the final query: Default to the disjunction of the unique queries,
377 # but allow the input query in case the ResultSet defines the query or the
378 # user is abusing find
379 my $alias = exists $attrs->{alias} ? $attrs->{alias} : $self->{attrs}{alias};
380 my $query = @unique_queries
381 ? [ map { $self->_add_alias($_, $alias) } @unique_queries ]
382 : $self->_add_alias($input_query, $alias);
386 my $rs = $self->search($query, $attrs);
387 return keys %{$rs->_resolved_attrs->{collapse}} ? $rs->next : $rs->single;
390 return keys %{$self->_resolved_attrs->{collapse}}
391 ? $self->search($query)->next
392 : $self->single($query);
398 # Add the specified alias to the specified query hash. A copy is made so the
399 # original query is not modified.
402 my ($self, $query, $alias) = @_;
404 my %aliased = %$query;
405 foreach my $col (grep { ! m/\./ } keys %aliased) {
406 $aliased{"$alias.$col"} = delete $aliased{$col};
414 # Build a list of queries which satisfy unique constraints.
416 sub _unique_queries {
417 my ($self, $query, $attrs) = @_;
419 my @constraint_names = exists $attrs->{key}
421 : $self->result_source->unique_constraint_names;
423 my $where = $self->_collapse_cond($self->{attrs}{where} || {});
424 my $num_where = scalar keys %$where;
427 foreach my $name (@constraint_names) {
428 my @unique_cols = $self->result_source->unique_constraint_columns($name);
429 my $unique_query = $self->_build_unique_query($query, \@unique_cols);
431 my $num_cols = scalar @unique_cols;
432 my $num_query = scalar keys %$unique_query;
434 my $total = $num_query + $num_where;
435 if ($num_query && ($num_query == $num_cols || $total == $num_cols)) {
436 # The query is either unique on its own or is unique in combination with
437 # the existing where clause
438 push @unique_queries, $unique_query;
442 return @unique_queries;
445 # _build_unique_query
447 # Constrain the specified query hash based on the specified column names.
449 sub _build_unique_query {
450 my ($self, $query, $unique_cols) = @_;
453 map { $_ => $query->{$_} }
454 grep { exists $query->{$_} }
459 =head2 search_related
463 =item Arguments: $rel, $cond, \%attrs?
465 =item Return Value: $new_resultset
469 $new_rs = $cd_rs->search_related('artist', {
473 Searches the specified relationship, optionally specifying a condition and
474 attributes for matching records. See L</ATTRIBUTES> for more information.
479 return shift->related_resultset(shift)->search(@_);
486 =item Arguments: none
488 =item Return Value: $cursor
492 Returns a storage-driven cursor to the given resultset. See
493 L<DBIx::Class::Cursor> for more information.
500 my $attrs = { %{$self->_resolved_attrs} };
501 return $self->{cursor}
502 ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select},
503 $attrs->{where},$attrs);
510 =item Arguments: $cond?
512 =item Return Value: $row_object?
516 my $cd = $schema->resultset('CD')->single({ year => 2001 });
518 Inflates the first result without creating a cursor if the resultset has
519 any records in it; if not returns nothing. Used by L</find> as an optimisation.
521 Can optionally take an additional condition *only* - this is a fast-code-path
522 method; if you need to add extra joins or similar call ->search and then
523 ->single without a condition on the $rs returned from that.
528 my ($self, $where) = @_;
529 my $attrs = { %{$self->_resolved_attrs} };
531 if (defined $attrs->{where}) {
534 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
535 $where, delete $attrs->{where} ]
538 $attrs->{where} = $where;
542 # XXX: Disabled since it doesn't infer uniqueness in all cases
543 # unless ($self->_is_unique_query($attrs->{where})) {
544 # carp "Query not guaranteed to return a single row"
545 # . "; please declare your unique constraints or use search instead";
548 my @data = $self->result_source->storage->select_single(
549 $attrs->{from}, $attrs->{select},
550 $attrs->{where}, $attrs
553 return (@data ? ($self->_construct_object(@data))[0] : undef);
558 # Try to determine if the specified query is guaranteed to be unique, based on
559 # the declared unique constraints.
561 sub _is_unique_query {
562 my ($self, $query) = @_;
564 my $collapsed = $self->_collapse_query($query);
565 my $alias = $self->{attrs}{alias};
567 foreach my $name ($self->result_source->unique_constraint_names) {
568 my @unique_cols = map {
570 } $self->result_source->unique_constraint_columns($name);
572 # Count the values for each unique column
573 my %seen = map { $_ => 0 } @unique_cols;
575 foreach my $key (keys %$collapsed) {
576 my $aliased = $key =~ /\./ ? $key : "$alias.$key";
577 next unless exists $seen{$aliased}; # Additional constraints are okay
578 $seen{$aliased} = scalar keys %{ $collapsed->{$key} };
581 # If we get 0 or more than 1 value for a column, it's not necessarily unique
582 return 1 unless grep { $_ != 1 } values %seen;
590 # Recursively collapse the query, accumulating values for each column.
592 sub _collapse_query {
593 my ($self, $query, $collapsed) = @_;
597 if (ref $query eq 'ARRAY') {
598 foreach my $subquery (@$query) {
599 next unless ref $subquery; # -or
600 # warn "ARRAY: " . Dumper $subquery;
601 $collapsed = $self->_collapse_query($subquery, $collapsed);
604 elsif (ref $query eq 'HASH') {
605 if (keys %$query and (keys %$query)[0] eq '-and') {
606 foreach my $subquery (@{$query->{-and}}) {
607 # warn "HASH: " . Dumper $subquery;
608 $collapsed = $self->_collapse_query($subquery, $collapsed);
612 # warn "LEAF: " . Dumper $query;
613 foreach my $col (keys %$query) {
614 my $value = $query->{$col};
615 $collapsed->{$col}{$value}++;
627 =item Arguments: $cond?
629 =item Return Value: $resultsetcolumn
633 my $max_length = $rs->get_column('length')->max;
635 Returns a L<DBIx::Class::ResultSetColumn> instance for a column of the ResultSet.
640 my ($self, $column) = @_;
641 my $new = DBIx::Class::ResultSetColumn->new($self, $column);
649 =item Arguments: $cond, \%attrs?
651 =item Return Value: $resultset (scalar context), @row_objs (list context)
655 # WHERE title LIKE '%blue%'
656 $cd_rs = $rs->search_like({ title => '%blue%'});
658 Performs a search, but uses C<LIKE> instead of C<=> as the condition. Note
659 that this is simply a convenience method. You most likely want to use
660 L</search> with specific operators.
662 For more information, see L<DBIx::Class::Manual::Cookbook>.
668 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
669 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
670 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
671 return $class->search($query, { %$attrs });
678 =item Arguments: $first, $last
680 =item Return Value: $resultset (scalar context), @row_objs (list context)
684 Returns a resultset or object list representing a subset of elements from the
685 resultset slice is called on. Indexes are from 0, i.e., to get the first
688 my ($one, $two, $three) = $rs->slice(0, 2);
693 my ($self, $min, $max) = @_;
694 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
695 $attrs->{offset} = $self->{attrs}{offset} || 0;
696 $attrs->{offset} += $min;
697 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
698 return $self->search(undef(), $attrs);
699 #my $slice = (ref $self)->new($self->result_source, $attrs);
700 #return (wantarray ? $slice->all : $slice);
707 =item Arguments: none
709 =item Return Value: $result?
713 Returns the next element in the resultset (C<undef> is there is none).
715 Can be used to efficiently iterate over records in the resultset:
717 my $rs = $schema->resultset('CD')->search;
718 while (my $cd = $rs->next) {
722 Note that you need to store the resultset object, and call C<next> on it.
723 Calling C<< resultset('Table')->next >> repeatedly will always return the
724 first record from the resultset.
730 if (my $cache = $self->get_cache) {
731 $self->{all_cache_position} ||= 0;
732 return $cache->[$self->{all_cache_position}++];
734 if ($self->{attrs}{cache}) {
735 $self->{all_cache_position} = 1;
736 return ($self->all)[0];
738 if ($self->{stashed_objects}) {
739 my $obj = shift(@{$self->{stashed_objects}});
740 delete $self->{stashed_objects} unless @{$self->{stashed_objects}};
744 exists $self->{stashed_row}
745 ? @{delete $self->{stashed_row}}
746 : $self->cursor->next
748 return undef unless (@row);
749 my ($row, @more) = $self->_construct_object(@row);
750 $self->{stashed_objects} = \@more if @more;
754 sub _construct_object {
755 my ($self, @row) = @_;
756 my $info = $self->_collapse_result($self->{_attrs}{as}, \@row);
757 my @new = $self->result_class->inflate_result($self->result_source, @$info);
758 @new = $self->{_attrs}{record_filter}->(@new)
759 if exists $self->{_attrs}{record_filter};
763 sub _collapse_result {
764 my ($self, $as_proto, $row) = @_;
768 # 'foo' => [ undef, 'foo' ]
769 # 'foo.bar' => [ 'foo', 'bar' ]
770 # 'foo.bar.baz' => [ 'foo.bar', 'baz' ]
772 my @construct_as = map { [ (/^(?:(.*)\.)?([^.]+)$/) ] } @$as_proto;
774 my %collapse = %{$self->{_attrs}{collapse}||{}};
778 # if we're doing collapsing (has_many prefetch) we need to grab records
779 # until the PK changes, so fill @pri_index. if not, we leave it empty so
780 # we know we don't have to bother.
782 # the reason for not using the collapse stuff directly is because if you
783 # had for e.g. two artists in a row with no cds, the collapse info for
784 # both would be NULL (undef) so you'd lose the second artist
786 # store just the index so we can check the array positions from the row
787 # without having to contruct the full hash
789 if (keys %collapse) {
790 my %pri = map { ($_ => 1) } $self->result_source->primary_columns;
791 foreach my $i (0 .. $#construct_as) {
792 next if defined($construct_as[$i][0]); # only self table
793 if (delete $pri{$construct_as[$i][1]}) {
794 push(@pri_index, $i);
796 last unless keys %pri; # short circuit (Johnny Five Is Alive!)
800 # no need to do an if, it'll be empty if @pri_index is empty anyway
802 my %pri_vals = map { ($_ => $copy[$_]) } @pri_index;
806 do { # no need to check anything at the front, we always want the first row
810 foreach my $this_as (@construct_as) {
811 $const{$this_as->[0]||''}{$this_as->[1]} = shift(@copy);
814 push(@const_rows, \%const);
816 } until ( # no pri_index => no collapse => drop straight out
819 do { # get another row, stash it, drop out if different PK
821 @copy = $self->cursor->next;
822 $self->{stashed_row} = \@copy;
824 # last thing in do block, counts as true if anything doesn't match
826 # check xor defined first for NULL vs. NOT NULL then if one is
827 # defined the other must be so check string equality
830 (defined $pri_vals{$_} ^ defined $copy[$_])
831 || (defined $pri_vals{$_} && ($pri_vals{$_} ne $copy[$_]))
836 my $alias = $self->{attrs}{alias};
843 foreach my $const (@const_rows) {
844 scalar @const_keys or do {
845 @const_keys = sort { length($a) <=> length($b) } keys %$const;
847 foreach my $key (@const_keys) {
850 my @parts = split(/\./, $key);
852 my $data = $const->{$key};
853 foreach my $p (@parts) {
854 $target = $target->[1]->{$p} ||= [];
856 if ($cur eq ".${key}" && (my @ckey = @{$collapse{$cur}||[]})) {
857 # collapsing at this point and on final part
858 my $pos = $collapse_pos{$cur};
859 CK: foreach my $ck (@ckey) {
860 if (!defined $pos->{$ck} || $pos->{$ck} ne $data->{$ck}) {
861 $collapse_pos{$cur} = $data;
862 delete @collapse_pos{ # clear all positioning for sub-entries
863 grep { m/^\Q${cur}.\E/ } keys %collapse_pos
870 if (exists $collapse{$cur}) {
871 $target = $target->[-1];
874 $target->[0] = $data;
876 $info->[0] = $const->{$key};
888 =item Arguments: $result_source?
890 =item Return Value: $result_source
894 An accessor for the primary ResultSource object from which this ResultSet
901 =item Arguments: $result_class?
903 =item Return Value: $result_class
907 An accessor for the class to use when creating row objects. Defaults to
908 C<< result_source->result_class >> - which in most cases is the name of the
909 L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class.
918 =item Arguments: $cond, \%attrs??
920 =item Return Value: $count
924 Performs an SQL C<COUNT> with the same query as the resultset was built
925 with to find the number of elements. If passed arguments, does a search
926 on the resultset and counts the results of that.
928 Note: When using C<count> with C<group_by>, L<DBIX::Class> emulates C<GROUP BY>
929 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
930 not support C<DISTINCT> with multiple columns. If you are using such a
931 database, you should only use columns from the main table in your C<group_by>
938 return $self->search(@_)->count if @_ and defined $_[0];
939 return scalar @{ $self->get_cache } if $self->get_cache;
940 my $count = $self->_count;
941 return 0 unless $count;
943 # need to take offset from resolved attrs
945 $count -= $self->{_attrs}{offset} if $self->{_attrs}{offset};
946 $count = $self->{attrs}{rows} if
947 $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
948 $count = 0 if ($count < 0);
952 sub _count { # Separated out so pager can get the full count
954 my $select = { count => '*' };
956 my $attrs = { %{$self->_resolved_attrs} };
957 if (my $group_by = delete $attrs->{group_by}) {
958 delete $attrs->{having};
959 my @distinct = (ref $group_by ? @$group_by : ($group_by));
960 # todo: try CONCAT for multi-column pk
961 my @pk = $self->result_source->primary_columns;
963 my $alias = $attrs->{alias};
964 foreach my $column (@distinct) {
965 if ($column =~ qr/^(?:\Q${alias}.\E)?$pk[0]$/) {
966 @distinct = ($column);
972 $select = { count => { distinct => \@distinct } };
975 $attrs->{select} = $select;
976 $attrs->{as} = [qw/count/];
978 # offset, order by and page are not needed to count. record_filter is cdbi
979 delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
981 my $tmp_rs = (ref $self)->new($self->result_source, $attrs);
982 my ($count) = $tmp_rs->cursor->next;
990 =item Arguments: $sql_fragment, @bind_values
992 =item Return Value: $count
996 Counts the results in a literal query. Equivalent to calling L</search_literal>
997 with the passed arguments, then L</count>.
1001 sub count_literal { shift->search_literal(@_)->count; }
1007 =item Arguments: none
1009 =item Return Value: @objects
1013 Returns all elements in the resultset. Called implicitly if the resultset
1014 is returned in list context.
1020 return @{ $self->get_cache } if $self->get_cache;
1024 # TODO: don't call resolve here
1025 if (keys %{$self->_resolved_attrs->{collapse}}) {
1026 # if ($self->{attrs}{prefetch}) {
1027 # Using $self->cursor->all is really just an optimisation.
1028 # If we're collapsing has_many prefetches it probably makes
1029 # very little difference, and this is cleaner than hacking
1030 # _construct_object to survive the approach
1031 my @row = $self->cursor->next;
1033 push(@obj, $self->_construct_object(@row));
1034 @row = (exists $self->{stashed_row}
1035 ? @{delete $self->{stashed_row}}
1036 : $self->cursor->next);
1039 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
1042 $self->set_cache(\@obj) if $self->{attrs}{cache};
1050 =item Arguments: none
1052 =item Return Value: $self
1056 Resets the resultset's cursor, so you can iterate through the elements again.
1062 delete $self->{_attrs} if exists $self->{_attrs};
1063 $self->{all_cache_position} = 0;
1064 $self->cursor->reset;
1072 =item Arguments: none
1074 =item Return Value: $object?
1078 Resets the resultset and returns an object for the first result (if the
1079 resultset returns anything).
1084 return $_[0]->reset->next;
1087 # _cond_for_update_delete
1089 # update/delete require the condition to be modified to handle
1090 # the differing SQL syntax available. This transforms the $self->{cond}
1091 # appropriately, returning the new condition.
1093 sub _cond_for_update_delete {
1094 my ($self, $full_cond) = @_;
1097 $full_cond ||= $self->{cond};
1098 # No-op. No condition, we're updating/deleting everything
1099 return $cond unless ref $full_cond;
1101 if (ref $full_cond eq 'ARRAY') {
1105 foreach my $key (keys %{$_}) {
1107 $hash{$1} = $_->{$key};
1113 elsif (ref $full_cond eq 'HASH') {
1114 if ((keys %{$full_cond})[0] eq '-and') {
1117 my @cond = @{$full_cond->{-and}};
1118 for (my $i = 0; $i < @cond; $i++) {
1119 my $entry = $cond[$i];
1122 if (ref $entry eq 'HASH') {
1123 $hash = $self->_cond_for_update_delete($entry);
1126 $entry =~ /([^.]+)$/;
1127 $hash->{$1} = $cond[++$i];
1130 push @{$cond->{-and}}, $hash;
1134 foreach my $key (keys %{$full_cond}) {
1136 $cond->{$1} = $full_cond->{$key};
1141 $self->throw_exception(
1142 "Can't update/delete on resultset with condition unless hash or array"
1154 =item Arguments: \%values
1156 =item Return Value: $storage_rv
1160 Sets the specified columns in the resultset to the supplied values in a
1161 single query. Return value will be true if the update succeeded or false
1162 if no records were updated; exact type of success value is storage-dependent.
1167 my ($self, $values) = @_;
1168 $self->throw_exception("Values for update must be a hash")
1169 unless ref $values eq 'HASH';
1171 my $cond = $self->_cond_for_update_delete;
1173 return $self->result_source->storage->update(
1174 $self->result_source, $values, $cond
1182 =item Arguments: \%values
1184 =item Return Value: 1
1188 Fetches all objects and updates them one at a time. Note that C<update_all>
1189 will run DBIC cascade triggers, while L</update> will not.
1194 my ($self, $values) = @_;
1195 $self->throw_exception("Values for update must be a hash")
1196 unless ref $values eq 'HASH';
1197 foreach my $obj ($self->all) {
1198 $obj->set_columns($values)->update;
1207 =item Arguments: none
1209 =item Return Value: 1
1213 Deletes the contents of the resultset from its result source. Note that this
1214 will not run DBIC cascade triggers. See L</delete_all> if you need triggers
1215 to run. See also L<DBIx::Class::Row/delete>.
1222 my $cond = $self->_cond_for_update_delete;
1224 $self->result_source->storage->delete($self->result_source, $cond);
1232 =item Arguments: none
1234 =item Return Value: 1
1238 Fetches all objects and deletes them one at a time. Note that C<delete_all>
1239 will run DBIC cascade triggers, while L</delete> will not.
1245 $_->delete for $self->all;
1253 =item Arguments: \@data;
1257 Pass an arrayref of hashrefs. Each hashref should be a structure suitable for
1258 submitting to a $resultset->create(...) method.
1260 In void context, C<insert_bulk> in L<DBIx::Class::Storage::DBI> is used
1261 to insert the data, as this is a faster method.
1263 Otherwise, each set of data is inserted into the database using
1264 L<DBIx::Class::ResultSet/create>, and a arrayref of the resulting row
1265 objects is returned.
1267 Example: Assuming an Artist Class that has many CDs Classes relating:
1269 my $Artist_rs = $schema->resultset("Artist");
1271 ## Void Context Example
1272 $Artist_rs->populate([
1273 { artistid => 4, name => 'Manufactured Crap', cds => [
1274 { title => 'My First CD', year => 2006 },
1275 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
1278 { artistid => 5, name => 'Angsty-Whiny Girl', cds => [
1279 { title => 'My parents sold me to a record company' ,year => 2005 },
1280 { title => 'Why Am I So Ugly?', year => 2006 },
1281 { title => 'I Got Surgery and am now Popular', year => 2007 }
1286 ## Array Context Example
1287 my ($ArtistOne, $ArtistTwo, $ArtistThree) = $Artist_rs->populate([
1288 { name => "Artist One"},
1289 { name => "Artist Two"},
1290 { name => "Artist Three", cds=> [
1291 { title => "First CD", year => 2007},
1292 { title => "Second CD", year => 2008},
1296 print $ArtistOne->name; ## response is 'Artist One'
1297 print $ArtistThree->cds->count ## reponse is '2'
1299 Please note an important effect on your data when choosing between void and
1300 wantarray context. Since void context goes straight to C<insert_bulk> in
1301 L<DBIx::Class::Storage::DBI> this will skip any component that is overriding
1302 c<insert>. So if you are using something like L<DBIx-Class-UUIDColumns> to
1303 create primary keys for you, you will find that your PKs are empty. In this
1304 case you will have to use the wantarray context in order to create those
1310 my ($self, $data) = @_;
1312 if(defined wantarray) {
1314 foreach my $item (@$data) {
1315 push(@created, $self->create($item));
1319 my ($first, @rest) = @$data;
1321 my @names = grep {!ref $first->{$_}} keys %$first;
1322 my @rels = grep { $self->result_source->has_relationship($_) } keys %$first;
1323 my @pks = $self->result_source->primary_columns;
1325 ## do the belongs_to relationships
1326 foreach my $index (0..$#$data) {
1327 if( grep { !defined $data->[$index]->{$_} } @pks ) {
1328 my @ret = $self->populate($data);
1332 foreach my $rel (@rels) {
1333 next unless $data->[$index]->{$rel} && ref $data->[$index]->{$rel} eq "HASH";
1334 my $result = $self->related_resultset($rel)->create($data->[$index]->{$rel});
1335 my ($reverse) = keys %{$self->result_source->reverse_relationship_info($rel)};
1336 my $related = $result->result_source->resolve_condition(
1337 $result->result_source->relationship_info($reverse)->{cond},
1342 delete $data->[$index]->{$rel};
1343 $data->[$index] = {%{$data->[$index]}, %$related};
1345 push @names, keys %$related if $index == 0;
1349 ## do bulk insert on current row
1350 my @values = map { [ @$_{@names} ] } @$data;
1352 $self->result_source->storage->insert_bulk(
1353 $self->result_source,
1358 ## do the has_many relationships
1359 foreach my $item (@$data) {
1361 foreach my $rel (@rels) {
1362 next unless $item->{$rel} && ref $item->{$rel} eq "ARRAY";
1364 my $parent = $self->find(map {{$_=>$item->{$_}} } @pks)
1365 || $self->throw_exception('Cannot find the relating object.');
1367 my $child = $parent->$rel;
1369 my $related = $child->result_source->resolve_condition(
1370 $parent->result_source->relationship_info($rel)->{cond},
1375 my @rows_to_add = ref $item->{$rel} eq 'ARRAY' ? @{$item->{$rel}} : ($item->{$rel});
1376 my @populate = map { {%$_, %$related} } @rows_to_add;
1378 $child->populate( \@populate );
1388 =item Arguments: none
1390 =item Return Value: $pager
1394 Return Value a L<Data::Page> object for the current resultset. Only makes
1395 sense for queries with a C<page> attribute.
1401 my $attrs = $self->{attrs};
1402 $self->throw_exception("Can't create pager for non-paged rs")
1403 unless $self->{attrs}{page};
1404 $attrs->{rows} ||= 10;
1405 return $self->{pager} ||= Data::Page->new(
1406 $self->_count, $attrs->{rows}, $self->{attrs}{page});
1413 =item Arguments: $page_number
1415 =item Return Value: $rs
1419 Returns a resultset for the $page_number page of the resultset on which page
1420 is called, where each page contains a number of rows equal to the 'rows'
1421 attribute set on the resultset (10 by default).
1426 my ($self, $page) = @_;
1427 return (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
1434 =item Arguments: \%vals
1436 =item Return Value: $object
1440 Creates a new row object in the resultset's result class and returns
1441 it. The row is not inserted into the database at this point, call
1442 L<DBIx::Class::Row/insert> to do that. Calling L<DBIx::Class::Row/in_storage>
1443 will tell you whether the row object has been inserted or not.
1445 Passes the hashref of input on to L<DBIx::Class::Row/new>.
1450 my ($self, $values) = @_;
1451 $self->throw_exception( "new_result needs a hash" )
1452 unless (ref $values eq 'HASH');
1453 $self->throw_exception(
1454 "Can't abstract implicit construct, condition not a hash"
1455 ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
1457 my $alias = $self->{attrs}{alias};
1458 my $collapsed_cond = $self->{cond} ? $self->_collapse_cond($self->{cond}) : {};
1460 # precendence must be given to passed values over values inherited from the cond,
1461 # so the order here is important.
1463 %{ $self->_remove_alias($collapsed_cond, $alias) },
1464 %{ $self->_remove_alias($values, $alias) },
1465 -source_handle => $self->_source_handle,
1466 -result_source => $self->result_source, # DO NOT REMOVE THIS, REQUIRED
1469 return $self->result_class->new(\%new);
1474 # Recursively collapse the condition.
1476 sub _collapse_cond {
1477 my ($self, $cond, $collapsed) = @_;
1481 if (ref $cond eq 'ARRAY') {
1482 foreach my $subcond (@$cond) {
1483 next unless ref $subcond; # -or
1484 # warn "ARRAY: " . Dumper $subcond;
1485 $collapsed = $self->_collapse_cond($subcond, $collapsed);
1488 elsif (ref $cond eq 'HASH') {
1489 if (keys %$cond and (keys %$cond)[0] eq '-and') {
1490 foreach my $subcond (@{$cond->{-and}}) {
1491 # warn "HASH: " . Dumper $subcond;
1492 $collapsed = $self->_collapse_cond($subcond, $collapsed);
1496 # warn "LEAF: " . Dumper $cond;
1497 foreach my $col (keys %$cond) {
1498 my $value = $cond->{$col};
1499 $collapsed->{$col} = $value;
1509 # Remove the specified alias from the specified query hash. A copy is made so
1510 # the original query is not modified.
1513 my ($self, $query, $alias) = @_;
1515 my %orig = %{ $query || {} };
1518 foreach my $key (keys %orig) {
1520 $unaliased{$key} = $orig{$key};
1523 $unaliased{$1} = $orig{$key}
1524 if $key =~ m/^(?:\Q$alias\E\.)?([^.]+)$/;
1534 =item Arguments: \%vals, \%attrs?
1536 =item Return Value: $object
1540 Find an existing record from this resultset. If none exists, instantiate a new
1541 result object and return it. The object will not be saved into your storage
1542 until you call L<DBIx::Class::Row/insert> on it.
1544 If you want objects to be saved immediately, use L</find_or_create> instead.
1550 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1551 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1552 my $exists = $self->find($hash, $attrs);
1553 return defined $exists ? $exists : $self->new_result($hash);
1560 =item Arguments: \%vals
1562 =item Return Value: $object
1566 Attempt to create a single new row or a row with multiple related rows
1567 in the table represented by the resultset (and related tables). This
1568 will not check for duplicate rows before inserting, use
1569 L</find_or_create> to do that.
1571 To create one row for this resultset, pass a hashref of key/value
1572 pairs representing the columns of the table and the values you wish to
1573 store. If the appropriate relationships are set up, foreign key fields
1574 can also be passed an object representing the foreign row, and the
1575 value will be set to it's primary key.
1577 To create related objects, pass a hashref for the value if the related
1578 item is a foreign key relationship (L<DBIx::Class::Relationship/belongs_to>),
1579 and use the name of the relationship as the key. (NOT the name of the field,
1580 necessarily). For C<has_many> and C<has_one> relationships, pass an arrayref
1581 of hashrefs containing the data for each of the rows to create in the foreign
1582 tables, again using the relationship name as the key.
1584 Instead of hashrefs of plain related data (key/value pairs), you may
1585 also pass new or inserted objects. New objects (not inserted yet, see
1586 L</new>), will be inserted into their appropriate tables.
1588 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
1590 Example of creating a new row.
1592 $person_rs->create({
1593 name=>"Some Person",
1594 email=>"somebody@someplace.com"
1597 Example of creating a new row and also creating rows in a related C<has_many>
1598 or C<has_one> resultset. Note Arrayref.
1601 { artistid => 4, name => 'Manufactured Crap', cds => [
1602 { title => 'My First CD', year => 2006 },
1603 { title => 'Yet More Tweeny-Pop crap', year => 2007 },
1608 Example of creating a new row and also creating a row in a related
1609 C<belongs_to>resultset. Note Hashref.
1612 title=>"Music for Silly Walks",
1615 name=>"Silly Musician",
1622 my ($self, $attrs) = @_;
1623 $self->throw_exception( "create needs a hashref" )
1624 unless ref $attrs eq 'HASH';
1625 return $self->new_result($attrs)->insert;
1628 =head2 find_or_create
1632 =item Arguments: \%vals, \%attrs?
1634 =item Return Value: $object
1638 $class->find_or_create({ key => $val, ... });
1640 Tries to find a record based on its primary key or unique constraint; if none
1641 is found, creates one and returns that instead.
1643 my $cd = $schema->resultset('CD')->find_or_create({
1645 artist => 'Massive Attack',
1646 title => 'Mezzanine',
1650 Also takes an optional C<key> attribute, to search by a specific key or unique
1651 constraint. For example:
1653 my $cd = $schema->resultset('CD')->find_or_create(
1655 artist => 'Massive Attack',
1656 title => 'Mezzanine',
1658 { key => 'cd_artist_title' }
1661 See also L</find> and L</update_or_create>. For information on how to declare
1662 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1666 sub find_or_create {
1668 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1669 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
1670 my $exists = $self->find($hash, $attrs);
1671 return defined $exists ? $exists : $self->create($hash);
1674 =head2 update_or_create
1678 =item Arguments: \%col_values, { key => $unique_constraint }?
1680 =item Return Value: $object
1684 $class->update_or_create({ col => $val, ... });
1686 First, searches for an existing row matching one of the unique constraints
1687 (including the primary key) on the source of this resultset. If a row is
1688 found, updates it with the other given column values. Otherwise, creates a new
1691 Takes an optional C<key> attribute to search on a specific unique constraint.
1694 # In your application
1695 my $cd = $schema->resultset('CD')->update_or_create(
1697 artist => 'Massive Attack',
1698 title => 'Mezzanine',
1701 { key => 'cd_artist_title' }
1704 If no C<key> is specified, it searches on all unique constraints defined on the
1705 source, including the primary key.
1707 If the C<key> is specified as C<primary>, it searches only on the primary key.
1709 See also L</find> and L</find_or_create>. For information on how to declare
1710 unique constraints, see L<DBIx::Class::ResultSource/add_unique_constraint>.
1714 sub update_or_create {
1716 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
1717 my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
1719 my $row = $self->find($cond, $attrs);
1721 $row->update($cond);
1725 return $self->create($cond);
1732 =item Arguments: none
1734 =item Return Value: \@cache_objects?
1738 Gets the contents of the cache for the resultset, if the cache is set.
1750 =item Arguments: \@cache_objects
1752 =item Return Value: \@cache_objects
1756 Sets the contents of the cache for the resultset. Expects an arrayref
1757 of objects of the same class as those produced by the resultset. Note that
1758 if the cache is set the resultset will return the cached objects rather
1759 than re-querying the database even if the cache attr is not set.
1764 my ( $self, $data ) = @_;
1765 $self->throw_exception("set_cache requires an arrayref")
1766 if defined($data) && (ref $data ne 'ARRAY');
1767 $self->{all_cache} = $data;
1774 =item Arguments: none
1776 =item Return Value: []
1780 Clears the cache for the resultset.
1785 shift->set_cache(undef);
1788 =head2 related_resultset
1792 =item Arguments: $relationship_name
1794 =item Return Value: $resultset
1798 Returns a related resultset for the supplied relationship name.
1800 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1804 sub related_resultset {
1805 my ($self, $rel) = @_;
1807 $self->{related_resultsets} ||= {};
1808 return $self->{related_resultsets}{$rel} ||= do {
1809 my $rel_obj = $self->result_source->relationship_info($rel);
1811 $self->throw_exception(
1812 "search_related: result source '" . $self->result_source->source_name .
1813 "' has no such relationship $rel")
1816 my ($from,$seen) = $self->_resolve_from($rel);
1818 my $join_count = $seen->{$rel};
1819 my $alias = ($join_count > 1 ? join('_', $rel, $join_count) : $rel);
1821 #XXX - temp fix for result_class bug. There likely is a more elegant fix -groditi
1822 my %attrs = %{$self->{attrs}||{}};
1823 delete @attrs{qw(result_class alias)};
1827 if (my $cache = $self->get_cache) {
1828 if ($cache->[0] && $cache->[0]->related_resultset($rel)->get_cache) {
1829 $new_cache = [ map { @{$_->related_resultset($rel)->get_cache} }
1834 my $rel_source = $self->result_source->related_source($rel);
1838 # The reason we do this now instead of passing the alias to the
1839 # search_rs below is that if you wrap/overload resultset on the
1840 # source you need to know what alias it's -going- to have for things
1841 # to work sanely (e.g. RestrictWithObject wants to be able to add
1842 # extra query restrictions, and these may need to be $alias.)
1844 my $attrs = $rel_source->resultset_attributes;
1845 local $attrs->{alias} = $alias;
1847 $rel_source->resultset
1855 where => $self->{cond},
1860 $new->set_cache($new_cache) if $new_cache;
1866 my ($self, $extra_join) = @_;
1867 my $source = $self->result_source;
1868 my $attrs = $self->{attrs};
1870 my $from = $attrs->{from}
1871 || [ { $attrs->{alias} => $source->from } ];
1873 my $seen = { %{$attrs->{seen_join}||{}} };
1875 my $join = ($attrs->{join}
1876 ? [ $attrs->{join}, $extra_join ]
1879 # we need to take the prefetch the attrs into account before we
1880 # ->resolve_join as otherwise they get lost - captainL
1881 my $merged = $self->_merge_attr( $join, $attrs->{prefetch} );
1885 ($join ? $source->resolve_join($merged, $attrs->{alias}, $seen) : ()),
1888 return ($from,$seen);
1891 sub _resolved_attrs {
1893 return $self->{_attrs} if $self->{_attrs};
1895 my $attrs = { %{$self->{attrs}||{}} };
1896 my $source = $self->result_source;
1897 my $alias = $attrs->{alias};
1899 $attrs->{columns} ||= delete $attrs->{cols} if exists $attrs->{cols};
1900 if ($attrs->{columns}) {
1901 delete $attrs->{as};
1902 } elsif (!$attrs->{select}) {
1903 $attrs->{columns} = [ $source->columns ];
1908 ? (ref $attrs->{select} eq 'ARRAY'
1909 ? [ @{$attrs->{select}} ]
1910 : [ $attrs->{select} ])
1911 : [ map { m/\./ ? $_ : "${alias}.$_" } @{delete $attrs->{columns}} ]
1915 ? (ref $attrs->{as} eq 'ARRAY'
1916 ? [ @{$attrs->{as}} ]
1918 : [ map { m/^\Q${alias}.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}} ]
1922 if ($adds = delete $attrs->{include_columns}) {
1923 $adds = [$adds] unless ref $adds eq 'ARRAY';
1924 push(@{$attrs->{select}}, @$adds);
1925 push(@{$attrs->{as}}, map { m/([^.]+)$/; $1 } @$adds);
1927 if ($adds = delete $attrs->{'+select'}) {
1928 $adds = [$adds] unless ref $adds eq 'ARRAY';
1929 push(@{$attrs->{select}},
1930 map { /\./ || ref $_ ? $_ : "${alias}.$_" } @$adds);
1932 if (my $adds = delete $attrs->{'+as'}) {
1933 $adds = [$adds] unless ref $adds eq 'ARRAY';
1934 push(@{$attrs->{as}}, @$adds);
1937 $attrs->{from} ||= [ { 'me' => $source->from } ];
1939 if (exists $attrs->{join} || exists $attrs->{prefetch}) {
1940 my $join = delete $attrs->{join} || {};
1942 if (defined $attrs->{prefetch}) {
1943 $join = $self->_merge_attr(
1944 $join, $attrs->{prefetch}
1949 $attrs->{from} = # have to copy here to avoid corrupting the original
1952 $source->resolve_join($join, $alias, { %{$attrs->{seen_join}||{}} })
1957 $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
1958 if ($attrs->{order_by}) {
1959 $attrs->{order_by} = (ref($attrs->{order_by}) eq 'ARRAY'
1960 ? [ @{$attrs->{order_by}} ]
1961 : [ $attrs->{order_by} ]);
1963 $attrs->{order_by} = [];
1966 my $collapse = $attrs->{collapse} || {};
1967 if (my $prefetch = delete $attrs->{prefetch}) {
1968 $prefetch = $self->_merge_attr({}, $prefetch);
1970 my $seen = $attrs->{seen_join} || {};
1971 foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
1972 # bring joins back to level of current class
1973 my @prefetch = $source->resolve_prefetch(
1974 $p, $alias, $seen, \@pre_order, $collapse
1976 push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
1977 push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
1979 push(@{$attrs->{order_by}}, @pre_order);
1981 $attrs->{collapse} = $collapse;
1983 if ($attrs->{page}) {
1984 $attrs->{offset} ||= 0;
1985 $attrs->{offset} += ($attrs->{rows} * ($attrs->{page} - 1));
1988 return $self->{_attrs} = $attrs;
1992 my ($self, $attr) = @_;
1994 if (ref $attr eq 'HASH') {
1995 return $self->_rollout_hash($attr);
1996 } elsif (ref $attr eq 'ARRAY') {
1997 return $self->_rollout_array($attr);
2003 sub _rollout_array {
2004 my ($self, $attr) = @_;
2007 foreach my $element (@{$attr}) {
2008 if (ref $element eq 'HASH') {
2009 push( @rolled_array, @{ $self->_rollout_hash( $element ) } );
2010 } elsif (ref $element eq 'ARRAY') {
2011 # XXX - should probably recurse here
2012 push( @rolled_array, @{$self->_rollout_array($element)} );
2014 push( @rolled_array, $element );
2017 return \@rolled_array;
2021 my ($self, $attr) = @_;
2024 foreach my $key (keys %{$attr}) {
2025 push( @rolled_array, { $key => $attr->{$key} } );
2027 return \@rolled_array;
2030 sub _calculate_score {
2031 my ($self, $a, $b) = @_;
2033 if (ref $b eq 'HASH') {
2034 my ($b_key) = keys %{$b};
2035 if (ref $a eq 'HASH') {
2036 my ($a_key) = keys %{$a};
2037 if ($a_key eq $b_key) {
2038 return (1 + $self->_calculate_score( $a->{$a_key}, $b->{$b_key} ));
2043 return ($a eq $b_key) ? 1 : 0;
2046 if (ref $a eq 'HASH') {
2047 my ($a_key) = keys %{$a};
2048 return ($b eq $a_key) ? 1 : 0;
2050 return ($b eq $a) ? 1 : 0;
2056 my ($self, $a, $b) = @_;
2058 return $b unless defined($a);
2059 return $a unless defined($b);
2061 $a = $self->_rollout_attr($a);
2062 $b = $self->_rollout_attr($b);
2065 foreach my $b_element ( @{$b} ) {
2066 # find best candidate from $a to merge $b_element into
2067 my $best_candidate = { position => undef, score => 0 }; my $position = 0;
2068 foreach my $a_element ( @{$a} ) {
2069 my $score = $self->_calculate_score( $a_element, $b_element );
2070 if ($score > $best_candidate->{score}) {
2071 $best_candidate->{position} = $position;
2072 $best_candidate->{score} = $score;
2076 my ($b_key) = ( ref $b_element eq 'HASH' ) ? keys %{$b_element} : ($b_element);
2077 if ($best_candidate->{score} == 0 || exists $seen_keys->{$b_key}) {
2078 push( @{$a}, $b_element );
2080 $seen_keys->{$b_key} = 1; # don't merge the same key twice
2081 my $a_best = $a->[$best_candidate->{position}];
2082 # merge a_best and b_element together and replace original with merged
2083 if (ref $a_best ne 'HASH') {
2084 $a->[$best_candidate->{position}] = $b_element;
2085 } elsif (ref $b_element eq 'HASH') {
2086 my ($key) = keys %{$a_best};
2087 $a->[$best_candidate->{position}] = { $key => $self->_merge_attr($a_best->{$key}, $b_element->{$key}) };
2099 $self->_source_handle($_[0]->handle);
2101 $self->_source_handle->resolve;
2105 =head2 throw_exception
2107 See L<DBIx::Class::Schema/throw_exception> for details.
2111 sub throw_exception {
2113 $self->_source_handle->schema->throw_exception(@_);
2116 # XXX: FIXME: Attributes docs need clearing up
2120 The resultset takes various attributes that modify its behavior. Here's an
2127 =item Value: ($order_by | \@order_by)
2131 Which column(s) to order the results by. This is currently passed
2132 through directly to SQL, so you can give e.g. C<year DESC> for a
2133 descending order on the column `year'.
2135 Please note that if you have C<quote_char> enabled (see
2136 L<DBIx::Class::Storage::DBI/connect_info>) you will need to do C<\'year DESC' > to
2137 specify an order. (The scalar ref causes it to be passed as raw sql to the DB,
2138 so you will need to manually quote things as appropriate.)
2144 =item Value: \@columns
2148 Shortcut to request a particular set of columns to be retrieved. Adds
2149 C<me.> onto the start of any column without a C<.> in it and sets C<select>
2150 from that, then auto-populates C<as> from C<select> as normal. (You may also
2151 use the C<cols> attribute, as in earlier versions of DBIC.)
2153 =head2 include_columns
2157 =item Value: \@columns
2161 Shortcut to include additional columns in the returned results - for example
2163 $schema->resultset('CD')->search(undef, {
2164 include_columns => ['artist.name'],
2168 would return all CDs and include a 'name' column to the information
2169 passed to object inflation. Note that the 'artist' is the name of the
2170 column (or relationship) accessor, and 'name' is the name of the column
2171 accessor in the related table.
2177 =item Value: \@select_columns
2181 Indicates which columns should be selected from the storage. You can use
2182 column names, or in the case of RDBMS back ends, function or stored procedure
2185 $rs = $schema->resultset('Employee')->search(undef, {
2188 { count => 'employeeid' },
2193 When you use function/stored procedure names and do not supply an C<as>
2194 attribute, the column names returned are storage-dependent. E.g. MySQL would
2195 return a column named C<count(employeeid)> in the above example.
2201 Indicates additional columns to be selected from storage. Works the same as
2202 L<select> but adds columns to the selection.
2210 Indicates additional column names for those added via L<+select>.
2218 =item Value: \@inflation_names
2222 Indicates column names for object inflation. That is, C<as>
2223 indicates the name that the column can be accessed as via the
2224 C<get_column> method (or via the object accessor, B<if one already
2225 exists>). It has nothing to do with the SQL code C<SELECT foo AS bar>.
2227 The C<as> attribute is used in conjunction with C<select>,
2228 usually when C<select> contains one or more function or stored
2231 $rs = $schema->resultset('Employee')->search(undef, {
2234 { count => 'employeeid' }
2236 as => ['name', 'employee_count'],
2239 my $employee = $rs->first(); # get the first Employee
2241 If the object against which the search is performed already has an accessor
2242 matching a column name specified in C<as>, the value can be retrieved using
2243 the accessor as normal:
2245 my $name = $employee->name();
2247 If on the other hand an accessor does not exist in the object, you need to
2248 use C<get_column> instead:
2250 my $employee_count = $employee->get_column('employee_count');
2252 You can create your own accessors if required - see
2253 L<DBIx::Class::Manual::Cookbook> for details.
2255 Please note: This will NOT insert an C<AS employee_count> into the SQL
2256 statement produced, it is used for internal access only. Thus
2257 attempting to use the accessor in an C<order_by> clause or similar
2258 will fail miserably.
2260 To get around this limitation, you can supply literal SQL to your
2261 C<select> attibute that contains the C<AS alias> text, eg:
2263 select => [\'myfield AS alias']
2269 =item Value: ($rel_name | \@rel_names | \%rel_names)
2273 Contains a list of relationships that should be joined for this query. For
2276 # Get CDs by Nine Inch Nails
2277 my $rs = $schema->resultset('CD')->search(
2278 { 'artist.name' => 'Nine Inch Nails' },
2279 { join => 'artist' }
2282 Can also contain a hash reference to refer to the other relation's relations.
2285 package MyApp::Schema::Track;
2286 use base qw/DBIx::Class/;
2287 __PACKAGE__->table('track');
2288 __PACKAGE__->add_columns(qw/trackid cd position title/);
2289 __PACKAGE__->set_primary_key('trackid');
2290 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
2293 # In your application
2294 my $rs = $schema->resultset('Artist')->search(
2295 { 'track.title' => 'Teardrop' },
2297 join => { cd => 'track' },
2298 order_by => 'artist.name',
2302 You need to use the relationship (not the table) name in conditions,
2303 because they are aliased as such. The current table is aliased as "me", so
2304 you need to use me.column_name in order to avoid ambiguity. For example:
2306 # Get CDs from 1984 with a 'Foo' track
2307 my $rs = $schema->resultset('CD')->search(
2310 'tracks.name' => 'Foo'
2312 { join => 'tracks' }
2315 If the same join is supplied twice, it will be aliased to <rel>_2 (and
2316 similarly for a third time). For e.g.
2318 my $rs = $schema->resultset('Artist')->search({
2319 'cds.title' => 'Down to Earth',
2320 'cds_2.title' => 'Popular',
2322 join => [ qw/cds cds/ ],
2325 will return a set of all artists that have both a cd with title 'Down
2326 to Earth' and a cd with title 'Popular'.
2328 If you want to fetch related objects from other tables as well, see C<prefetch>
2335 =item Value: ($rel_name | \@rel_names | \%rel_names)
2339 Contains one or more relationships that should be fetched along with
2340 the main query (when they are accessed afterwards the data will
2341 already be available, without extra queries to the database). This is
2342 useful for when you know you will need the related objects, because it
2343 saves at least one query:
2345 my $rs = $schema->resultset('Tag')->search(
2354 The initial search results in SQL like the following:
2356 SELECT tag.*, cd.*, artist.* FROM tag
2357 JOIN cd ON tag.cd = cd.cdid
2358 JOIN artist ON cd.artist = artist.artistid
2360 L<DBIx::Class> has no need to go back to the database when we access the
2361 C<cd> or C<artist> relationships, which saves us two SQL statements in this
2364 Simple prefetches will be joined automatically, so there is no need
2365 for a C<join> attribute in the above search. If you're prefetching to
2366 depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
2367 specify the join as well.
2369 C<prefetch> can be used with the following relationship types: C<belongs_to>,
2370 C<has_one> (or if you're using C<add_relationship>, any relationship declared
2371 with an accessor type of 'single' or 'filter').
2381 Makes the resultset paged and specifies the page to retrieve. Effectively
2382 identical to creating a non-pages resultset and then calling ->page($page)
2385 If L<rows> attribute is not specified it defualts to 10 rows per page.
2395 Specifes the maximum number of rows for direct retrieval or the number of
2396 rows per page if the page attribute or method is used.
2402 =item Value: $offset
2406 Specifies the (zero-based) row number for the first row to be returned, or the
2407 of the first row of the first page if paging is used.
2413 =item Value: \@columns
2417 A arrayref of columns to group by. Can include columns of joined tables.
2419 group_by => [qw/ column1 column2 ... /]
2425 =item Value: $condition
2429 HAVING is a select statement attribute that is applied between GROUP BY and
2430 ORDER BY. It is applied to the after the grouping calculations have been
2433 having => { 'count(employee)' => { '>=', 100 } }
2439 =item Value: (0 | 1)
2443 Set to 1 to group by all columns.
2449 Adds to the WHERE clause.
2451 # only return rows WHERE deleted IS NULL for all searches
2452 __PACKAGE__->resultset_attributes({ where => { deleted => undef } }); )
2454 Can be overridden by passing C<{ where => undef }> as an attribute
2461 Set to 1 to cache search results. This prevents extra SQL queries if you
2462 revisit rows in your ResultSet:
2464 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
2466 while( my $artist = $resultset->next ) {
2470 $rs->first; # without cache, this would issue a query
2472 By default, searches are not cached.
2474 For more examples of using these attributes, see
2475 L<DBIx::Class::Manual::Cookbook>.
2481 =item Value: \@from_clause
2485 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
2486 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
2489 NOTE: Use this on your own risk. This allows you to shoot off your foot!
2491 C<join> will usually do what you need and it is strongly recommended that you
2492 avoid using C<from> unless you cannot achieve the desired result using C<join>.
2493 And we really do mean "cannot", not just tried and failed. Attempting to use
2494 this because you're having problems with C<join> is like trying to use x86
2495 ASM because you've got a syntax error in your C. Trust us on this.
2497 Now, if you're still really, really sure you need to use this (and if you're
2498 not 100% sure, ask the mailing list first), here's an explanation of how this
2501 The syntax is as follows -
2504 { <alias1> => <table1> },
2506 { <alias2> => <table2>, -join_type => 'inner|left|right' },
2507 [], # nested JOIN (optional)
2508 { <table1.column1> => <table2.column2>, ... (more conditions) },
2510 # More of the above [ ] may follow for additional joins
2517 ON <table1.column1> = <table2.column2>
2518 <more joins may follow>
2520 An easy way to follow the examples below is to remember the following:
2522 Anything inside "[]" is a JOIN
2523 Anything inside "{}" is a condition for the enclosing JOIN
2525 The following examples utilize a "person" table in a family tree application.
2526 In order to express parent->child relationships, this table is self-joined:
2528 # Person->belongs_to('father' => 'Person');
2529 # Person->belongs_to('mother' => 'Person');
2531 C<from> can be used to nest joins. Here we return all children with a father,
2532 then search against all mothers of those children:
2534 $rs = $schema->resultset('Person')->search(
2537 alias => 'mother', # alias columns in accordance with "from"
2539 { mother => 'person' },
2542 { child => 'person' },
2544 { father => 'person' },
2545 { 'father.person_id' => 'child.father_id' }
2548 { 'mother.person_id' => 'child.mother_id' }
2555 # SELECT mother.* FROM person mother
2558 # JOIN person father
2559 # ON ( father.person_id = child.father_id )
2561 # ON ( mother.person_id = child.mother_id )
2563 The type of any join can be controlled manually. To search against only people
2564 with a father in the person table, we could explicitly use C<INNER JOIN>:
2566 $rs = $schema->resultset('Person')->search(
2569 alias => 'child', # alias columns in accordance with "from"
2571 { child => 'person' },
2573 { father => 'person', -join_type => 'inner' },
2574 { 'father.id' => 'child.father_id' }
2581 # SELECT child.* FROM person child
2582 # INNER JOIN person father ON child.father_id = father.id