Browse Source

Trap errors from incomplete queries.

__debugInfo() should not trigger errors on incomplete queries. This
makes using queries on the interactive console a bit easier.

Refs #8812
Mark Story 9 years ago
parent
commit
bf1c15036b
2 changed files with 29 additions and 2 deletions
  1. 15 2
      src/Database/Query.php
  2. 14 0
      tests/TestCase/Database/QueryTest.php

+ 15 - 2
src/Database/Query.php

@@ -1896,10 +1896,23 @@ class Query implements ExpressionInterface, IteratorAggregate
      */
     public function __debugInfo()
     {
+        try {
+            $restore = set_error_handler(function ($errno, $errstr) {
+                throw new RuntimeException($errstr, $errno);
+            }, E_ALL);
+            $sql = $this->sql();
+            $params = $this->valueBinder()->bindings();
+        } catch (RuntimeException $e) {
+            $sql = 'SQL could not be generated for this query as it is incomplete.';
+            $params = [];
+        } finally {
+            restore_error_handler();
+        }
+
         return [
             '(help)' => 'This is a Query object, to get the results execute or iterate it.',
-            'sql' => $this->sql(),
-            'params' => $this->valueBinder()->bindings(),
+            'sql' => $sql,
+            'params' => $params,
             'defaultTypes' => $this->defaultTypes(),
             'decorators' => count($this->_resultDecorators),
             'executed' => $this->_iterator ? true : false

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

@@ -3478,6 +3478,20 @@ class QueryTest extends TestCase
     }
 
     /**
+     * Tests __debugInfo on incomplete query
+     *
+     * @return void
+     */
+    public function testDebugInfoIncompleteQuery()
+    {
+        $query = (new Query($this->connection))
+            ->insert(['title']);
+        $result = $query->__debugInfo();
+        $this->assertContains('incomplete', $result['sql']);
+        $this->assertSame([], $result['params']);
+    }
+
+    /**
      * Tests that it is possible to pass ExpressionInterface to isNull and isNotNull
      *
      * @return void