Skip to main content

uqa_sql/assignment/
conversion.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Declared-column assignment coercion for scalar, array, vector, and temporal values.
8
9use super::AssignmentContext;
10use crate::{ColumnType, SQLError};
11use uqa_core::{ArrayValue, DecimalValue, TemporalValue, Value};
12
13mod catalog_production;
14pub use catalog_production::coerce_assignment_value_with_control;
15
16mod carrier;
17pub(super) use carrier::normalize_existing;
18pub use carrier::{contains_legacy_vectors, normalize_legacy_vector_carrier_with_control};
19
20pub fn coerce_assignment_value(
21    context: &dyn AssignmentContext,
22    value: Value,
23    target: &ColumnType,
24    source: Option<&ColumnType>,
25) -> Result<Value, SQLError> {
26    let control = uqa_core::memory::ProductionControl::uncontrolled();
27    coerce_assignment_value_with_control(
28        context,
29        control.finish(value, None)?,
30        target,
31        source,
32        &control,
33    )?
34    .into_uncontrolled()
35    .map_err(|_| SQLError::Internal("ordinary catalog assignment owner".into()))
36}
37
38/// An admitted physical value needs no payload read for a binary identity assignment. A domain source can be relabeled to its base without repeating its checks; target modifiers must still match exactly.
39fn physical_identity(value: &Value, source: Option<&ColumnType>, target: &ColumnType) -> bool {
40    if !matches!(value, Value::Datum(_)) {
41        return false;
42    }
43    source.is_some_and(|mut source| {
44        while source != target {
45            let ColumnType::Domain { base, .. } = source else {
46                return false;
47            };
48            source = base;
49        }
50        true
51    })
52}
53
54fn same_catalog_value_type(source: &ColumnType, target: &ColumnType) -> bool {
55    match (source, target) {
56        (ColumnType::Domain { oid: source, .. }, ColumnType::Domain { oid: target, .. }) => {
57            source == target
58        }
59        (ColumnType::Composite(source), ColumnType::Composite(target)) => source.oid == target.oid,
60        (ColumnType::InternalChar, ColumnType::InternalChar)
61        | (ColumnType::Xml, ColumnType::Xml)
62        | (ColumnType::PgNodeTree, ColumnType::PgNodeTree) => true,
63        (ColumnType::Domain { base, .. }, _) => same_catalog_value_type(base, target),
64        (ColumnType::Array(source), ColumnType::Array(target)) => {
65            same_catalog_value_type(source, target)
66        }
67        _ => false,
68    }
69}
70
71pub fn coerce_json_value(value: Value, jsonb: bool) -> Result<Value, SQLError> {
72    crate::expr::cast_value(&value, if jsonb { "jsonb" } else { "json" })
73}
74
75pub fn convert_declared_value_to_column_type(
76    context: &dyn AssignmentContext,
77    value: Value,
78    source_ty: &ColumnType,
79    target_ty: &ColumnType,
80) -> Result<Value, SQLError> {
81    if physical_identity(&value, Some(source_ty), target_ty)
82        || same_catalog_value_type(source_ty, target_ty)
83    {
84        return normalize_existing(value, target_ty);
85    }
86    let value = match value {
87        Value::Datum(datum) => crate::expr::datums::read_with_catalog(&datum, Some(context))?,
88        value => value,
89    };
90    match (source_ty, target_ty) {
91        (ColumnType::Domain { base, .. }, target) => {
92            convert_declared_value_to_column_type(context, value, base, target)
93        }
94        (source, ColumnType::Domain { base, .. }) => {
95            convert_declared_value_to_column_type(context, value, source, base)
96        }
97        (ColumnType::Array(source), ColumnType::Array(target)) => {
98            let Value::Array(array) = value else {
99                return Err(SQLError::TypeMismatch(format!(
100                    "cannot cast a non-array value to {}[]",
101                    column_type_name(target)
102                )));
103            };
104            let source = array_scalar_type(source);
105            let target = array_scalar_type(target);
106            let converted =
107                convert_declared_array_elements(context, array.elements(), source, target)?;
108            ArrayValue::with_lower_bounds(converted, array.lower_bounds().to_vec())
109                .map(|array| {
110                    array.with_element_type_oid(Some(crate::catalog::type_metadata::pg_type_oid(
111                        target,
112                    ) as u32))
113                })
114                .map(Value::Array)
115                .ok_or_else(|| {
116                    SQLError::TypeMismatch(
117                        "multidimensional arrays must have matching dimensions".into(),
118                    )
119                })
120        }
121        (ColumnType::Range(source), ColumnType::Range(target)) if source == target => {
122            crate::expr::cast_value_from(&value, target.range_name(), Some(source.range_name()))
123        }
124        (ColumnType::Range(source), ColumnType::Multirange(target)) if source == target => {
125            crate::expr::cast_value_from(
126                &value,
127                target.multirange_name(),
128                Some(source.range_name()),
129            )
130        }
131        (ColumnType::Multirange(source), ColumnType::Multirange(target)) if source == target => {
132            crate::expr::cast_value_from(
133                &value,
134                target.multirange_name(),
135                Some(source.multirange_name()),
136            )
137        }
138        (_, ColumnType::Range(_) | ColumnType::Multirange(_)) => {
139            Err(SQLError::TypeMismatch(format!(
140                "column cannot be cast automatically from type {} to type {}",
141                column_type_name(source_ty),
142                column_type_name(target_ty)
143            )))
144        }
145        (source, ColumnType::Oid)
146            if matches!(
147                source,
148                ColumnType::SmallInteger
149                    | ColumnType::Integer
150                    | ColumnType::BigInteger
151                    | ColumnType::Oid
152                    | ColumnType::Regproc
153                    | ColumnType::Regprocedure
154                    | ColumnType::Regclass
155                    | ColumnType::Regcollation
156                    | ColumnType::Regnamespace
157                    | ColumnType::Regrole
158                    | ColumnType::Regtype
159            ) =>
160        {
161            crate::expr::cast_value_from(&value, "oid", Some(column_type_name(source)))
162        }
163        (ColumnType::Xid, ColumnType::Xid) => Ok(value),
164        (ColumnType::Bytea, ColumnType::Bytea) => Ok(value),
165        (_, ColumnType::Oid | ColumnType::Xid | ColumnType::Bytea) => {
166            Err(SQLError::TypeMismatch(format!(
167                "column cannot be cast automatically from type {} to type {}",
168                column_type_name(source_ty),
169                column_type_name(target_ty)
170            )))
171        }
172        _ => convert_value_to_column_type_with_context_from(
173            context,
174            value,
175            target_ty,
176            Some(source_ty),
177        ),
178    }
179}
180
181/// Whether converting a value to `ty` needs the statement's catalog or session: enum labels, domain constraints, composite attributes, role names or the current time zone.
182pub(crate) fn type_requires_catalog_resolution(ty: &ColumnType) -> bool {
183    match ty {
184        // The OID alias types read a name through the catalog, so an assigned text value becomes the object's OID, as `regclassin` and its siblings read it.
185        ColumnType::Regrole
186        | ColumnType::Xml
187        | ColumnType::Regclass
188        | ColumnType::Regtype
189        | ColumnType::Regproc
190        | ColumnType::Regprocedure
191        | ColumnType::Regcollation
192        | ColumnType::Regnamespace
193        | ColumnType::Domain { .. }
194        | ColumnType::Enum(_)
195        | ColumnType::Composite(_)
196        | ColumnType::TimestampTz
197        | ColumnType::TimestampTzPrecision(_) => true,
198        ColumnType::Array(element) => type_requires_catalog_resolution(element),
199        _ => false,
200    }
201}
202
203pub fn convert_value_to_column_type_with_context(
204    context: &dyn AssignmentContext,
205    value: Value,
206    ty: &ColumnType,
207) -> Result<Value, SQLError> {
208    convert_value_to_column_type_with_context_from(context, value, ty, None)
209}
210
211fn convert_value_to_column_type_with_context_from(
212    context: &dyn AssignmentContext,
213    value: Value,
214    ty: &ColumnType,
215    source: Option<&ColumnType>,
216) -> Result<Value, SQLError> {
217    let control = uqa_core::memory::ProductionControl::uncontrolled();
218    catalog_production::convert_with_catalog(
219        context,
220        control.finish(value, None)?,
221        ty,
222        source,
223        &control,
224    )?
225    .into_uncontrolled()
226    .map_err(|_| SQLError::Internal("ordinary catalog conversion owner".into()))
227}
228
229fn textual_target(ty: &ColumnType) -> bool {
230    match ty {
231        ColumnType::Array(element) => textual_target(element),
232        other => other.is_character_string(),
233    }
234}
235
236mod production;
237pub(crate) use production::{convert_tensor_with_control, convert_vector_with_control};
238pub use production::{
239    convert_value_to_column_type_from_with_control, convert_value_to_column_type_with_control,
240    numeric_field_overflow,
241};
242
243pub fn convert_value_to_column_type(value: Value, ty: &ColumnType) -> Result<Value, SQLError> {
244    convert_value_to_column_type_from(value, ty, None)
245}
246
247/// Convert a catalog-free assignment while retaining the analyzed source identity.
248pub fn convert_value_to_column_type_from(
249    value: Value,
250    ty: &ColumnType,
251    source: Option<&ColumnType>,
252) -> Result<Value, SQLError> {
253    let control = uqa_core::memory::ProductionControl::uncontrolled();
254    convert_value_to_column_type_from_with_control(
255        control.finish(value, None)?,
256        ty,
257        source,
258        &control,
259    )?
260    .into_uncontrolled()
261    .map_err(|_| SQLError::Internal("ordinary assignment production owner".into()))
262}
263
264fn convert_declared_array_elements(
265    context: &dyn AssignmentContext,
266    elements: &[Value],
267    source_type: &ColumnType,
268    target_type: &ColumnType,
269) -> Result<Vec<Value>, SQLError> {
270    elements
271        .iter()
272        .cloned()
273        .map(|element| match element {
274            Value::List(nested) => {
275                convert_declared_array_elements(context, &nested, source_type, target_type)
276                    .map(Value::List)
277            }
278            scalar => {
279                convert_declared_value_to_column_type(context, scalar, source_type, target_type)
280            }
281        })
282        .collect()
283}
284
285fn array_scalar_type(mut ty: &ColumnType) -> &ColumnType {
286    while let ColumnType::Array(element) = ty {
287        ty = element;
288    }
289    ty
290}
291
292pub fn validate_vector_dimensions(expected: u32, actual: usize) -> Result<(), SQLError> {
293    let expected = usize::try_from(expected).map_err(|_| {
294        SQLError::TypeMismatch(format!(
295            "declared vector dimension {expected} exceeds the platform usize range"
296        ))
297    })?;
298    if actual == expected {
299        Ok(())
300    } else {
301        Err(SQLError::VectorDimMismatch { expected, actual })
302    }
303}
304
305pub use crate::catalog::type_metadata::column_type_name;
306
307pub use crate::expr::value_to_text;
308
309pub fn json_to_core_value(json: serde_json::Value) -> Value {
310    match json {
311        serde_json::Value::Null => Value::Null,
312        serde_json::Value::Bool(b) => Value::Bool(b),
313        serde_json::Value::Number(n) => {
314            if let Some(i) = n.as_i64() {
315                Value::Int(i)
316            } else if let Some(d) = DecimalValue::parse(&n.to_string()) {
317                Value::Decimal(d)
318            } else if let Some(f) = n.as_f64() {
319                Value::Float(f)
320            } else {
321                Value::Null
322            }
323        }
324        serde_json::Value::String(s) => Value::Str(s),
325        serde_json::Value::Array(items) => {
326            Value::List(items.into_iter().map(json_to_core_value).collect())
327        }
328        serde_json::Value::Object(obj) => {
329            if let Ok(temporal) =
330                serde_json::from_value::<TemporalValue>(serde_json::Value::Object(obj.clone()))
331            {
332                return Value::Temporal(temporal);
333            }
334            Value::Map(
335                obj.into_iter()
336                    .map(|(k, v)| (k, json_to_core_value(v)))
337                    .collect(),
338            )
339        }
340    }
341}
342
343pub use crate::expr::core_value_to_json;
344
345pub fn json_table_value_to_text(value: &serde_json::Value) -> Value {
346    match value {
347        serde_json::Value::Null => Value::Null,
348        serde_json::Value::String(s) => Value::Str(s.clone()),
349        serde_json::Value::Bool(b) => Value::Str(b.to_string()),
350        serde_json::Value::Number(n) => Value::Str(n.to_string()),
351        serde_json::Value::Array(_) | serde_json::Value::Object(_) => Value::Str(value.to_string()),
352    }
353}
354
355pub fn json_table_arg(value: &Value, name: &str) -> Result<serde_json::Value, SQLError> {
356    match value {
357        Value::Json(s) | Value::JsonB(s) | Value::Str(s) => {
358            serde_json::from_str::<serde_json::Value>(s)
359                .map_err(|e| SQLError::TypeMismatch(format!("{name}: invalid JSON: {e}")))
360        }
361        other => core_value_to_json(other),
362    }
363}