Skip to content
Open
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
34 changes: 27 additions & 7 deletions src/boring_semantic_layer/calc_compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,25 @@ def apply_calc_measures(
return real_agg_tbl


def _carry_constant_total_col(col_expr):
"""Aggregate a constant-per-row windowed-totals column across GROUP BY.

Uses ``min()`` (or ``any()`` for booleans, since Postgres lacks
``MIN(boolean)``) instead of ``arbitrary()``, which Ibis compiles to
``FIRST(...)`` on Postgres where that function does not exist (#281).
Falls back to ``arbitrary()`` only for non-orderable types.
"""
try:
if col_expr.type().is_boolean():
return col_expr.any()
except Exception:
pass
try:
return col_expr.min()
except Exception:
return col_expr.arbitrary()


def attach_windowed_totals(
base_tbl,
agg_specs: dict[str, Any],
Expand All @@ -651,24 +670,25 @@ def attach_windowed_totals(
``base.distance.mean()``), wrap it in ``.over(window())`` to produce
a window function over the entire base, and add the result as a
new column ``f"{totals_prefix}{name}"``. Returns the mutated base
table plus a dict of arbitrary-aggregator specs that callers should
add to their per-group aggregation so the totals propagate as
table plus a dict of constant-carrying aggregator specs that callers
should add to their per-group aggregation so the totals propagate as
ordinary columns on the result.

This expresses "ungrouped aggregate alongside a grouped one" as a
single-pass query: the totals are computed once via window function,
broadcast to every base row, and surface as a per-group column via
``arbitrary()`` in the aggregation. No cross-join, no shared-ancestor
collapse, compiles to SQL on every backend that supports window
functions.
``min()`` (or ``any()`` for booleans) in the aggregation. No
cross-join, no shared-ancestor collapse, compiles to standard SQL on
every backend that supports window functions (including Postgres,
where ``arbitrary()`` would emit unsupported ``FIRST(...)``).

Returns
-------
(new_base_tbl, totals_arbitrary_specs):
- ``new_base_tbl`` carries the original columns plus
``__bsl_totals__<name>`` for each requested measure.
- ``totals_arbitrary_specs[col]`` is an agg-spec callable that
wraps ``t[col].arbitrary()``.
carries ``t[col]`` across ``GROUP BY`` via ``min()`` / ``any()``.
"""
new_base = base_tbl
arbitrary_specs: dict[str, Any] = {}
Expand All @@ -693,7 +713,7 @@ def attach_windowed_totals(
) from exc
col = f"{totals_prefix}{name}"
new_base = new_base.mutate(**{col: windowed})
arbitrary_specs[col] = lambda t, _c=col: t[_c].arbitrary()
arbitrary_specs[col] = lambda t, _c=col: _carry_constant_total_col(t[_c])
return new_base, arbitrary_specs


Expand Down
6 changes: 3 additions & 3 deletions src/boring_semantic_layer/ops/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1801,10 +1801,10 @@ def _compile_aggregation(
# When any calc references ``t.all(measure_ref)``, compute that
# measure's formula as a window function over the entire base
# *before* group_by, then carry it through the per-group aggregation
# via ``arbitrary()``. This expresses "ungrouped aggregate alongside
# via ``min()`` / ``any()``. This expresses "ungrouped aggregate alongside
# grouped one" as a single-pass query — no cross-join, no
# shared-ancestor collapse, compiles to SQL on every backend
# supporting window functions. Skipped on the nested-array path:
# shared-ancestor collapse, compiles to standard SQL on every backend
# supporting window functions (including Postgres). Skipped on the nested-array path:
# totals across multiple grains aren't well-defined; we surface a
# clear error in the apply loop.
#
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ FROM (
SELECT
"t2"."region",
SUM("t2"."amount") AS "revenue",
ANY_VALUE("t2"."__bsl_totals__revenue") AS "__bsl_totals__revenue"
MIN("t2"."__bsl_totals__revenue") AS "__bsl_totals__revenue"
FROM (
SELECT
"t1"."order_id",
Expand Down
45 changes: 45 additions & 0 deletions src/boring_semantic_layer/tests/test_percent_of_total.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,48 @@ def test_percent_of_total_grand_total():
for k, v in expected.items():
assert pytest.approx(v) == got[k]
assert pytest.approx(sum(got.values())) == 1.0


def test_all_totals_postgres_avoids_first_aggregate():
"""Postgres dialect compiles .all(...) totals to MIN/BOOL_OR, never FIRST() (#281)."""
from boring_semantic_layer import from_config
from boring_semantic_layer._xorq import ibis as xibis

tbl = ibis.table({"phase": "string", "target_cells": "int64"}, name="target_phase_cells")
models = from_config(
{
"target_phase_cells": {
"table": "target_phase_cells",
"dimensions": {"phase": "_.phase"},
"measures": {"target_cells": "_.target_cells.sum()"},
"calculated_measures": {
"pct_of_all_target_cells": "_.target_cells / _.all(_.target_cells) * 100"
},
}
},
tables={"target_phase_cells": tbl},
)
q = models["target_phase_cells"].query(
dimensions=("phase",), measures=("pct_of_all_target_cells",)
)
sql = xibis.to_sql(q.to_untagged(), dialect="postgres")
assert "FIRST(" not in sql.upper()
assert "MIN(" in sql.upper()


def test_all_totals_boolean_measure_postgres_uses_bool_or():
"""Boolean measures referenced via t.all(...) compile to BOOL_OR, never FIRST() or MIN()."""
from boring_semantic_layer._xorq import ibis as xibis

tbl = ibis.table({"phase": "string", "flag": "boolean"}, name="phase_flags")
model = (
to_semantic_table(tbl, name="phase_flags")
.with_dimensions(phase=lambda t: t.phase)
.with_measures(any_flag=lambda t: t.flag.any())
.with_measures(same_as_global=lambda t: t.any_flag == t.all(t.any_flag))
)
sql = xibis.to_sql(
model.group_by("phase").aggregate("same_as_global").to_untagged(), dialect="postgres"
)
assert "FIRST(" not in sql.upper()
assert "BOOL_OR(" in sql.upper()