Skip to main content

uqa_execution/mutation/
command_scope.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Command state boundaries independent of the owning session.
8use crate::query::CteScope;
9use uqa_sql::catalog::roles::RoleReference;
10use uqa_sql::SQLError;
11/// Mutation lifecycle operations on the active transaction frame.
12pub trait MutationCommandState {
13    fn prepare_writer(&self) -> Result<(), SQLError>;
14    fn begin_overlay(&self);
15    fn end_overlay(&self) -> super::overlay::CommandMutationOverlay;
16}
17/// Capture catalog, namespace, trigger transition, and privilege state for a command.
18pub trait CommandScopeSource<S: Clone> {
19    fn read_control(&self) -> Result<uqa_storage::read_control::StorageReadControl, SQLError>;
20    fn cancellation(&self) -> &uqa_core::CancellationToken;
21
22    fn command_scope(
23        &self,
24        privilege_subject: Option<&RoleReference>,
25        relations_bound: bool,
26    ) -> Result<CteScope<S>, SQLError>;
27}
28pub struct MutationOverlayScope<'a> {
29    state: Option<&'a dyn MutationCommandState>,
30}
31impl<'a> MutationOverlayScope<'a> {
32    pub fn new(state: &'a dyn MutationCommandState) -> Self {
33        state.begin_overlay();
34        Self { state: Some(state) }
35    }
36
37    pub fn finish(mut self) -> Option<super::overlay::CommandMutationOverlay> {
38        self.state
39            .take()
40            .expect("an active command overlay")
41            .end_overlay()
42            .published_rows()
43    }
44}
45impl Drop for MutationOverlayScope<'_> {
46    fn drop(&mut self) {
47        if let Some(state) = self.state.take() {
48            state.end_overlay();
49        }
50    }
51}
52
53/// Retain the command's original read generation when CTE writes or BEFORE statement triggers can change visible rows.
54pub fn capture_command_read_snapshot<S: Clone + 'static>(
55    snapshots: &dyn crate::query::statement::context::SnapshotSource<S>,
56    inherited: Option<&CteScope<S>>,
57    before_statement_trigger: bool,
58    ctes: &[uqa_sql::plan::CtePlan],
59) -> Result<Option<std::sync::Arc<S>>, SQLError> {
60    match inherited.and_then(CteScope::command_cte_snapshot) {
61        Some(snapshot) => Ok(Some(snapshot)),
62        None if before_statement_trigger || ctes.iter().any(|cte| cte.body.modifies_data()) => {
63            Ok(Some(std::sync::Arc::new(snapshots.capture()?)))
64        }
65        None => Ok(None),
66    }
67}