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) =
69                engine.cast_domain_with_control(value, Some(source_name), &target, control)?
70            {
71                return Ok(output);
72            }
73        }
74        self.evaluate(value, control)
75    }
76
77    pub(crate) fn target_type(self) -> ColumnType {
78        match self {
79            Self::SmallInteger => ColumnType::SmallInteger,
80            Self::Integer => ColumnType::Integer,
81            Self::BigInteger => ColumnType::BigInteger,
82            Self::Real => ColumnType::Real,
83            Self::DoublePrecision => ColumnType::DoublePrecision,
84            Self::Numeric { precision, scale } => ColumnType::Numeric { precision, scale },
85        }
86    }
87
88    /// Execute after the caller's catalog/domain checks, using the existing numeric conversion kernels and the current invocation's resource control.
89    pub fn evaluate(
90        self,
91        value: &Value,
92        control: &ProductionControl<'_>,
93    ) -> Result<Produced<Value>, SQLError> {
94        control.check()?;
95        if let Value::Datum(datum) = value {
96            return self.evaluate(
97                &*super::super::datums::read_with_control(datum, control)?,
98                control,
99            );
100        }
101        let converted = match (self, value) {
102            (_, Value::Null) => Value::Null,
103            (Self::SmallInteger, _) => super::cast_integer(value, "smallint", control)?,
104            (Self::Integer, _) => super::cast_integer(value, "integer", control)?,
105            (Self::BigInteger, _) => super::cast_integer(value, "bigint", control)?,
106            (Self::Real, _) => Value::Float(super::super::floating::to_float_with_control(
107                value,
108                super::super::FloatWidth::Real,
109                control,
110            )?),
111            (Self::DoublePrecision, _) => {
112                Value::Float(super::super::floating::to_float_with_control(
113                    value,
114                    super::super::FloatWidth::DoublePrecision,
115                    control,
116                )?)
117            }
118            (Self::Numeric { precision, scale }, _) => {
119                return finish(
120                    super::super::conversion::to_decimal_with_control(value, control)?,
121                    precision.map(|precision| (precision, scale.unwrap_or(0))),
122                    control,
123                );
124            }
125        };
126        Ok(control.finish(converted, control.empty_reservation())?)
127    }
128}
129
130pub(super) fn finish(
131    value: Produced<DecimalValue>,
132    modifier: Option<(u32, i32)>,
133    control: &ProductionControl<'_>,
134) -> Result<Produced<Value>, SQLError> {
135    let value = if let Some((precision, scale)) = modifier {
136        let rounded = value
137            .round_to_scale_with_control(scale, control)?
138            .ok_or_else(|| super::out_of_range("numeric"))?;
139        if !rounded.fits_precision_with_control(precision, scale, control)? {
140            return Err(crate::assignment::conversion::numeric_field_overflow(
141                precision, scale,
142            ));
143        }
144        rounded
145    } else {
146        value
147    };
148    let (value, memory) = value.into_parts();
149    Ok(control.finish(Value::Decimal(value), memory)?)
150}
151
152#[cfg(test)]
153mod tests;