Skip to main content

uqa_sql/assignment/
containers.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Rebuild typed assignment containers without evaluating SQL operands.
8
9use crate::SQLError;
10use uqa_core::{
11    memory::{Produced, ProductionControl},
12    ArrayAssignmentError, ArrayValue, Value,
13};
14
15pub type SubscriptBound = (Option<i32>, Option<i32>);
16
17/// Shared bound scheduling for native expressions and mutation assignment evaluation.
18pub fn evaluate_subscript_bounds(
19    dimensions: usize,
20    slice: bool,
21    control: &ProductionControl<'_>,
22    mut bound: impl FnMut(usize, bool) -> Result<Option<i32>, SQLError>,
23) -> Result<Produced<Vec<SubscriptBound>>, SQLError> {
24    if dimensions > crate::ast::MAX_ARRAY_SUBSCRIPT_DIMENSIONS {
25        return Err(array_error(ArrayAssignmentError::SubscriptCount));
26    }
27    let mut bounds = uqa_core::memory::ProductionVec::new(*control);
28    for _ in 0..dimensions {
29        bounds.push_copy((None, None))?;
30    }
31    for upper in [true, false].into_iter().take(if slice { 2 } else { 1 }) {
32        for (dimension, pair) in bounds.as_mut_slice().iter_mut().enumerate() {
33            control.check()?;
34            let value = bound(dimension, upper)?;
35            if upper {
36                pair.1 = value;
37            } else {
38                pair.0 = value;
39            }
40        }
41    }
42    Ok(bounds.finish()?)
43}
44
45pub(super) fn field_store(
46    type_oid: u32,
47    number: i16,
48    current: &Value,
49    rhs: &Value,
50    catalog: Option<&dyn crate::expr::SQLValueCatalog>,
51    control: &ProductionControl<'_>,
52) -> Result<Produced<Value>, SQLError> {
53    control.check()?;
54    let types = crate::expr::ValueCompositeCatalog(catalog);
55    let descriptor = crate::expr::composites::descriptor(Some(&types), type_oid)?;
56    if !descriptor
57        .attributes
58        .iter()
59        .any(|attribute| attribute.number == number)
60    {
61        return Err(SQLError::Internal(
62            "field assignment attribute disappeared".into(),
63        ));
64    }
65    let decoded = match current {
66        Value::Datum(datum) => Some(crate::expr::datums::read_with_value_catalog_and_control(
67            datum, catalog, control,
68        )?),
69        _ => None,
70    };
71    let current = decoded.as_deref().unwrap_or(current);
72    crate::expr::composites::constructor::construct_current_with_control(
73        &descriptor,
74        Some(&types),
75        control,
76        |position| {
77            let attribute = &descriptor.attributes[position];
78            let value = if attribute.number == number {
79                rhs
80            } else {
81                match current {
82                    Value::Null => &Value::Null,
83                    Value::Record(record) => record
84                        .iter()
85                        .find(|(name, _)| *name == &attribute.name)
86                        .map_or(&Value::Null, |(_, value)| value),
87                    _ => {
88                        return Err(SQLError::Internal(
89                            "field assignment has a non-composite container".into(),
90                        ))
91                    }
92                }
93            };
94            Ok(control.copy_value(value)?)
95        },
96    )
97}
98
99/// SQL NULL containers become empty arrays before assignment; NULL slice sources preserve that container. Keep production admission through both paths.
100pub fn assign_array_with_control(
101    current: &Value,
102    value: &Value,
103    bounds: &[(Option<i32>, Option<i32>)],
104    slice: bool,
105    catalog: Option<&dyn crate::expr::SQLValueCatalog>,
106    control: &ProductionControl<'_>,
107) -> Result<Produced<Value>, SQLError> {
108    control.check()?;
109    let decoded = match current {
110        Value::Datum(datum) => Some(crate::expr::datums::read_with_value_catalog_and_control(
111            datum, catalog, control,
112        )?),
113        _ => None,
114    };
115    let current = decoded.as_deref().unwrap_or(current);
116    let empty = if *current == Value::Null {
117        Some(
118            ArrayValue::try_new_with_control(
119                control.finish(Vec::new(), control.empty_reservation())?,
120                control,
121            )?
122            .expect("empty array"),
123        )
124    } else {
125        None
126    };
127    let array = match current {
128        Value::Null => empty.as_deref().expect("NULL array replacement"),
129        Value::Array(array) => array,
130        _ => {
131            return Err(SQLError::Internal(
132                "declared array column has a nonarray carrier".into(),
133            ))
134        }
135    };
136    if slice && *value == Value::Null {
137        return if let Some(empty) = empty {
138            let (array, memory) = empty.into_parts();
139            Ok(control.finish(Value::Array(array), memory)?)
140        } else {
141            Ok(control.copy_value(current)?)
142        };
143    }
144    let source = match value {
145        Value::Datum(datum) if slice => Some(
146            crate::expr::datums::read_with_value_catalog_and_control(datum, catalog, control)?,
147        ),
148        _ => None,
149    };
150    let value = source.as_deref().unwrap_or(value);
151    let result = if slice {
152        let Value::Array(source) = value else {
153            return Err(SQLError::Internal(
154                "array slice conversion returned a nonarray".into(),
155            ));
156        };
157        array.assign_slice_with_control(bounds, source, control)
158    } else {
159        let mut indexes = [0; 6];
160        if bounds.len() > indexes.len() {
161            return Err(array_error(ArrayAssignmentError::SubscriptCount));
162        }
163        for (index, (_, upper)) in indexes.iter_mut().zip(bounds) {
164            *index =
165                upper.ok_or_else(|| SQLError::Internal("element index lost its bound".into()))?;
166        }
167        array.assign_element_with_control(&indexes[..bounds.len()], value, control)
168    }
169    .map_err(array_error)?;
170    let (array, memory) = result.into_parts();
171    Ok(control.finish(Value::Array(array), memory)?)
172}
173
174pub fn array_error(error: ArrayAssignmentError) -> SQLError {
175    let code = match &error {
176        ArrayAssignmentError::Retention(_) => {
177            let ArrayAssignmentError::Retention(error) = error else {
178                unreachable!()
179            };
180            return error.into();
181        }
182        ArrayAssignmentError::SizeLimit | ArrayAssignmentError::LowerBound(_) => "54000",
183        ArrayAssignmentError::ElementShape => "42804",
184        _ => "2202E",
185    };
186    SQLError::Diagnostic {
187        sqlstate: code.into(), message: error.to_string(), hint: None,
188        detail: matches!(error, ArrayAssignmentError::MissingBounds).then(|| "When assigning to a slice of an empty array value, slice boundaries must be fully specified.".into()),
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195    use uqa_core::{memory::MemoryBudget, CancellationToken};
196
197    #[test]
198    fn assignment_upper_bounds_precede_lower_bounds_and_null_stops_before_rhs() {
199        let token = CancellationToken::new();
200        let budget = MemoryBudget::new(4096);
201        let control = ProductionControl::new(&budget, &token, &token);
202        let mut reached = Vec::new();
203        let values = [
204            Value::Null,
205            Value::Null,
206            Value::Int(1),
207            Value::Array(ArrayValue::try_new(vec![Value::Int(7)]).unwrap()),
208        ];
209        let binding = crate::ast::AssignmentBinding {
210            path: vec![crate::ast::AssignmentPathStep::Subscripts {
211                first_argument: 1,
212                dimensions: 1,
213                slice: true,
214                bounds: crate::ast::ArraySliceBounds::default(),
215            }],
216            value_argument: 3,
217        };
218        let error = super::super::path::evaluate(&binding, values.len(), None, &control, |index| {
219            reached.push(index);
220            Ok(&values[index])
221        })
222        .unwrap_err();
223        // PostgreSQL 18 evaluates the upper nextval first, reports the NULL lower bound, and never reaches the RHS.
224        assert_eq!(error.sqlstate(), Some("22004"));
225        assert_eq!(reached, [0, 2, 1]);
226        assert_eq!(budget.used(), 0);
227        token.cancel();
228        reached.clear();
229        let error = super::super::path::evaluate(&binding, values.len(), None, &control, |index| {
230            reached.push(index);
231            Ok(&values[index])
232        })
233        .unwrap_err();
234        assert_eq!(error.sqlstate(), Some("57014"));
235        assert!(reached.is_empty());
236        assert_eq!(budget.used(), 0);
237    }
238
239    #[test]
240    fn null_slice_preserves_existing_values_and_materializes_a_null_container() {
241        let budget = MemoryBudget::new(8192);
242        let token = CancellationToken::new();
243        let control = ProductionControl::new(&budget, &token, &token);
244        let original = Value::Array(
245            ArrayValue::with_lower_bounds(vec![Value::Str("retained".repeat(16))], vec![-3])
246                .unwrap(),
247        );
248        for current in [&Value::Null, &original] {
249            let output = assign_array_with_control(
250                current,
251                &Value::Null,
252                &[(Some(1), Some(2))],
253                true,
254                None,
255                &control,
256            )
257            .unwrap();
258            assert_eq!(budget.used(), output.reserved_bytes());
259            assert!(output.reserved_bytes() > 0);
260            if *current == Value::Null {
261                let Value::Array(array) = &*output else {
262                    panic!("NULL slice must produce an array");
263                };
264                assert_eq!(array.elements().len(), 0);
265                assert_eq!(array.dimensions().len(), 0);
266            } else {
267                assert_eq!(*output, original);
268            }
269            drop(output);
270            assert_eq!(budget.used(), 0);
271        }
272        let refused = MemoryBudget::new(0);
273        let control = ProductionControl::new(&refused, &token, &token);
274        for current in [&Value::Null, &original] {
275            assert_eq!(
276                assign_array_with_control(
277                    current,
278                    &Value::Null,
279                    &[(Some(1), Some(2))],
280                    true,
281                    None,
282                    &control
283                )
284                .unwrap_err()
285                .sqlstate(),
286                Some("53200")
287            );
288            assert_eq!(refused.used(), 0);
289        }
290    }
291
292    #[test]
293    fn cancellation_precedes_null_slice_container_copy_and_keeps_the_original_owner() {
294        let budget = MemoryBudget::new(8192);
295        let original = CancellationToken::new();
296        let invoking = CancellationToken::new();
297        invoking.cancel();
298        let control = ProductionControl::new(&budget, &original, &invoking);
299        let error = assign_array_with_control(
300            &Value::Null,
301            &Value::Null,
302            &[(Some(1), Some(2))],
303            true,
304            None,
305            &control,
306        )
307        .unwrap_err();
308        assert!(matches!(error, SQLError::Cancelled(_)));
309        assert_eq!(budget.used(), 0);
310    }
311}