uqa_execution/mutation/statement/
context.rs1use 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 with_destination<'b>(
33 self,
34 destination: Option<crate::mutation::returning::ReturningDestination<'b>>,
35 ) -> MutationStatementContext<'b, S>
36 where
37 'a: 'b,
38 {
39 let mut context = self;
40 context.mutation.preparation.returning.destination = destination;
41 context
42 }
43
44 pub fn insert_source(&self) -> InsertSourceContext<'a, S> {
45 InsertSourceContext {
46 rows: self.mutation.preparation,
47 identities: self.mutation.identities,
48 runtime: self.query.source.relational.runtime,
49 }
50 }
51}
52
53pub fn with_mutation_snapshot<S: Clone + 'static, T>(
54 snapshots: &dyn MutationSnapshots<S>,
55 snapshot: &S,
56 action: impl for<'scope> FnOnce(&MutationStatementContext<'scope, S>) -> Result<T, SQLError>,
57) -> Result<T, SQLError> {
58 struct Operation<F, T> {
59 action: Option<F>,
60 result: Option<T>,
61 }
62 impl<S: Clone + 'static, F, T> ScopedMutationOperation<S> for Operation<F, T>
63 where
64 F: for<'scope> FnOnce(&MutationStatementContext<'scope, S>) -> Result<T, SQLError>,
65 {
66 fn run(&mut self, context: &MutationStatementContext<'_, S>) -> Result<(), SQLError> {
67 let action = self.action.take().ok_or_else(|| {
68 SQLError::Internal("statement snapshot operation was invoked more than once".into())
69 })?;
70 self.result = Some(action(context)?);
71 Ok(())
72 }
73 }
74 let mut operation = Operation {
75 action: Some(action),
76 result: None,
77 };
78 snapshots.with_snapshot(snapshot, &mut operation)?;
79 operation
80 .result
81 .ok_or_else(|| SQLError::Internal("statement snapshot operation was not invoked".into()))
82}