Skip to main content

uqa_sql/semantics/rules/binding/actions/query/values/
owned.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Native VALUES action construction retains default provenance and every generated input under the invoking request's allowance.
8
9use super::{overrides_identity, ValuesInput};
10use crate::{
11    ast::{ColumnDef, Expr, FunctionOrderSyntax},
12    plan::{
13        copy::{copy_syntax_with_control, SyntaxProduction},
14        CommandPlan, InsertPlan, MutableCommandPlan,
15    },
16    production::Buffer,
17    semantics::rules::analysis::{rule_returning_columns_with_control, RuleAnalysisContext},
18    ColumnType, SQLError, ScalarExpr,
19};
20use uqa_core::{
21    memory::{Produced, ProductionControl},
22    Value,
23};
24
25mod source;
26
27impl ValuesInput {
28    pub fn describe_with_control(
29        insert: &InsertPlan,
30        control: &ProductionControl<'_>,
31    ) -> Result<Option<Produced<Self>>, SQLError> {
32        control.check()?;
33        if insert.source.is_some() {
34            return insert
35                .rule_values_input
36                .as_ref()
37                .map(|input| input.copy_resolved(&[], control))
38                .transpose();
39        }
40        let width = insert.rows.first().map_or(insert.columns.len(), Vec::len);
41        for row in &insert.rows {
42            control.check()?;
43            if row.len() != width {
44                return Err(SQLError::Routine {
45                    sqlstate: "42601".into(),
46                    message: "VALUES lists must all be the same length".into(),
47                });
48            }
49        }
50        let output = SyntaxProduction::new(*control);
51        let mut defaults = output.vector(0)?;
52        for position in 0..width {
53            output.check()?;
54            if insert
55                .rows
56                .iter()
57                .any(|row| matches!(row[position], ScalarExpr::Default))
58            {
59                defaults.push(position)?;
60            }
61        }
62        let defaults = defaults.finish()?;
63        let value = Self {
64            width,
65            inline: insert.rows.len() == 1,
66            unresolved: output.set_copy(defaults.iter().copied())?,
67            defaults,
68            written: output.set_copy((0..width).filter(|position| {
69                insert
70                    .rows
71                    .iter()
72                    .any(|row| !matches!(row[*position], ScalarExpr::Default))
73            }))?,
74        };
75        Ok(Some(output.finish(value)?))
76    }
77
78    fn copy_resolved(
79        &self,
80        resolved: &[bool],
81        control: &ProductionControl<'_>,
82    ) -> Result<Produced<Self>, SQLError> {
83        let output = SyntaxProduction::new(*control);
84        let value = Self {
85            width: self.width,
86            inline: self.inline,
87            defaults: output.copy(&self.defaults)?,
88            unresolved: output.set_copy(
89                self.unresolved
90                    .iter()
91                    .copied()
92                    .filter(|position| !resolved.get(*position).copied().unwrap_or(false)),
93            )?,
94            written: output.set_copy(self.written.iter().copied())?,
95        };
96        output.finish(value)
97    }
98}
99
100struct InputColumns {
101    definitions: Produced<Vec<ColumnDef>>,
102    selected: Buffer<(usize, Produced<ColumnType>)>,
103}
104
105fn input_columns(
106    context: RuleAnalysisContext<'_>,
107    mut command: MutableCommandPlan,
108    width: usize,
109    control: &ProductionControl<'_>,
110) -> Result<(MutableCommandPlan, InputColumns), SQLError> {
111    let definitions =
112        rule_returning_columns_with_control(context, &insert(&command)?.table, control)?;
113    command = command.set_implicit_insert_columns(
114        definitions
115            .iter()
116            .take(width)
117            .map(|column| column.name.as_str()),
118        control,
119    )?;
120    let insert = insert(&command)?;
121    if insert.columns.len() != width {
122        return Err(SQLError::Routine {
123            sqlstate: "42601".into(),
124            message: if insert.columns.len() < width {
125                "INSERT has more expressions than target columns"
126            } else {
127                "INSERT has more target columns than expressions"
128            }
129            .into(),
130        });
131    }
132    let mut selected = Buffer::new(control);
133    for target in &insert.columns {
134        control.check()?;
135        let index = definitions
136            .iter()
137            .position(|column| column.name == target.column)
138            .ok_or_else(|| SQLError::UnknownColumn(target.column.clone()))?;
139        let ty = crate::assignment::targets::assignment_input_type_with_control(
140            target,
141            &definitions[index].ty,
142            context.composites,
143            control,
144        )?;
145        selected.push((index, ty), control)?;
146    }
147    Ok((
148        command,
149        InputColumns {
150            definitions,
151            selected,
152        },
153    ))
154}
155
156fn insert(command: &MutableCommandPlan) -> Result<&InsertPlan, SQLError> {
157    let CommandPlan::Insert(insert) = &**command else {
158        return Err(SQLError::Internal(
159            "VALUES action preparation requires INSERT".into(),
160        ));
161    };
162    Ok(insert)
163}
164
165pub(in crate::semantics::rules::binding::actions::query) fn default_expression(
166    context: RuleAnalysisContext<'_>,
167    column: &ColumnDef,
168    control: &ProductionControl<'_>,
169) -> Result<Option<Produced<Expr>>, SQLError> {
170    if let Some(identity) = column
171        .auto_increment
172        .as_ref()
173        .filter(|identity| identity.is_identity())
174    {
175        let sequence = identity
176            .sequence
177            .as_deref()
178            .ok_or_else(|| SQLError::Routine {
179                sqlstate: "XX000".into(),
180                message: "no owned sequence found".into(),
181            })?;
182        let output = SyntaxProduction::new(*control);
183        let mut arguments = output.vector(1)?;
184        arguments.push(Expr::Literal(Value::Str(output.text(sequence)?)))?;
185        let expression = Expr::Func {
186            name: output.text("nextval")?,
187            binding: None,
188            args: arguments.finish()?,
189            order_syntax: FunctionOrderSyntax::Ordinary,
190            distinct: false,
191            order_by: Vec::new(),
192            filter: None,
193        };
194        return Ok(Some(output.finish(expression)?));
195    }
196    if let Some(default) = &column.default {
197        return Ok(Some(copy_syntax_with_control(default, control)?));
198    }
199    let mut ty = &column.ty;
200    while let ColumnType::Domain { oid, base, .. } = ty {
201        if let Some(domain) = context.domains.domain_by_oid_with_control(*oid, control)? {
202            if let Some(default) = &domain.definition.default {
203                return Ok(Some(copy_syntax_with_control(default, control)?));
204            }
205        }
206        ty = base;
207    }
208    Ok(None)
209}