Skip to main content

uqa_sql/expr/context/
casting.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Catalog-aware cast selection shares controlled type, array and value constructors.
8
9use uqa_core::{
10    memory::{Produced, ProductionControl, ProductionString, ProductionVec},
11    ArrayValue, Value,
12};
13
14use super::super::casting::{cast_value_from_with_control, parse_pg_array_literal_with_input};
15use super::super::ResolvedCast;
16use super::{format_regtype_elements_with_control, format_regtype_value_with_control, EngineHook};
17use crate::{
18    ast::ColumnType,
19    error::{Result, SQLError},
20};
21
22mod datestyle;
23mod intervalstyle;
24mod metadata;
25pub use metadata::{
26    cast_value_with_scoped_resolution, CatalogCastScope, RetainedCatalogCast, ScopedCastResult,
27};
28mod ranges;
29mod timezone;
30mod xml;
31
32/// Catalog input needed after analysis selects a type for an unknown literal. Domain array input includes each element's constraints, so the caller must retain this value rather than read the text again at execution.
33pub trait CatalogInputFunctions {
34    fn read_unknown_input(&self, text: &str, target: &ColumnType) -> Result<Value>;
35}
36
37pub(crate) fn requires_domain_array_input(target: &ColumnType) -> bool {
38    matches!(target, ColumnType::Array(element) if matches!(array_leaf_type(element), ColumnType::Domain { .. }))
39}
40
41/// Input constants containing declared composites/ranges, domain arrays or XML need the definition's catalog or session input context.
42pub(crate) fn requires_catalog_constant_input(target: &ColumnType) -> bool {
43    requires_domain_array_input(target)
44        || match target {
45            ColumnType::Xml
46            | ColumnType::Composite(_)
47            | ColumnType::DeclaredRange(_)
48            | ColumnType::DeclaredMultirange(_) => true,
49            ColumnType::Array(element) | ColumnType::Domain { base: element, .. } => {
50                requires_catalog_constant_input(element)
51            }
52            _ => false,
53        }
54}
55
56/// Read a catalog-dependent constant once, retaining its typed datum in stored syntax.
57pub fn read_catalog_input(
58    text: &str,
59    target: &ColumnType,
60    engine: &dyn EngineHook,
61) -> Result<Value> {
62    if requires_domain_array_input(target) {
63        return read_catalog_array_input(text, target, engine);
64    }
65    if !requires_catalog_constant_input(target) {
66        return Err(SQLError::Internal(
67            "constant input requires a catalog or session context".into(),
68        ));
69    }
70    super::cast_value_with_type_resolution(
71        &Value::Str(text.into()),
72        Some("unknown"),
73        &target.catalog_name(),
74        Some(engine),
75    )
76}
77
78/// Read an array whose elements are domains with the same input and constraint path as a catalog-aware cast. The resolved target preserves domain identity; a scalar outer domain remains the surrounding expression's runtime coercion.
79pub fn read_catalog_array_input(
80    text: &str,
81    target: &ColumnType,
82    engine: &dyn EngineHook,
83) -> Result<Value> {
84    if !requires_domain_array_input(target) {
85        return Err(SQLError::Internal(
86            "catalog array input requires domain elements".into(),
87        ));
88    }
89    let control = ProductionControl::uncontrolled();
90    let element = array_leaf_type(target);
91    let target_name = element.catalog_name_with_control(&control)?;
92    let array = parse_pg_array_literal_with_input(text, &control, |value| {
93        cast_value_with_type_resolution_with_control(
94            &value,
95            None,
96            &target_name,
97            Some(engine),
98            &control,
99        )
100    })?;
101    let (array, memory) = array.into_parts();
102    let oid = crate::catalog::type_metadata::pg_type_oid(element) as u32;
103    control
104        .finish(Value::Array(array.with_element_type_oid(Some(oid))), memory)?
105        .into_uncontrolled()
106        .map_err(|_| SQLError::Internal("ordinary catalog array input owner".into()))
107}
108
109#[must_use]
110pub fn coercion_type_name(ty: &ColumnType) -> String {
111    coercion_type_name_with_control(ty, &ProductionControl::uncontrolled())
112        .expect("ordinary coercion type name")
113        .into_uncontrolled()
114        .expect("ordinary coercion type name owner")
115}
116
117fn coercion_type_name_with_control(
118    ty: &ColumnType,
119    control: &ProductionControl<'_>,
120) -> Result<Produced<String>> {
121    control.check()?;
122    match ty {
123        ColumnType::Domain { base, .. } => coercion_type_name_with_control(base, control),
124        ColumnType::Array(element) => {
125            let element = coercion_type_name_with_control(element, control)?;
126            let mut name = ProductionString::new(*control);
127            name.push_str(&element)?;
128            name.push_str("[]")?;
129            Ok(name.finish()?)
130        }
131        _ => Ok(ty.sql_name_with_control(control)?),
132    }
133}
134
135/// The types of `PostgreSQL`'s string category, which any type casts to through its output function.
136fn is_string_type(ty: &ColumnType) -> bool {
137    matches!(
138        ty,
139        ColumnType::Text
140            | ColumnType::Name
141            | ColumnType::Varchar(_)
142            | ColumnType::Character(_)
143            | ColumnType::Bpchar
144    )
145}
146
147fn regrole_array_type(ty: &ColumnType) -> bool {
148    match ty {
149        ColumnType::Array(element) => {
150            matches!(element.as_ref(), ColumnType::Regrole) || regrole_array_type(element)
151        }
152        _ => false,
153    }
154}
155
156fn array_leaf_type(ty: &ColumnType) -> &ColumnType {
157    match ty {
158        ColumnType::Array(element) => array_leaf_type(element),
159        _ => ty,
160    }
161}
162
163fn optional_type_name(
164    name: &str,
165    control: &ProductionControl<'_>,
166) -> Result<Option<Produced<ColumnType>>> {
167    match ColumnType::from_sql_name_with_control(name, control) {
168        Ok(ty) => Ok(Some(ty)),
169        Err(error) if matches!(error.sqlstate(), Some("53200" | "57014")) => Err(error),
170        Err(_) => Ok(None),
171    }
172}
173
174/// Cast a value after resolving catalog-owned types and enforcing domain constraints before exposing a base-type carrier.
175pub fn cast_value_with_type_resolution(
176    value: &Value,
177    source_ty: Option<&str>,
178    target_ty: &str,
179    engine: Option<&dyn EngineHook>,
180) -> Result<Value> {
181    cast_value_with_type_resolution_with_control(
182        value,
183        source_ty,
184        target_ty,
185        engine,
186        &ProductionControl::uncontrolled(),
187    )?
188    .into_uncontrolled()
189    .map_err(|_| SQLError::Internal("ordinary catalog cast owner".into()))
190}
191
192/// Container-to-string coercion observes each field or element through its SQL output function. It does not repeat input or domain checks.
193fn container_output_cast(
194    value: &Value,
195    source: Option<&ColumnType>,
196    target_ty: &str,
197    target: &ColumnType,
198    engine: &dyn EngineHook,
199    control: &ProductionControl<'_>,
200) -> Result<Option<Produced<Value>>> {
201    if !matches!(value, Value::Array(_) | Value::Row(_) | Value::Record(_))
202        || !is_string_type(target)
203    {
204        return Ok(None);
205    }
206    let unspecified;
207    let source = if let Some(source) = source {
208        source
209    } else {
210        unspecified = if matches!(value, Value::Array(_)) {
211            ColumnType::array_with_control(
212                control.finish(ColumnType::Text, control.empty_reservation())?,
213                control,
214            )?
215        } else {
216            control.finish(ColumnType::Record, control.empty_reservation())?
217        };
218        &unspecified
219    };
220    let text =
221        crate::result::format_postgres_text_with_control(value, source, Some(engine), control)?;
222    let (text, memory) = text.into_parts();
223    let text = control.finish(Value::Str(text), memory)?;
224    if matches!(target, ColumnType::Text) {
225        return Ok(Some(text));
226    }
227    cast_value_from_with_control(&text, target_ty, Some("text"), control).map(Some)
228}
229
230fn physical_output_cast(
231    value: &Value,
232    source_ty: Option<&str>,
233    target_ty: &str,
234    target: &ColumnType,
235    engine: &dyn EngineHook,
236    control: &ProductionControl<'_>,
237) -> Result<Option<Produced<Value>>> {
238    let Value::Datum(datum) = value else {
239        return Ok(None);
240    };
241    if !is_string_type(target) {
242        return Ok(None);
243    }
244    let decoded =
245        super::super::datums::read_with_catalog_and_control(datum, Some(engine), control)?;
246    cast_value_with_type_resolution_with_control(
247        &decoded,
248        source_ty,
249        target_ty,
250        Some(engine),
251        control,
252    )
253    .map(Some)
254}
255
256/// Resolve catalog inputs at their external handoff, then admit SQL-owned names, element conversions and output before constructing them.
257pub fn cast_value_with_type_resolution_with_control(
258    value: &Value,
259    source_ty: Option<&str>,
260    target_ty: &str,
261    engine: Option<&dyn EngineHook>,
262    control: &ProductionControl<'_>,
263) -> Result<Produced<Value>> {
264    cast_with_resolution(value, source_ty, target_ty, engine, control, &mut None)
265}
266
267/// Return an immutable numeric conversion when the ordinary catalog-aware cast selected one. Callers may retain it only within the same prepared expression and type-schema scope; the first evaluation keeps the original resolution, callback and failure order.
268pub fn cast_value_with_numeric_resolution_with_control(
269    value: &Value,
270    source_ty: Option<&str>,
271    target_ty: &str,
272    engine: Option<&dyn EngineHook>,
273    control: &ProductionControl<'_>,
274) -> Result<(Produced<Value>, Option<super::super::NumericCast>)> {
275    let (output, resolved) =
276        cast_value_with_resolution_with_control(value, source_ty, target_ty, engine, control)?;
277    Ok((output, resolved.and_then(|cast| cast.numeric())))
278}
279
280/// Return the builtin scalar selection reached by an ordinary successful conversion. The caller may reuse it only for the same immutable expression and type-schema identity with explicit builtin type names.
281pub fn cast_value_with_resolution_with_control(
282    value: &Value,
283    source_ty: Option<&str>,
284    target_ty: &str,
285    engine: Option<&dyn EngineHook>,
286    control: &ProductionControl<'_>,
287) -> Result<(Produced<Value>, Option<ResolvedCast>)> {
288    let mut resolved = None;
289    let output = cast_with_resolution(value, source_ty, target_ty, engine, control, &mut resolved)?;
290    Ok((output, resolved))
291}
292
293fn cast_with_resolution(
294    value: &Value,
295    source_ty: Option<&str>,
296    target_ty: &str,
297    engine: Option<&dyn EngineHook>,
298    control: &ProductionControl<'_>,
299    resolved: &mut Option<ResolvedCast>,
300) -> Result<Produced<Value>> {
301    let types = metadata::CastTypes::resolve(source_ty, target_ty, engine, control)?;
302    cast_with_resolved_types(
303        value, source_ty, target_ty, engine, control, &types, resolved,
304    )
305}
306
307fn cast_with_resolved_types(
308    value: &Value,
309    source_ty: Option<&str>,
310    target_ty: &str,
311    engine: Option<&dyn EngineHook>,
312    control: &ProductionControl<'_>,
313    types: &metadata::CastTypes,
314    resolved: &mut Option<ResolvedCast>,
315) -> Result<Produced<Value>> {
316    let resolved_target = &types.target;
317    let resolved_source_type = &types.source;
318    let parsed_target = &types.parsed_target;
319    let source_type = resolved_source_type.as_deref();
320    let target_column_type = resolved_target.as_deref().or(parsed_target.as_deref());
321    let _date_order = datestyle::input_scope(value, target_column_type, engine, control)?;
322    let _interval_style = intervalstyle::cast_scope(value, target_column_type, engine, control)?;
323    if let (Some(engine), Some(target)) = (engine, resolved_target.as_deref()) {
324        if let Some(value) = record_identity_cast(value, source_type, target, engine, control)? {
325            return Ok(value);
326        }
327        if let Some(output) =
328            physical_output_cast(value, source_ty, target_ty, target, engine, control)?
329        {
330            return Ok(output);
331        }
332        if let Some(value) =
333            cast_defined_type(engine, value, source_ty, source_type, target, control)?
334        {
335            return Ok(value);
336        }
337        if let Some(output) =
338            container_output_cast(value, source_type, target_ty, target, engine, control)?
339        {
340            return Ok(output);
341        }
342        if let Value::Enum(label) = value {
343            let output =
344                super::super::enums::enum_output_for_cast(engine.enum_labels(), label, target)?;
345            return cast_value_with_type_resolution_with_control(
346                &output,
347                Some("text"),
348                target_ty,
349                Some(engine),
350                control,
351            );
352        }
353        control.check()?;
354        if matches!(target, ColumnType::Array(_))
355            && (requires_catalog_array_cast(target)
356                || source_type.is_some_and(|source| {
357                    crate::type_resolution::cast_volatility(source, target)
358                        != crate::ast::FunctionVolatility::Immutable
359                })
360                || super::super::enums::contains_enum_carrier(value)
361                || resolved_source_type
362                    .as_deref()
363                    .is_some_and(super::super::enums::is_enum_bearing))
364        {
365            return cast_catalog_array(value, source_ty, target, engine, control);
366        }
367    }
368    if let (Some(source), Some(target)) = (source_type, target_column_type) {
369        if let Some(cast) = ResolvedCast::select(source, target).filter(|cast| cast.accepts(value))
370        {
371            let output = evaluate_selected_value(&cast, value, source_ty, engine, control)?;
372            *resolved = Some(cast);
373            return Ok(output);
374        }
375    }
376    let resolved_source = resolved_source_type
377        .as_ref()
378        .map(|ty| coercion_type_name_with_control(ty, control))
379        .transpose()?;
380    let source_ty = resolved_source.as_deref().map(String::as_str).or(source_ty);
381    let target_name = resolved_target
382        .as_ref()
383        .map(|ty| coercion_type_name_with_control(ty, control))
384        .transpose()?;
385    let target_ty = target_name.as_ref().map_or(target_ty, |name| name.as_str());
386    cast_resolved_value(
387        value,
388        source_ty,
389        target_ty,
390        target_column_type,
391        engine,
392        control,
393    )
394}
395
396/// Reuse a selected builtin conversion while preserving live setting scopes before callbacks and conversion.
397pub(crate) fn evaluate_selected_cast(
398    cast: &ResolvedCast,
399    value: &Value,
400    source_name: &str,
401    engine: Option<&dyn EngineHook>,
402    control: &ProductionControl<'_>,
403) -> Result<Produced<Value>> {
404    let target = cast.target_type();
405    let _date_order = datestyle::input_scope(value, Some(&target), engine, control)?;
406    let _interval_style = intervalstyle::cast_scope(value, Some(&target), engine, control)?;
407    if let Some(engine) = engine {
408        if let Some(output) =
409            engine.cast_domain_with_control(value, Some(source_name), &target, control)?
410        {
411            return Ok(output);
412        }
413    }
414    evaluate_selected_value(cast, value, Some(source_name), engine, control)
415}
416
417fn evaluate_selected_value(
418    cast: &ResolvedCast,
419    value: &Value,
420    source_name: Option<&str>,
421    engine: Option<&dyn EngineHook>,
422    control: &ProductionControl<'_>,
423) -> Result<Produced<Value>> {
424    let target = cast.target_type();
425    if let Some(output) = datestyle::date_text(value, Some(&target), engine, control)? {
426        let (text, memory) = output.into_parts();
427        if matches!(target, ColumnType::Text) {
428            return Ok(control.finish(Value::Str(text), memory)?);
429        }
430        return cast.evaluate_from(&Value::Str(text), Some("text"), control);
431    }
432    let zoned = timezone::cast_timestamp(value, Some(&target), engine, control)?;
433    cast.evaluate_from(zoned.as_ref().unwrap_or(value), source_name, control)
434}
435
436/// Declared type input and identity coercion precede generic output and array casts. Domain checks keep their established first position.
437fn cast_defined_type(
438    engine: &dyn EngineHook,
439    value: &Value,
440    source_name: Option<&str>,
441    source: Option<&ColumnType>,
442    target: &ColumnType,
443    control: &ProductionControl<'_>,
444) -> Result<Option<Produced<Value>>> {
445    if let Some(value) = engine.cast_domain_with_control(value, source_name, target, control)? {
446        return Ok(Some(value));
447    }
448    if matches!(target, ColumnType::Xml) {
449        return xml::cast(value, source_name, source, engine, control).map(Some);
450    }
451    if let Some(value) = ranges::cast(engine, value, source, target, control)? {
452        return Ok(Some(value));
453    }
454    if let Some(value) = super::super::enums::cast_to_enum_with_control(
455        engine.enum_labels(),
456        value,
457        source,
458        target,
459        control,
460    )? {
461        return Ok(Some(value));
462    }
463    super::super::composites::cast_to_composite(engine, value, source, target)?
464        .map(|value| control.retain_external_value(value).map_err(SQLError::from))
465        .transpose()
466}
467
468fn resolve_catalog_type_with_control(
469    name: &str,
470    engine: Option<&dyn EngineHook>,
471    control: &ProductionControl<'_>,
472) -> Result<Option<Produced<ColumnType>>> {
473    engine
474        .map(|engine| engine.resolve_type_name(name))
475        .transpose()
476        .map_err(SQLError::Internal)?
477        .flatten()
478        .map(|ty| {
479            ty.retain_external_with_control(control)
480                .map_err(SQLError::from)
481        })
482        .transpose()
483}
484
485fn record_identity_cast(
486    value: &Value,
487    resolved_source_type: Option<&ColumnType>,
488    target: &ColumnType,
489    engine: &dyn EngineHook,
490    control: &ProductionControl<'_>,
491) -> Result<Option<Produced<Value>>> {
492    if matches!(target, ColumnType::Record) {
493        // Composite-to-record coercion is a binary relabel: even malformed physical fields remain unread.
494        if let Value::Datum(datum) = value {
495            if crate::expr::composites::datum_is_composite(datum, engine)? {
496                return Ok(Some(control.copy_value(value)?));
497            }
498        }
499        if let (Value::Record(record), Some(ColumnType::Composite(source))) =
500            (value, resolved_source_type)
501        {
502            let (value, memory) = control.copy_value(value)?.into_parts();
503            let Value::Record(value) = value else {
504                unreachable!();
505            };
506            return Ok(Some(control.finish(
507                Value::Record(value.with_type_oid(Some(record.type_oid().unwrap_or(source.oid)))),
508                memory,
509            )?));
510        }
511    }
512
513    Ok(None)
514}
515
516fn cast_resolved_value(
517    value: &Value,
518    source_ty: Option<&str>,
519    target_ty: &str,
520    target_column_type: Option<&ColumnType>,
521    engine: Option<&dyn EngineHook>,
522    control: &ProductionControl<'_>,
523) -> Result<Produced<Value>> {
524    if target_column_type.is_some_and(regrole_array_type) {
525        let source_column_type = source_ty
526            .map(|name| optional_type_name(name, control))
527            .transpose()?
528            .flatten();
529        let source_name = source_column_type
530            .as_deref()
531            .map(array_leaf_type)
532            .map(|ty| ty.sql_name_with_control(control))
533            .transpose()?;
534        return cast_array(
535            value,
536            source_name.as_ref().map(|name| name.as_str()),
537            &ColumnType::Regrole,
538            "regrole[]",
539            engine,
540            control,
541        );
542    }
543    // `find_coercion_pathway` casts an OID alias to a string type through its output function, as `CoerceViaIO`, and the string type then applies its own modifier; an array does so element by element.
544    if let Some(ColumnType::Array(element)) = target_column_type {
545        if is_string_type(element) {
546            if let Some(source_ty) = source_ty
547                .map(|source| optional_type_name(source, control))
548                .transpose()?
549                .flatten()
550            {
551                if let Some(elements) =
552                    format_regtype_elements_with_control(value, &source_ty, engine, control)?
553                {
554                    let (elements, _memory) = elements.into_parts();
555                    return cast_value_from_with_control(
556                        &Value::Array(elements),
557                        target_ty,
558                        Some("text[]"),
559                        control,
560                    );
561                }
562            }
563        }
564    }
565    let text_target = target_ty.eq_ignore_ascii_case("text");
566    if text_target || target_column_type.is_some_and(is_string_type) {
567        if let Some(source_ty) = source_ty
568            .map(|source| optional_type_name(source, control))
569            .transpose()?
570            .flatten()
571        {
572            if let Some(text) =
573                format_regtype_value_with_control(value, &source_ty, engine, control)?
574            {
575                let (text, memory) = text.into_parts();
576                if text_target {
577                    return Ok(control.finish(Value::Str(text), memory)?);
578                }
579                return cast_value_from_with_control(
580                    &Value::Str(text),
581                    target_ty,
582                    Some("text"),
583                    control,
584                );
585            }
586        }
587    }
588    if let (Some(engine), Value::Str(name) | Value::FixedChar(name)) = (engine, value) {
589        let oid = resolve_regobject_input(name, target_ty, target_column_type, engine, control)?;
590        if let Some(oid) = oid {
591            return Ok(control.finish(Value::Int(oid), control.empty_reservation())?);
592        }
593    }
594    if let Some(output) =
595        datestyle::date_output(value, target_ty, target_column_type, engine, control)?
596    {
597        return Ok(output);
598    }
599    let zoned = timezone::cast_timestamp(value, target_column_type, engine, control)?;
600    cast_value_from_with_control(
601        zoned.as_ref().unwrap_or(value),
602        target_ty,
603        source_ty,
604        control,
605    )
606}
607
608fn resolve_regobject_input(
609    name: &str,
610    target_ty: &str,
611    target_column_type: Option<&ColumnType>,
612    engine: &dyn EngineHook,
613    control: &ProductionControl<'_>,
614) -> Result<Option<i64>> {
615    enum ObjectKind {
616        Relation,
617        RoutineName,
618        Routine,
619        Role,
620        Namespace,
621        Collation,
622        Type,
623    }
624    let kind = if target_ty.eq_ignore_ascii_case("regclass") {
625        ObjectKind::Relation
626    } else if matches!(target_column_type, Some(ColumnType::Regproc))
627        || target_ty.eq_ignore_ascii_case("regproc")
628    {
629        ObjectKind::RoutineName
630    } else if target_ty.eq_ignore_ascii_case("regprocedure") {
631        ObjectKind::Routine
632    } else if matches!(target_column_type, Some(ColumnType::Regrole))
633        || target_ty.eq_ignore_ascii_case("regrole")
634    {
635        ObjectKind::Role
636    } else if matches!(target_column_type, Some(ColumnType::Regnamespace)) {
637        ObjectKind::Namespace
638    } else if matches!(target_column_type, Some(ColumnType::Regcollation)) {
639        ObjectKind::Collation
640    } else if matches!(target_column_type, Some(ColumnType::Regtype)) {
641        ObjectKind::Type
642    } else {
643        return Ok(None);
644    };
645    let oid = match kind {
646        ObjectKind::Relation => engine.resolve_regclass_input(name)?,
647        // `regprocin` reports its own missing and ambiguous names.
648        ObjectKind::RoutineName => return engine.resolve_regproc(name),
649        ObjectKind::Routine => engine.resolve_regprocedure_input(name)?,
650        ObjectKind::Role => engine.resolve_regrole(name)?,
651        ObjectKind::Namespace => engine.resolve_regnamespace(name)?,
652        ObjectKind::Collation => engine.resolve_regcollation(name)?,
653        ObjectKind::Type => engine.resolve_regtype_input(name)?,
654    };
655    control.check()?;
656    if oid.is_some() || matches!(kind, ObjectKind::Type) {
657        return Ok(oid);
658    }
659    let (sqlstate, message) = match kind {
660        ObjectKind::Relation => ("42P01", format!("relation \"{name}\" does not exist")),
661        ObjectKind::Routine => ("42883", format!("function \"{name}\" does not exist")),
662        ObjectKind::Role => ("42704", format!("role \"{name}\" does not exist")),
663        ObjectKind::Namespace => ("3F000", format!("schema \"{name}\" does not exist")),
664        ObjectKind::Collation => (
665            "42704",
666            format!("collation \"{name}\" for encoding \"UTF8\" does not exist"),
667        ),
668        ObjectKind::Type | ObjectKind::RoutineName => {
669            unreachable!("regtype and regproc input return before reporting a missing object")
670        }
671    };
672    Err(SQLError::Routine {
673        sqlstate: sqlstate.into(),
674        message,
675    })
676}
677
678/// Whether an array cast needs the catalog for its elements: domains, enums, composites and the OID alias types whose input functions read catalog names. `regrole[]` has its own path above.
679fn requires_catalog_array_cast(ty: &ColumnType) -> bool {
680    match ty {
681        ColumnType::Domain { .. }
682        | ColumnType::Xml
683        | ColumnType::Regtype
684        | ColumnType::Regclass
685        | ColumnType::Regproc
686        | ColumnType::Regprocedure
687        | ColumnType::Regcollation
688        | ColumnType::Regnamespace
689        | ColumnType::Enum(_)
690        | ColumnType::Composite(_)
691        | ColumnType::DeclaredRange(_)
692        | ColumnType::DeclaredMultirange(_)
693        | ColumnType::TimestampTz
694        | ColumnType::TimestampTzPrecision(_) => true,
695        ColumnType::Array(element) => requires_catalog_array_cast(element),
696        _ => false,
697    }
698}
699
700fn cast_catalog_array(
701    value: &Value,
702    source: Option<&str>,
703    target: &ColumnType,
704    engine: &dyn EngineHook,
705    control: &ProductionControl<'_>,
706) -> Result<Produced<Value>> {
707    if matches!(value, Value::Null) {
708        return Ok(control.finish(Value::Null, control.empty_reservation())?);
709    }
710    let source_element = source.map(|name| name.trim_end_matches("[]"));
711    let leaf = array_leaf_type(target);
712    let target_name = target.sql_name_with_control(control)?;
713    let output = cast_array(
714        value,
715        source_element,
716        leaf,
717        &target_name,
718        Some(engine),
719        control,
720    )?;
721    let (Value::Array(array), memory) = output.into_parts() else {
722        return Err(SQLError::Internal(
723            "catalog array cast returned a non-array".into(),
724        ));
725    };
726    let oid = crate::catalog::type_metadata::pg_type_oid(leaf) as u32;
727    Ok(control.finish(Value::Array(array.with_element_type_oid(Some(oid))), memory)?)
728}
729
730fn cast_array(
731    value: &Value,
732    source: Option<&str>,
733    target_element: &ColumnType,
734    target_name: &str,
735    engine: Option<&dyn EngineHook>,
736    control: &ProductionControl<'_>,
737) -> Result<Produced<Value>> {
738    control.check()?;
739    if matches!(value, Value::Null) {
740        return Ok(control.finish(Value::Null, control.empty_reservation())?);
741    }
742    let vector_element = match value {
743        Value::LegacyVector(vector) => Some(match vector.kind() {
744            uqa_core::LegacyVectorKind::SmallInteger => ColumnType::SmallInteger,
745            uqa_core::LegacyVectorKind::Oid => ColumnType::Oid,
746        }),
747        _ => None,
748    };
749    let vector_name = vector_element
750        .as_ref()
751        .map(|element| element.sql_name_with_control(control))
752        .transpose()?;
753    let source = vector_name.as_deref().map(String::as_str).or(source);
754    let target_element_name = target_element.catalog_name_with_control(control)?;
755    let array = if let Value::Str(text) = value {
756        parse_pg_array_literal_with_input(text, control, |value| {
757            cast_value_with_type_resolution_with_control(
758                &value,
759                source,
760                &target_element_name,
761                engine,
762                control,
763            )
764        })?
765    } else {
766        let array = match value {
767            Value::Array(array) => array,
768            Value::LegacyVector(vector) => vector.as_array(),
769            other => {
770                return Err(SQLError::TypeMismatch(format!(
771                    "CAST AS {target_name}: expected array, got {other:?}"
772                )));
773            }
774        };
775        let elements = cast_array_elements(
776            array.elements(),
777            source,
778            &target_element_name,
779            engine,
780            control,
781        )?;
782        let normalize_empty =
783            if let Some(source) = vector_element.filter(|_| array.elements().is_empty()) {
784                source != *target_element
785                    && !crate::type_resolution::cast_catalog_entry_with_control(
786                        &source,
787                        target_element,
788                        control,
789                    )?
790                    .is_some_and(|entry| entry.method == crate::type_resolution::CastMethod::Binary)
791            } else {
792                false
793            };
794        if normalize_empty {
795            ArrayValue::try_new_with_control(elements, control)?
796        } else {
797            rebuild_array(array, elements, control)?
798        }
799        .ok_or_else(|| SQLError::TypeMismatch("array dimensions changed during cast".into()))?
800    };
801    let (array, memory) = array.into_parts();
802    let oid = if matches!(target_element, ColumnType::Regrole) {
803        Some(crate::catalog::type_metadata::pg_type_oid(&ColumnType::Regrole) as u32)
804    } else {
805        array.element_type_oid()
806    };
807    Ok(control.finish(Value::Array(array.with_element_type_oid(oid)), memory)?)
808}
809
810fn cast_array_elements(
811    values: &[Value],
812    source: Option<&str>,
813    target: &str,
814    engine: Option<&dyn EngineHook>,
815    control: &ProductionControl<'_>,
816) -> Result<Produced<Vec<Value>>> {
817    let mut output = ProductionVec::new(*control);
818    output.reserve(values.len())?;
819    for value in values {
820        let value = match value {
821            Value::List(values) => {
822                let (values, memory) =
823                    cast_array_elements(values, source, target, engine, control)?.into_parts();
824                control.finish(Value::List(values), memory)?
825            }
826            value => cast_value_with_type_resolution_with_control(
827                value, source, target, engine, control,
828            )?,
829        };
830        output.push_produced(value)?;
831    }
832    Ok(output.finish()?)
833}
834
835pub(super) fn rebuild_array(
836    source: &ArrayValue,
837    elements: Produced<Vec<Value>>,
838    control: &ProductionControl<'_>,
839) -> Result<Option<Produced<ArrayValue>>> {
840    let mut bounds = ProductionVec::new(*control);
841    bounds.reserve(source.lower_bounds().len())?;
842    for bound in source.lower_bounds() {
843        bounds.push_copy(*bound)?;
844    }
845    ArrayValue::with_lower_bounds_with_control(elements, bounds.finish()?, control)?
846        .map(|array| {
847            let (array, memory) = array.into_parts();
848            control
849                .finish(
850                    array.with_element_type_oid(source.element_type_oid()),
851                    memory,
852                )
853                .map_err(Into::into)
854        })
855        .transpose()
856}
857
858#[cfg(test)]
859mod tests;