Skip to main content

uqa_execution/mutation/
dispatch.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Resolve mutation execution paths using SQL view rewriting and execution-owned command loops.
8use super::insert::table::InsertPlanning;
9use crate::mutation::output::MutationOutput;
10use crate::mutation::statement::context::MutationStatementContext;
11use crate::query::CteScope;
12use uqa_sql::{
13    plan::{DeletePlan, InsertPlan, MergePlan, UpdatePlan},
14    semantics::{view_privileges, view_rewrite},
15    SQLError, SQLParam,
16};
17
18pub fn run_insert<S: Clone + Send + Sync + 'static>(
19    context: &MutationStatementContext<'_, S>,
20    planning: InsertPlanning<'_>,
21    stmt: &InsertPlan,
22    params: &[SQLParam],
23    inherited_ctes: Option<&CteScope<S>>,
24) -> Result<MutationOutput, SQLError> {
25    let rewrite = context.mutation.rules.views;
26    let retained = context.mutation.scopes.read_control()?;
27    let control = uqa_core::memory::ProductionControl::new(
28        retained.memory(),
29        retained.cancellation(),
30        context.mutation.scopes.cancellation(),
31    );
32
33    if let Some(kind) = rewrite
34        .catalog
35        .target_view_kind_with_control(&stmt.table, &control)?
36    {
37        if kind == uqa_sql::catalog::view::StoredViewKind::Materialized {
38            let _ =
39                view_privileges::ensure_insert_with_control(rewrite.authorization, stmt, &control)?;
40            let relation = uqa_core::RelationIdentity::from_legacy_name(&stmt.table)
41                .map_err(SQLError::Internal)?;
42            return Err(SQLError::Routine {
43                sqlstate: "42809".into(),
44                message: format!("cannot change materialized view \"{}\"", relation.name),
45            });
46        }
47        if rewrite.catalog.has_trigger_definition_with_control(
48            &stmt.table,
49            uqa_sql::ast::TriggerTiming::InsteadOf,
50            uqa_sql::ast::TriggerEvent::Insert,
51            true,
52            &control,
53        )? || rewrite
54            .catalog
55            .capture_rules_with_control(&stmt.table, uqa_sql::ast::RuleEvent::Insert, &control)?
56            .any(|rule| rule.definition.instead && rule.definition.condition.is_none())?
57        {
58            let _ =
59                view_privileges::ensure_insert_with_control(rewrite.authorization, stmt, &control)?;
60            let expanded = set_returning_values_query(context, stmt, &control)?;
61            let stmt = expanded.as_deref().map_or(stmt, expanded_insert);
62            super::routine_calls::insert(context, stmt, params, inherited_ctes)?;
63            return super::views::commands::run_view_insert_inner(
64                context,
65                planning.prune_source_outputs,
66                stmt,
67                params,
68                inherited_ctes,
69            );
70        }
71        let bindings = inherited_ctes
72            .map(|scope| crate::query::binding::binding_snapshot_with_control(scope, &control))
73            .transpose()?;
74        let rewritten = view_rewrite::rewrite_insert_owned(
75            rewrite,
76            stmt.copy_for_rewrite(&control)?,
77            params,
78            bindings
79                .as_ref()
80                .map(view_rewrite::ViewRewriteBindings::Controlled),
81            &control,
82        )?;
83        let uqa_sql::plan::CommandPlan::Insert(plan) = &*rewritten else {
84            unreachable!("rewritten INSERT")
85        };
86        return run_insert(context, planning, plan, params, inherited_ctes);
87    }
88    let expanded = set_returning_values_query(context, stmt, &control)?;
89    crate::mutation::insert::table::run_table_insert(
90        context,
91        planning,
92        expanded.as_deref().map_or(stmt, expanded_insert),
93        params,
94        inherited_ctes,
95    )
96}
97
98/// A single VALUES row runs as a target list, so its set-returning calls insert one row per result; the INSERT then takes its `INSERT ... SELECT` form. The target's own rewrite rules decide whether they read such an entry.
99fn set_returning_values_query<S: Clone + Send + Sync + 'static>(
100    context: &MutationStatementContext<'_, S>,
101    stmt: &InsertPlan,
102    control: &uqa_core::memory::ProductionControl<'_>,
103) -> Result<Option<uqa_sql::plan::MutableCommandPlan>, SQLError> {
104    uqa_sql::semantics::insert_values::single_row_values_query_with_control(
105        context.query.source.ctes.routines,
106        stmt,
107        || {
108            uqa_sql::semantics::rules::analysis::relation_rule_row_columns_with_control(
109                context.mutation.rules.rules.analysis,
110                &stmt.table,
111                uqa_sql::ast::RuleEvent::Insert,
112                control,
113            )
114        },
115        || {
116            uqa_sql::semantics::insert_values::implicit_target_columns_with_control(
117                context.mutation.rules.views,
118                &stmt.table,
119                control,
120            )
121        },
122        control,
123    )
124}
125
126fn expanded_insert(command: &uqa_sql::plan::CommandPlan) -> &InsertPlan {
127    let uqa_sql::plan::CommandPlan::Insert(plan) = command else {
128        unreachable!("INSERT VALUES expansion")
129    };
130    plan
131}
132
133pub fn run_update<S: Clone + Send + Sync + 'static>(
134    context: &MutationStatementContext<'_, S>,
135    stmt: &UpdatePlan,
136    params: &[SQLParam],
137    inherited_ctes: Option<&CteScope<S>>,
138) -> Result<MutationOutput, SQLError> {
139    super::rules::schedule::run_update(context, stmt, params, inherited_ctes)
140}
141
142pub fn run_delete<S: Clone + Send + Sync + 'static>(
143    context: &MutationStatementContext<'_, S>,
144    stmt: &DeletePlan,
145    params: &[SQLParam],
146    inherited_ctes: Option<&CteScope<S>>,
147) -> Result<MutationOutput, SQLError> {
148    super::rules::schedule::run_delete(context, stmt, params, inherited_ctes)
149}
150
151pub fn run_merge<S: Clone + Send + Sync + 'static>(
152    context: &MutationStatementContext<'_, S>,
153    stmt: &MergePlan,
154    params: &[SQLParam],
155    inherited_ctes: Option<&CteScope<S>>,
156) -> Result<MutationOutput, SQLError> {
157    let rewrite = context.mutation.rules.views;
158    let retained = context.mutation.scopes.read_control()?;
159    let control = uqa_core::memory::ProductionControl::new(
160        retained.memory(),
161        retained.cancellation(),
162        context.mutation.scopes.cancellation(),
163    );
164
165    if rewrite
166        .catalog
167        .target_view_kind_with_control(&stmt.target, &control)?
168        .is_some()
169    {
170        let scope = super::merge::analysis::merge_analysis_scope(
171            context.mutation.scopes,
172            stmt,
173            inherited_ctes,
174        )?;
175        let bindings = crate::query::binding::binding_context_with_control(&scope, &control)?;
176        let source = uqa_sql::binding::analyze_source_plan_schema_with_control(
177            rewrite.routines,
178            &stmt.source,
179            params,
180            bindings,
181            None,
182            &control,
183        )?;
184        view_rewrite::validate_public_merge_targets_with_control(rewrite, stmt, &control)?;
185        view_rewrite::validate_public_merge_contract_with_control(
186            rewrite, stmt, &source, &control,
187        )?;
188        return match view_rewrite::merge_view_target_path_with_control(rewrite, stmt, &control)? {
189            view_rewrite::MergeViewTargetPath::AutomaticRewrite => {
190                let inherited = inherited_ctes
191                    .map(|scope| {
192                        crate::query::binding::binding_snapshot_with_control(scope, &control)
193                    })
194                    .transpose()?;
195                let rewritten = view_rewrite::rewrite_merge_owned(
196                    rewrite,
197                    stmt.copy_for_rewrite(&control)?,
198                    params,
199                    inherited
200                        .as_ref()
201                        .map(view_rewrite::ViewRewriteBindings::Controlled),
202                    &control,
203                )?;
204                let uqa_sql::plan::CommandPlan::Merge(plan) = &*rewritten else {
205                    unreachable!("rewritten MERGE")
206                };
207                run_merge(context, plan, params, inherited_ctes)
208            }
209            view_rewrite::MergeViewTargetPath::ViewTriggers => {
210                let _ = view_privileges::ensure_merge_with_control(
211                    rewrite.authorization,
212                    stmt,
213                    &control,
214                )?;
215                super::routine_calls::merge(context, stmt, params, inherited_ctes)?;
216                super::merge::views::run_view_merge(context, stmt, params, inherited_ctes)
217            }
218        };
219    }
220    super::merge::table::run_table_merge(context, stmt, params, inherited_ctes)
221}