Skip to main content

uqa_execution/mutation/statement/
context.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Read generation and writable services for mutation command orchestration.
8use super::MutationExecutionContext;
9use crate::mutation::insert::source::InsertSourceContext;
10use crate::query::statement::context::{QueryContext, SnapshotSource};
11use uqa_sql::SQLError;
12
13pub trait MutationSnapshots<S: Clone + 'static>: SnapshotSource<S> {
14    fn with_snapshot(
15        &self,
16        snapshot: &S,
17        operation: &mut dyn ScopedMutationOperation<S>,
18    ) -> Result<(), SQLError>;
19}
20pub trait ScopedMutationOperation<S: Clone + 'static> {
21    fn run(&mut self, context: &MutationStatementContext<'_, S>) -> Result<(), SQLError>;
22}
23#[derive(Clone)]
24pub struct MutationStatementContext<'a, S: Clone + 'static> {
25    pub query: QueryContext<'a, S>,
26    pub mutation: MutationExecutionContext<'a, S>,
27    pub snapshots: &'a dyn MutationSnapshots<S>,
28}
29impl<S: Clone + 'static> Copy for MutationStatementContext<'_, S> {}
30
31impl<'a, S: Clone + 'static> MutationStatementContext<'a, S> {
32    pub fn insert_source(&self) -> InsertSourceContext<'a, S> {
33        InsertSourceContext {
34            rows: self.mutation.preparation,
35            identities: self.mutation.identities,
36            runtime: self.query.source.relational.runtime,
37        }
38    }
39}
40
41pub fn with_mutation_snapshot<S: Clone + 'static, T>(
42    snapshots: &dyn MutationSnapshots<S>,
43    snapshot: &S,
44    action: impl for<'scope> FnOnce(&MutationStatementContext<'scope, S>) -> Result<T, SQLError>,
45) -> Result<T, SQLError> {
46    struct Operation<F, T> {
47        action: Option<F>,
48        result: Option<T>,
49    }
50    impl<S: Clone + 'static, F, T> ScopedMutationOperation<S> for Operation<F, T>
51    where
52        F: for<'scope> FnOnce(&MutationStatementContext<'scope, S>) -> Result<T, SQLError>,
53    {
54        fn run(&mut self, context: &MutationStatementContext<'_, S>) -> Result<(), SQLError> {
55            let action = self.action.take().ok_or_else(|| {
56                SQLError::Internal("statement snapshot operation was invoked more than once".into())
57            })?;
58            self.result = Some(action(context)?);
59            Ok(())
60        }
61    }
62    let mut operation = Operation {
63        action: Some(action),
64        result: None,
65    };
66    snapshots.with_snapshot(snapshot, &mut operation)?;
67    operation
68        .result
69        .ok_or_else(|| SQLError::Internal("statement snapshot operation was not invoked".into()))
70}