Spaces:
Running

shelf-talk / engine /compiler.py
Ashish-K's picture
Deploy Shelf Talk (replay mode)
f1cd642 verified
Raw History Blame Contribute Delete
2.81 kB
"""Layer 6 (deterministic): compile a validated QueryPlan into SQL.
The one rule that matters most: metrics from DIFFERENT semantic models are
aggregated SEPARATELY (one CTE per model) and only then joined on the shared
dimensions. Joining raw fact tables first and aggregating after multiplies
rows (fan-out) and silently inflates sums - the classic analytics bug.
"""
from __future__ import annotations
from . import config
from .plan import QueryPlan
def _lit(v: str) -> str:
return "'" + v.replace("'", "''") + "'"
def _where(plan: QueryPlan, contract) -> str:
clauses = []
for f in plan.filters:
col = contract.column(f.dimension)
if f.operator == "contains":
ors = " OR ".join(f"{col} ILIKE {_lit('%' + v + '%')}" for v in f.values)
clauses.append(f"({ors})")
elif f.values:
op = "IN" if f.operator == "in" else "NOT IN"
clauses.append(f"{col} {op} ({', '.join(_lit(v) for v in f.values)})")
return ("\n WHERE " + "\n AND ".join(clauses)) if clauses else ""
def compile_plan(plan: QueryPlan, contract) -> str:
dim_cols = [contract.column(d) for d in plan.dimensions]
aliases = [f"{contract.column(d)} AS {d}" if contract.column(d) != d else d for d in plan.dimensions]
by_model: dict[str, list[str]] = {}
for m in plan.metrics:
by_model.setdefault(contract.model_of(m), []).append(m)
ctes = []
for i, (model, metrics) in enumerate(by_model.items()):
select = aliases + [f"{contract.metrics[m]['sql']} AS {m}" for m in metrics]
group = f"\n GROUP BY {', '.join(dim_cols)}" if dim_cols else ""
ctes.append(f"m{i} AS (\n -- {model}: {contract.raw['models'][model]['grain']}\n"
f" SELECT {', '.join(select)}\n FROM {model}{_where(plan, contract)}{group}\n)")
dims = plan.dimensions
if len(ctes) == 1:
body = "SELECT * FROM m0"
else:
body = "SELECT * FROM m0"
for i in range(1, len(ctes)):
body += f"\nFULL OUTER JOIN m{i} USING ({', '.join(dims)})" if dims else f"\nCROSS JOIN m{i}"
having = []
for mf in plan.metric_filters:
having.append(f"{mf.metric} {mf.operator} {mf.value}")
if having:
body = f"SELECT * FROM ({body}) AS j\nWHERE " + " AND ".join(having)
if plan.order_by:
body += f"\nORDER BY {plan.order_by.metric} {plan.order_by.direction.upper()} NULLS LAST"
elif "quarter" in dims or "fiscal_year" in dims:
body += "\nORDER BY " + ", ".join(dims)
elif plan.metrics:
body += f"\nORDER BY {plan.metrics[0]} DESC NULLS LAST"
body += f"\nLIMIT {plan.limit or config.DEFAULT_LIMIT}"
return "WITH " + ",\n".join(ctes) + "\n" + body