Skip to main content

uqa_sql/expr/casting/
array.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! `PostgreSQL` array literal parsing, shape validation, and element conversion.
8
9use uqa_core::{
10    memory::{Produced, ProductionControl, ProductionVec},
11    ArrayValue, Value, ValueRetentionError,
12};
13
14use crate::error::{Result, SQLError};
15
16use super::cast_value_from_with_control;
17
18/// Binary array coercion retains even an empty explicit dimension; element conversion constructs an ordinary dimensionless empty array.
19pub(super) fn binary_compatible_elements(
20    source: Option<&str>,
21    target: &str,
22    control: &ProductionControl<'_>,
23) -> Result<bool> {
24    let Some(source) = source else {
25        return Ok(true);
26    };
27    let source = crate::ColumnType::from_sql_name_with_control(source, control)?;
28    let target = crate::ColumnType::from_sql_name_with_control(target, control)?;
29    Ok(*source == *target
30        || crate::type_resolution::cast_catalog_entry_with_control(&source, &target, control)?
31            .is_some_and(|entry| entry.method == crate::type_resolution::CastMethod::Binary))
32}
33
34mod literal;
35
36/// Parse a `PostgreSQL` array literal (`{1,2,3}`, `{"a b",NULL}`,
37/// `{{1,2},{3,4}}`) into nested lists of string/NULL values; the caller
38/// casts elements.
39pub fn parse_pg_array_literal(text: &str) -> Result<ArrayValue> {
40    parse_pg_array_literal_with_control(text, &ProductionControl::uncontrolled())?
41        .into_uncontrolled()
42        .map_err(|_| SQLError::Internal("ordinary array parse owner".into()))
43}
44
45pub fn parse_pg_array_literal_with_control(
46    text: &str,
47    control: &ProductionControl<'_>,
48) -> Result<Produced<ArrayValue>> {
49    parse_pg_array_literal_with_input(text, control, Ok)
50}
51
52/// Convert each completed leaf before reading later tokens, retaining both its value and its admitted owner.
53pub(in crate::expr) fn parse_pg_array_literal_with_input(
54    text: &str,
55    control: &ProductionControl<'_>,
56    mut input: impl FnMut(Produced<Value>) -> Result<Produced<Value>>,
57) -> Result<Produced<ArrayValue>> {
58    let mut parser = literal::ArrayLiteralParser::new(text, *control);
59    let (declared_dimensions, items) = parser.parse(&mut input)?;
60    match array_shape_with_control(&items, control) {
61        Ok(shape) => drop(shape),
62        Err(ShapeProductionError::Shape(_)) => return Err(parser.dimension_error()),
63        Err(ShapeProductionError::Control(error)) => return Err(error.into()),
64    }
65    let array = match &declared_dimensions {
66        Some(declared) => {
67            let mut bounds = ProductionVec::new(*control);
68            bounds.reserve(declared.len())?;
69            for (lower, _) in &**declared {
70                bounds.push_copy(*lower)?;
71            }
72            ArrayValue::with_lower_bounds_with_control(items, bounds.finish()?, control)?
73        }
74        None => ArrayValue::try_new_with_control(items, control)?,
75    }
76    .ok_or_else(|| parser.dimension_error())?;
77    if let Some(declared) = declared_dimensions {
78        if !declared
79            .iter()
80            .map(|(_, length)| *length)
81            .eq(array.dimensions().iter().copied())
82        {
83            return Err(parser.dimension_error());
84        }
85    }
86    Ok(array)
87}
88
89pub(super) fn cast_array_elements(
90    items: &[Value],
91    element_type: &str,
92    source_element_type: Option<&str>,
93    control: &ProductionControl<'_>,
94) -> Result<Produced<Vec<Value>>> {
95    let mut output = ProductionVec::new(*control);
96    output.reserve(items.len())?;
97    for item in items {
98        let value = match item {
99            Value::List(nested) => {
100                let (nested, memory) =
101                    cast_array_elements(nested, element_type, source_element_type, control)?
102                        .into_parts();
103                control.finish(Value::List(nested), memory)?
104            }
105            other => {
106                cast_value_from_with_control(other, element_type, source_element_type, control)?
107            }
108        };
109        output.push_produced(value)?;
110    }
111    Ok(output.finish()?)
112}
113
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub(super) enum ArrayShapeError {
116    MixedNesting,
117    MismatchedDimensions,
118}
119
120impl ArrayShapeError {
121    fn message(self) -> &'static str {
122        match self {
123            Self::MixedNesting => "cannot mix nested arrays and scalar elements",
124            Self::MismatchedDimensions => "multidimensional arrays must have matching dimensions",
125        }
126    }
127}
128
129pub(super) fn array_shape(items: &[Value]) -> std::result::Result<Vec<usize>, ArrayShapeError> {
130    match array_shape_with_control(items, &ProductionControl::uncontrolled()) {
131        Ok(shape) => Ok(shape.into_uncontrolled().expect("ordinary array shape")),
132        Err(ShapeProductionError::Shape(error)) => Err(error),
133        Err(ShapeProductionError::Control(_)) => unreachable!("ordinary shape production"),
134    }
135}
136
137enum ShapeProductionError {
138    Shape(ArrayShapeError),
139    Control(ValueRetentionError),
140}
141impl From<ValueRetentionError> for ShapeProductionError {
142    fn from(error: ValueRetentionError) -> Self {
143        Self::Control(error)
144    }
145}
146
147fn array_shape_with_control(
148    items: &[Value],
149    control: &ProductionControl<'_>,
150) -> std::result::Result<Produced<Vec<usize>>, ShapeProductionError> {
151    let mut dimensions = ProductionVec::new(*control);
152    dimensions.push_copy(items.len())?;
153    let mut nested_shape: Option<Produced<Vec<usize>>> = None;
154    let mut has_scalar = false;
155    for item in items {
156        control.check()?;
157        if let Value::List(nested) = item {
158            let shape = array_shape_with_control(nested, control)?;
159            if has_scalar {
160                return Err(ShapeProductionError::Shape(ArrayShapeError::MixedNesting));
161            }
162            if nested_shape
163                .as_ref()
164                .is_some_and(|expected| **expected != *shape)
165            {
166                return Err(ShapeProductionError::Shape(
167                    ArrayShapeError::MismatchedDimensions,
168                ));
169            }
170            nested_shape = Some(shape);
171        } else {
172            if nested_shape.is_some() {
173                return Err(ShapeProductionError::Shape(ArrayShapeError::MixedNesting));
174            }
175            has_scalar = true;
176        }
177    }
178    if let Some(shape) = nested_shape {
179        for length in &*shape {
180            dimensions.push_copy(*length)?;
181        }
182    }
183    Ok(dimensions.finish()?)
184}
185
186/// Return every dimension of a rectangular array value.
187///
188/// `PostgreSQL` arrays cannot mix scalar and nested elements or contain
189/// sub-arrays with different extents.
190pub fn array_dimensions(items: &[Value]) -> Result<Vec<usize>> {
191    array_shape(items).map_err(|error| SQLError::TypeMismatch(error.message().to_string()))
192}