Skip to main content

uqa_sql/assignment/
targets.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Type selection and duplicate-column rules for whole and subscripted assignments.
8
9use crate::{
10    ast::{AssignmentStep, AssignmentTarget},
11    ColumnType, SQLError,
12};
13use uqa_core::memory::{ProductionControl, ProductionMap};
14
15mod types;
16pub use types::{assignment_input_type_with_control, field_assignment_types_with_control};
17
18#[cfg(test)]
19mod tests;
20
21/// Produce an implicit whole-column target without cloning unrelated declaration expressions.
22pub fn whole_column_with_control<E>(
23    name: &str,
24    control: &ProductionControl<'_>,
25) -> Result<uqa_core::memory::Produced<AssignmentTarget<E>>, SQLError> {
26    let (column, memory) = control.copy_text(name)?.into_parts();
27    Ok(control.finish(AssignmentTarget::from(column), memory)?)
28}
29
30fn error(code: &str, message: String) -> SQLError {
31    SQLError::Routine {
32        sqlstate: code.into(),
33        message,
34    }
35}
36
37/// Whole-column writes may target an open schema. Partial writes require a declared container type before evaluating bounds or values.
38pub fn validate_assignment_type<E>(
39    target: &AssignmentTarget<E>,
40    declared: Option<&ColumnType>,
41) -> Result<(), SQLError> {
42    if declared.is_none() && !target.is_whole_column() {
43        array_assignment_type(target, &ColumnType::Named("unknown".into()))?;
44    }
45    Ok(())
46}
47
48/// Repeated partial targets compose, but a whole-column write cannot share its destination.
49pub fn validate_repeated_targets<'a, E: 'a>(
50    targets: impl IntoIterator<Item = &'a AssignmentTarget<E>>,
51    insert: bool,
52) -> Result<(), SQLError> {
53    validate_repeated_targets_with_control(targets, insert, &ProductionControl::uncontrolled())
54}
55
56pub fn validate_repeated_targets_with_control<'a, E: 'a>(
57    targets: impl IntoIterator<Item = &'a AssignmentTarget<E>>,
58    insert: bool,
59    control: &ProductionControl<'_>,
60) -> Result<(), SQLError> {
61    control.check()?;
62    let mut seen = ProductionMap::new(*control);
63    for target in targets {
64        let whole = target.is_whole_column();
65        if let Some(previous) = seen.insert_copy(target.column.as_str(), whole)? {
66            if whole || previous {
67                let sqlstate = control.copy_text(if insert { "42701" } else { "42601" })?;
68                let message = if insert {
69                    control.format(format_args!(
70                        "column \"{}\" specified more than once",
71                        target.column
72                    ))?
73                } else {
74                    control.format(format_args!(
75                        "multiple assignments to same column \"{}\"",
76                        target.column
77                    ))?
78                };
79                return Err(SQLError::Routine {
80                    sqlstate: sqlstate.into_parts().0,
81                    message: message.into_parts().0,
82                });
83            }
84        }
85    }
86    Ok(())
87}
88
89/// The array container produced by subscripting, before restoring a domain or legacy vector type.
90pub fn array_assignment_type<E>(
91    target: &AssignmentTarget<E>,
92    declared: &ColumnType,
93) -> Result<ColumnType, SQLError> {
94    Ok(array_assignment_type_with_control(
95        target,
96        declared,
97        &uqa_core::memory::ProductionControl::uncontrolled(),
98    )?
99    .into_uncontrolled()
100    .expect("ordinary array assignment type"))
101}
102
103pub fn array_assignment_type_with_control<E>(
104    target: &AssignmentTarget<E>,
105    declared: &ColumnType,
106    control: &uqa_core::memory::ProductionControl<'_>,
107) -> Result<uqa_core::memory::Produced<ColumnType>, SQLError> {
108    control.check()?;
109    let mut base = declared;
110    while let ColumnType::Domain { base: inner, .. } = base {
111        control.check()?;
112        base = inner;
113    }
114    if let Some(AssignmentStep::Field(field)) = target.indirection.first() {
115        return Err(error("42804", format!(
116            "cannot assign to field \"{field}\" of column \"{}\" because its type {} is not a composite type",
117            target.column, &*declared.sql_name_with_control(control)?
118        )));
119    }
120    let array = match base {
121        ColumnType::Array(_) => base.clone_with_control(control)?,
122        ColumnType::Int2Vector | ColumnType::OidVector => {
123            let output = crate::plan::copy::SyntaxProduction::new(*control);
124            let element = if matches!(base, ColumnType::Int2Vector) {
125                ColumnType::SmallInteger
126            } else {
127                ColumnType::Oid
128            };
129            let array = ColumnType::Array(output.boxed(element)?);
130            output.finish(array)?
131        }
132        _ => {
133            return Err(error(
134                "42804",
135                format!(
136                    "cannot subscript type {} because it does not support subscripting",
137                    &*declared.sql_name_with_control(control)?
138                ),
139            ))
140        }
141    };
142    if let Some(AssignmentStep::Field(field)) = target
143        .indirection
144        .iter()
145        .find(|step| matches!(step, AssignmentStep::Field(_)))
146    {
147        let mut element = &*array;
148        while let ColumnType::Array(inner) = element {
149            element = inner;
150        }
151        return Err(error("42804", format!(
152            "cannot assign to field \"{field}\" of column \"{}\" because its type {} is not a composite type",
153            target.column, &*element.sql_name_with_control(control)?
154        )));
155    }
156    if target.indirection.len() > 6 {
157        return Err(error(
158            "54000",
159            format!(
160                "number of array dimensions ({}) exceeds the maximum allowed (6)",
161                target.indirection.len()
162            ),
163        ));
164    }
165    Ok(array)
166}
167
168/// One level of an assignment target: a composite field, or the consecutive subscripts that `transformAssignmentSubscripts` applies together.
169pub enum AssignmentLevel<'a, E> {
170    Field(&'a str),
171    Subscripts(&'a [AssignmentStep<E>]),
172}
173
174impl<E> AssignmentLevel<'_, E> {
175    /// Whether a subscript group writes a slice.
176    pub fn is_slice(&self) -> bool {
177        match self {
178            Self::Field(_) => false,
179            Self::Subscripts(steps) => steps
180                .iter()
181                .any(|step| matches!(step, AssignmentStep::Slice { .. })),
182        }
183    }
184}
185
186/// Group an assignment's indirection into fields and subscript groups, in order.
187pub fn assignment_levels<E>(steps: &[AssignmentStep<E>]) -> Vec<AssignmentLevel<'_, E>> {
188    assignment_level_iter(steps).collect()
189}
190
191pub(crate) fn assignment_level_iter<E>(
192    steps: &[AssignmentStep<E>],
193) -> impl Iterator<Item = AssignmentLevel<'_, E>> {
194    let mut remaining = steps;
195    std::iter::from_fn(move || {
196        let first = remaining.first()?;
197        if let AssignmentStep::Field(field) = first {
198            remaining = &remaining[1..];
199            Some(AssignmentLevel::Field(field))
200        } else {
201            let count = remaining
202                .iter()
203                .take_while(|step| !matches!(step, AssignmentStep::Field(_)))
204                .count();
205            let (group, tail) = remaining.split_at(count);
206            remaining = tail;
207            Some(AssignmentLevel::Subscripts(group))
208        }
209    })
210}
211
212/// Whether an assignment writes a composite field somewhere along its indirection.
213pub fn has_field_step<E>(target: &AssignmentTarget<E>) -> bool {
214    target
215        .indirection
216        .iter()
217        .any(|step| matches!(step, AssignmentStep::Field(_)))
218}
219
220/// The type each level of a field assignment applies to, followed by the type the assigned value must have, as `transformAssignmentIndirection` resolves them: a field names an attribute of a composite type or of a domain over one, and a subscript group selects an array element, or keeps the array for a slice.
221pub fn field_assignment_types<E>(
222    target: &AssignmentTarget<E>,
223    declared: &ColumnType,
224    composites: Option<&dyn crate::expr::composites::CompositeTypeCatalog>,
225) -> Result<Vec<ColumnType>, SQLError> {
226    Ok(field_assignment_types_with_control(
227        target,
228        declared,
229        composites,
230        &uqa_core::memory::ProductionControl::uncontrolled(),
231    )?
232    .into_uncontrolled()
233    .expect("ordinary assignment types"))
234}
235
236/// Slices consume an array; any number of element subscripts consumes one scalar element.
237pub fn assignment_value_type<E>(
238    target: &AssignmentTarget<E>,
239    declared: &ColumnType,
240) -> Result<ColumnType, SQLError> {
241    if target.is_whole_column() {
242        return Ok(declared.clone());
243    }
244    let array = array_assignment_type(target, declared)?;
245    if target
246        .indirection
247        .iter()
248        .any(|step| matches!(step, AssignmentStep::Slice { .. }))
249    {
250        Ok(array)
251    } else {
252        let mut element = &array;
253        while let ColumnType::Array(inner) = element {
254            element = inner;
255        }
256        Ok(element.clone())
257    }
258}
259
260/// Type errors retain `PostgreSQL`'s separate primary message and rewrite hint.
261pub fn validate_assignment_source<E>(
262    target: &AssignmentTarget<E>,
263    required: &ColumnType,
264    source: Option<&ColumnType>,
265) -> Result<(), SQLError> {
266    if let Some(source) = source {
267        if !crate::assignment_type_compatible(source, required) {
268            // `transformAssignmentIndirection` names the innermost field it assigns through.
269            let levels = assignment_levels(&target.indirection);
270            let name = levels
271                .iter()
272                .rev()
273                .find_map(|level| match level {
274                    AssignmentLevel::Field(field) => Some(*field),
275                    AssignmentLevel::Subscripts(_) => None,
276                })
277                .unwrap_or(&target.column);
278            let message = match levels.last() {
279                None => format!(
280                    "column \"{}\" is of type {} but expression is of type {}",
281                    target.column,
282                    required.display_name(),
283                    source.display_name()
284                ),
285                Some(AssignmentLevel::Field(field)) => format!(
286                    "subfield \"{field}\" is of type {} but expression is of type {}",
287                    required.display_name(),
288                    source.display_name()
289                ),
290                Some(AssignmentLevel::Subscripts(_)) => format!(
291                    "subscripted assignment to \"{name}\" requires type {} but expression is of type {}",
292                    required.display_name(),
293                    source.display_name()
294                ),
295            };
296            return Err(SQLError::Diagnostic {
297                sqlstate: "42804".into(),
298                message,
299                detail: None,
300                hint: Some("You will need to rewrite or cast the expression.".into()),
301            });
302        }
303    }
304    Ok(())
305}
306
307/// Subscripting yields an ordinary array; the declared destination must accept that container.
308pub fn validate_assignment_result<E>(
309    target: &AssignmentTarget<E>,
310    declared: &ColumnType,
311) -> Result<(), SQLError> {
312    validate_assignment_result_with_control(
313        target,
314        declared,
315        &uqa_core::memory::ProductionControl::uncontrolled(),
316    )
317}
318
319pub fn validate_assignment_result_with_control<E>(
320    target: &AssignmentTarget<E>,
321    declared: &ColumnType,
322    control: &uqa_core::memory::ProductionControl<'_>,
323) -> Result<(), SQLError> {
324    control.check()?;
325    // A field write rebuilds the column's own composite value.
326    if target.is_whole_column() || has_field_step(target) {
327        return Ok(());
328    }
329    let container = array_assignment_type_with_control(target, declared, control)?;
330    if !crate::type_resolution::explicit_type_compatible(&container, declared) {
331        return Err(error(
332            "42846",
333            format!(
334                "cannot cast type {} to {}",
335                &*container.sql_name_with_control(control)?,
336                &*declared.sql_name_with_control(control)?
337            ),
338        ));
339    }
340    Ok(())
341}
342
343pub fn validate_assignment_default<E>(target: &AssignmentTarget<E>) -> Result<(), SQLError> {
344    match target.indirection.first() {
345        None => Ok(()),
346        Some(AssignmentStep::Field(_)) => {
347            Err(error("0A000", "cannot set a subfield to DEFAULT".into()))
348        }
349        Some(_) => Err(error(
350            "0A000",
351            "cannot set an array element to DEFAULT".into(),
352        )),
353    }
354}