Skip to main content

uqa_execution/aggregation/
template.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Aggregate call metadata and comparison support retained across groups, frames and spill restoration.
8
9use super::{AggregateAccumulator, AggregateStatePlan, SQLAggregateFactory};
10use std::sync::Arc;
11use uqa_sql::ast::ColumnType;
12use uqa_sql::expr::enums::EnumComparisonState;
13
14#[derive(Clone)]
15pub struct AggregateAccumulatorTemplate {
16    kind: AggregateKind,
17    extrema: Option<Arc<EnumComparisonState>>,
18    ordering: Option<Arc<[EnumComparisonState]>>,
19    ordering_types: Option<Arc<[Option<ColumnType>]>>,
20    distinct_arguments: Option<usize>,
21}
22
23#[derive(Clone)]
24enum AggregateKind {
25    Builtin(AggregateStatePlan),
26    Registered(Arc<dyn SQLAggregateFactory>),
27}
28
29impl AggregateAccumulatorTemplate {
30    pub(crate) fn builtin(name: &str, input_type: Option<&ColumnType>) -> Self {
31        Self {
32            kind: AggregateKind::Builtin(AggregateStatePlan::builtin_with_input_type(
33                name, input_type,
34            )),
35            extrema: enum_extrema_state(name, input_type),
36            ordering: None,
37            ordering_types: None,
38            distinct_arguments: None,
39        }
40    }
41
42    pub(super) fn generic() -> Self {
43        Self {
44            kind: AggregateKind::Builtin(AggregateStatePlan::Generic),
45            extrema: None,
46            ordering: None,
47            ordering_types: None,
48            distinct_arguments: None,
49        }
50    }
51
52    pub(super) fn registered(function: Arc<dyn SQLAggregateFactory>) -> Self {
53        Self {
54            kind: AggregateKind::Registered(function),
55            extrema: None,
56            ordering: None,
57            ordering_types: None,
58            distinct_arguments: None,
59        }
60    }
61
62    pub(super) fn with_ordering(mut self, keys: usize) -> Self {
63        if keys != 0 {
64            self.ordering = Some((0..keys).map(|_| EnumComparisonState::default()).collect());
65        }
66        self
67    }
68
69    pub(super) fn with_ordering_types(mut self, types: Vec<Option<ColumnType>>) -> Self {
70        if !types.is_empty() {
71            self.ordering_types = Some(types.into());
72        }
73        self
74    }
75
76    pub(super) fn with_distinct_arguments(mut self, count: usize) -> Self {
77        self.distinct_arguments = Some(count);
78        self
79    }
80
81    pub(super) fn state_plan(&self) -> Option<AggregateStatePlan> {
82        match self.kind {
83            AggregateKind::Builtin(plan) => Some(plan),
84            AggregateKind::Registered(_) => None,
85        }
86    }
87
88    pub(crate) fn instantiate(
89        &self,
90        budget_bytes: usize,
91    ) -> Result<AggregateAccumulator, uqa_sql::SQLError> {
92        let mut accumulator = match &self.kind {
93            AggregateKind::Builtin(plan) => {
94                AggregateAccumulator::from_plan_with_budget(*plan, budget_bytes)
95            }
96            AggregateKind::Registered(function) => {
97                AggregateAccumulator::registered_with_budget(Arc::clone(function), budget_bytes)?
98            }
99        };
100        self.restore_comparison(&mut accumulator);
101        Ok(accumulator)
102    }
103
104    pub(super) fn restore_comparison(&self, accumulator: &mut AggregateAccumulator) {
105        accumulator.enum_comparison.clone_from(&self.extrema);
106        accumulator.distinct.argument_count = self.distinct_arguments;
107        accumulator
108            .values
109            .key_types
110            .clone_from(&self.ordering_types);
111        accumulator
112            .distinct
113            .values
114            .key_types
115            .clone_from(&self.ordering_types);
116        accumulator
117            .registered_ordered
118            .key_types
119            .clone_from(&self.ordering_types);
120        accumulator
121            .values
122            .comparison_states
123            .clone_from(&self.ordering);
124        accumulator
125            .distinct
126            .values
127            .comparison_states
128            .clone_from(&self.ordering);
129        accumulator
130            .registered_ordered
131            .comparison_states
132            .clone_from(&self.ordering);
133    }
134}
135
136pub(super) fn enum_extrema_state(
137    name: &str,
138    input_type: Option<&ColumnType>,
139) -> Option<Arc<EnumComparisonState>> {
140    let name = uqa_sql::semantics::builtin_aggregate_dispatch_name(name);
141    if let Some(ColumnType::Domain { base, .. }) = input_type {
142        return enum_extrema_state(name, Some(base));
143    }
144    ((name.eq_ignore_ascii_case("min") || name.eq_ignore_ascii_case("max"))
145        && matches!(input_type, Some(ColumnType::Enum(_))))
146    .then(|| Arc::new(EnumComparisonState::default()))
147}