Skip to content
Permalink
Browse files

Implementing 3.0 version of find('first')

  • Loading branch information...
lorenzo committed Aug 31, 2013
1 parent ca35282 commit 850d26323c8faba325591e4c2d36fb738ffb67d1
Showing with 72 additions and 0 deletions.
  1. +23 −0 lib/Cake/ORM/Query.php
  2. +49 −0 lib/Cake/Test/TestCase/ORM/QueryTest.php
@@ -557,6 +557,29 @@ public function mapReduce(callable $mapper = null, callable $reducer = null, $ov
return $this;
}
/**
* Returns the first result out of executed this query, if the query has not been
* executed before, it will set the limit clause to 1 for performance reasons.
*
* ###Example:
*
* ``$singleUser = $query->select(['id', 'username'])->first()``
*
* @return mixed the first result from the ResultSet
*/
public function first() {
if ($this->_dirty) {
$this->limit(1);
}
$this->bufferResults();
$this->_results = $this->execute();
// Calls foreach so we cursor is rewinded automatically
foreach ($this->_results as $row) {
// Just get the first result from the iterator
return $row;
}
}
/**
* Decorates the ResultSet iterator with MapReduce routines
*
@@ -1023,4 +1023,53 @@ function($k, $v, $mr) {
$this->assertEquals([2, 3], iterator_to_array($query->execute()));
}
/**
* Tests first() method when the query has not been executed before
*
* @return void
*/
public function testFirstDirtyQuery() {
$this->_createTables();
$table = Table::build('article', ['table' => 'articles']);
$query = new Query($this->connection, $table);
$result = $query->select(['id'])->first();
$this->assertEquals(['id' => 1], $result);
$this->assertEquals(1, $query->clause('limit'));
$result = $query->select(['id'])->first();
$this->assertEquals(['id' => 1], $result);
}
/**
* Tests that first can be called again on an already executed query
*
* @return void
*/
public function testFirstCleanQuery() {
$this->_createTables();
$table = Table::build('article', ['table' => 'articles']);
$query = new Query($this->connection, $table);
$query->select(['id'])->toArray();
$first = $query->first();
$this->assertEquals(['id' => 1], $first);
$this->assertNull($query->clause('limit'));
}
/**
* Tests that first() will not execute the same query twice
*
* @return void
*/
public function testFirstSameResult() {
$this->_createTables();
$table = Table::build('article', ['table' => 'articles']);
$query = new Query($this->connection, $table);
$query->select(['id'])->toArray();
$first = $query->first();
$resultSet = $query->execute();
$this->assertEquals(['id' => 1], $first);
$this->assertSame($resultSet, $query->execute());
}
}

0 comments on commit 850d263

Please sign in to comment.
You can’t perform that action at this time.