Browse Source

adds new executeAndClose method

thinkingmedia 9 years ago
parent
commit
fdbe9c17fd
2 changed files with 47 additions and 0 deletions
  1. 31 0
      src/Database/Query.php
  2. 16 0
      tests/TestCase/Database/QueryTest.php

+ 31 - 0
src/Database/Query.php

@@ -226,6 +226,37 @@ class Query implements ExpressionInterface, IteratorAggregate
     }
 
     /**
+     * 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.
      *
      * This function will compile this query to make it compatible

+ 16 - 0
tests/TestCase/Database/QueryTest.php

@@ -3882,6 +3882,22 @@ class QueryTest extends TestCase
     }
 
     /**
+     * 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.
      *
      * @return void