Skip to main content

uqa_execution/aggregation/
rewrite.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Aggregate expression replacement, input extraction, and observation.
8
9use super::{
10    eval_scalar, AggregateAccumulator, AggregateAccumulatorTemplate, SQLError, ScalarEvalContext,
11    ScalarExpr, ScalarOrder, Value,
12};
13
14pub fn aggregate_input_value(
15    name: &str,
16    args: &[ScalarExpr],
17    order_by: &[ScalarOrder],
18    ctx: &ScalarEvalContext<'_>,
19) -> Result<Value, SQLError> {
20    if name.eq_ignore_ascii_case("count") && (args.is_empty() || matches!(args, [ScalarExpr::Star]))
21    {
22        return Ok(Value::Int(1));
23    }
24    // Ordered-set aggregates: the percentile / mode fraction is a
25    // direct positional argument; the value to fold comes from
26    // `WITHIN GROUP (ORDER BY ...)` which the compiler parks in
27    // `order_by[0]`.
28    if is_ordered_set_aggregate(name) {
29        return order_by
30            .first()
31            .map(|ob| eval_scalar(&ob.expr, ctx))
32            .transpose()
33            .map(|v| v.unwrap_or(Value::Null));
34    }
35    if name.eq_ignore_ascii_case("string_agg") {
36        let [value, delimiter] = args else {
37            return Err(SQLError::TypeMismatch(
38                "string_agg requires 2 arguments".into(),
39            ));
40        };
41        let value = eval_scalar(value, ctx)?;
42        let delimiter = eval_scalar(delimiter, ctx)?;
43        return Ok(if matches!(value, Value::Null) {
44            Value::Null
45        } else {
46            Value::List(vec![value, delimiter])
47        });
48    }
49    if is_json_object_aggregate(name) {
50        return match args {
51            [key_expr, value_expr] => {
52                let key = eval_scalar(key_expr, ctx)?;
53                if matches!(key, Value::Null) {
54                    return Err(json_object_aggregate_null_key(name));
55                }
56                let value = eval_scalar(value_expr, ctx)?;
57                Ok(Value::List(vec![key, value]))
58            }
59            _ => Err(SQLError::TypeMismatch(format!(
60                "{name} requires 2 arguments"
61            ))),
62        };
63    }
64    if is_json_array_aggregate(name) {
65        return match args {
66            [arg] => eval_scalar(arg, ctx),
67            _ => Err(SQLError::TypeMismatch(format!(
68                "{name} requires 1 argument"
69            ))),
70        };
71    }
72    let arg = args
73        .first()
74        .ok_or_else(|| SQLError::Internal("aggregate missing arg".into()))?;
75    eval_scalar(arg, ctx)
76}
77
78pub fn aggregate_input_values(
79    args: &[ScalarExpr],
80    ctx: &ScalarEvalContext<'_>,
81) -> Result<Vec<Value>, SQLError> {
82    args.iter()
83        .map(|arg| match arg {
84            ScalarExpr::Star => Ok(Value::Int(1)),
85            other => eval_scalar(other, ctx),
86        })
87        .collect()
88}
89
90pub fn new_aggregate_accumulators_with_budget(
91    context: &dyn crate::functions::AggregateFunctionRegistry,
92    aggregate_targets: &[ScalarExpr],
93    input_schema: &crate::RowSchema,
94    params: &[uqa_sql::SQLParam],
95    budget_bytes: usize,
96) -> Result<Vec<AggregateAccumulator>, SQLError> {
97    Ok(instantiate_aggregate_accumulators(
98        &aggregate_accumulator_templates(context, aggregate_targets, input_schema, params)?,
99        budget_bytes,
100    ))
101}
102
103pub fn aggregate_accumulator_templates(
104    context: &dyn crate::functions::AggregateFunctionRegistry,
105    aggregate_targets: &[ScalarExpr],
106    input_schema: &crate::RowSchema,
107    params: &[uqa_sql::SQLParam],
108) -> Result<Vec<AggregateAccumulatorTemplate>, SQLError> {
109    let has_enums = context
110        .enum_labels()
111        .is_some_and(uqa_sql::expr::enums::EnumLabelCatalog::has_enum_types);
112    aggregate_targets
113        .iter()
114        .map(|expression| match expression {
115            ScalarExpr::Func {
116                name,
117                args,
118                distinct,
119                order_by,
120                ..
121            } => {
122                let key_count = if has_enums {
123                    order_by.len() + usize::from(*distinct)
124                } else {
125                    0
126                };
127                if let Some(function) = context.registered_aggregate_function(name) {
128                    return Ok(
129                        AggregateAccumulatorTemplate::registered(function).with_ordering(key_count)
130                    );
131                }
132                let input_type = args
133                    .first()
134                    .map(|argument| {
135                        crate::scalar_type_with_resolver(argument, input_schema, params, context)
136                    })
137                    .transpose()?
138                    .flatten();
139                Ok(
140                    AggregateAccumulatorTemplate::builtin(name, input_type.as_ref())
141                        .with_ordering(key_count),
142                )
143            }
144            _ => Ok(AggregateAccumulatorTemplate::generic()),
145        })
146        .collect()
147}
148
149pub fn instantiate_aggregate_accumulators(
150    templates: &[AggregateAccumulatorTemplate],
151    budget_bytes: usize,
152) -> Vec<AggregateAccumulator> {
153    templates
154        .iter()
155        .map(|template| template.instantiate(budget_bytes))
156        .collect()
157}
158
159pub fn observe_aggregate(
160    acc: &mut AggregateAccumulator,
161    name: &str,
162    args: &[ScalarExpr],
163    distinct: bool,
164    order_by: &[ScalarOrder],
165    ctx: &ScalarEvalContext<'_>,
166) -> Result<(), SQLError> {
167    let enums = ctx
168        .function_hook()
169        .and_then(uqa_sql::expr::EngineHook::enum_labels);
170    if acc.registered.is_some() {
171        let values = uqa_sql::expr::enums::render_host_arguments(
172            ctx.function_hook()
173                .and_then(uqa_sql::expr::EngineHook::enum_labels),
174            &aggregate_input_values(args, ctx)?,
175        )?;
176        let mut sort_keys: Vec<super::ordering::AggregateSortKey> =
177            Vec::with_capacity(order_by.len());
178        for ob in order_by {
179            let v = eval_scalar(&ob.expr, ctx)?;
180            sort_keys.push(super::ordering::AggregateSortKey::ordered(v, ob));
181        }
182        if distinct {
183            return acc.distinct.insert(&Value::List(values), sort_keys, enums);
184        }
185        acc.observe_registered(values, sort_keys, enums)?;
186        return Ok(());
187    }
188
189    let value = aggregate_input_value(name, args, order_by, ctx)?;
190    observe_builtin_aggregate_value(acc, &value, distinct, order_by, ctx)
191}
192
193/// The accumulator's state plan decides whether a NULL input reaches the aggregate.
194pub fn observe_builtin_aggregate_value(
195    acc: &mut AggregateAccumulator,
196    value: &Value,
197    distinct: bool,
198    order_by: &[ScalarOrder],
199    ctx: &ScalarEvalContext<'_>,
200) -> Result<(), SQLError> {
201    let enums = ctx
202        .function_hook()
203        .and_then(uqa_sql::expr::EngineHook::enum_labels);
204    let mut sort_keys: Vec<super::ordering::AggregateSortKey> = Vec::with_capacity(order_by.len());
205    for ob in order_by {
206        let v = eval_scalar(&ob.expr, ctx)?;
207        sort_keys.push(super::ordering::AggregateSortKey::ordered(v, ob));
208    }
209    if distinct {
210        if acc.admits_null_input() || !matches!(value, Value::Null) {
211            acc.distinct.insert(value, sort_keys, enums)?;
212        }
213        return Ok(());
214    }
215    if order_by.is_empty() {
216        acc.observe_with_enum_catalog(value, enums)
217    } else {
218        acc.observe_with_sort_keys(value, sort_keys, enums)
219    }
220}
221
222pub fn is_json_array_aggregate(name: &str) -> bool {
223    name.eq_ignore_ascii_case("json_agg") || name.eq_ignore_ascii_case("jsonb_agg")
224}
225
226/// The transition-function error of `json_object_agg` and `jsonb_object_agg` for a NULL key.
227pub(super) fn json_object_aggregate_null_key(name: &str) -> SQLError {
228    if name.eq_ignore_ascii_case("jsonb_object_agg") {
229        SQLError::Routine {
230            sqlstate: "22023".into(),
231            message: "field name must not be null".into(),
232        }
233    } else {
234        SQLError::Routine {
235            sqlstate: "22004".into(),
236            message: "null value not allowed for object key".into(),
237        }
238    }
239}
240
241pub fn is_json_object_aggregate(name: &str) -> bool {
242    name.eq_ignore_ascii_case("json_object_agg") || name.eq_ignore_ascii_case("jsonb_object_agg")
243}
244
245pub fn is_ordered_set_aggregate(name: &str) -> bool {
246    name.eq_ignore_ascii_case("percentile_cont")
247        || name.eq_ignore_ascii_case("percentile_disc")
248        || name.eq_ignore_ascii_case("mode")
249}