Question

I am using DBIx::Class::ResultSet to query for items and paginate my data. This is the query I use:

my $clients = $c->model('DB::User')->search(
    { active_yn => 'y', client_yn => 'y' },
    {   
        columns => [qw/id first_name last_name username email/],
        order_by => ['last_name'],
        page     => ($c->req->param('page') || 1), 
        rows     => 20,
    }   
); 

Once, I get the resultset, I loop through the results in Template::Toolkit like so:

[% WHILE (client = clients.next) %]
    <tr>
        <td>[% client.first_name %] [% client.last_name %]</td>
    </tr>
[% END %]

My question is, does each time I call next issue a new query? It is unclear to me because the all method says it returns all elements in the set, so does the first query not do that? I'd like to be as efficient as possible. Thanks!

Was it helpful?

Solution

The answer is no: it will not execute a new query each time you call next, as long as you are working with the same resultset instance. It is intended to be a fast way of iterating the records.

OTHER TIPS

Search returns a ResultSet object in scalar and a list of Result objects in list context. You can force returning a ResultSet by using search_rs.

Next will use cursors if your database supports them but only fetches one row per call and constructs the Result object from it.

If the number of rows is low, doing a single SQL query and constructing all Result objects at once is faster. That's usually the case when you paginate.

Next makes sense when the amount of memory to construct all Results objects would be too large, for example when exporting millions of rows.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top