From 0c9bccf1168015b565e498f1060e8f9ebebfb569 Mon Sep 17 00:00:00 2001
From: Coleman Watts <coleman@civicrm.org>
Date: Wed, 10 Jun 2020 20:41:51 -0400
Subject: [PATCH] APIv4 - Skip empty leaves in WHERE clause

Fixes an annoying problem with search builder
where the api gives a sql error while building your where clause.
The solution is to skip empty leaves, treating them as WIP.
---
 Civi/Api4/Query/Api4SelectQuery.php | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/Civi/Api4/Query/Api4SelectQuery.php b/Civi/Api4/Query/Api4SelectQuery.php
index 794df9580a..92dee1d128 100644
--- a/Civi/Api4/Query/Api4SelectQuery.php
+++ b/Civi/Api4/Query/Api4SelectQuery.php
@@ -199,7 +199,10 @@ class Api4SelectQuery extends SelectQuery {
    */
   protected function buildWhereClause() {
     foreach ($this->where as $clause) {
-      $this->query->where($this->treeWalkClauses($clause, 'WHERE'));
+      $sql = $this->treeWalkClauses($clause, 'WHERE');
+      if ($sql) {
+        $this->query->where($sql);
+      }
     }
   }
 
@@ -270,6 +273,10 @@ class Api4SelectQuery extends SelectQuery {
    * @uses composeClause() to generate the SQL etc.
    */
   protected function treeWalkClauses($clause, $type) {
+    // Skip empty leaf.
+    if (in_array($clause[0], ['AND', 'OR', 'NOT']) && empty($clause[1])) {
+      return '';
+    }
     switch ($clause[0]) {
       case 'OR':
       case 'AND':
-- 
2.25.1