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    // The parser owns syntactic dimensions. A converted scalar domain may itself contain an array; its carrier must not add another syntactic dimension.
66    let array = match &declared_dimensions {
67        Some(declared) => {
68            let mut bounds = ProductionVec::new(*control);
69            bounds.reserve(declared.len())?;
70            for (lower, _) in &**declared {
71                bounds.push_copy(*lower)?;
72            }
73            ArrayValue::with_lower_bounds_with_control(items, bounds.finish()?, control)?
74        }
75        None if items.is_empty() => ArrayValue::try_new_with_control(items, control)?,
76        None => {
77            let mut bounds = ProductionVec::new(*control);
78            for _ in 0..parser.rank() {
79                bounds.push_copy(1)?;
80            }
81            ArrayValue::with_lower_bounds_with_control(items, bounds.finish()?, control)?
82        }
83    }
84    .ok_or_else(|| parser.dimension_error())?;
85    if let Some(declared) = declared_dimensions {
86        if !declared
87            .iter()
88            .map(|(_, length)| *length)
89            .eq(array.dimensions().iter().copied())
90        {
91            return Err(parser.dimension_error());
92        }
93    }
94    Ok(array)
95}
96
97pub(super) fn cast_array_elements(
98    items: &[Value],
99    element_type: &str,
100    source_element_type: Option<&str>,
101    control: &ProductionControl<'_>,
102) -> Result<Produced<Vec<Value>>> {
103    let mut output = ProductionVec::new(*control);
104    output.reserve(items.len())?;
105    for item in items {
106        let value = match item {
107            Value::List(nested) => {
108                let (nested, memory) =
109                    cast_array_elements(nested, element_type, source_element_type, control)?
110                        .into_parts();
111                control.finish(Value::List(nested), memory)?
112            }
113            other => {
114                cast_value_from_with_control(other, element_type, source_element_type, control)?
115            }
116        };
117        output.push_produced(value)?;
118    }
119    Ok(output.finish()?)
120}
121
122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123pub(super) enum ArrayShapeError {
124    MixedNesting,
125    MismatchedDimensions,
126}
127
128impl ArrayShapeError {
129    fn message(self) -> &'static str {
130        match self {
131            Self::MixedNesting => "cannot mix nested arrays and scalar elements",
132            Self::MismatchedDimensions => "multidimensional arrays must have matching dimensions",
133        }
134    }
135}
136
137pub(super) fn array_shape(items: &[Value]) -> std::result::Result<Vec<usize>, ArrayShapeError> {
138    match array_shape_with_control(items, &ProductionControl::uncontrolled()) {
139        Ok(shape) => Ok(shape.into_uncontrolled().expect("ordinary array shape")),
140        Err(ShapeProductionError::Shape(error)) => Err(error),
141        Err(ShapeProductionError::Control(_)) => unreachable!("ordinary shape production"),
142    }
143}
144
145enum ShapeProductionError {
146    Shape(ArrayShapeError),
147    Control(ValueRetentionError),
148}
149impl From<ValueRetentionError> for ShapeProductionError {
150    fn from(error: ValueRetentionError) -> Self {
151        Self::Control(error)
152    }
153}
154
155fn array_shape_with_control(
156    items: &[Value],
157    control: &ProductionControl<'_>,
158) -> std::result::Result<Produced<Vec<usize>>, ShapeProductionError> {
159    let mut dimensions = ProductionVec::new(*control);
160    dimensions.push_copy(items.len())?;
161    let mut nested_shape: Option<Produced<Vec<usize>>> = None;
162    let mut has_scalar = false;
163    for item in items {
164        control.check()?;
165        if let Value::List(nested) = item {
166            let shape = array_shape_with_control(nested, control)?;
167            if has_scalar {
168                return Err(ShapeProductionError::Shape(ArrayShapeError::MixedNesting));
169            }
170            if nested_shape
171                .as_ref()
172                .is_some_and(|expected| **expected != *shape)
173            {
174                return Err(ShapeProductionError::Shape(
175                    ArrayShapeError::MismatchedDimensions,
176                ));
177            }
178            nested_shape = Some(shape);
179        } else {
180            if nested_shape.is_some() {
181                return Err(ShapeProductionError::Shape(ArrayShapeError::MixedNesting));
182            }
183            has_scalar = true;
184        }
185    }
186    if let Some(shape) = nested_shape {
187        for length in &*shape {
188            dimensions.push_copy(*length)?;
189        }
190    }
191    Ok(dimensions.finish()?)
192}
193
194/// Return every dimension of a rectangular array value.
195///
196/// `PostgreSQL` arrays cannot mix scalar and nested elements or contain
197/// sub-arrays with different extents.
198pub fn array_dimensions(items: &[Value]) -> Result<Vec<usize>> {
199    array_shape(items).map_err(|error| SQLError::TypeMismatch(error.message().to_string()))
200}