Skip to main content

uqa_execution/aggregation/
accumulator.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Streaming aggregate state and registered aggregate adapters.
8
9use super::{
10    value_as_f64, AggregateValueBuffer, Arc, DecimalValue, DistinctTracker,
11    RegisteredAggregateBuffer, SQLAggregateFunction, SQLAggregateState, SQLError, Value,
12};
13use uqa_core::TemporalInfinity;
14use uqa_sql::expr::enums::{EnumComparisonState, EnumLabelCatalog};
15use uqa_sql::expr::IntervalFields;
16
17pub struct AggregateAccumulator {
18    pub(super) registered: Option<Arc<dyn SQLAggregateFunction>>,
19    pub(super) registered_state: Option<Box<dyn SQLAggregateState>>,
20    pub(super) registered_ordered: RegisteredAggregateBuffer,
21    pub(super) count: u64,
22    pub(super) sum: f64,
23    pub(super) integer_sum: i128,
24    pub(super) decimal_sum: Option<DecimalValue>,
25    /// The finite `sumX` of `sum(interval)` and `avg(interval)`; infinite inputs are counted separately.
26    pub(super) interval_sum: Option<IntervalFields>,
27    pub(super) interval_positive_infinity: u64,
28    pub(super) interval_negative_infinity: u64,
29    pub(super) numeric_inputs: NumericInputKind,
30    pub(super) min: Option<Value>,
31    pub(super) max: Option<Value>,
32    /// MIN/MAX's transition support function belongs to the call, across groups and frame restarts.
33    pub(super) enum_comparison: Option<Arc<EnumComparisonState>>,
34    /// DISTINCT arguments are sorted with their SQL comparison operators before finalization.
35    pub(super) distinct: DistinctTracker,
36    /// Only collection, ordered-set, and statistical aggregates need
37    /// their complete input. Streaming aggregates keep constant-size
38    /// state and must not spill values that their finalizer never reads.
39    pub(super) state_plan: AggregateStatePlan,
40    pub(super) values: AggregateValueBuffer,
41    /// Shape of the first `array_agg(anyarray)` input observed in transition order.
42    pub(super) array_inputs: super::array_inputs::ArrayInputShape,
43    /// Boolean folds for `BOOL_AND` / `BOOL_OR`. Stay `None` until the
44    /// first observation so an empty input set returns `NULL` (matches
45    /// `PostgreSQL`).
46    pub(super) bool_and: Option<bool>,
47    pub(super) bool_or: Option<bool>,
48    /// Welford state for variance/stddev. This avoids retaining the complete group for statistical aggregates.
49    pub(super) statistics_count: u64,
50    pub(super) statistics_mean: f64,
51    pub(super) statistics_m2: f64,
52    pub(super) statistics_moments_valid: bool,
53    pub(super) statistics_has_float: bool,
54    pub(super) statistics_nonzero_deviation: bool,
55    pub(super) statistics_origin: Option<DecimalValue>,
56    pub(super) statistics_sum: Option<DecimalValue>,
57    pub(super) statistics_sum_squares: Option<DecimalValue>,
58}
59
60#[derive(Clone, Copy, Default)]
61pub enum NumericInputKind {
62    #[default]
63    Integers,
64    Decimals,
65    Floats,
66    DecimalsAndFloats,
67}
68
69impl NumericInputKind {
70    pub(super) fn observe_decimal(&mut self) {
71        *self = match self {
72            Self::Integers | Self::Decimals => Self::Decimals,
73            Self::Floats | Self::DecimalsAndFloats => Self::DecimalsAndFloats,
74        };
75    }
76
77    pub(super) fn observe_float(&mut self) {
78        *self = match self {
79            Self::Integers | Self::Floats => Self::Floats,
80            Self::Decimals | Self::DecimalsAndFloats => Self::DecimalsAndFloats,
81        };
82    }
83
84    pub(super) fn all_integers(self) -> bool {
85        matches!(self, Self::Integers)
86    }
87
88    pub(super) fn decimal_without_float(self) -> bool {
89        matches!(self, Self::Decimals)
90    }
91
92    pub(super) fn has_decimal(self) -> bool {
93        matches!(self, Self::Decimals | Self::DecimalsAndFloats)
94    }
95
96    pub(super) fn has_float(self) -> bool {
97        matches!(self, Self::Floats | Self::DecimalsAndFloats)
98    }
99}
100
101#[derive(Clone, Copy)]
102pub enum AggregateStatePlan {
103    /// Conservative fallback for an aggregate whose state requirements
104    /// are not known here.
105    Generic,
106    Count,
107    Sum,
108    SumReal,
109    Min,
110    Max,
111    BoolAnd,
112    BoolOr,
113    /// Retains non-NULL inputs: `string_agg`, the ordered-set aggregates and the JSON object aggregates, whose pairs are never NULL.
114    Buffered,
115    /// Retains every input including NULL, as `array_agg` over non-array input, `json_agg` and `jsonb_agg` do.
116    BufferedWithNulls,
117    /// `array_agg` over array input, whose transition rejects NULL, empty and differently shaped arrays.
118    BufferedArrays,
119    Statistics,
120}
121
122impl AggregateStatePlan {
123    pub(super) fn builtin_with_input_type(
124        name: &str,
125        input_type: Option<&uqa_sql::ast::ColumnType>,
126    ) -> Self {
127        use uqa_sql::ast::ColumnType;
128        if let Some(ColumnType::Domain { base, .. }) = input_type {
129            return Self::builtin_with_input_type(name, Some(base));
130        }
131        if name.eq_ignore_ascii_case("sum") && matches!(input_type, Some(ColumnType::Real)) {
132            Self::SumReal
133        } else if name.eq_ignore_ascii_case("array_agg")
134            && matches!(input_type, Some(ColumnType::Array(_)))
135        {
136            Self::BufferedArrays
137        } else {
138            Self::builtin(name)
139        }
140    }
141
142    pub(super) fn builtin(name: &str) -> Self {
143        match name.to_ascii_lowercase().as_str() {
144            "count" => Self::Count,
145            "sum" | "avg" => Self::Sum,
146            "min" => Self::Min,
147            "max" => Self::Max,
148            "bool_and" => Self::BoolAnd,
149            "bool_or" => Self::BoolOr,
150            "stddev" | "stddev_samp" | "stddev_pop" | "variance" | "var_samp" | "var_pop" => {
151                Self::Statistics
152            }
153            "array_agg" | "json_agg" | "jsonb_agg" => Self::BufferedWithNulls,
154            "string_agg" | "json_object_agg" | "jsonb_object_agg" | "percentile_cont"
155            | "percentile_disc" | "mode" => Self::Buffered,
156            _ => Self::Generic,
157        }
158    }
159
160    pub(super) fn retains_values(self) -> bool {
161        matches!(
162            self,
163            Self::Generic | Self::Buffered | Self::BufferedWithNulls | Self::BufferedArrays
164        )
165    }
166}
167
168impl Default for AggregateAccumulator {
169    fn default() -> Self {
170        Self {
171            registered: None,
172            registered_state: None,
173            registered_ordered: RegisteredAggregateBuffer::default(),
174            count: 0,
175            sum: 0.0,
176            integer_sum: 0,
177            decimal_sum: None,
178            interval_sum: None,
179            interval_positive_infinity: 0,
180            interval_negative_infinity: 0,
181            numeric_inputs: NumericInputKind::default(),
182            min: None,
183            max: None,
184            enum_comparison: None,
185            distinct: DistinctTracker::default(),
186            state_plan: AggregateStatePlan::Generic,
187            values: AggregateValueBuffer::default(),
188            array_inputs: super::array_inputs::ArrayInputShape::default(),
189            bool_and: None,
190            bool_or: None,
191            statistics_count: 0,
192            statistics_mean: 0.0,
193            statistics_m2: 0.0,
194            statistics_moments_valid: true,
195            statistics_has_float: false,
196            statistics_nonzero_deviation: false,
197            statistics_origin: None,
198            statistics_sum: None,
199            statistics_sum_squares: None,
200        }
201    }
202}
203
204impl AggregateAccumulator {
205    pub(super) fn with_budget(budget_bytes: usize) -> Self {
206        let component_budget = (budget_bytes / 2).max(1);
207        Self {
208            registered: None,
209            registered_state: None,
210            registered_ordered: RegisteredAggregateBuffer::new(component_budget),
211            count: 0,
212            sum: 0.0,
213            integer_sum: 0,
214            decimal_sum: None,
215            interval_sum: None,
216            interval_positive_infinity: 0,
217            interval_negative_infinity: 0,
218            numeric_inputs: NumericInputKind::default(),
219            min: None,
220            max: None,
221            enum_comparison: None,
222            distinct: DistinctTracker::new(component_budget),
223            state_plan: AggregateStatePlan::Generic,
224            values: AggregateValueBuffer::new(component_budget),
225            array_inputs: super::array_inputs::ArrayInputShape::default(),
226            bool_and: None,
227            bool_or: None,
228            statistics_count: 0,
229            statistics_mean: 0.0,
230            statistics_m2: 0.0,
231            statistics_moments_valid: true,
232            statistics_has_float: false,
233            statistics_nonzero_deviation: false,
234            statistics_origin: None,
235            statistics_sum: None,
236            statistics_sum_squares: None,
237        }
238    }
239
240    pub fn builtin(name: &str) -> Self {
241        Self {
242            state_plan: AggregateStatePlan::builtin(name),
243            ..Self::default()
244        }
245    }
246
247    pub fn builtin_with_input_type(
248        name: &str,
249        input_type: Option<&uqa_sql::ast::ColumnType>,
250    ) -> Self {
251        let mut accumulator = Self::builtin(name);
252        accumulator.state_plan = AggregateStatePlan::builtin_with_input_type(name, input_type);
253        accumulator.enum_comparison = super::template::enum_extrema_state(name, input_type);
254        accumulator
255    }
256
257    pub(super) fn builtin_with_budget(name: &str, budget_bytes: usize) -> Self {
258        Self::from_plan_with_budget(AggregateStatePlan::builtin(name), budget_bytes)
259    }
260
261    pub(super) fn from_plan_with_budget(
262        state_plan: AggregateStatePlan,
263        budget_bytes: usize,
264    ) -> Self {
265        let mut accumulator = Self::with_budget(budget_bytes);
266        accumulator.state_plan = state_plan;
267        accumulator
268    }
269
270    pub(super) fn registered_with_budget(
271        function: Arc<dyn SQLAggregateFunction>,
272        budget_bytes: usize,
273    ) -> Self {
274        let state = function.create_state();
275        let mut accumulator = Self::with_budget(budget_bytes);
276        accumulator.registered = Some(function);
277        accumulator.registered_state = Some(state);
278        accumulator
279    }
280
281    pub fn observe(&mut self, value: &Value) -> Result<(), SQLError> {
282        self.observe_with_enum_catalog(value, None)
283    }
284
285    pub fn observe_with_enum_catalog(
286        &mut self,
287        value: &Value,
288        enums: Option<&dyn EnumLabelCatalog>,
289    ) -> Result<(), SQLError> {
290        if let AggregateStatePlan::BufferedArrays = self.state_plan {
291            self.array_inputs.accept(value)?;
292        }
293        if matches!(value, Value::Null) {
294            return self.observe_null(Vec::new(), enums);
295        }
296        self.observe_state(value, enums)?;
297        if self.state_plan.retains_values() {
298            self.values.push(value.clone(), Vec::new(), enums)?;
299        }
300        Ok(())
301    }
302
303    pub(super) fn observe_projected(
304        &mut self,
305        value: &Value,
306        enums: Option<&dyn EnumLabelCatalog>,
307    ) -> Result<(), SQLError> {
308        match value {
309            Value::Int(value) => self.observe_projected_integer(*value),
310            _ => self.observe_with_enum_catalog(value, enums),
311        }
312    }
313
314    pub(super) fn observe_projected_integer(&mut self, value: i64) -> Result<(), SQLError> {
315        match self.state_plan {
316            AggregateStatePlan::Count => {
317                self.count = self
318                    .count
319                    .checked_add(1)
320                    .ok_or_else(|| SQLError::TypeMismatch("aggregate count overflow".into()))?;
321                Ok(())
322            }
323            AggregateStatePlan::Sum | AggregateStatePlan::SumReal => {
324                self.count = self
325                    .count
326                    .checked_add(1)
327                    .ok_or_else(|| SQLError::TypeMismatch("aggregate count overflow".into()))?;
328                self.integer_sum = self
329                    .integer_sum
330                    .checked_add(i128::from(value))
331                    .ok_or_else(|| SQLError::TypeMismatch("integer aggregate overflow".into()))?;
332                if self.numeric_inputs.has_decimal() {
333                    let next = DecimalValue::from_i64(value);
334                    self.decimal_sum = Some(
335                        self.decimal_sum
336                            .as_ref()
337                            .and_then(|sum| sum.checked_add(&next))
338                            .ok_or_else(|| {
339                                SQLError::TypeMismatch("decimal aggregate overflow".into())
340                            })?,
341                    );
342                }
343                if self.numeric_inputs.has_float() {
344                    self.sum += value as f64;
345                }
346                Ok(())
347            }
348            _ => self.observe(&Value::Int(value)),
349        }
350    }
351
352    pub(super) fn observe_state(
353        &mut self,
354        value: &Value,
355        enums: Option<&dyn EnumLabelCatalog>,
356    ) -> Result<(), SQLError> {
357        match self.state_plan {
358            AggregateStatePlan::Generic => {
359                self.count = self
360                    .count
361                    .checked_add(1)
362                    .ok_or_else(|| SQLError::TypeMismatch("aggregate count overflow".into()))?;
363                if matches!(value, Value::Int(_) | Value::Float(_) | Value::Decimal(_)) {
364                    self.observe_sum(value)?;
365                }
366                self.observe_min(value, enums)?;
367                self.observe_max(value, enums)?;
368                if matches!(value, Value::Bool(_)) {
369                    self.observe_bool_and(value)?;
370                    self.observe_bool_or(value)?;
371                }
372            }
373            AggregateStatePlan::Count => {
374                self.count = self
375                    .count
376                    .checked_add(1)
377                    .ok_or_else(|| SQLError::TypeMismatch("aggregate count overflow".into()))?;
378            }
379            AggregateStatePlan::Sum | AggregateStatePlan::SumReal => {
380                self.count = self
381                    .count
382                    .checked_add(1)
383                    .ok_or_else(|| SQLError::TypeMismatch("aggregate count overflow".into()))?;
384                self.observe_sum(value)?;
385            }
386            AggregateStatePlan::Min => self.observe_min(value, enums)?,
387            AggregateStatePlan::Max => self.observe_max(value, enums)?,
388            AggregateStatePlan::BoolAnd => self.observe_bool_and(value)?,
389            AggregateStatePlan::BoolOr => self.observe_bool_or(value)?,
390            AggregateStatePlan::Buffered
391            | AggregateStatePlan::BufferedWithNulls
392            | AggregateStatePlan::BufferedArrays => {}
393            AggregateStatePlan::Statistics => self.observe_statistics(value)?,
394        }
395        Ok(())
396    }
397
398    fn observe_statistics(&mut self, value: &Value) -> Result<(), SQLError> {
399        let previous_count = self.statistics_count;
400        let next_count = previous_count
401            .checked_add(1)
402            .ok_or_else(|| SQLError::TypeMismatch("statistical aggregate count overflow".into()))?;
403        if matches!(value, Value::Float(_)) {
404            if !self.statistics_moments_valid {
405                return Err(SQLError::TypeMismatch(
406                    "numeric statistical state does not fit double precision".into(),
407                ));
408            }
409            self.statistics_has_float = true;
410            self.observe_float_statistic(value_as_f64(value)?, next_count);
411        } else {
412            let decimal = match value {
413                Value::Int(value) => DecimalValue::from_i64(*value),
414                Value::Decimal(value) => value.clone(),
415                other => {
416                    return Err(SQLError::TypeMismatch(format!(
417                        "statistical aggregate requires a numeric value, got {other:?}"
418                    )))
419                }
420            };
421            if self.statistics_moments_valid {
422                if let Some(float) = decimal.to_f64() {
423                    self.observe_float_statistic(float, next_count);
424                } else {
425                    self.statistics_moments_valid = false;
426                    if self.statistics_has_float {
427                        return Err(SQLError::TypeMismatch(
428                            "numeric statistical input does not fit double precision".into(),
429                        ));
430                    }
431                }
432            }
433            if decimal.is_nan() || decimal.is_infinite() {
434                let nan = decimal.checked_sub(&decimal).ok_or_else(|| {
435                    SQLError::Internal("numeric special value did not produce NaN".into())
436                })?;
437                self.statistics_origin
438                    .get_or_insert_with(|| DecimalValue::from_i64(0));
439                self.statistics_sum = Some(nan.clone());
440                self.statistics_sum_squares = Some(nan);
441                self.statistics_nonzero_deviation = true;
442                self.statistics_count = next_count;
443                return Ok(());
444            }
445            if self
446                .statistics_sum_squares
447                .as_ref()
448                .is_some_and(DecimalValue::is_nan)
449            {
450                self.statistics_count = next_count;
451                return Ok(());
452            }
453            let origin = if let Some(origin) = &self.statistics_origin {
454                origin.clone()
455            } else {
456                let origin = decimal.clone();
457                self.statistics_origin = Some(origin.clone());
458                origin
459            };
460            let deviation = decimal.checked_sub(&origin).ok_or_else(|| {
461                SQLError::TypeMismatch("numeric statistical deviation overflow".into())
462            })?;
463            self.statistics_nonzero_deviation |= !deviation.is_zero();
464            let square = deviation.checked_mul(&deviation).ok_or_else(|| {
465                SQLError::TypeMismatch("numeric statistical deviation square overflow".into())
466            })?;
467            self.statistics_sum = Some(match self.statistics_sum.take() {
468                Some(sum) => sum.checked_add(&deviation).ok_or_else(|| {
469                    SQLError::TypeMismatch("numeric statistical deviation sum overflow".into())
470                })?,
471                None => deviation,
472            });
473            self.statistics_sum_squares = Some(match self.statistics_sum_squares.take() {
474                Some(sum) => sum.checked_add(&square).ok_or_else(|| {
475                    SQLError::TypeMismatch(
476                        "numeric statistical deviation square sum overflow".into(),
477                    )
478                })?,
479                None => square,
480            });
481        }
482        self.statistics_count = next_count;
483        Ok(())
484    }
485
486    fn observe_float_statistic(&mut self, value: f64, count: u64) {
487        let delta = value - self.statistics_mean;
488        self.statistics_mean += delta / count as f64;
489        let delta_after = value - self.statistics_mean;
490        self.statistics_m2 += delta * delta_after;
491    }
492
493    pub(super) fn observe_sum(&mut self, value: &Value) -> Result<(), SQLError> {
494        if let Value::Temporal(temporal) = value {
495            let interval = IntervalFields::of(temporal).ok_or_else(|| {
496                SQLError::TypeMismatch(format!(
497                    "SUM/AVG requires a numeric or interval value, got {value:?}"
498                ))
499            })?;
500            if let Some(infinity) = temporal.infinity() {
501                let count = match infinity {
502                    TemporalInfinity::Positive => &mut self.interval_positive_infinity,
503                    TemporalInfinity::Negative => &mut self.interval_negative_infinity,
504                };
505                *count = count
506                    .checked_add(1)
507                    .ok_or_else(|| SQLError::TypeMismatch("aggregate count overflow".into()))?;
508                return Ok(());
509            }
510            self.interval_sum = Some(
511                self.interval_sum
512                    .unwrap_or(IntervalFields::ZERO)
513                    .plus(interval)?,
514            );
515            return Ok(());
516        }
517        if !matches!(value, Value::Int(_) | Value::Float(_) | Value::Decimal(_)) {
518            return Err(SQLError::TypeMismatch(format!(
519                "SUM/AVG requires a numeric or interval value, got {value:?}"
520            )));
521        }
522        match value {
523            Value::Int(n) => {
524                self.integer_sum = self
525                    .integer_sum
526                    .checked_add(i128::from(*n))
527                    .ok_or_else(|| SQLError::TypeMismatch("integer aggregate overflow".into()))?;
528                if self.numeric_inputs.has_decimal() {
529                    let next = DecimalValue::from_i64(*n);
530                    self.decimal_sum = Some(
531                        self.decimal_sum
532                            .as_ref()
533                            .and_then(|sum| sum.checked_add(&next))
534                            .ok_or_else(|| {
535                                SQLError::TypeMismatch("decimal aggregate overflow".into())
536                            })?,
537                    );
538                }
539                if self.numeric_inputs.has_float() {
540                    self.sum += *n as f64;
541                }
542            }
543            Value::Decimal(d) => {
544                let next = match &self.decimal_sum {
545                    Some(sum) => sum.checked_add(d),
546                    None if self.integer_sum == 0 => Some(d.clone()),
547                    None => {
548                        DecimalValue::from_i128(self.integer_sum).and_then(|sum| sum.checked_add(d))
549                    }
550                }
551                .ok_or_else(|| SQLError::TypeMismatch("decimal aggregate overflow".into()))?;
552                self.decimal_sum = Some(next);
553                if self.numeric_inputs.has_float() {
554                    self.sum += d.to_f64().ok_or_else(|| {
555                        SQLError::TypeMismatch("decimal aggregate does not fit float".into())
556                    })?;
557                }
558                self.numeric_inputs.observe_decimal();
559            }
560            Value::Float(value) => {
561                if !self.numeric_inputs.has_float() {
562                    // Exact integer/decimal aggregates do not maintain a shadow
563                    // floating total. Convert the accumulated total only if a
564                    // floating input actually makes it necessary.
565                    self.sum = if self.numeric_inputs.has_decimal() {
566                        self.decimal_sum
567                            .as_ref()
568                            .and_then(DecimalValue::to_f64)
569                            .ok_or_else(|| {
570                                SQLError::TypeMismatch(
571                                    "decimal aggregate does not fit float".into(),
572                                )
573                            })?
574                    } else {
575                        self.integer_sum as f64
576                    };
577                }
578                self.sum = if self.count == 1 {
579                    *value
580                } else {
581                    self.combine_float_sum(self.sum, *value)?
582                };
583                self.numeric_inputs.observe_float();
584            }
585            _ => {
586                return Err(SQLError::TypeMismatch(format!(
587                    "SUM/AVG requires a numeric or interval value, got {value:?}"
588                )))
589            }
590        }
591        Ok(())
592    }
593
594    /// Select the interval result after all transitions, preserving finite overflow and later input errors even when both signs of infinity have been seen.
595    pub(super) fn interval_result(&self) -> Result<Option<IntervalFields>, SQLError> {
596        let infinity = match (
597            self.interval_positive_infinity != 0,
598            self.interval_negative_infinity != 0,
599        ) {
600            (true, true) => {
601                return Err(SQLError::Routine {
602                    sqlstate: "22008".into(),
603                    message: "interval out of range".into(),
604                })
605            }
606            (true, false) => Some(TemporalInfinity::Positive),
607            (false, true) => Some(TemporalInfinity::Negative),
608            (false, false) => None,
609        };
610        Ok(infinity.map_or(self.interval_sum, |value| {
611            IntervalFields::of(&value.interval())
612        }))
613    }
614
615    pub(super) fn combine_float_sum(&self, left: f64, right: f64) -> Result<f64, SQLError> {
616        use uqa_sql::expr::{eval_float_arithmetic, FloatWidth};
617        let width = if matches!(self.state_plan, AggregateStatePlan::SumReal) {
618            FloatWidth::Real
619        } else {
620            FloatWidth::DoublePrecision
621        };
622        match eval_float_arithmetic(
623            uqa_sql::ast::BinaryOp::Add,
624            &Value::Float(left),
625            &Value::Float(right),
626            width,
627        )? {
628            Value::Float(value) => Ok(value),
629            _ => Err(SQLError::Internal(
630                "floating sum lost its numeric carrier".into(),
631            )),
632        }
633    }
634
635    pub(super) fn observe_min(
636        &mut self,
637        value: &Value,
638        enums: Option<&dyn EnumLabelCatalog>,
639    ) -> Result<(), SQLError> {
640        match &self.min {
641            Some(cur)
642                if !super::ordering::compare_extrema_with_catalog(
643                    cur,
644                    value,
645                    enums,
646                    self.enum_comparison.as_deref(),
647                )?
648                .is_gt() => {}
649            _ => self.min = Some(value.clone()),
650        }
651        Ok(())
652    }
653
654    pub(super) fn observe_max(
655        &mut self,
656        value: &Value,
657        enums: Option<&dyn EnumLabelCatalog>,
658    ) -> Result<(), SQLError> {
659        match &self.max {
660            Some(cur)
661                if !super::ordering::compare_extrema_with_catalog(
662                    cur,
663                    value,
664                    enums,
665                    self.enum_comparison.as_deref(),
666                )?
667                .is_lt() => {}
668            _ => self.max = Some(value.clone()),
669        }
670        Ok(())
671    }
672
673    pub(super) fn observe_bool_and(&mut self, value: &Value) -> Result<(), SQLError> {
674        let Value::Bool(value) = value else {
675            return Err(SQLError::TypeMismatch(format!(
676                "BOOL_AND requires a boolean value, got {value:?}"
677            )));
678        };
679        self.bool_and = Some(self.bool_and.unwrap_or(true) && *value);
680        Ok(())
681    }
682
683    pub(super) fn observe_bool_or(&mut self, value: &Value) -> Result<(), SQLError> {
684        let Value::Bool(value) = value else {
685            return Err(SQLError::TypeMismatch(format!(
686                "BOOL_OR requires a boolean value, got {value:?}"
687            )));
688        };
689        self.bool_or = Some(self.bool_or.unwrap_or(false) || *value);
690        Ok(())
691    }
692
693    /// Ordered inputs reach the transition only after sorting, so array inputs are checked when the aggregate finishes.
694    pub(super) fn observe_with_sort_keys(
695        &mut self,
696        value: &Value,
697        keys: Vec<super::ordering::AggregateSortKey>,
698        enums: Option<&dyn EnumLabelCatalog>,
699    ) -> Result<(), SQLError> {
700        if matches!(value, Value::Null) {
701            return match self.state_plan {
702                AggregateStatePlan::BufferedArrays => self.values.push(Value::Null, keys, enums),
703                _ => self.observe_null(keys, enums),
704            };
705        }
706        if self.state_plan.retains_values() {
707            self.observe_state(value, enums)?;
708        }
709        self.values.push(value.clone(), keys, enums)?;
710        Ok(())
711    }
712
713    /// A NULL input is part of the aggregate's input only for aggregates that retain NULLs.
714    fn observe_null(
715        &mut self,
716        keys: Vec<super::ordering::AggregateSortKey>,
717        enums: Option<&dyn EnumLabelCatalog>,
718    ) -> Result<(), SQLError> {
719        match self.state_plan {
720            AggregateStatePlan::BufferedWithNulls => self.values.push(Value::Null, keys, enums),
721            _ => Ok(()),
722        }
723    }
724
725    /// Whether DISTINCT keeps a NULL input. Array accumulation rejects it when the transition sees it.
726    pub(super) fn admits_null_input(&self) -> bool {
727        matches!(
728            self.state_plan,
729            AggregateStatePlan::BufferedWithNulls | AggregateStatePlan::BufferedArrays
730        )
731    }
732
733    pub(super) fn observe_registered(
734        &mut self,
735        values: Vec<Value>,
736        sort_keys: Vec<super::ordering::AggregateSortKey>,
737        enums: Option<&dyn EnumLabelCatalog>,
738    ) -> Result<(), SQLError> {
739        if sort_keys.is_empty() {
740            let state = self
741                .registered_state
742                .as_mut()
743                .ok_or_else(|| SQLError::Internal("registered aggregate state missing".into()))?;
744            state.observe(&values)?;
745            return Ok(());
746        }
747        self.registered_ordered.push(values, sort_keys, enums)
748    }
749
750    pub(super) fn registered_value(
751        &self,
752        enums: Option<&dyn EnumLabelCatalog>,
753    ) -> Option<Result<Value, SQLError>> {
754        let function = self.registered.as_ref()?;
755        if self.registered_ordered.is_empty() {
756            let state = self
757                .registered_state
758                .as_ref()
759                .ok_or_else(|| SQLError::Internal("registered aggregate state missing".into()));
760            return Some(state.and_then(|state| state.finish()));
761        }
762        Some((|| {
763            let mut state = function.create_state();
764            self.registered_ordered
765                .observe_ordered_into(state.as_mut(), enums)?;
766            state.finish()
767        })())
768    }
769}