Browse Source

Fix empty clauses causing errors in matching().

Instead of null the where clause should be set to an empty expression.
Storing null causes issues in other parts of the framework.

Refs #7102
Mark Story 10 years ago
parent
commit
ffb14bcd53

+ 2 - 1
src/Database/Query.php

@@ -1643,10 +1643,11 @@ class Query implements ExpressionInterface, IteratorAggregate
      */
     protected function _conjugate($part, $append, $conjunction, $types)
     {
+        $expression = $this->_parts[$part] ?: $this->newExpr();
         if (empty($append)) {
+            $this->_parts[$part] = $expression;
             return;
         }
-        $expression = $this->_parts[$part] ?: $this->newExpr();
 
         if (!is_string($append) && is_callable($append)) {
             $append = $append($this->newExpr(), $this);

+ 2 - 2
tests/TestCase/Database/QueryTest.php

@@ -1190,10 +1190,10 @@ class QueryTest extends TestCase
         $query->from('comments')
             ->where('');
 
-        $this->assertNull($query->clause('where'));
+        $this->assertCount(0, $query->clause('where'));
 
         $query->where([]);
-        $this->assertNull($query->clause('where'));
+        $this->assertCount(0, $query->clause('where'));
     }
 
     /**

+ 25 - 0
tests/TestCase/ORM/QueryRegressionTest.php

@@ -880,6 +880,31 @@ class QueryRegressionTest extends TestCase
     }
 
     /**
+     * Test that empty conditions in a matching clause don't cause errors.
+     *
+     * @return void
+     */
+    public function testMatchingEmptyQuery()
+    {
+        $table = TableRegistry::get('Articles');
+        $table->belongsToMany('Tags');
+
+        $rows = $table->find()
+            ->matching('Tags', function ($q) {
+                return $q->where([]);
+            })
+            ->all();
+        $this->assertNotEmpty($rows);
+
+        $rows = $table->find()
+            ->matching('Tags', function ($q) {
+                return $q->where(null);
+            })
+            ->all();
+        $this->assertNotEmpty($rows);
+    }
+
+    /**
      * Tests that using a subquery as part of an expression will not make invalid SQL
      *
      * @return void