X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=lib%2FDBIx%2FClass%2FResultSet.pm;h=282651f0cd1e5e8218d4d0c303a5bd404a78f52a;hb=194311161bdbebd2402c457ded300fc83b773f02;hp=cc87db1a0b4216bb448394942a4dbee632e348f4;hpb=132bc9dc0c1b5fe97dfb4750360ab414fa1250f5;p=dbsrgits%2FDBIx-Class.git diff --git a/lib/DBIx/Class/ResultSet.pm b/lib/DBIx/Class/ResultSet.pm index cc87db1..282651f 100644 --- a/lib/DBIx/Class/ResultSet.pm +++ b/lib/DBIx/Class/ResultSet.pm @@ -46,29 +46,15 @@ A new ResultSet is returned from calling L on an existing ResultSet. The new one will contain all the conditions of the original, plus any new conditions added in the C call. -A ResultSet is also an iterator. L is used to return all the -Ls the ResultSet represents. +A ResultSet also incorporates an implicit iterator. L and L +can be used to walk through all the Ls the ResultSet +represents. The query that the ResultSet represents is B executed against the database when these methods are called: +L L L L L L -=over - -=item L - -=item L - -=item L - -=item L - -=item L - -=item L - -=back - -=head1 EXAMPLES +=head1 EXAMPLES =head2 Chaining resultsets @@ -193,7 +179,7 @@ sub new { return $class->new_result(@_) if ref $class; my ($source, $attrs) = @_; - $source = $source->handle + $source = $source->handle unless $source->isa('DBIx::Class::ResultSourceHandle'); $attrs = { %{$attrs||{}} }; @@ -296,7 +282,7 @@ sub search_rs { unless ( (@_ && defined($_[0])) # @_ == () or (undef) - || + || (keys %$attrs # empty attrs or only 'safe' attrs && List::Util::first { !$safe{$_} } keys %$attrs) ) { @@ -393,7 +379,7 @@ Pass a literal chunk of SQL to be added to the conditional part of the resultset query. CAVEAT: C is provided for Class::DBI compatibility and should -only be used in that context. C is a convenience method. +only be used in that context. C is a convenience method. It is equivalent to calling $schema->search(\[]), but if you want to ensure columns are bound correctly, use C. @@ -403,14 +389,14 @@ Example of how to use C instead of C my @cds = $cd_rs->search(\[ 'cdid = ? AND (artist = ? OR artist = ?)', [ 'cdid', 2 ], [ 'artist', 1 ], [ 'artist', 2 ] ]); -See L and +See L and L for searching techniques that do not require C. =cut sub search_literal { - my ($self, $sql, @bind) = @_; + my ($self, $sql, @bind) = @_; my $attr; if ( @bind && ref($bind[-1]) eq 'HASH' ) { $attr = pop @bind; @@ -505,7 +491,7 @@ sub find { && ($info = $self->result_source->relationship_info($key))) { my $val = delete $input_query->{$key}; next KEY if (ref($val) eq 'ARRAY'); # has_many for multi_create - my $rel_q = $self->result_source->resolve_condition( + my $rel_q = $self->result_source->_resolve_condition( $info->{cond}, $val, $key ); die "Can't handle OR join condition in find" if ref($rel_q) eq 'ARRAY'; @@ -674,7 +660,9 @@ L for more information. sub cursor { my ($self) = @_; - my $attrs = { %{$self->_resolved_attrs} }; + my $attrs = $self->_resolved_attrs_copy; + $attrs->{_virtual_order_by} = $self->_gen_virtual_order; + return $self->{cursor} ||= $self->result_source->storage->select($attrs->{from}, $attrs->{select}, $attrs->{where},$attrs); @@ -712,7 +700,7 @@ a warning: Query returned more than one row In this case, you should be using L or L instead, or if you really -know what you are doing, use the L attribute to explicitly limit the size +know what you are doing, use the L attribute to explicitly limit the size of the resultset. =back @@ -725,7 +713,9 @@ sub single { $self->throw_exception('single() only takes search conditions, no attributes. You want ->search( $cond, $attrs )->single()'); } - my $attrs = { %{$self->_resolved_attrs} }; + my $attrs = $self->_resolved_attrs_copy; + $attrs->{_virtual_order_by} = $self->_gen_virtual_order; + if ($where) { if (defined $attrs->{where}) { $attrs->{where} = { @@ -752,6 +742,16 @@ sub single { return (@data ? ($self->_construct_object(@data))[0] : undef); } +# _gen_virtual_order +# +# This is a horrble hack, but seems like the best we can do at this point +# Some limit emulations (Top) require an ordered resultset in order to +# function at all. So supply a PK order to be used if necessary + +sub _gen_virtual_order { + return [ shift->result_source->primary_columns ]; +} + # _is_unique_query # # Try to determine if the specified query is guaranteed to be unique, based on @@ -870,10 +870,10 @@ instead. An example conversion is: sub search_like { my $class = shift; - carp join ("\n", - 'search_like() is deprecated and will be removed in 0.09.', - 'Instead use ->search({ x => { -like => "y%" } })', - '(note the outer pair of {}s - they are important!)' + carp ( + 'search_like() is deprecated and will be removed in DBIC version 0.09.' + .' Instead use ->search({ x => { -like => "y%" } })' + .' (note the outer pair of {}s - they are important!)' ); my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {}); my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_}; @@ -1016,7 +1016,7 @@ sub _collapse_result { do { # no need to check anything at the front, we always want the first row my %const; - + foreach my $this_as (@construct_as) { $const{$this_as->[0]||''}{$this_as->[1]} = shift(@copy); } @@ -1063,7 +1063,7 @@ sub _collapse_result { foreach my $p (@parts) { $target = $target->[1]->{$p} ||= []; $cur .= ".${p}"; - if ($cur eq ".${key}" && (my @ckey = @{$collapse{$cur}||[]})) { + if ($cur eq ".${key}" && (my @ckey = @{$collapse{$cur}||[]})) { # collapsing at this point and on final part my $pos = $collapse_pos{$cur}; CK: foreach my $ck (@ckey) { @@ -1114,8 +1114,8 @@ is derived. =back -An accessor for the class to use when creating row objects. Defaults to -C<< result_source->result_class >> - which in most cases is the name of the +An accessor for the class to use when creating row objects. Defaults to +C<< result_source->result_class >> - which in most cases is the name of the L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class. Note that changing the result_class will also remove any components @@ -1145,42 +1145,63 @@ sub result_class { =back Performs an SQL C with the same query as the resultset was built -with to find the number of elements. If passed arguments, does a search -on the resultset and counts the results of that. +with to find the number of elements. Passing arguments is equivalent to +C<< $rs->search ($cond, \%attrs)->count >> =cut -my @count_via_subq_attrs = qw/join seen_join group_by/; sub count { my $self = shift; return $self->search(@_)->count if @_ and defined $_[0]; return scalar @{ $self->get_cache } if $self->get_cache; - my @check_attrs = @count_via_subq_attrs; - + my @grouped_subq_attrs = qw/prefetch collapse distinct group_by having/; + my @subq_attrs = (); + + my $attrs = $self->_resolved_attrs; # if we are not paged - we are simply asking for a limit - if (not $self->{attrs}{page} and not $self->{attrs}{software_limit}) { - push @check_attrs, qw/rows offset/; + if (not $attrs->{page} and not $attrs->{software_limit}) { + push @subq_attrs, qw/rows offset/; } - return $self->_has_attr (@check_attrs) - ? $self->_count_subq + my $need_subq = $self->_has_attr (@subq_attrs); + my $need_group_subq = $self->_has_attr (@grouped_subq_attrs); + + return ($need_subq || $need_group_subq) + ? $self->_count_subq ($need_group_subq) : $self->_count_simple } sub _count_subq { - my $self = shift; + my ($self, $add_group_by) = @_; + + my $attrs = $self->_resolved_attrs_copy; + + # copy for the subquery, we need to do some adjustments to it too + my $sub_attrs = { %$attrs }; - my $attrs = { %{$self->_resolved_attrs} }; + # these can not go in the subquery, and there is no point of ordering it + delete $sub_attrs->{$_} for qw/prefetch collapse select +select as +as columns +columns order_by/; + + # if needed force a group_by and the same set of columns (most databases require this) + if ($add_group_by) { + + # if we prefetch, we group_by primary keys only as this is what we would get out of the rs via ->next/->all + # simply deleting group_by suffices, as the code below will re-fill it + # Note: we check $attrs, as $sub_attrs has collapse deleted + if (ref $attrs->{collapse} and keys %{$attrs->{collapse}} ) { + delete $sub_attrs->{group_by}; + } + + $sub_attrs->{columns} = $sub_attrs->{group_by} ||= [ map { "$attrs->{alias}.$_" } ($self->result_source->primary_columns) ]; + } - my $select_cols = $attrs->{group_by} || [ map { "$attrs->{alias}.$_" } ($self->result_source->primary_columns) ]; $attrs->{from} = [{ - count_subq => $self->search ({}, { columns => $select_cols, group_by => $select_cols }) - ->as_query + count_subq => (ref $self)->new ($self->result_source, $sub_attrs )->as_query }]; - # the subquery above will integrate everything, including 'where' and any pagers - delete $attrs->{$_} for (@count_via_subq_attrs, qw/where rows offset pager page/ ); + # the subquery replaces this + delete $attrs->{$_} for qw/where bind prefetch collapse distinct group_by having having_bind/; return $self->__count ($attrs); } @@ -1193,9 +1214,10 @@ sub _count_simple { # need to take offset from resolved attrs - $count -= $self->{_attrs}{offset} if $self->{_attrs}{offset}; - $count = $self->{attrs}{rows} if - $self->{attrs}{rows} and $self->{attrs}{rows} < $count; + my $attrs = $self->_resolved_attrs; + + $count -= $attrs->{offset} if $attrs->{offset}; + $count = $attrs->{rows} if $attrs->{rows} and $attrs->{rows} < $count; $count = 0 if ($count < 0); return $count; } @@ -1203,14 +1225,14 @@ sub _count_simple { sub __count { my ($self, $attrs) = @_; - $attrs ||= { %{$self->{attrs}} }; + $attrs ||= $self->_resolved_attrs_copy; + + # take off any column specs, any pagers, record_filter is cdbi, and no point of ordering a count + delete $attrs->{$_} for (qw/columns +columns select +select as +as rows offset page pager order_by record_filter/); $attrs->{select} = { count => '*' }; $attrs->{as} = [qw/count/]; - # take off any pagers, record_filter is cdbi, and no point of ordering a count - delete $attrs->{$_} for qw/rows offset page pager order_by record_filter/; - my $tmp_rs = (ref $self)->new($self->result_source, $attrs); my ($count) = $tmp_rs->cursor->next; @@ -1327,14 +1349,68 @@ sub first { } -# _update_delete_via_subq -# -# Presence of some rs attributes requires a subquery to reliably -# update/deletre +# _rs_update_delete # +# Determines whether and what type of subquery is required for the $rs operation. +# If grouping is necessary either supplies its own, or verifies the current one +# After all is done delegates to the proper storage method. + +sub _rs_update_delete { + my ($self, $op, $values) = @_; + + my $rsrc = $self->result_source; + + my $needs_group_by_subq = $self->_has_attr (qw/prefetch distinct join seen_join group_by/); + my $needs_subq = $self->_has_attr (qw/row offset page/); + + if ($needs_group_by_subq or $needs_subq) { + + # make a new $rs selecting only the PKs (that's all we really need) + my $attrs = $self->_resolved_attrs_copy; + + delete $attrs->{$_} for qw/prefetch collapse select +select as +as columns +columns/; + $attrs->{columns} = [ map { "$attrs->{alias}.$_" } ($self->result_source->primary_columns) ]; + + if ($needs_group_by_subq) { + # make sure no group_by was supplied, or if there is one - make sure it matches + # the columns compiled above perfectly. Anything else can not be sanely executed + # on most databases so croak right then and there + + if (my $g = $attrs->{group_by}) { + my @current_group_by = map + { $_ =~ /\./ ? $_ : "$attrs->{alias}.$_" } + (ref $g eq 'ARRAY' ? @$g : $g ); + + if ( + join ("\x00", sort @current_group_by) + ne + join ("\x00", sort @{$attrs->{columns}} ) + ) { + $self->throw_exception ( + "You have just attempted a $op operation on a resultset which does group_by" + . ' on columns other than the primary keys, while DBIC internally needs to retrieve' + . ' the primary keys in a subselect. All sane RDBMS engines do not support this' + . ' kind of queries. Please retry the operation with a modified group_by or' + . ' without using one at all.' + ); + } + } + else { + $attrs->{group_by} = $attrs->{columns}; + } + } -sub _update_delete_via_subq { - return $_[0]->_has_attr (qw/join seen_join group_by row offset page/); + my $subrs = (ref $self)->new($rsrc, $attrs); + + return $self->result_source->storage->subq_update_delete($subrs, $op, $values); + } + else { + return $rsrc->storage->$op( + $rsrc, + $op eq 'update' ? $values : (), + $self->_cond_for_update_delete, + ); + } } @@ -1417,16 +1493,7 @@ sub update { $self->throw_exception('Values for update must be a hash') unless ref $values eq 'HASH'; - # rs operations with subqueries are Storage dependent - delegate - if ($self->_update_delete_via_subq) { - return $self->result_source->storage->subq_update_delete($self, 'update', $values); - } - - my $cond = $self->_cond_for_update_delete; - - return $self->result_source->storage->update( - $self->result_source, $values, $cond - ); + return $self->_rs_update_delete ('update', $values); } =head2 update_all @@ -1460,7 +1527,7 @@ sub update_all { =item Arguments: none -=item Return Value: 1 +=item Return Value: $storage_rv =back @@ -1468,11 +1535,8 @@ Deletes the contents of the resultset from its result source. Note that this will not run DBIC cascade triggers. See L if you need triggers to run. See also L. -delete may not generate correct SQL for a query with joins or a resultset -chained from a related resultset. In this case it will generate a warning:- - -In these cases you may find that delete_all is more appropriate, or you -need to respecify your query in a way that can be expressed without a join. +Return value will be the amount of rows deleted; exact type of return value +is storage-dependent. =cut @@ -1481,15 +1545,7 @@ sub delete { $self->throw_exception('delete does not accept any arguments') if @_; - # rs operations with subqueries are Storage dependent - delegate - if ($self->_update_delete_via_subq) { - return $self->result_source->storage->subq_update_delete($self, 'delete'); - } - - my $cond = $self->_cond_for_update_delete; - - $self->result_source->storage->delete($self->result_source, $cond); - return 1; + return $self->_rs_update_delete ('delete'); } =head2 delete_all @@ -1529,7 +1585,7 @@ For the arrayref of hashrefs style each hashref should be a structure suitable forsubmitting to a $resultset->create(...) method. In void context, C in L is used -to insert the data, as this is a faster method. +to insert the data, as this is a faster method. Otherwise, each set of data is inserted into the database using L, and a arrayref of the resulting row @@ -1538,10 +1594,10 @@ objects is returned. Example: Assuming an Artist Class that has many CDs Classes relating: my $Artist_rs = $schema->resultset("Artist"); - - ## Void Context Example + + ## Void Context Example $Artist_rs->populate([ - { artistid => 4, name => 'Manufactured Crap', cds => [ + { artistid => 4, name => 'Manufactured Crap', cds => [ { title => 'My First CD', year => 2006 }, { title => 'Yet More Tweeny-Pop crap', year => 2007 }, ], @@ -1553,7 +1609,7 @@ Example: Assuming an Artist Class that has many CDs Classes relating: ], }, ]); - + ## Array Context Example my ($ArtistOne, $ArtistTwo, $ArtistThree) = $Artist_rs->populate([ { name => "Artist One"}, @@ -1563,7 +1619,7 @@ Example: Assuming an Artist Class that has many CDs Classes relating: { title => "Second CD", year => 2008}, ]} ]); - + print $ArtistOne->name; ## response is 'Artist One' print $ArtistThree->cds->count ## reponse is '2' @@ -1579,11 +1635,11 @@ example: ]); Please note an important effect on your data when choosing between void and -wantarray context. Since void context goes straight to C in +wantarray context. Since void context goes straight to C in L this will skip any component that is overriding -c. So if you are using something like L to -create primary keys for you, you will find that your PKs are empty. In this -case you will have to use the wantarray context in order to create those +C. So if you are using something like L to +create primary keys for you, you will find that your PKs are empty. In this +case you will have to use the wantarray context in order to create those values. =cut @@ -1593,7 +1649,7 @@ sub populate { my $data = ref $_[0][0] eq 'HASH' ? $_[0] : ref $_[0][0] eq 'ARRAY' ? $self->_normalize_populate_args($_[0]) : $self->throw_exception('Populate expects an arrayref of hashes or arrayref of arrayrefs'); - + if(defined wantarray) { my @created; foreach my $item (@$data) { @@ -1605,28 +1661,28 @@ sub populate { my @names = grep {!ref $first->{$_}} keys %$first; my @rels = grep { $self->result_source->has_relationship($_) } keys %$first; - my @pks = $self->result_source->primary_columns; + my @pks = $self->result_source->primary_columns; - ## do the belongs_to relationships + ## do the belongs_to relationships foreach my $index (0..$#$data) { if( grep { !defined $data->[$index]->{$_} } @pks ) { my @ret = $self->populate($data); return; } - + foreach my $rel (@rels) { next unless $data->[$index]->{$rel} && ref $data->[$index]->{$rel} eq "HASH"; my $result = $self->related_resultset($rel)->create($data->[$index]->{$rel}); my ($reverse) = keys %{$self->result_source->reverse_relationship_info($rel)}; - my $related = $result->result_source->resolve_condition( + my $related = $result->result_source->_resolve_condition( $result->result_source->relationship_info($reverse)->{cond}, - $self, - $result, + $self, + $result, ); delete $data->[$index]->{$rel}; $data->[$index] = {%{$data->[$index]}, %$related}; - + push @names, keys %$related if $index == 0; } } @@ -1635,8 +1691,8 @@ sub populate { my @values = map { [ @$_{@names} ] } @$data; $self->result_source->storage->insert_bulk( - $self->result_source, - \@names, + $self->result_source, + \@names, \@values, ); @@ -1646,12 +1702,12 @@ sub populate { foreach my $rel (@rels) { next unless $item->{$rel} && ref $item->{$rel} eq "ARRAY"; - my $parent = $self->find(map {{$_=>$item->{$_}} } @pks) + my $parent = $self->find(map {{$_=>$item->{$_}} } @pks) || $self->throw_exception('Cannot find the relating object.'); - + my $child = $parent->$rel; - - my $related = $child->result_source->resolve_condition( + + my $related = $child->result_source->_resolve_condition( $parent->result_source->relationship_info($rel)->{cond}, $child, $parent, @@ -1683,7 +1739,7 @@ sub _normalize_populate_args { foreach my $index (0..$#names) { $result_to_create{$names[$index]} = $$datum[$index]; } - push @results_to_create, \%result_to_create; + push @results_to_create, \%result_to_create; } return \@results_to_create; } @@ -1716,7 +1772,7 @@ sub pager { unless $self->{attrs}{page}; $attrs->{rows} ||= 10; - # throw away the paging flags and re-run the count (possibly + # throw away the paging flags and re-run the count (possibly # with a subselect) to get the real total count my $count_attrs = { %$attrs }; delete $count_attrs->{$_} for qw/rows offset page pager/; @@ -1787,13 +1843,13 @@ sub new_result { $self->throw_exception( "Can't abstract implicit construct, condition not a hash" ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH')); - + my $collapsed_cond = ( $self->{cond} ? $self->_collapse_cond($self->{cond}) : {} ); - + # precendence must be given to passed values over values inherited from # the cond, so the order here is important. my %implied = %{$self->_remove_alias($collapsed_cond, $alias)}; @@ -1818,7 +1874,7 @@ sub new_result { # _is_deterministic_value # -# Make an effor to strip non-deterministic values from the condition, +# Make an effor to strip non-deterministic values from the condition, # to make sure new_result chokes less sub _is_deterministic_value { @@ -1845,8 +1901,21 @@ sub _has_attr { my $join_check_req; for my $n (@attr_names) { - return 1 if defined $attrs->{$n}; ++$join_check_req if $n =~ /join/; + + my $attr = $attrs->{$n}; + + next if not defined $attr; + + if (ref $attr eq 'HASH') { + return 1 if keys %$attr; + } + elsif (ref $attr eq 'ARRAY') { + return 1 if @$attr; + } + else { + return 1 if $attr; + } } # a join can be expressed as a multi-level from @@ -1855,7 +1924,7 @@ sub _has_attr { and ref $attrs->{from} eq 'ARRAY' and - @{$attrs->{from}} > 1 + @{$attrs->{from}} > 1 ); return 0; @@ -2019,12 +2088,12 @@ Example of creating a new row. name=>"Some Person", email=>"somebody@someplace.com" }); - + Example of creating a new row and also creating rows in a related C or C resultset. Note Arrayref. $artist_rs->create( - { artistid => 4, name => 'Manufactured Crap', cds => [ + { artistid => 4, name => 'Manufactured Crap', cds => [ { title => 'My First CD', year => 2006 }, { title => 'Yet More Tweeny-Pop crap', year => 2007 }, ], @@ -2140,10 +2209,10 @@ For example: { key => 'cd_artist_title' } ); - $cd->cd_to_producer->update_or_create({ - producer => $producer, + $cd->cd_to_producer->update_or_create({ + producer => $producer, name => 'harry', - }, { + }, { key => 'primary, }); @@ -2328,7 +2397,7 @@ sub related_resultset { "search_related: result source '" . $self->result_source->source_name . "' has no such relationship $rel") unless $rel_obj; - + my ($from,$seen) = $self->_resolve_from($rel); my $join_count = $seen->{$rel}; @@ -2421,32 +2490,43 @@ sub current_source_alias { return ($self->{attrs} || {})->{alias} || 'me'; } +# This code is called by search_related, and makes sure there +# is clear separation between the joins before, during, and +# after the relationship. This information is needed later +# in order to properly resolve prefetch aliases (any alias +# with a relation_chain_depth less than the depth of the +# current prefetch is not considered) sub _resolve_from { my ($self, $extra_join) = @_; my $source = $self->result_source; my $attrs = $self->{attrs}; - + my $from = $attrs->{from} || [ { $attrs->{alias} => $source->from } ]; - + my $seen = { %{$attrs->{seen_join}||{}} }; - my $join = ($attrs->{join} - ? [ $attrs->{join}, $extra_join ] - : $extra_join); + # we need to take the prefetch the attrs into account before we + # ->_resolve_join as otherwise they get lost - captainL + my $merged = $self->_merge_attr( $attrs->{join}, $attrs->{prefetch} ); + + push @$from, $source->_resolve_join($merged, $attrs->{alias}, $seen) if ($merged); + + ++$seen->{-relation_chain_depth}; - # we need to take the prefetch the attrs into account before we - # ->resolve_join as otherwise they get lost - captainL - my $merged = $self->_merge_attr( $join, $attrs->{prefetch} ); + push @$from, $source->_resolve_join($extra_join, $attrs->{alias}, $seen); - $from = [ - @$from, - ($join ? $source->resolve_join($merged, $attrs->{alias}, $seen) : ()), - ]; + ++$seen->{-relation_chain_depth}; return ($from,$seen); } +# too many times we have to do $attrs = { %{$self->_resolved_attrs} } +sub _resolved_attrs_copy { + my $self = shift; + return { %{$self->_resolved_attrs (@_)} }; +} + sub _resolved_attrs { my $self = shift; return $self->{_attrs} if $self->{_attrs}; @@ -2465,14 +2545,14 @@ sub _resolved_attrs { ? $_ : { ( - /^\Q${alias}.\E(.+)$/ + /^\Q${alias}.\E(.+)$/ ? "$1" : "$_" ) - => + => ( - /\./ - ? "$_" + /\./ + ? "$_" : "${alias}.$_" ) } @@ -2540,15 +2620,13 @@ sub _resolved_attrs { $attrs->{from} = # have to copy here to avoid corrupting the original [ @{ $attrs->{from} }, - $source->resolve_join( + $source->_resolve_join( $join, $alias, { %{ $attrs->{seen_join} || {} } } ) ]; } - $attrs->{group_by} ||= $attrs->{select} - if delete $attrs->{distinct}; if ( $attrs->{order_by} ) { $attrs->{order_by} = ( ref( $attrs->{order_by} ) eq 'ARRAY' @@ -2564,30 +2642,53 @@ sub _resolved_attrs { if ( my $prefetch = delete $attrs->{prefetch} ) { $prefetch = $self->_merge_attr( {}, $prefetch ); my @pre_order; - my $seen = { %{ $attrs->{seen_join} || {} } }; foreach my $p ( ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch) ) { # bring joins back to level of current class + my $join_map = $self->_joinpath_aliases ($attrs->{from}, $attrs->{seen_join}); my @prefetch = - $source->resolve_prefetch( $p, $alias, $seen, \@pre_order, $collapse ); + $source->_resolve_prefetch( $p, $alias, $join_map, \@pre_order, $collapse ); push( @{ $attrs->{select} }, map { $_->[0] } @prefetch ); push( @{ $attrs->{as} }, map { $_->[1] } @prefetch ); } push( @{ $attrs->{order_by} }, @pre_order ); } + + if (delete $attrs->{distinct}) { + $attrs->{group_by} ||= [ grep { !ref($_) || (ref($_) ne 'HASH') } @{$attrs->{select}} ]; + } + $attrs->{collapse} = $collapse; - if ( $attrs->{page} ) { - $attrs->{offset} ||= 0; - $attrs->{offset} += ( $attrs->{rows} * ( $attrs->{page} - 1 ) ); + if ( $attrs->{page} and not defined $attrs->{offset} ) { + $attrs->{offset} = ( $attrs->{rows} * ( $attrs->{page} - 1 ) ); } return $self->{_attrs} = $attrs; } +sub _joinpath_aliases { + my ($self, $fromspec, $seen) = @_; + + my $paths = {}; + return $paths unless ref $fromspec eq 'ARRAY'; + + for my $j (@$fromspec) { + + next if ref $j ne 'ARRAY'; + next if $j->[0]{-relation_chain_depth} < ( $seen->{-relation_chain_depth} || 0); + + my $p = $paths; + $p = $p->{$_} ||= {} for @{$j->[0]{-join_path}}; + push @{$p->{-join_aliases} }, $j->[0]{-join_alias}; + } + + return $paths; +} + sub _rollout_attr { my ($self, $attr) = @_; - + if (ref $attr eq 'HASH') { return $self->_rollout_hash($attr); } elsif (ref $attr eq 'ARRAY') { @@ -2638,7 +2739,7 @@ sub _calculate_score { } } else { return ($a eq $b_key) ? 1 : 0; - } + } } else { if (ref $a eq 'HASH') { my ($a_key) = keys %{$a}; @@ -2654,7 +2755,7 @@ sub _merge_attr { return $import unless defined($orig); return $orig unless defined($import); - + $orig = $self->_rollout_attr($orig); $import = $self->_rollout_attr($import); @@ -2930,19 +3031,19 @@ For example: } ); -You need to use the relationship (not the table) name in conditions, -because they are aliased as such. The current table is aliased as "me", so +You need to use the relationship (not the table) name in conditions, +because they are aliased as such. The current table is aliased as "me", so you need to use me.column_name in order to avoid ambiguity. For example: - # Get CDs from 1984 with a 'Foo' track + # Get CDs from 1984 with a 'Foo' track my $rs = $schema->resultset('CD')->search( - { + { 'me.year' => 1984, 'tracks.name' => 'Foo' }, { join => 'tracks' } ); - + If the same join is supplied twice, it will be aliased to _2 (and similarly for a third time). For e.g. @@ -2995,12 +3096,12 @@ C or C relationships, which saves us two SQL statements in this case. Simple prefetches will be joined automatically, so there is no need -for a C attribute in the above search. +for a C attribute in the above search. C can be used with the following relationship types: C, C (or if you're using C, any relationship declared with an accessor type of 'single' or 'filter'). A more complex example that -prefetches an artists cds, the tracks on those cds, and the tags associted +prefetches an artists cds, the tracks on those cds, and the tags associted with that artist is given below (assuming many-to-many from artists to tags): my $rs = $schema->resultset('Artist')->search( @@ -3012,7 +3113,7 @@ with that artist is given below (assuming many-to-many from artists to tags): ] } ); - + B If you specify a C attribute, the C and C