Skip to content
This repository has been archived by the owner on Jan 8, 2020. It is now read-only.

Fix iterating over empty result set with buffering enabled #4450

Closed
wants to merge 3 commits into from
Closed

Fix iterating over empty result set with buffering enabled #4450

wants to merge 3 commits into from

Conversation

mrsombre
Copy link
Contributor

@mrsombre mrsombre commented May 9, 2013

In case we using result set with buffering dataSource rewind method should be called at least once before resultSet rewind call, to ensure dataSource valid() would work as expected.

Simple test case:

$adapter = new \Zend\Db\Adapter\Adapter(...);

$hydrator = new Zend\Stdlib\Hydrator\ArraySerializable();
$resultSet = new \Zend\Db\ResultSet\HydratingResultSet($hydrator);
// any empty table for test
$table = new \Zend\Db\TableGateway\TableGateway('test', $adapter, null, $resultSet);

$test = $table->select();
$test->buffer();
foreach ($test as $item) {
    var_dump($item);
}

If no data in result set (ie empty result) when Iterator rewind calls (\Zend\Db\ResultSet\AbstractResultSet::rewind) and buffer is enabled, then dataSource rewind never be called and in this case iteration loop started and first item will be false (at least for Adapter/Pdo/Result). But expected behavior is iteration not started for empty result set.

    public function rewind()
    {
        if (!is_array($this->buffer)) {
            if ($this->dataSource instanceof Iterator) {
                $this->dataSource->rewind();
            } else {
                reset($this->dataSource);
            }
        }
        $this->position = 0;
    }

So, we introduce result set position default state is -1, to ensure first iteration calls dataSource rewind at least one even buffer is enabled
if (!is_array($this->buffer) || $this->position === -1) {
BTW if buffering is disabled we call rewind on dataSource for every iteration as before

@iquabius
Copy link
Contributor

iquabius commented May 9, 2013

Your changes broke some tests --> https://travis-ci.org/zendframework/zf2/jobs/7012084#L264

@mrsombre
Copy link
Contributor Author

mrsombre commented May 9, 2013

Gotcha

weierophinney added a commit that referenced this pull request May 9, 2013
Fix iterating over empty result set with buffering enabled
weierophinney added a commit that referenced this pull request May 9, 2013
@ghost ghost assigned weierophinney May 9, 2013
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants