Skip to content

Commit

Permalink
Add Query::bufferResults()
Browse files Browse the repository at this point in the history
This method changes the ResultSet into a BufferedResultSet. Using
buffered result sets allows you to re-use a result set and more easily
cache + iterate results.
  • Loading branch information
markstory committed Aug 8, 2013
1 parent e7386d7 commit 6b441f5
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
32 changes: 31 additions & 1 deletion lib/Cake/ORM/Query.php
Expand Up @@ -83,13 +83,23 @@ class Query extends DatabaseQuery {
];

/**
* A hydrated ResultSet.
* A ResultSet.
*
* When set, query execution will be bypassed.
*
* @var Cake\ORM\ResultSet
* @see setResult()
*/
protected $_results;

/**
* Boolean for tracking whether or not buffered results
* are enabled.
*
* @var boolean
*/
protected $_useBufferedResults = false;

/**
* @param Cake\Database\Connection $connection
* @param Cake\ORM\Table $table
Expand Down Expand Up @@ -322,6 +332,23 @@ public function normalizedContainments() {
return $this->_normalizedContainments = $contain;
}

/**
* Enable buffered results.
*
* When enabled the ResultSet returned by this Query will be
* buffered. This enables you to iterate a ResultSet multiple times, or
* both cache and iterate the ResultSet.
*
* This mode will consume more memory as the result set will stay in memory
* until the ResultSet if freed.
*
* @return Query The query instance;
*/
public function bufferResults() {
$this->_useBufferedResults = true;
return $this;
}

/**
* Set the result set for a query.
*
Expand Down Expand Up @@ -354,6 +381,9 @@ public function execute() {
if (isset($this->_results)) {
return $this->_results;
}
if ($this->_useBufferedResults) {
return new BufferedResultSet($this, parent::execute());
}
return new ResultSet($this, parent::execute());
}

Expand Down
15 changes: 15 additions & 0 deletions lib/Cake/Test/TestCase/ORM/QueryTest.php
Expand Up @@ -823,4 +823,19 @@ public function testSetResult() {
$this->assertSame($results, $query->execute());
}

/**
* Test enabling buffering of results.
*
* @return void
*/
public function testBufferResults() {
$table = Table::build('article', ['connection' => $this->connection, 'table' => 'articles']);
$query = new Query($this->connection, $table);

$result = $query->select()->bufferResults();
$this->assertSame($query, $result, 'Query should be the same');
$result = $query->execute();
$this->assertInstanceOf('Cake\ORM\BufferedResultSet', $result);
}

}

0 comments on commit 6b441f5

Please sign in to comment.