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