Skip to main content

uqa_sql/expr/casting/
numeric.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Numeric coercions selected from resolved SQL types, without spelling or parsing their names again.
8
9use crate::{ColumnType, SQLError};
10use uqa_core::{
11    memory::{Produced, ProductionControl},
12    DecimalValue, Value,
13};
14
15/// An immutable builtin numeric conversion selected from resolved source and destination identities.
16#[derive(Clone, Copy, Debug)]
17pub enum NumericCast {
18    SmallInteger,
19    Integer,
20    BigInteger,
21    Real,
22    DoublePrecision,
23    Numeric {
24        precision: Option<u32>,
25        scale: Option<i32>,
26    },
27}
28
29impl NumericCast {
30    /// Select only builtin numeric identities. Domains, OID aliases, containers and catalog-defined types retain their distinct coercion paths.
31    pub fn select(source: &ColumnType, target: &ColumnType) -> Option<Self> {
32        if !matches!(
33            source,
34            ColumnType::SmallInteger
35                | ColumnType::Integer
36                | ColumnType::BigInteger
37                | ColumnType::Real
38                | ColumnType::DoublePrecision
39                | ColumnType::Numeric { .. }
40        ) {
41            return None;
42        }
43        Some(match target {
44            ColumnType::SmallInteger => Self::SmallInteger,
45            ColumnType::Integer => Self::Integer,
46            ColumnType::BigInteger => Self::BigInteger,
47            ColumnType::Real => Self::Real,
48            ColumnType::DoublePrecision => Self::DoublePrecision,
49            ColumnType::Numeric { precision, scale } => Self::Numeric {
50                precision: *precision,
51                scale: *scale,
52            },
53            _ => return None,
54        })
55    }
56
57    /// Execute a retained conversion with the invoking catalog hook. Type resolution is already complete, but domain adapters still observe each value before the builtin kernel.
58    pub fn evaluate_with_catalog(
59        self,
60        value: &Value,
61        source_name: &str,
62        engine: Option<&dyn super::super::EngineHook>,
63        control: &ProductionControl<'_>,
64    ) -> Result<Produced<Value>, SQLError> {
65        control.check()?;
66        let target = self.target_type();
67        if let Some(engine) = engine {
68            if let Some(output) = engine.cast_domain(value, Some(source_name), &target)? {
69                return Ok(control.retain_external_value(output)?);
70            }
71        }
72        self.evaluate(value, control)
73    }
74
75    pub(crate) fn target_type(self) -> ColumnType {
76        match self {
77            Self::SmallInteger => ColumnType::SmallInteger,
78            Self::Integer => ColumnType::Integer,
79            Self::BigInteger => ColumnType::BigInteger,
80            Self::Real => ColumnType::Real,
81            Self::DoublePrecision => ColumnType::DoublePrecision,
82            Self::Numeric { precision, scale } => ColumnType::Numeric { precision, scale },
83        }
84    }
85
86    /// Execute after the caller's catalog/domain checks, using the existing numeric conversion kernels and the current invocation's resource control.
87    pub fn evaluate(
88        self,
89        value: &Value,
90        control: &ProductionControl<'_>,
91    ) -> Result<Produced<Value>, SQLError> {
92        control.check()?;
93        if let Value::Datum(datum) = value {
94            return self.evaluate(
95                &*super::super::datums::read_with_control(datum, control)?,
96                control,
97            );
98        }
99        let converted = match (self, value) {
100            (_, Value::Null) => Value::Null,
101            (Self::SmallInteger, _) => super::cast_integer(value, "smallint", control)?,
102            (Self::Integer, _) => super::cast_integer(value, "integer", control)?,
103            (Self::BigInteger, _) => super::cast_integer(value, "bigint", control)?,
104            (Self::Real, _) => Value::Float(super::super::floating::to_float_with_control(
105                value,
106                super::super::FloatWidth::Real,
107                control,
108            )?),
109            (Self::DoublePrecision, _) => {
110                Value::Float(super::super::floating::to_float_with_control(
111                    value,
112                    super::super::FloatWidth::DoublePrecision,
113                    control,
114                )?)
115            }
116            (Self::Numeric { precision, scale }, _) => {
117                return finish(
118                    super::super::conversion::to_decimal_with_control(value, control)?,
119                    precision.map(|precision| (precision, scale.unwrap_or(0))),
120                    control,
121                );
122            }
123        };
124        Ok(control.finish(converted, control.empty_reservation())?)
125    }
126}
127
128pub(super) fn finish(
129    value: Produced<DecimalValue>,
130    modifier: Option<(u32, i32)>,
131    control: &ProductionControl<'_>,
132) -> Result<Produced<Value>, SQLError> {
133    let value = if let Some((precision, scale)) = modifier {
134        let rounded = value
135            .round_to_scale_with_control(scale, control)?
136            .ok_or_else(|| super::out_of_range("numeric"))?;
137        if !rounded.fits_precision_with_control(precision, scale, control)? {
138            return Err(crate::assignment::conversion::numeric_field_overflow(
139                precision, scale,
140            ));
141        }
142        rounded
143    } else {
144        value
145    };
146    let (value, memory) = value.into_parts();
147    Ok(control.finish(Value::Decimal(value), memory)?)
148}
149
150#[cfg(test)]
151mod tests;