diff --git a/spp_cel_domain/README.rst b/spp_cel_domain/README.rst
index 9a72fa2b4..8ad8d603b 100644
--- a/spp_cel_domain/README.rst
+++ b/spp_cel_domain/README.rst
@@ -142,6 +142,13 @@ Dependencies
Changelog
=========
+19.0.2.1.1
+~~~~~~~~~~
+
+- fix(executor): include households with no matching memberships for
+ ``count >= 0`` in SQL and when zero satisfies a Python count
+ comparison without a base domain
+
19.0.2.1.0
~~~~~~~~~~
diff --git a/spp_cel_domain/__manifest__.py b/spp_cel_domain/__manifest__.py
index 550c3d0f3..d53b3c3a2 100644
--- a/spp_cel_domain/__manifest__.py
+++ b/spp_cel_domain/__manifest__.py
@@ -2,7 +2,7 @@
{
"name": "CEL Domain Query Builder",
"summary": "Write simple CEL-like expressions to filter records (OpenSPP/OpenG2P friendly)",
- "version": "19.0.2.1.0",
+ "version": "19.0.2.1.1",
"license": "LGPL-3",
"development_status": "Production/Stable",
"author": "OpenSPP.org, OpenSPP Community",
diff --git a/spp_cel_domain/models/cel_executor.py b/spp_cel_domain/models/cel_executor.py
index b9fb36003..45931026a 100644
--- a/spp_cel_domain/models/cel_executor.py
+++ b/spp_cel_domain/models/cel_executor.py
@@ -156,10 +156,9 @@ def _count_to_sql(self, p: CountThrough) -> SQL | None:
Returns SQL selecting parent IDs where child count matches the comparison.
Special handling for edge cases:
- - count == 0: Parents with NO matching children (NOT IN subquery)
- - count < N or count <= N: Fall back to Python (needs special handling for 0-count parents)
- - count != N: Fall back to Python (complex edge cases)
- - count > 0, count >= N, count > N: Use GROUP BY + HAVING (standard approach)
+ - count >= 0: Select all parents, including those with no matching children.
+ - count == 0, count < N, count <= N, count != N: Fall back to Python.
+ - Other supported comparisons: Use GROUP BY + HAVING.
"""
try:
through_table = self.env[p.through_model]._table
@@ -197,6 +196,12 @@ def _count_to_sql(self, p: CountThrough) -> SQL | None:
op = "="
rhs = p.rhs
+ # Every count is at least zero.
+ # GROUP BY on memberships alone would omit parents with no matching rows.
+ if op == ">=" and isinstance(rhs, (int, float)) and not isinstance(rhs, bool) and rhs == 0:
+ parent_model = self.env[p.through_model]._fields[p.parent_field].comodel_name
+ return builder.select_ids_from_domain(parent_model, [])
+
# Fall back to Python for comparisons that need zero-count parents included
# These are complex to handle correctly in SQL without the parent table:
# - count == 0: Parents with no rows in membership table won't appear in SQL
@@ -856,7 +861,7 @@ def _exec_count(self, p: CountThrough) -> list[int]: # noqa: C901
base_domain = cfg.get("base_domain")
candidate_parents: set[int] = set()
- if parent_model_name and base_domain:
+ if parent_model_name and (base_domain or self._compare(0, p.op, p.rhs)):
candidate_parents = set(int(pid) for pid in self.env[parent_model_name].search(base_domain).ids)
if child_subplan is not None:
diff --git a/spp_cel_domain/readme/HISTORY.md b/spp_cel_domain/readme/HISTORY.md
index 1b4fd10d3..0971d7602 100644
--- a/spp_cel_domain/readme/HISTORY.md
+++ b/spp_cel_domain/readme/HISTORY.md
@@ -1,3 +1,7 @@
+### 19.0.2.1.1
+
+- fix(executor): include households with no matching memberships for `count >= 0` in SQL and when zero satisfies a Python count comparison without a base domain
+
### 19.0.2.1.0
- feat(sql): compile CEL ternary expressions to SQL CASE via `to_sql_case`, with `case_when`/`comparison` builders and a right-associative ternary parsing fix
diff --git a/spp_cel_domain/static/description/index.html b/spp_cel_domain/static/description/index.html
index f280ce2a1..9644c39f8 100644
--- a/spp_cel_domain/static/description/index.html
+++ b/spp_cel_domain/static/description/index.html
@@ -522,6 +522,14 @@
+
19.0.2.1.1
+
+- fix(executor): include households with no matching memberships for
+count >= 0 in SQL and when zero satisfies a Python count
+comparison without a base domain
+
+
+
19.0.2.1.0
- feat(sql): compile CEL ternary expressions to SQL CASE via
@@ -533,7 +541,7 @@
19.0.2.1.0
- test(translator): add coverage for the CEL translation cache helpers
-
+
19.0.2.0.0
- Initial migration to OpenSPP2
diff --git a/spp_cel_domain/tests/test_cel_sql_generation.py b/spp_cel_domain/tests/test_cel_sql_generation.py
index 7d2564c2e..924d63391 100644
--- a/spp_cel_domain/tests/test_cel_sql_generation.py
+++ b/spp_cel_domain/tests/test_cel_sql_generation.py
@@ -9,6 +9,7 @@
"""
from datetime import date, timedelta
+from random import Random
from unittest.mock import patch
from odoo.tests.common import TransactionCase
@@ -527,6 +528,100 @@ def test_parity_empty_results(self):
"Empty result set - no households with more than 10 members",
)
+ def test_count_at_least_zero_without_base_domain(self):
+ config = self.env["spp.cel.registry"].load_profile("registry_groups")
+ config["base_domain"] = []
+ executor = self.executor.with_context(cel_cfg=config)
+ candidates = self.env["res.partner"].search([])
+ for materialize_sql, path in ((False, "sql"), (True, "python")):
+ with self.subTest(path=path):
+ result = executor.compile_and_preview(
+ "res.partner", "members.count(m, true) >= 0", limit=len(candidates), materialize_sql=materialize_sql
+ )
+ self.assertEqual(result["path"], path)
+ self.assertCountEqual(result["ids"], candidates.ids)
+
+ def test_count_equals_zero_without_base_domain(self):
+ config = self.env["spp.cel.registry"].load_profile("registry_groups")
+ config["base_domain"] = []
+ executor = self.executor.with_context(cel_cfg=config)
+ result = executor.compile_and_preview(
+ "res.partner", "members.count(m, true) == 0", limit=self.env["res.partner"].search_count([])
+ )
+ self.assertEqual(result["path"], "python")
+ self.assertIn(self.household4.id, result["ids"])
+ self.assertNotIn(self.household1.id, result["ids"])
+
+
+class TestGeneratedSQLPythonParity(TransactionCase):
+ """Compare both execution paths on generated household rules and data."""
+
+ def _run_both_paths(self, expression, households):
+ service = self.env["spp.cel.service"]
+ options = {
+ "base_domain": [("id", "in", households.ids)],
+ "limit": len(households),
+ }
+ sql = service.compile_expression(expression, "registry_groups", **options)
+ python = service.compile_expression(expression, "registry_groups", materialize_sql=True, **options)
+ for key, result in (("sql", sql), ("python", python)):
+ self.assertTrue(result["valid"], result["error"])
+ self.assertEqual(result["path"], key)
+ self.assertEqual(result["count"], len(result["ids"]))
+ return set(sql["ids"]), set(python["ids"])
+
+ def test_count_at_least_zero_includes_empty_household(self):
+ household = self.env["res.partner"].create({"name": "Empty household", "is_registrant": True, "is_group": True})
+ sql, python = self._run_both_paths("members.count(m, true) >= 0", household)
+ self.assertEqual(python, {household.id})
+ self.assertEqual(sql, {household.id})
+
+ def test_generated_household_rules(self):
+ seed = 1729
+ rng = Random(seed)
+ partners = self.env["res.partner"]
+ households = partners.create(
+ [{"name": f"Generated household {i}", "is_registrant": True, "is_group": True} for i in range(18)]
+ )
+ today = date.today()
+ membership_vals = []
+ for index, household in enumerate(households):
+ # Include an empty household and cover every size from zero to five.
+ for member_index in range(index % 6):
+ age = rng.choice([None, 3, 12, 30, 72])
+ member = partners.create(
+ {
+ "name": f"Generated member {index}-{member_index}",
+ "is_registrant": True,
+ "birthdate": today - timedelta(days=age * 365) if age is not None else False,
+ }
+ )
+ membership_vals.append({"group": household.id, "individual": member.id})
+ self.env["spp.group.membership"].create(membership_vals)
+ self.env.flush_all()
+
+ predicates = ["true", "false", "age_years(m.birthdate) < 5", "age_years(m.birthdate) >= 65"]
+ rules = []
+ for predicate in predicates:
+ rules.append(f"members.exists(m, {predicate})")
+ for count in range(6):
+ rules.append(f"members.count(m, {predicate}) >= {count}")
+ rules.append(f"members.count(m, {predicate}) > {count}")
+ if count:
+ rules.append(f"members.count(m, {predicate}) == {count}")
+
+ # Combine SQL-capable atoms to exercise INTERSECT and UNION as well.
+ combined_rules = []
+ for _ in range(24):
+ left, right = rng.sample(rules, 2)
+ op = rng.choice(["&&", "||"])
+ combined_rules.append(f"({left}) {op} ({right})")
+
+ for expression in rules + combined_rules:
+ with self.subTest(seed=seed, expression=expression):
+ sql, python = self._run_both_paths(expression, households)
+ self.assertSetEqual(sql, python)
+
class TestSQLEdgeCases(TransactionCase):
"""Edge case tests for SQL generation."""