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