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