Skip to main content

uqa_sql/assignment/
path.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Evaluate each partial-write operand once, then rebuild its typed containers.
8
9use super::{containers, targets};
10use crate::{
11    ast::{
12        ArraySliceBounds, AssignmentBinding, AssignmentPathStep, AssignmentStep, AssignmentTarget,
13    },
14    expr::{composites::CompositeTypeCatalog, SQLValueCatalog},
15    ColumnType, SQLError,
16};
17use uqa_core::{
18    memory::{Produced, ProductionControl, ProductionVec},
19    Value,
20};
21
22#[cfg(test)]
23mod physical_tests;
24#[cfg(test)]
25mod tests;
26
27/// Bind field identities and operand positions independently of their scalar representation.
28pub fn bind<E>(
29    target: &AssignmentTarget<E>,
30    types: &[ColumnType],
31    composites: Option<&dyn CompositeTypeCatalog>,
32) -> Result<AssignmentBinding, SQLError> {
33    let levels = targets::assignment_levels(&target.indirection);
34    let mut path = Vec::with_capacity(levels.len());
35    let mut next_argument = 1;
36    for (level, ty) in levels.iter().zip(types) {
37        path.push(match level {
38            targets::AssignmentLevel::Field(field) => {
39                let mut base = ty;
40                while let ColumnType::Domain { base: inner, .. } = base {
41                    base = inner;
42                }
43                let ColumnType::Composite(reference) = base else {
44                    return Err(SQLError::Internal(
45                        "field assignment lost its composite type".into(),
46                    ));
47                };
48                let descriptor = crate::expr::composites::descriptor(composites, reference.oid)?;
49                let (_, attribute) = descriptor
50                    .attribute(field)
51                    .ok_or_else(|| SQLError::UnknownColumn((*field).to_owned()))?;
52                AssignmentPathStep::Field {
53                    type_oid: reference.oid,
54                    number: attribute.number,
55                }
56            }
57            targets::AssignmentLevel::Subscripts(steps) => {
58                let slice = level.is_slice();
59                let mut bounds = ArraySliceBounds::default();
60                for (dimension, step) in steps.iter().enumerate() {
61                    if let AssignmentStep::Slice { lower, upper } = step {
62                        bounds.omit(dimension, lower.is_none(), upper.is_none());
63                    }
64                }
65                let first_argument = next_argument;
66                next_argument += steps.len() * if slice { 2 } else { 1 };
67                AssignmentPathStep::Subscripts {
68                    first_argument,
69                    dimensions: steps.len(),
70                    slice,
71                    bounds,
72                }
73            }
74        });
75    }
76    Ok(AssignmentBinding {
77        path,
78        value_argument: next_argument,
79    })
80}
81
82/// Evaluated subscript groups use `PostgreSQL`'s fixed maximum dimensionality.
83#[derive(Clone, Copy)]
84pub enum AssignmentContainer {
85    Field {
86        type_oid: u32,
87        number: i16,
88    },
89    Subscripts {
90        bounds: [(Option<i32>, Option<i32>); crate::ast::MAX_ARRAY_SUBSCRIPT_DIMENSIONS],
91        dimensions: usize,
92        slice: bool,
93    },
94}
95
96impl AssignmentContainer {
97    pub fn subscripts(
98        bounds: &[(Option<i32>, Option<i32>)],
99        slice: bool,
100    ) -> Result<Self, SQLError> {
101        let mut stored = [(None, None); crate::ast::MAX_ARRAY_SUBSCRIPT_DIMENSIONS];
102        if bounds.len() > stored.len() {
103            return Err(containers::array_error(
104                uqa_core::ArrayAssignmentError::SubscriptCount,
105            ));
106        }
107        stored[..bounds.len()].copy_from_slice(bounds);
108        Ok(Self::Subscripts {
109            bounds: stored,
110            dimensions: bounds.len(),
111            slice,
112        })
113    }
114}
115
116pub fn evaluate<B: std::ops::Deref<Target = Value>>(
117    binding: &AssignmentBinding,
118    arguments: usize,
119    catalog: Option<&dyn SQLValueCatalog>,
120    control: &ProductionControl<'_>,
121    mut evaluate: impl FnMut(usize) -> Result<B, SQLError>,
122) -> Result<Produced<Value>, SQLError> {
123    control.check()?;
124    if binding.value_argument.checked_add(1) != Some(arguments) {
125        return Err(SQLError::Internal(
126            "assignment operand layout changed".into(),
127        ));
128    }
129    let current = evaluate(0)?;
130    let mut path = ProductionVec::new(*control);
131    for step in &binding.path {
132        control.check()?;
133        path.push_copy(match *step {
134            AssignmentPathStep::Field { type_oid, number } => {
135                AssignmentContainer::Field { type_oid, number }
136            }
137            AssignmentPathStep::Subscripts {
138                first_argument,
139                dimensions,
140                slice,
141                bounds: omitted,
142            } => {
143                let width = if slice { 2 } else { 1 };
144                if first_argument == 0
145                    || first_argument
146                        .checked_add(dimensions.saturating_mul(width))
147                        .is_none_or(|end| end > binding.value_argument)
148                {
149                    return Err(SQLError::Internal(
150                        "assignment subscript operands changed".into(),
151                    ));
152                }
153                let access = crate::ast::ArrayAccess::from_dispatch(
154                    if slice {
155                        crate::ast::FunctionDispatch::ArraySlicesWithBounds(omitted)
156                    } else {
157                        crate::ast::FunctionDispatch::ArraySubscripts
158                    },
159                    1 + dimensions * width,
160                    |_| false,
161                )
162                .expect("array assignment access")?;
163                access.validate_dimensions()?;
164                let bounds = containers::evaluate_subscript_bounds(
165                    dimensions,
166                    slice,
167                    control,
168                    |dimension, upper| {
169                        let offset = dimension * width + if slice { usize::from(upper) } else { 0 };
170                        if access.is_omitted(1 + offset) {
171                            return Ok(None);
172                        }
173                        let bound = evaluate(first_argument + offset)?;
174                        let bound = crate::expr::cast_value_from_with_control(
175                            &bound, "integer", None, control,
176                        )?;
177                        match *bound {
178                            Value::Int(value) => {
179                                i32::try_from(value)
180                                    .map(Some)
181                                    .map_err(|_| SQLError::Routine {
182                                        sqlstate: "22003".into(),
183                                        message: "integer out of range".into(),
184                                    })
185                            }
186                            Value::Null => Err(SQLError::Routine {
187                                sqlstate: "22004".into(),
188                                message: "array subscript in assignment must not be null".into(),
189                            }),
190                            _ => Err(SQLError::Internal(
191                                "array assignment bound is not an integer".into(),
192                            )),
193                        }
194                    },
195                )?;
196                AssignmentContainer::subscripts(&bounds, slice)?
197            }
198        })?;
199    }
200    let value = evaluate(binding.value_argument)?;
201    assign_with_control(&current, &path, &value, catalog, control)
202}
203
204/// Walk once down the path and rebuild in reverse; retained parents and scratch frames stay admitted until completion or error.
205pub fn assign_with_control(
206    current: &Value,
207    path: &[AssignmentContainer],
208    value: &Value,
209    catalog: Option<&dyn SQLValueCatalog>,
210    control: &ProductionControl<'_>,
211) -> Result<Produced<Value>, SQLError> {
212    struct Frame {
213        current: Value,
214        step: AssignmentContainer,
215    }
216    control.check()?;
217    let mut frames = ProductionVec::new(*control);
218    let mut current = control.copy_value(current)?;
219    for (position, step) in path.iter().enumerate() {
220        control.check()?;
221        if matches!(step, AssignmentContainer::Subscripts { dimensions, .. } if *dimensions > crate::ast::MAX_ARRAY_SUBSCRIPT_DIMENSIONS)
222        {
223            return Err(containers::array_error(
224                uqa_core::ArrayAssignmentError::SubscriptCount,
225            ));
226        }
227        if let Value::Datum(datum) = &*current {
228            current =
229                crate::expr::datums::read_with_value_catalog_and_control(datum, catalog, control)?;
230        }
231        let child = if position + 1 == path.len() {
232            control.copy_value(&Value::Null)?
233        } else {
234            read_child(&current, *step, catalog, control)?
235        };
236        let (parent, memory) = current.into_parts();
237        frames.push_produced(control.finish(
238            Frame {
239                current: parent,
240                step: *step,
241            },
242            memory,
243        )?)?;
244        current = child;
245    }
246    let mut result = control.copy_value(value)?;
247    let frames = frames.finish()?;
248    for frame in frames.iter().rev() {
249        control.check()?;
250        result = match frame.step {
251            AssignmentContainer::Field { type_oid, number } => containers::field_store(
252                type_oid,
253                number,
254                &frame.current,
255                &result,
256                catalog,
257                control,
258            )?,
259            AssignmentContainer::Subscripts {
260                bounds,
261                dimensions,
262                slice,
263            } => containers::assign_array_with_control(
264                &frame.current,
265                &result,
266                &bounds[..dimensions],
267                slice,
268                catalog,
269                control,
270            )?,
271        };
272    }
273    Ok(result)
274}
275
276fn read_child(
277    current: &Value,
278    step: AssignmentContainer,
279    catalog: Option<&dyn SQLValueCatalog>,
280    control: &ProductionControl<'_>,
281) -> Result<Produced<Value>, SQLError> {
282    let value = match step {
283        AssignmentContainer::Field { type_oid, number } => {
284            let types = crate::expr::ValueCompositeCatalog(catalog);
285            let descriptor = crate::expr::composites::descriptor(Some(&types), type_oid)?;
286            let attribute = descriptor
287                .attributes
288                .iter()
289                .find(|attribute| attribute.number == number)
290                .ok_or_else(|| SQLError::Internal("assignment field disappeared".into()))?;
291            return Ok(control.copy_value(match current {
292                Value::Null => &Value::Null,
293                Value::Record(record) => record
294                    .iter()
295                    .find(|(name, _)| *name == &attribute.name)
296                    .map_or(&Value::Null, |(_, value)| value),
297                _ => {
298                    return Err(SQLError::Internal(
299                        "field assignment has a non-composite container".into(),
300                    ))
301                }
302            })?);
303        }
304        AssignmentContainer::Subscripts {
305            bounds,
306            dimensions,
307            slice,
308        } => {
309            if slice {
310                return Err(SQLError::Internal(
311                    "assignment slice cannot have a child field".into(),
312                ));
313            }
314            let mut indices = [0; crate::ast::MAX_ARRAY_SUBSCRIPT_DIMENSIONS];
315            for (index, (_, upper)) in indices.iter_mut().zip(&bounds[..dimensions]) {
316                *index = upper
317                    .ok_or_else(|| SQLError::Internal("assignment index lost its bound".into()))?;
318            }
319            match current {
320                Value::Null => &Value::Null,
321                Value::Array(array) => array
322                    .element_at(&indices[..dimensions])
323                    .unwrap_or(&Value::Null),
324                _ => {
325                    return Err(SQLError::Internal(
326                        "array assignment has a nonarray container".into(),
327                    ))
328                }
329            }
330        }
331    };
332    Ok(control.copy_value(value)?)
333}