Skip to content

Commit

Permalink
Add setResult() to Query.
Browse files Browse the repository at this point in the history
This will allow beforeFind() callbacks to avoid query execution by
setting seeding results.
  • Loading branch information
markstory committed Aug 4, 2013
1 parent 62e68d0 commit c6a5ab0
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
32 changes: 31 additions & 1 deletion lib/Cake/ORM/Query.php
Expand Up @@ -82,6 +82,14 @@ class Query extends DatabaseQuery {
'matching' => 1
];

/**
* A hydrated ResultSet.
*
* @var Cake\ORM\ResultSet
* @see setResult()
*/
protected $_results;

/**
* Returns the default table object that will be used by this query,
* that is, the table that will appear in the from clause.
Expand Down Expand Up @@ -305,16 +313,38 @@ public function normalizedContainments() {
return $this->_normalizedContainments = $contain;
}

/**
* Set the result set for a query.
*
* Setting the resultset of a query will make execute() a no-op. Instead
* of executing the SQL query and fetching results, the ResultSet provided to this
* method will be returned.
*
* This method is most useful when combined with results stored in a persistent cache.
*
* @param Cake\ORM\ResultSet $results The results this query should return.
* @return Query The query instance.
*/
public function setResult(ResultSet $results) {
$this->_results = $results;
return $this;
}

/**
* Compiles the SQL representation of this query and executes it using the
* provided connection object. Returns a ResultSet iterator object
* provided connection object. Returns a ResultSet iterator object.
*
* If a result set was set using setResult() that ResultSet will be returned.
*
* Resulting object is traversable, so it can be used in any loop as you would
* with an array.
*
* @return Cake\ORM\ResultSet
*/
public function execute() {
if (isset($this->_results)) {
return $this->_results;
}
return new ResultSet($this, parent::execute());
}

Expand Down
14 changes: 14 additions & 0 deletions lib/Cake/Test/TestCase/ORM/QueryTest.php
Expand Up @@ -19,6 +19,7 @@
use Cake\Core\Configure;
use Cake\Model\ConnectionManager;
use Cake\ORM\Query;
use Cake\ORM\ResultSet;
use Cake\ORM\Table;

/**
Expand Down Expand Up @@ -812,4 +813,17 @@ public function testFilteringByBelongsToMany() {
$this->assertEquals($expected, $results);
}

/**
* Test setResult()
*
* @return void
*/
public function testSetResult() {
$query = new Query($this->connection);
$stmt = $this->getMock('Cake\Database\StatementInterface');
$results = new ResultSet($query, $stmt);
$query->setResult($results);
$this->assertSame($results, $query->execute());
}

}

0 comments on commit c6a5ab0

Please sign in to comment.