Skip to main content

uqa_sql/semantics/
insert_values.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! A single `INSERT ... VALUES` row, which `PostgreSQL` processes like the target list of a SELECT without FROM.
8
9use super::view_rewrite::context::ViewRewriteContext;
10use crate::ast::AssignmentTarget;
11use crate::catalog::view::StoredViewKind;
12use crate::plan::{
13    AccessPathPlan, ComputePlan, InsertPlan, ProjectionPlan, QueryBlockPlan, QueryPlan,
14    RelationalPlan,
15};
16use crate::{SQLError, ScalarExpr};
17use std::collections::BTreeSet;
18
19/// The `INSERT ... SELECT` form of an INSERT whose single VALUES row contains a set-returning call, so the call expands into one inserted row per result as in `PostgreSQL`. A DEFAULT entry leaves its column out of the target list, where the column default fills it as for an omitted column. Any other INSERT has no such form.
20///
21/// `observed` names the NEW columns a rewrite rule of the target reads, or `None` when a rule reads the whole row; it is consulted only for a row that contains a set-returning call. `PostgreSQL` substitutes each VALUES entry for the NEW references to its column, so a rule action or condition that reads a set-returning entry evaluates it outside any target list and fails. `implicit_columns` names the target's columns when the INSERT lists none.
22pub fn single_row_values_query(
23    routines: &dyn crate::routines::RoutineResolution,
24    insert: &InsertPlan,
25    observed: impl FnOnce() -> Result<Option<BTreeSet<String>>, SQLError>,
26    implicit_columns: impl FnOnce() -> Result<Option<Vec<String>>, SQLError>,
27) -> Result<Option<InsertPlan>, SQLError> {
28    let [row] = insert.rows.as_slice() else {
29        return Ok(None);
30    };
31    let set_valued = row
32        .iter()
33        .map(|value| {
34            crate::semantics::sets::static_setness::expression_may_return_set_statically(
35                routines, value,
36            )
37        })
38        .collect::<Vec<_>>();
39    if !set_valued.contains(&true) {
40        return Ok(None);
41    }
42    let Some(observed) = observed()? else {
43        return Err(crate::semantics::sets::placement::set_valued_call_error());
44    };
45    let defaults = row.iter().any(|value| matches!(value, ScalarExpr::Default));
46    let targets = if !insert.columns.is_empty() {
47        insert.columns.clone()
48    } else if defaults || !observed.is_empty() {
49        let Some(columns) = implicit_columns()? else {
50            return Ok(None);
51        };
52        columns
53            .into_iter()
54            .take(row.len())
55            .map(AssignmentTarget::from)
56            .collect()
57    } else {
58        Vec::new()
59    };
60    let explicit = !insert.columns.is_empty() || defaults;
61    if (explicit || !targets.is_empty()) && targets.len() != row.len() {
62        return Ok(None);
63    }
64    if targets
65        .iter()
66        .zip(&set_valued)
67        .any(|(target, set_valued)| *set_valued && observed.contains(&target.column))
68    {
69        return Err(crate::semantics::sets::placement::set_valued_call_error());
70    }
71    let mut columns = Vec::with_capacity(targets.len());
72    let mut projections = Vec::with_capacity(row.len());
73    for (position, value) in row.iter().enumerate() {
74        if matches!(value, ScalarExpr::Default) {
75            continue;
76        }
77        if explicit {
78            columns.push(targets[position].clone());
79        }
80        projections.push(ProjectionPlan {
81            expr: value.clone(),
82            alias: None,
83        });
84    }
85    let values_input = crate::plan::RuleValuesInput {
86        width: projections.len(),
87        inline: true,
88        defaults: Vec::new(),
89        unresolved: uqa_core::memory::OwnedSet::new(),
90        written: (0..projections.len()).collect(),
91    };
92    let source = QueryPlan {
93        analyzed_output: None,
94        analyzed_source: None,
95        analyzed_grouping: None,
96        relation_privilege_subject: None,
97        relations_bound: insert.relations_bound,
98        ctes: Vec::new(),
99        root: RelationalPlan::QueryBlock(Box::new(QueryBlockPlan {
100            deferred_outer_rewrites: Vec::new(),
101            windows: Vec::new(),
102            projections,
103            privilege_columns: uqa_core::memory::OwnedSet::new(),
104            from: None,
105            r#where: None,
106            compute: ComputePlan::Project,
107            group_by: Vec::new(),
108            grouping_sets: Vec::new(),
109            group_distinct: false,
110            having: None,
111            order_by: Vec::new(),
112            limit: None,
113            with_ties: false,
114            offset: None,
115            distinct: false,
116            distinct_on: Vec::new(),
117            subqueries: insert.subqueries.clone(),
118            access: AccessPathPlan::Row,
119            locking: Vec::new(),
120        })),
121    };
122    let mut expanded = insert.clone();
123    expanded.rows = Vec::new();
124    expanded.columns = columns;
125    expanded.source = Some(Box::new(source));
126    expanded.rule_values_input = Some(values_input);
127    Ok(Some(expanded))
128}
129
130/// The columns an INSERT without a column list fills in order: a table's columns or a view's output columns. A materialized view cannot be a target, and its INSERT keeps the form that reports so.
131pub fn implicit_target_columns(
132    context: ViewRewriteContext<'_>,
133    table: &str,
134) -> Result<Option<Vec<String>>, SQLError> {
135    match context.catalog.target_view_kind(table)? {
136        Some(StoredViewKind::View) => Ok(Some(
137            super::view_mutation::resolve_view_target(context, table)?.columns,
138        )),
139        Some(StoredViewKind::Materialized) => Ok(None),
140        None => context
141            .catalog
142            .try_table_columns(table)
143            .map(Some)
144            .map_err(SQLError::Internal),
145    }
146}
147
148#[cfg(test)]
149mod tests;