Skip to main content

uqa_sql/expr/casting/
resolved.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Builtin scalar conversion kernels selected from resolved SQL identities.
8
9use super::{numeric::NumericCast, Produced, ProductionControl, Result, SQLError, Value};
10use crate::{expr::EngineHook, ColumnType};
11
12mod temporal;
13use temporal::TemporalCast;
14
15/// A conversion's immutable selection, without retaining a row value or a catalog decision.
16#[derive(Clone, Debug)]
17pub struct ResolvedCast {
18    source: Source,
19    target: Target,
20}
21
22#[derive(Clone, Copy, Debug)]
23enum Source {
24    Numeric,
25    Real,
26    InternalChar,
27    Scalar,
28    Temporal,
29}
30
31#[derive(Clone, Copy, Debug)]
32enum Target {
33    Numeric(NumericCast),
34    Text,
35    Varchar(Option<u32>),
36    Character(u32),
37    Bpchar,
38    Boolean,
39    Uuid,
40    Json { binary: bool },
41    Temporal(TemporalCast),
42}
43
44impl Target {
45    fn column_type(self) -> ColumnType {
46        match self {
47            Self::Numeric(numeric) => numeric.target_type(),
48            Self::Text => ColumnType::Text,
49            Self::Varchar(length) => ColumnType::Varchar(length),
50            Self::Character(length) => ColumnType::Character(length),
51            Self::Bpchar => ColumnType::Bpchar,
52            Self::Boolean => ColumnType::Boolean,
53            Self::Uuid => ColumnType::Uuid,
54            Self::Json { binary: false } => ColumnType::Json,
55            Self::Json { binary: true } => ColumnType::JsonB,
56            Self::Temporal(cast) => cast.column_type(),
57        }
58    }
59}
60
61impl ResolvedCast {
62    /// Select builtin scalar kernels whose identities do not depend on a live catalog or session setting. Temporal conversions still consult live settings on every row.
63    pub fn select(source: &ColumnType, target: &ColumnType) -> Option<Self> {
64        let source = scalar_source(source)?;
65        let target = match target {
66            ColumnType::Text => Target::Text,
67            ColumnType::Varchar(length) => Target::Varchar(*length),
68            ColumnType::Character(length) => Target::Character(*length),
69            ColumnType::Bpchar => Target::Bpchar,
70            ColumnType::Boolean => Target::Boolean,
71            ColumnType::Uuid => Target::Uuid,
72            ColumnType::Json => Target::Json { binary: false },
73            ColumnType::JsonB => Target::Json { binary: true },
74            _ => match TemporalCast::select(target) {
75                Some(cast) => Target::Temporal(cast),
76                None if !matches!(source, Source::Temporal) => {
77                    Target::Numeric(NumericCast::select(target, target)?)
78                }
79                None => return None,
80            },
81        };
82        if matches!(source, Source::Temporal)
83            && !matches!(
84                target,
85                Target::Temporal(_)
86                    | Target::Text
87                    | Target::Varchar(_)
88                    | Target::Character(_)
89                    | Target::Bpchar
90            )
91        {
92            return None;
93        }
94        Some(Self { source, target })
95    }
96
97    /// The narrower numeric selection exposed by the existing numeric cast API.
98    pub fn numeric(&self) -> Option<NumericCast> {
99        match (self.source, self.target) {
100            (Source::Numeric | Source::Real, Target::Numeric(numeric)) => Some(numeric),
101            _ => None,
102        }
103    }
104
105    /// Catalog-bearing carriers keep their existing physical output and live label paths even when a caller supplies a builtin source schema.
106    pub(crate) fn accepts(&self, value: &Value) -> bool {
107        matches!(
108            value,
109            Value::Null
110                | Value::Int(_)
111                | Value::Float(_)
112                | Value::Decimal(_)
113                | Value::Bool(_)
114                | Value::Str(_)
115                | Value::FixedChar(_)
116                | Value::Bytes(_)
117                | Value::Json(_)
118                | Value::JsonB(_)
119        ) || (self.numeric().is_some() && matches!(value, Value::Datum(_)))
120            || (matches!(self.source, Source::Temporal) && matches!(value, Value::Temporal(_)))
121    }
122
123    /// Reuse only type selection. The original source and target spellings must identify this selection; borrowing them preserves fallback callback/error order without constructing another name. Current callbacks, cancellation, values and allocation admission remain part of each evaluation.
124    pub fn evaluate_with_catalog(
125        &self,
126        value: &Value,
127        source_name: &str,
128        target_name: &str,
129        engine: Option<&dyn EngineHook>,
130        control: &ProductionControl<'_>,
131    ) -> Result<Produced<Value>> {
132        control.check()?;
133        if !self.accepts(value) {
134            return super::super::cast_value_with_type_resolution_with_control(
135                value,
136                Some(source_name),
137                target_name,
138                engine,
139                control,
140            );
141        }
142        super::super::context::evaluate_selected_cast(self, value, source_name, engine, control)
143    }
144
145    pub(crate) fn target_type(&self) -> ColumnType {
146        self.target.column_type()
147    }
148
149    /// Run after the ordinary catalog checks, using the same scalar value constructors as named casts.
150    #[cfg(test)]
151    pub(crate) fn evaluate(
152        &self,
153        value: &Value,
154        control: &ProductionControl<'_>,
155    ) -> Result<Produced<Value>> {
156        self.evaluate_from(value, None, control)
157    }
158
159    pub(crate) fn evaluate_from(
160        &self,
161        value: &Value,
162        source_name: Option<&str>,
163        control: &ProductionControl<'_>,
164    ) -> Result<Produced<Value>> {
165        control.check()?;
166        if let Target::Numeric(numeric) = self.target {
167            if matches!(self.source, Source::InternalChar)
168                && matches!(numeric, NumericCast::Integer)
169                && !matches!(value, Value::Null)
170            {
171                return Ok(control.finish(
172                    super::binary_oid::cast_integer_from(value, Some("\"char\""), control)?,
173                    control.empty_reservation(),
174                )?);
175            }
176            return numeric.evaluate(value, control);
177        }
178        if matches!(value, Value::Null) {
179            return Ok(control.finish(Value::Null, control.empty_reservation())?);
180        }
181        match self.target {
182            Target::Text | Target::Varchar(_) | Target::Bpchar | Target::Character(_) => {
183                self.text(value, control)
184            }
185            Target::Boolean => {
186                Ok(control.finish(super::cast_boolean(value)?, control.empty_reservation())?)
187            }
188            Target::Uuid => super::cast_uuid(value, control),
189            Target::Json { binary } => {
190                super::super::json::cast_json_value_with_control(value, binary, control)
191            }
192            Target::Temporal(cast) => cast.evaluate(value, source_name, control),
193            Target::Numeric(_) => unreachable!("numeric conversion already executed"),
194        }
195    }
196
197    fn text(&self, value: &Value, control: &ProductionControl<'_>) -> Result<Produced<Value>> {
198        let source = match self.source {
199            Source::Real => Some(ColumnType::Real),
200            Source::InternalChar => Some(ColumnType::InternalChar),
201            Source::Numeric | Source::Scalar | Source::Temporal => None,
202        };
203        let text = match (self.target, value) {
204            (Target::Bpchar, Value::FixedChar(text)) => control.copy_text(text)?,
205            _ => super::cast_text_from_type(value, source.as_ref(), control)?,
206        };
207        let (fixed, length) = match self.target {
208            Target::Bpchar => (true, None),
209            Target::Character(length) => (true, Some(length)),
210            Target::Varchar(length) => (false, length),
211            _ => (false, None),
212        };
213        match length {
214            Some(0) if fixed => Err(SQLError::TypeMismatch(
215                "CHARACTER length must be greater than zero".into(),
216            )),
217            Some(length) => super::character_value(text, length as usize, fixed, control),
218            None => super::text_value(text, fixed, control),
219        }
220    }
221}
222
223fn scalar_source(source: &ColumnType) -> Option<Source> {
224    Some(match source {
225        ColumnType::SmallInteger
226        | ColumnType::Integer
227        | ColumnType::BigInteger
228        | ColumnType::DoublePrecision
229        | ColumnType::Numeric { .. } => Source::Numeric,
230        ColumnType::Real => Source::Real,
231        ColumnType::InternalChar => Source::InternalChar,
232        ColumnType::Boolean
233        | ColumnType::Text
234        | ColumnType::Name
235        | ColumnType::Varchar(_)
236        | ColumnType::Bpchar
237        | ColumnType::Character(_)
238        | ColumnType::Uuid
239        | ColumnType::Json
240        | ColumnType::JsonB
241        | ColumnType::Bytea => Source::Scalar,
242        temporal if TemporalCast::select(temporal).is_some() => Source::Temporal,
243        _ => return None,
244    })
245}
246
247#[cfg(test)]
248mod tests;