Skip to main content

uqa_sql/expr/range/
typed.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Selected SQL identities preserve admitted range fields through text and physical readers.
8
9use super::{
10    parse_multirange_with_control, parse_range_with_control, CanonicalMultirange, CanonicalRange,
11    Ordering, Produced, ProductionControl, Result, SQLError, Value,
12};
13use crate::{expr::SQLValueCatalog, ColumnType};
14
15/// Admitted range bounds shared by comparison and exact SQL equality-key consumers. Parsing and normalization retain the caller's reservations until this value is released.
16pub enum RangeComparisonValue {
17    Range(Produced<CanonicalRange>),
18    Multirange(Produced<CanonicalMultirange>),
19    DeclaredRange(Produced<CanonicalRange<u32>>),
20    DeclaredMultirange(Produced<CanonicalMultirange<u32>>),
21}
22
23impl RangeComparisonValue {
24    /// Declared ranges carry an unambiguous physical SQL identity. Native text carriers still require their selected field type, so ordinary text does not acquire range comparison or key semantics from another operand.
25    pub fn declared_physical_oid(
26        value: &Value,
27        catalog: Option<&dyn SQLValueCatalog>,
28    ) -> Result<Option<u32>> {
29        let Value::Datum(datum) = value else {
30            return Ok(None);
31        };
32        let oid = datum.type_oid();
33        if crate::catalog::type_metadata::builtin_scalar_type(oid).is_some() {
34            return Ok(None);
35        }
36        Ok(catalog
37            .map(|catalog| catalog.value_range_type(oid))
38            .transpose()?
39            .flatten()
40            .map(|_| oid))
41    }
42
43    /// Resolve an already selected field type through the existing builtin or statement catalog. Text and unrelated SQL types keep their original interpretation.
44    pub fn from_declared_with_control(
45        value: &Value,
46        oid: u32,
47        catalog: Option<&dyn SQLValueCatalog>,
48        control: &ProductionControl<'_>,
49    ) -> Result<Option<Self>> {
50        control.check()?;
51        if matches!(value, Value::Null) {
52            return Ok(None);
53        }
54        if let Some(ty) = crate::catalog::type_metadata::builtin_scalar_type(oid) {
55            return Self::from_type(value, ty, catalog, control);
56        }
57        let ty = catalog
58            .map(|catalog| catalog.value_type_by_oid(oid))
59            .transpose()?
60            .flatten()
61            .map(|ty| ty.retain_external_with_control(control))
62            .transpose()?;
63        match ty {
64            Some(ty) => Self::from_type(value, &ty, catalog, control),
65            None => Ok(None),
66        }
67    }
68
69    /// Observe an admitted value under an already selected type without resolving its identity again. Unrelated types and SQL NULL retain their ordinary consumer semantics.
70    pub fn from_type_with_control(
71        value: &Value,
72        ty: &ColumnType,
73        catalog: Option<&dyn SQLValueCatalog>,
74        control: &ProductionControl<'_>,
75    ) -> Result<Option<Self>> {
76        control.check()?;
77        if matches!(value, Value::Null) {
78            return Ok(None);
79        }
80        Self::from_type(value, ty, catalog, control)
81    }
82
83    fn from_type(
84        value: &Value,
85        ty: &ColumnType,
86        catalog: Option<&dyn SQLValueCatalog>,
87        control: &ProductionControl<'_>,
88    ) -> Result<Option<Self>> {
89        control.check()?;
90        if matches!(
91            ty,
92            ColumnType::DeclaredRange(_) | ColumnType::DeclaredMultirange(_)
93        ) {
94            return match value {
95                Value::Datum(datum) => {
96                    super::super::datums::range_comparison(datum, ty, catalog, control).map(Some)
97                }
98                _ => Err(SQLError::Internal(
99                    "declared range comparison requires admitted physical bounds".into(),
100                )),
101            };
102        }
103        let (subtype, multirange) = match ty {
104            ColumnType::Range(subtype) => (*subtype, false),
105            ColumnType::Multirange(subtype) => (*subtype, true),
106            ColumnType::Domain { base, .. } => {
107                return Self::from_type(value, base, catalog, control)
108            }
109            _ => return Ok(None),
110        };
111        if let Value::Datum(datum) = value {
112            return super::super::datums::range_comparison(datum, ty, catalog, control).map(Some);
113        }
114        let Value::Str(text) = value else {
115            return Err(SQLError::Internal(
116                "selected range comparison requires an admitted range value".into(),
117            ));
118        };
119        Ok(Some(if multirange {
120            Self::Multirange(parse_multirange_with_control(text, subtype, control)?)
121        } else {
122            Self::Range(parse_range_with_control(text, subtype, control)?)
123        }))
124    }
125
126    /// Compare values with the same selected range identity; NULL placement remains with the containing SQL operation.
127    pub fn cmp_with_control(
128        &self,
129        other: &Self,
130        control: &ProductionControl<'_>,
131    ) -> Result<Ordering> {
132        self.cmp_with_catalog_and_control(other, None, control)
133    }
134
135    pub fn cmp_with_catalog_and_control(
136        &self,
137        other: &Self,
138        catalog: Option<&dyn SQLValueCatalog>,
139        control: &ProductionControl<'_>,
140    ) -> Result<Ordering> {
141        let compare = |oid, left: &Value, right: &Value, control: &ProductionControl<'_>| {
142            catalog
143                .ok_or_else(|| {
144                    SQLError::Internal("selected range comparison support is unavailable".into())
145                })?
146                .compare_range_bounds(oid, left, right, control)
147        };
148        match (self, other) {
149            (Self::Range(left), Self::Range(right)) => left.cmp_with_control(right, control),
150            (Self::Multirange(left), Self::Multirange(right)) => {
151                left.cmp_with_control(right, control)
152            }
153            (Self::DeclaredRange(left), Self::DeclaredRange(right)) => {
154                left.cmp_by_with_control(right, control, |a, b, control| {
155                    compare(*left.identity(), a, b, control)
156                })
157            }
158            (Self::DeclaredMultirange(left), Self::DeclaredMultirange(right)) => left
159                .cmp_by_with_control(right, control, |a, b, control| {
160                    compare(*left.identity(), a, b, control)
161                }),
162            _ => Err(SQLError::Routine {
163                sqlstate: "XX000".into(),
164                message: "range types do not match".into(),
165            }),
166        }
167    }
168}