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::catalog::view::StoredViewKind;
11use crate::plan::{CommandPlan, InsertPlan};
12use crate::SQLError;
13use std::collections::BTreeSet;
14use uqa_core::memory::ProductionControl;
15
16mod production;
17pub use production::{implicit_target_columns_with_control, single_row_values_query_with_control};
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 control = ProductionControl::uncontrolled();
29    let expanded = single_row_values_query_with_control(
30        routines,
31        insert,
32        || {
33            observed()?
34                .map(|names| Ok(control.finish(names.into_iter().collect(), None)?))
35                .transpose()
36        },
37        || {
38            implicit_columns()?
39                .map(|names| Ok(control.finish(names, None)?))
40                .transpose()
41        },
42        &control,
43    )?;
44    expanded
45        .map(|expanded| {
46            let CommandPlan::Insert(plan) = expanded
47                .finish(&control)?
48                .into_uncontrolled()
49                .expect("ordinary VALUES expansion")
50            else {
51                unreachable!("INSERT VALUES expansion")
52            };
53            Ok(*plan)
54        })
55        .transpose()
56}
57
58/// 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.
59pub fn implicit_target_columns(
60    context: ViewRewriteContext<'_>,
61    table: &str,
62) -> Result<Option<Vec<String>>, SQLError> {
63    match context.catalog.target_view_kind(table)? {
64        Some(StoredViewKind::View) => Ok(Some(
65            super::view_mutation::resolve_view_target(context, table)?.columns,
66        )),
67        Some(StoredViewKind::Materialized) => Ok(None),
68        None => context
69            .catalog
70            .try_table_columns(table)
71            .map(Some)
72            .map_err(SQLError::Internal),
73    }
74}
75
76#[cfg(test)]
77mod tests;