Fix iterating over empty result set with buffering enabled #4450

Closed
wants to merge 3 commits into
from

Conversation

Projects
None yet
3 participants
Contributor

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

Contributor

iquabius commented May 9, 2013

Contributor

mrsombre commented May 9, 2013

Gotcha

weierophinney added a commit that referenced this pull request May 9, 2013

Merge pull request #4450 from mrsombre/hotfix/result-set-with-buffer
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 join this conversation on GitHub. Already have an account? Sign in to comment