Skip to main content

Module aggregate_walk

Module aggregate_walk 

Source
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 t
  • SELECT CAST(SUM(x) AS TEXT) FROM t
  • SELECT -SUM(x) FROM t
  • SELECT 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 true if any aggregate function call appears anywhere inside expr — at any nesting depth, inside any expression position.
extract_aggregates
Extract every aggregate function call from expr, binding each to the given output alias. 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.