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 carrier;
14pub(super) use carrier::normalize_existing;
15pub use carrier::{contains_legacy_vectors, normalize_legacy_vector_carrier_with_control};
16
17pub fn coerce_assignment_value(
18    context: &dyn AssignmentContext,
19    value: Value,
20    target: &ColumnType,
21    source: Option<&ColumnType>,
22) -> Result<Value, SQLError> {
23    if physical_identity(&value, source, target)
24        || source.is_some_and(|source| same_catalog_value_type(source, target))
25    {
26        return normalize_existing(value, target);
27    }
28    if matches!(target, ColumnType::Domain { .. }) {
29        let source = source.map(ColumnType::catalog_name);
30        if let Some(value) =
31            super::domain::assign_domain_value_from(context, &value, source.as_deref(), target)?
32        {
33            return Ok(value);
34        }
35    }
36    let value = if target.is_character_string() {
37        source
38            .map(|source| crate::expr::format_regtype_value(&value, source, Some(context)))
39            .transpose()?
40            .flatten()
41            .map(Value::Str)
42            .unwrap_or(value)
43    } else {
44        value
45    };
46    convert_value_to_column_type_with_context_from(context, value, target, source)
47}
48
49/// 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.
50fn physical_identity(value: &Value, source: Option<&ColumnType>, target: &ColumnType) -> bool {
51    if !matches!(value, Value::Datum(_)) {
52        return false;
53    }
54    source.is_some_and(|mut source| {
55        while source != target {
56            let ColumnType::Domain { base, .. } = source else {
57                return false;
58            };
59            source = base;
60        }
61        true
62    })
63}
64
65fn same_catalog_value_type(source: &ColumnType, target: &ColumnType) -> bool {
66    match (source, target) {
67        (ColumnType::Domain { oid: source, .. }, ColumnType::Domain { oid: target, .. }) => {
68            source == target
69        }
70        (ColumnType::Composite(source), ColumnType::Composite(target)) => source.oid == target.oid,
71        (ColumnType::InternalChar, ColumnType::InternalChar)
72        | (ColumnType::Xml, ColumnType::Xml)
73        | (ColumnType::PgNodeTree, ColumnType::PgNodeTree) => true,
74        (ColumnType::Domain { base, .. }, _) => same_catalog_value_type(base, target),
75        (ColumnType::Array(source), ColumnType::Array(target)) => {
76            same_catalog_value_type(source, target)
77        }
78        _ => false,
79    }
80}
81
82pub fn coerce_json_value(value: Value, jsonb: bool) -> Result<Value, SQLError> {
83    crate::expr::cast_value(&value, if jsonb { "jsonb" } else { "json" })
84}
85
86pub fn convert_declared_value_to_column_type(
87    context: &dyn AssignmentContext,
88    value: Value,
89    source_ty: &ColumnType,
90    target_ty: &ColumnType,
91) -> Result<Value, SQLError> {
92    if physical_identity(&value, Some(source_ty), target_ty)
93        || same_catalog_value_type(source_ty, target_ty)
94    {
95        return normalize_existing(value, target_ty);
96    }
97    let value = match value {
98        Value::Datum(datum) => crate::expr::datums::read_with_catalog(&datum, Some(context))?,
99        value => value,
100    };
101    match (source_ty, target_ty) {
102        (ColumnType::Domain { base, .. }, target) => {
103            convert_declared_value_to_column_type(context, value, base, target)
104        }
105        (source, ColumnType::Domain { base, .. }) => {
106            convert_declared_value_to_column_type(context, value, source, base)
107        }
108        (ColumnType::Array(source), ColumnType::Array(target)) => {
109            let Value::Array(array) = value else {
110                return Err(SQLError::TypeMismatch(format!(
111                    "cannot cast a non-array value to {}[]",
112                    column_type_name(target)
113                )));
114            };
115            let source = array_scalar_type(source);
116            let target = array_scalar_type(target);
117            let converted =
118                convert_declared_array_elements(context, array.elements(), source, target)?;
119            ArrayValue::with_lower_bounds(converted, array.lower_bounds().to_vec())
120                .map(|array| {
121                    array.with_element_type_oid(Some(crate::catalog::type_metadata::pg_type_oid(
122                        target,
123                    ) as u32))
124                })
125                .map(Value::Array)
126                .ok_or_else(|| {
127                    SQLError::TypeMismatch(
128                        "multidimensional arrays must have matching dimensions".into(),
129                    )
130                })
131        }
132        (ColumnType::Range(source), ColumnType::Range(target)) if source == target => {
133            crate::expr::cast_value_from(&value, target.range_name(), Some(source.range_name()))
134        }
135        (ColumnType::Range(source), ColumnType::Multirange(target)) if source == target => {
136            crate::expr::cast_value_from(
137                &value,
138                target.multirange_name(),
139                Some(source.range_name()),
140            )
141        }
142        (ColumnType::Multirange(source), ColumnType::Multirange(target)) if source == target => {
143            crate::expr::cast_value_from(
144                &value,
145                target.multirange_name(),
146                Some(source.multirange_name()),
147            )
148        }
149        (_, ColumnType::Range(_) | ColumnType::Multirange(_)) => {
150            Err(SQLError::TypeMismatch(format!(
151                "column cannot be cast automatically from type {} to type {}",
152                column_type_name(source_ty),
153                column_type_name(target_ty)
154            )))
155        }
156        (source, ColumnType::Oid)
157            if matches!(
158                source,
159                ColumnType::SmallInteger
160                    | ColumnType::Integer
161                    | ColumnType::BigInteger
162                    | ColumnType::Oid
163                    | ColumnType::Regproc
164                    | ColumnType::Regprocedure
165                    | ColumnType::Regclass
166                    | ColumnType::Regcollation
167                    | ColumnType::Regnamespace
168                    | ColumnType::Regrole
169                    | ColumnType::Regtype
170            ) =>
171        {
172            crate::expr::cast_value_from(&value, "oid", Some(column_type_name(source)))
173        }
174        (ColumnType::Xid, ColumnType::Xid) => Ok(value),
175        (ColumnType::Bytea, ColumnType::Bytea) => Ok(value),
176        (_, ColumnType::Oid | ColumnType::Xid | ColumnType::Bytea) => {
177            Err(SQLError::TypeMismatch(format!(
178                "column cannot be cast automatically from type {} to type {}",
179                column_type_name(source_ty),
180                column_type_name(target_ty)
181            )))
182        }
183        _ => convert_value_to_column_type_with_context_from(
184            context,
185            value,
186            target_ty,
187            Some(source_ty),
188        ),
189    }
190}
191
192/// 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.
193pub(crate) fn type_requires_catalog_resolution(ty: &ColumnType) -> bool {
194    match ty {
195        // 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.
196        ColumnType::Regrole
197        | ColumnType::Xml
198        | ColumnType::Regclass
199        | ColumnType::Regtype
200        | ColumnType::Regproc
201        | ColumnType::Regprocedure
202        | ColumnType::Regcollation
203        | ColumnType::Regnamespace
204        | ColumnType::Domain { .. }
205        | ColumnType::Enum(_)
206        | ColumnType::Composite(_)
207        | ColumnType::TimestampTz
208        | ColumnType::TimestampTzPrecision(_) => true,
209        ColumnType::Array(element) => type_requires_catalog_resolution(element),
210        _ => false,
211    }
212}
213
214pub fn convert_value_to_column_type_with_context(
215    context: &dyn AssignmentContext,
216    value: Value,
217    ty: &ColumnType,
218) -> Result<Value, SQLError> {
219    convert_value_to_column_type_with_context_from(context, value, ty, None)
220}
221
222fn convert_value_to_column_type_with_context_from(
223    context: &dyn AssignmentContext,
224    value: Value,
225    ty: &ColumnType,
226    source: Option<&ColumnType>,
227) -> Result<Value, SQLError> {
228    // Assignment to a string type calls the enum output function, which reads the current label.
229    let value = if textual_target(ty) && crate::expr::enums::contains_enum_carrier(&value) {
230        crate::expr::enums::render_enum_labels(
231            crate::expr::EngineHook::enum_labels(context),
232            &value,
233        )?
234    } else {
235        value
236    };
237    if let Some(value) = super::domain::assign_domain_value(context, &value, ty)? {
238        return Ok(value);
239    }
240    if matches!(value, Value::Null) {
241        return Ok(Value::Null);
242    }
243    let value = match value {
244        Value::Datum(datum) => crate::expr::datums::read_with_catalog(&datum, Some(context))?,
245        value => value,
246    };
247    if let ColumnType::Array(element) = ty {
248        if type_requires_catalog_resolution(element) {
249            return convert_catalog_array(context, value, element);
250        }
251    }
252    if type_requires_catalog_resolution(ty) {
253        return crate::expr::cast_value_with_type_resolution(
254            &value,
255            None,
256            &ty.catalog_name(),
257            Some(context),
258        );
259    }
260    convert_value_to_column_type_from(value, ty, source)
261}
262
263fn textual_target(ty: &ColumnType) -> bool {
264    match ty {
265        ColumnType::Array(element) => textual_target(element),
266        other => other.is_character_string(),
267    }
268}
269
270fn convert_catalog_array(
271    context: &dyn AssignmentContext,
272    value: Value,
273    element: &ColumnType,
274) -> Result<Value, SQLError> {
275    let array = match value {
276        Value::Array(array) => array,
277        Value::Str(text) => crate::expr::parse_pg_array_literal(&text)?,
278        other => {
279            return Err(SQLError::TypeMismatch(format!(
280                "expected an array, got {other:?}"
281            )))
282        }
283    };
284    let values = convert_catalog_array_elements(context, array.elements(), element)?;
285    ArrayValue::with_lower_bounds(values, array.lower_bounds().to_vec())
286        .map(|array| {
287            array.with_element_type_oid(Some(crate::catalog::type_metadata::pg_type_oid(
288                array_scalar_type(element),
289            ) as u32))
290        })
291        .map(Value::Array)
292        .ok_or_else(|| {
293            SQLError::TypeMismatch("multidimensional arrays must have matching dimensions".into())
294        })
295}
296
297fn convert_catalog_array_elements(
298    context: &dyn AssignmentContext,
299    values: &[Value],
300    element: &ColumnType,
301) -> Result<Vec<Value>, SQLError> {
302    let mut element = element;
303    while let ColumnType::Array(nested) = element {
304        element = nested;
305    }
306    values
307        .iter()
308        .map(|value| match value {
309            Value::List(values) => {
310                convert_catalog_array_elements(context, values, element).map(Value::List)
311            }
312            value => convert_value_to_column_type_with_context(context, value.clone(), element),
313        })
314        .collect()
315}
316
317mod production;
318pub(crate) use production::{convert_tensor_with_control, convert_vector_with_control};
319pub use production::{
320    convert_value_to_column_type_from_with_control, convert_value_to_column_type_with_control,
321    numeric_field_overflow,
322};
323
324pub fn convert_value_to_column_type(value: Value, ty: &ColumnType) -> Result<Value, SQLError> {
325    convert_value_to_column_type_from(value, ty, None)
326}
327
328/// Convert a catalog-free assignment while retaining the analyzed source identity.
329pub fn convert_value_to_column_type_from(
330    value: Value,
331    ty: &ColumnType,
332    source: Option<&ColumnType>,
333) -> Result<Value, SQLError> {
334    let control = uqa_core::memory::ProductionControl::uncontrolled();
335    convert_value_to_column_type_from_with_control(
336        control.finish(value, None)?,
337        ty,
338        source,
339        &control,
340    )?
341    .into_uncontrolled()
342    .map_err(|_| SQLError::Internal("ordinary assignment production owner".into()))
343}
344
345fn convert_declared_array_elements(
346    context: &dyn AssignmentContext,
347    elements: &[Value],
348    source_type: &ColumnType,
349    target_type: &ColumnType,
350) -> Result<Vec<Value>, SQLError> {
351    elements
352        .iter()
353        .cloned()
354        .map(|element| match element {
355            Value::List(nested) => {
356                convert_declared_array_elements(context, &nested, source_type, target_type)
357                    .map(Value::List)
358            }
359            scalar => {
360                convert_declared_value_to_column_type(context, scalar, source_type, target_type)
361            }
362        })
363        .collect()
364}
365
366fn array_scalar_type(mut ty: &ColumnType) -> &ColumnType {
367    while let ColumnType::Array(element) = ty {
368        ty = element;
369    }
370    ty
371}
372
373pub fn validate_vector_dimensions(expected: u32, actual: usize) -> Result<(), SQLError> {
374    let expected = usize::try_from(expected).map_err(|_| {
375        SQLError::TypeMismatch(format!(
376            "declared vector dimension {expected} exceeds the platform usize range"
377        ))
378    })?;
379    if actual == expected {
380        Ok(())
381    } else {
382        Err(SQLError::VectorDimMismatch { expected, actual })
383    }
384}
385
386pub use crate::catalog::type_metadata::column_type_name;
387
388pub use crate::expr::value_to_text;
389
390pub fn json_to_core_value(json: serde_json::Value) -> Value {
391    match json {
392        serde_json::Value::Null => Value::Null,
393        serde_json::Value::Bool(b) => Value::Bool(b),
394        serde_json::Value::Number(n) => {
395            if let Some(i) = n.as_i64() {
396                Value::Int(i)
397            } else if let Some(d) = DecimalValue::parse(&n.to_string()) {
398                Value::Decimal(d)
399            } else if let Some(f) = n.as_f64() {
400                Value::Float(f)
401            } else {
402                Value::Null
403            }
404        }
405        serde_json::Value::String(s) => Value::Str(s),
406        serde_json::Value::Array(items) => {
407            Value::List(items.into_iter().map(json_to_core_value).collect())
408        }
409        serde_json::Value::Object(obj) => {
410            if let Ok(temporal) =
411                serde_json::from_value::<TemporalValue>(serde_json::Value::Object(obj.clone()))
412            {
413                return Value::Temporal(temporal);
414            }
415            Value::Map(
416                obj.into_iter()
417                    .map(|(k, v)| (k, json_to_core_value(v)))
418                    .collect(),
419            )
420        }
421    }
422}
423
424pub use crate::expr::core_value_to_json;
425
426pub fn json_table_value_to_text(value: &serde_json::Value) -> Value {
427    match value {
428        serde_json::Value::Null => Value::Null,
429        serde_json::Value::String(s) => Value::Str(s.clone()),
430        serde_json::Value::Bool(b) => Value::Str(b.to_string()),
431        serde_json::Value::Number(n) => Value::Str(n.to_string()),
432        serde_json::Value::Array(_) | serde_json::Value::Object(_) => Value::Str(value.to_string()),
433    }
434}
435
436pub fn json_table_arg(value: &Value, name: &str) -> Result<serde_json::Value, SQLError> {
437    match value {
438        Value::Json(s) | Value::JsonB(s) | Value::Str(s) => {
439            serde_json::from_str::<serde_json::Value>(s)
440                .map_err(|e| SQLError::TypeMismatch(format!("{name}: invalid JSON: {e}")))
441        }
442        other => core_value_to_json(other),
443    }
444}