Skip to main content

uqa_sql/expr/
array_construction.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Array constructors preserve the boundary between dimensions and array-valued domain elements.
8
9use crate::{catalog::type_metadata::pg_type_oid, ColumnType, SQLError};
10use uqa_core::{
11    memory::{Produced, ProductionControl, ProductionVec},
12    ArrayValue, Value,
13};
14
15/// Form ARRAY expression output from already selected scalar element metadata. Domain input has already run in each evaluated expression; retaining an array-valued scalar must not run it again.
16pub fn construct_array_with_control(
17    count: usize,
18    input_type: Option<&ColumnType>,
19    control: &ProductionControl<'_>,
20    mut evaluate: impl FnMut(usize) -> Result<Produced<Value>, SQLError>,
21) -> Result<Produced<Value>, SQLError> {
22    let element_type = input_type.map(|ty| ty.array_element_type().unwrap_or(ty));
23    let mut values = ProductionVec::new(*control);
24    values.reserve(count)?;
25    for index in 0..count {
26        values.push_produced(evaluate(index)?)?;
27    }
28    let values = values.finish()?;
29    let array = if count == 0 || input_type.is_none_or(|ty| matches!(ty, ColumnType::Array(_))) {
30        ArrayValue::try_new_with_control(values, control)?
31    } else {
32        let mut bounds = ProductionVec::new(*control);
33        bounds.push_copy(1)?;
34        ArrayValue::with_lower_bounds_with_control(values, bounds.finish()?, control)?
35    }
36    .ok_or_else(|| {
37        SQLError::TypeMismatch("multidimensional arrays must have matching dimensions".into())
38    })?;
39
40    let (array, memory) = array.into_parts();
41    Ok(control.finish(
42        Value::Array(array.with_element_type_oid(element_type.map(|ty| pg_type_oid(ty) as u32))),
43        memory,
44    )?)
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50    use uqa_core::{memory::MemoryBudget, CancellationToken};
51
52    #[test]
53    fn declared_scalar_arrays_survive_nested_construction_and_native_output() {
54        let domain = ColumnType::Domain {
55            collation_oid: None,
56            schema: "public".into(),
57            name: "array_leaf".into(),
58            oid: 20_000,
59            array_oid: Some(20_001),
60            base: Box::new(ColumnType::Array(Box::new(ColumnType::Integer))),
61        };
62        let budget = MemoryBudget::new(16_384);
63        let token = CancellationToken::new();
64        let control = ProductionControl::new(&budget, &token, &token);
65        let children = [
66            Value::Array(ArrayValue::try_new(vec![Value::Int(1), Value::Int(2)]).unwrap()),
67            Value::Array(ArrayValue::try_new(vec![]).unwrap()),
68        ];
69        let first = construct_array_with_control(2, Some(&domain), &control, |index| {
70            Ok(control.copy_value(&children[index])?)
71        })
72        .unwrap();
73        let second = construct_array_with_control(2, Some(&domain), &control, |_| {
74            Ok(control.finish(Value::Null, control.empty_reservation())?)
75        })
76        .unwrap();
77        let ty = ColumnType::Array(Box::new(domain));
78        let mut rows = [first, second].into_iter();
79        let value =
80            construct_array_with_control(2, Some(&ty), &control, |_| Ok(rows.next().unwrap()))
81                .unwrap();
82        let Value::Array(array) = &*value else {
83            panic!("array")
84        };
85        assert_eq!(array.dimensions(), [2, 2]);
86        let text =
87            crate::result::format_postgres_text_with_control(&value, &ty, None, &control).unwrap();
88        assert_eq!(&*text, "{{\"{1,2}\",\"{}\"},{NULL,NULL}}");
89        assert_eq!(
90            budget.used(),
91            value.reserved_bytes() + text.reserved_bytes()
92        );
93        drop((value, text));
94        assert_eq!(budget.used(), 0);
95    }
96}