Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions spp_cel_domain/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
~~~~~~~~~~

Expand Down
2 changes: 1 addition & 1 deletion spp_cel_domain/__manifest__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
15 changes: 10 additions & 5 deletions spp_cel_domain/models/cel_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
4 changes: 4 additions & 0 deletions spp_cel_domain/readme/HISTORY.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
10 changes: 9 additions & 1 deletion spp_cel_domain/static/description/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,14 @@ <h2><a class="toc-backref" href="#toc-entry-1">Changelog</a></h2>
</div>
</div>
<div class="section" id="section-1">
<h1>19.0.2.1.1</h1>
<ul class="simple">
<li>fix(executor): include households with no matching memberships for
<tt class="docutils literal">count &gt;= 0</tt> in SQL and when zero satisfies a Python count
comparison without a base domain</li>
</ul>
</div>
<div class="section" id="section-2">
<h1>19.0.2.1.0</h1>
<ul class="simple">
<li>feat(sql): compile CEL ternary expressions to SQL CASE via
Expand All @@ -533,7 +541,7 @@ <h1>19.0.2.1.0</h1>
<li>test(translator): add coverage for the CEL translation cache helpers</li>
</ul>
</div>
<div class="section" id="section-2">
<div class="section" id="section-3">
<h1>19.0.2.0.0</h1>
<ul class="simple">
<li>Initial migration to OpenSPP2</li>
Expand Down
95 changes: 95 additions & 0 deletions spp_cel_domain/tests/test_cel_sql_generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"""

from datetime import date, timedelta
from random import Random
from unittest.mock import patch

from odoo.tests.common import TransactionCase
Expand Down Expand Up @@ -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."""
Expand Down
Loading