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