Skip to main content

uqa_sql/semantics/
aggregates.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Aggregate discovery and expression equivalence for SQL grouping.
8
9use crate::plan::{AggregateClassifier, ProjectionPlan, QueryBlockPlan};
10use crate::ScalarExpr;
11use uqa_core::Value;
12
13#[cfg(test)]
14mod production_tests;
15#[cfg(test)]
16mod tests;
17
18mod matching;
19pub use matching::exprs_match_with_control;
20
21pub fn exprs_match(lhs: &ScalarExpr, rhs: &ScalarExpr) -> bool {
22    exprs_match_with_control(
23        lhs,
24        rhs,
25        &uqa_core::memory::ProductionControl::uncontrolled(),
26    )
27    .unwrap_or(false)
28}
29
30pub fn literals_equal(a: &Value, b: &Value) -> bool {
31    a.has_same_representation(b)
32}
33
34pub fn has_aggregate(aggregates: &dyn AggregateClassifier, projections: &[ProjectionPlan]) -> bool {
35    projections
36        .iter()
37        .any(|p| contains_aggregate(aggregates, &p.expr))
38}
39
40pub fn is_aggregate(aggregates: &dyn AggregateClassifier, expr: &ScalarExpr) -> bool {
41    is_builtin_aggregate(expr)
42        || matches!(expr, ScalarExpr::Func { name, .. } if aggregates.is_registered_aggregate(name))
43}
44
45pub use super::is_builtin_aggregate;
46
47pub fn aggregate_exprs<'a>(
48    aggregates: &dyn AggregateClassifier,
49    projections: &'a [ProjectionPlan],
50) -> Vec<&'a ScalarExpr> {
51    let mut out = Vec::new();
52    for projection in projections {
53        collect_aggregate_exprs(aggregates, &projection.expr, &mut out);
54    }
55    out
56}
57
58/// Aggregate states needed by a query block, in accumulator order.
59///
60/// Projection aggregates remain first (including repeated expressions) because
61/// projection rewriting consumes them positionally. Aggregates referenced only
62/// by HAVING are appended once as hidden targets, matching `PostgreSQL`'s rule
63/// that HAVING need not expose an aggregate in the SELECT list.
64pub fn aggregate_targets<'a>(
65    aggregates: &dyn AggregateClassifier,
66    statement: &'a QueryBlockPlan,
67) -> Vec<&'a ScalarExpr> {
68    let mut targets = aggregate_exprs(aggregates, &statement.projections);
69    if let Some(having) = statement.having.as_ref() {
70        let mut hidden = Vec::new();
71        collect_aggregate_exprs(aggregates, having, &mut hidden);
72        for aggregate in hidden {
73            if !targets
74                .iter()
75                .any(|existing| exprs_match(existing, aggregate))
76            {
77                targets.push(aggregate);
78            }
79        }
80    }
81    targets
82}
83
84mod observation;
85pub use observation::{
86    contains_aggregate_with_control, has_aggregate_with_control, is_aggregate_with_control,
87    visit_aggregate_exprs_with_control,
88};
89
90pub fn collect_aggregate_exprs<'a>(
91    aggregates: &dyn AggregateClassifier,
92    expr: &'a ScalarExpr,
93    out: &mut Vec<&'a ScalarExpr>,
94) {
95    observation::visit_ordinary(aggregates, expr, &mut |expr| out.push(expr));
96}
97
98pub fn contains_aggregate(aggregates: &dyn AggregateClassifier, expr: &ScalarExpr) -> bool {
99    let mut found = false;
100    observation::visit_ordinary(aggregates, expr, &mut |_| found = true);
101    found
102}
103
104/// Collect the top-level column names an expression reads. Returns
105/// `false` when the expression can reach arbitrary fields (`*`,
106/// subqueries, window calls), in which case callers must materialise
107/// whole documents.
108pub fn expr_references_columns(expr: &ScalarExpr) -> bool {
109    match expr {
110        ScalarExpr::Star
111        | ScalarExpr::QualifiedStar(_)
112        | ScalarExpr::Column(_)
113        | ScalarExpr::Position(_)
114        | ScalarExpr::InternalColumn(_)
115        | ScalarExpr::QualifiedColumn { .. } => true,
116        ScalarExpr::Func { args, filter, .. } => {
117            args.iter().any(expr_references_columns)
118                || filter.as_deref().is_some_and(expr_references_columns)
119        }
120        ScalarExpr::Array(items)
121        | ScalarExpr::Row(items)
122        | ScalarExpr::CompositeRow { items, .. }
123        | ScalarExpr::And(items)
124        | ScalarExpr::Or(items) => items.iter().any(expr_references_columns),
125        ScalarExpr::Binary { lhs, rhs, .. } => {
126            expr_references_columns(lhs) || expr_references_columns(rhs)
127        }
128        ScalarExpr::Not(inner)
129        | ScalarExpr::UnaryMinus(inner)
130        | ScalarExpr::Cast { expr: inner, .. }
131        | ScalarExpr::Collated { expr: inner, .. } => expr_references_columns(inner),
132        ScalarExpr::IsNull { expr, .. } => expr_references_columns(expr),
133        ScalarExpr::Between { expr, low, high } => {
134            expr_references_columns(expr)
135                || expr_references_columns(low)
136                || expr_references_columns(high)
137        }
138        ScalarExpr::InList { expr, list, .. } => {
139            expr_references_columns(expr) || list.iter().any(expr_references_columns)
140        }
141        ScalarExpr::WindowCall { args, filter, .. } => {
142            args.iter().any(expr_references_columns)
143                || filter.as_deref().is_some_and(expr_references_columns)
144        }
145        ScalarExpr::Case {
146            base,
147            when,
148            else_branch,
149        } => {
150            base.as_deref().is_some_and(expr_references_columns)
151                || when.iter().any(|(condition, result)| {
152                    expr_references_columns(condition) || expr_references_columns(result)
153                })
154                || else_branch.as_deref().is_some_and(expr_references_columns)
155        }
156        ScalarExpr::InSubquery { expr, .. } => expr_references_columns(expr),
157        ScalarExpr::ScalarSubquery(_) | ScalarExpr::Exists { .. } => true,
158        ScalarExpr::Default
159        | ScalarExpr::Literal(_)
160        | ScalarExpr::TypedLiteral { .. }
161        | ScalarExpr::RetainedLiteral(_)
162        | ScalarExpr::Param(_) => false,
163    }
164}
165
166mod slots;
167pub use slots::{
168    aggregate_slot_index, compile_group_slots, compile_having_aggregate_slots,
169    compile_projection_aggregate_slots, select_grouping_set,
170};