Skip to main content

uqa_execution/aggregation/
distinct.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Bounded, ordered DISTINCT input and aggregate value comparisons.
8
9use super::{AggregateValueBuffer, SQLError, Value};
10use uqa_core::memory::ProductionControl;
11use uqa_sql::expr::enums::EnumLabelCatalog;
12
13/// Aggregate DISTINCT uses SQL ordering before eliminating adjacent equal inputs.
14/// Reusing sorted runs keeps both comparisons and spill behavior fallible.
15pub struct DistinctTracker {
16    pub(super) values: AggregateValueBuffer,
17}
18
19impl Default for DistinctTracker {
20    fn default() -> Self {
21        Self::new(32 * 1024 * 1024)
22    }
23}
24
25impl DistinctTracker {
26    pub(super) fn new(budget_bytes: usize) -> Self {
27        Self {
28            values: AggregateValueBuffer::new(budget_bytes),
29        }
30    }
31
32    pub(super) fn is_empty(&self) -> bool {
33        self.values.next_sequence == 0
34    }
35
36    pub(super) fn insert(
37        &mut self,
38        value: &Value,
39        mut sort_keys: Vec<super::ordering::AggregateSortKey>,
40        enums: Option<&dyn EnumLabelCatalog>,
41    ) -> Result<(), SQLError> {
42        // Explicit ORDER BY keys come first; the complete argument tuple resolves their ties.
43        sort_keys.push(super::ordering::AggregateSortKey::ascending(value.clone()));
44        self.values.push(value.clone(), sort_keys, enums)
45    }
46
47    pub(super) fn for_each(
48        &self,
49        enums: Option<&dyn EnumLabelCatalog>,
50        mut observe: impl FnMut(&Value) -> Result<(), SQLError>,
51    ) -> Result<(), SQLError> {
52        let mut previous: Option<Value> = None;
53        self.values.for_each_ordered(enums, |record| {
54            if let Some(previous) = &previous {
55                if uqa_sql::expr::equal_typed_values_with_enum_catalog(
56                    previous,
57                    &record.value,
58                    &ProductionControl::uncontrolled(),
59                    enums,
60                )? {
61                    return Ok(());
62                }
63            }
64            observe(&record.value)?;
65            previous = Some(record.value);
66            Ok(())
67        })
68    }
69}
70
71pub fn value_as_f64(v: &Value) -> Result<f64, SQLError> {
72    match v {
73        Value::Int(n) => Ok(*n as f64),
74        Value::Float(f) => Ok(*f),
75        Value::Decimal(d) => d.to_f64().ok_or_else(|| {
76            SQLError::TypeMismatch(format!("expected number that fits float, got {v:?}"))
77        }),
78        other => Err(SQLError::TypeMismatch(format!(
79            "expected number, got {other:?}"
80        ))),
81    }
82}
83
84pub fn value_lt(a: &Value, b: &Value) -> Result<bool, SQLError> {
85    Ok(match (a, b) {
86        (
87            Value::Int(_) | Value::Float(_) | Value::Decimal(_),
88            Value::Int(_) | Value::Float(_) | Value::Decimal(_),
89        ) => a < b,
90        (Value::Str(x), Value::Str(y)) => x < y,
91        (Value::FixedChar(x), Value::FixedChar(y)) => x.trim_end() < y.trim_end(),
92        (Value::Bytes(x), Value::Bytes(y)) => x < y,
93        (Value::Temporal(x), Value::Temporal(y)) => x < y,
94        // PostgreSQL MIN/MAX bind array_smaller/array_larger for catalog vectors; OID-vector scalar operators use a different order.
95        (Value::LegacyVector(left), Value::LegacyVector(right)) => {
96            left.compare_as_array(right).is_lt()
97        }
98        (Value::Array(_), Value::Array(_))
99        | (Value::List(_), Value::List(_))
100        | (Value::Row(_), Value::Row(_))
101        | (Value::Record(_), Value::Record(_)) => super::compare_extrema(a, b)?.is_lt(),
102        (Value::Map(x), Value::Map(y)) => x < y,
103        // MIN and MAX over `anyenum` use `enum_smaller` and `enum_larger`: label keys in declaration order.
104        (Value::Enum(x), Value::Enum(y)) => {
105            if x.type_oid() != y.type_oid() {
106                return Err(SQLError::Internal(format!(
107                    "MIN/MAX received enum type OIDs {} and {}",
108                    x.type_oid(),
109                    y.type_oid()
110                )));
111            }
112            x.key() < y.key()
113        }
114        _ => false,
115    })
116}
117
118pub fn value_gt(a: &Value, b: &Value) -> Result<bool, SQLError> {
119    value_lt(b, a)
120}