Skip to content

Commit

Permalink
adds new executeAndClose method
Browse files Browse the repository at this point in the history
  • Loading branch information
thinkingmedia committed Feb 22, 2017
1 parent 2ad18f9 commit fdbe9c1
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/Database/Query.php
Expand Up @@ -225,6 +225,37 @@ public function execute()
return $this->_iterator;
}

/**
* Executes the SQL of this query and immediately closes the statement before returning the row count of records
* changed.
*
* This method can be used with UPDATE and DELETE queries, but is not recommended for SELECT queries and is not
* used to count records.
*
* ## Example
*
* ```
* $rowCount = $query->update('articles')
* ->set(['published'=>true])
* ->where(['published'=>false])
* ->executeAndClose();
* ```
*
* The above example will change the published column to true for all false records, and return the number of
* records that were updated.
*
* @return int
*/
public function executeAndClose()
{
$statement = $this->execute();
try {
return $statement->rowCount();
} finally {
$statement->closeCursor();
}
}

/**
* Returns the SQL representation of this object.
*
Expand Down
16 changes: 16 additions & 0 deletions tests/TestCase/Database/QueryTest.php
Expand Up @@ -3881,6 +3881,22 @@ public function testDirectIsNotNull()
$this->assertNotEquals(['name' => 'larry'], $results->fetch('assoc'));
}

/**
* Performs the simple update query and verifies the row count.
*
* @return void
*/
public function testExecuteAndClose()
{
$this->loadFixtures('Authors');
$query = new Query($this->connection);
$rowCount = $query->update('authors')
->set('name', 'mark')
->where(['id' => 1])
->executeAndClose();
$this->assertCount(1, $rowCount);
}

/**
* Tests that case statements work correctly for various use-cases.
*
Expand Down

0 comments on commit fdbe9c1

Please sign in to comment.