Skip to content

Commit

Permalink
Fixed issue where query would be executed twice if used inside a coll…
Browse files Browse the repository at this point in the history
…ection
  • Loading branch information
lorenzo committed Mar 12, 2015
1 parent bba6bb2 commit 23fd927
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
13 changes: 11 additions & 2 deletions src/Database/Statement/StatementDecorator.php
Expand Up @@ -46,6 +46,13 @@ class StatementDecorator implements StatementInterface, \Countable, \IteratorAgg
*/
protected $_driver;

/**
* Whether or not this statement has already been executed
*
* @var bool
*/
protected $_hasExecuted = false;

/**
* Constructor
*
Expand Down Expand Up @@ -158,6 +165,7 @@ public function errorInfo()
*/
public function execute($params = null)
{
$this->_hasExecuted = true;
return $this->_statement->execute($params);
}

Expand Down Expand Up @@ -228,7 +236,6 @@ public function rowCount()
*
* ```
* $statement = $connection->prepare('SELECT id, title from articles');
* $statement->execute();
* foreach ($statement as $row) {
* //do stuff
* }
Expand All @@ -238,7 +245,9 @@ public function rowCount()
*/
public function getIterator()
{
$this->execute();
if (!$this->_hasExecuted) {
$this->execute();
}
return $this->_statement;
}

Expand Down
20 changes: 19 additions & 1 deletion tests/TestCase/Database/Statement/StatementDecoratorTest.php
Expand Up @@ -44,7 +44,8 @@ public function testLastInsertId()
}

/**
* Tests that calling lastInsertId will get the
* Tests that calling lastInsertId will get the last insert id by
* column name
*
* @return void
*/
Expand All @@ -62,4 +63,21 @@ public function testLastInsertIdWithReturning()
$driver->expects($this->never())->method('lastInsertId');
$this->assertEquals(2, $statement->lastInsertId('users', 'id'));
}

/**
* Tests that the statement will not be executed twice if the iterator
* is requested more than once
*
* @return void
*/
public function testNoDoubleExecution() {
$inner = $this->getMock('\PDOStatement');
$driver = $this->getMock('\Cake\Database\Driver');
$statement = new StatementDecorator($inner, $driver);

$inner->expects($this->once())->method('execute');
$this->assertSame($inner, $statement->getIterator());
$this->assertSame($inner, $statement->getIterator());
}

}

0 comments on commit 23fd927

Please sign in to comment.