[Dbix-class] cache=> 1 and has_many?

Daniel Westermann-Clark dwc at pobox.com
Fri Aug 11 04:46:45 CEST 2006


On 2006-08-10 19:00:56 -0700, George Hartzell wrote:
> I'm using DBIx-Class-0.06003, and have cache => 1 in my ->search.
> 
> I have an 
> 
>   rn
>     has_many nodes
> 
>   nodes
>     has_many attrs
> 
> and I have a bunch of code that looks vaguely like this:
> 
>   ($n1, $n2) = $rn->nodes;

At this point, you're dealing with Row objects because (under the
hood) you called search_related and thus search in list context.  The
Row objects won't know about the cache.

>   ($apes_1) = grep {$_->name eq 'APE'} $n1->attrs();
>   ($meece_1) = grep {$_->name eq 'MOOSE'} $n1->attrs();
>   ($mice_1) = grep {$_->name eq 'MOUSE'} $n1->attrs();
> 
>   ($apes_2) = grep {$_->name eq 'APE'} $n2->attrs();
>   ($meece_2) = grep {$_->name eq 'MOOSE'} $n2->attrs();
>   ($mice_2) = grep {$_->name eq 'MOUSE'} $n2->attrs();
> 
> And, watching the output generated by setting
> DBIX_CLASS_STORAGE_DBI_DEBUG I see it constantly going back to the
> database for the same set of attrs.

Since you only want one, you should consider rewriting the grep as a
database query:

    my $apes_1 = $n1->attrs->find({ name => 'APE' });

Or, if name is not unique:

    my $apes_1 = $n1->attrs->search({ name => 'APE' })->first;

This is almost certainly more efficient than fetching the full list of
node attrs from the database.

> Is the cachedness somehow associated with $rn, but not the nodes
> that I get from ->nodes()?

Right, caching works at the ResultSet level.  Any relationship
accessor on a Row object won't know about the cache.

-- 
Daniel Westermann-Clark



More information about the Dbix-class mailing list