Browse Source

Merge pull request #5732 from cakephp/issue-5720-fix

Fix first() failing on unbuffered queries.
José Lorenzo Rodríguez 11 years ago
parent
commit
75ac510de3
2 changed files with 39 additions and 6 deletions
  1. 22 6
      src/ORM/ResultSet.php
  2. 17 0
      tests/TestCase/ORM/QueryTest.php

+ 22 - 6
src/ORM/ResultSet.php

@@ -224,13 +224,9 @@ class ResultSet implements ResultSetInterface
                 $this->_current = $this->_results[$this->_index];
                 return true;
             }
-        }
-
-        if (!$valid) {
-            if ($this->_statement !== null) {
-                $this->_statement->closeCursor();
+            if (!$valid) {
+                return $valid;
             }
-            return false;
         }
 
         $this->_current = $this->_fetchResult();
@@ -239,11 +235,31 @@ class ResultSet implements ResultSetInterface
         if ($valid && $this->_useBuffering) {
             $this->_results[$this->_index] = $this->_current;
         }
+        if (!$valid && $this->_statement !== null) {
+            $this->_statement->closeCursor();
+        }
 
         return $valid;
     }
 
     /**
+     * Get the first record from a result set.
+     *
+     * This method will also close the underlying statement cursor.
+     *
+     * @return array|object
+     */
+    public function first()
+    {
+        foreach ($this as $result) {
+            if ($this->_statement && !$this->_useBuffering) {
+                $this->_statement->closeCursor();
+            }
+            return $result;
+        }
+    }
+
+    /**
      * Serializes a resultset.
      *
      * Part of Serializable interface.

+ 17 - 0
tests/TestCase/ORM/QueryTest.php

@@ -1098,6 +1098,23 @@ class QueryTest extends TestCase
     }
 
     /**
+     * Tests that first can be called on an unbuffered query
+     *
+     * @return void
+     */
+    public function testFirstUnbuffered()
+    {
+        $table = TableRegistry::get('Articles');
+        $query = new Query($this->connection, $table);
+        $query->select(['id']);
+
+        $first = $query->hydrate(false)
+            ->bufferResults(false)->first();
+
+        $this->assertEquals(['id' => 1], $first);
+    }
+
+    /**
      * Testing hydrating a result set into Entity objects
      *
      * @return void