Expand description
AST traversal for aggregate detection and extraction.
Uses sqlparser’s own Visitor so aggregates nested inside any
expression position — CASE, CAST, COALESCE, -SUM(x),
SUM(x) BETWEEN ..., SUM(x) IN (...), window specs, array
elements — are found without us maintaining a hand-written walker
that has to enumerate every Expr variant.
§What this replaces
Two earlier hand-written walkers only descended through Function,
BinaryOp, and Nested. Every other position was a silent
fall-through that produced wrong plans for ordinary SQL:
SELECT CASE WHEN x > 0 THEN SUM(y) ELSE 0 END FROM tSELECT CAST(SUM(x) AS TEXT) FROM tSELECT -SUM(x) FROM tSELECT COALESCE(SUM(x), 0) FROM t
None of those were recognised as aggregates; the planner took the non-aggregate path and produced a plan that executed the inner column scan without grouping.
Functions§
- contains_
aggregate - Return
trueif any aggregate function call appears anywhere insideexpr— at any nesting depth, inside any expression position. - extract_
aggregates - Extract every aggregate function call from
expr, binding each to the given outputalias. Nested aggregates (e.g.SUM(AVG(x)), which is illegal SQL in Postgres and most other systems) are reported as a planner error rather than silently double-extracted.