uqa_execution/query/statement/
context.rs1use crate::query::{sources::SourceContext, CteScope};
10use crate::{PhysicalOperator, RowSchema};
11use std::collections::BTreeMap;
12use uqa_sql::{plan::QueryPlan, SQLError, SQLParam, ScalarExpr};
13
14pub trait SnapshotSource<S: Clone + 'static> {
16 fn capture(&self) -> Result<S, SQLError>;
17}
18
19pub trait QuerySnapshots<S: Clone + 'static>: SnapshotSource<S> {
20 fn with_snapshot(
21 &self,
22 snapshot: &S,
23 operation: &mut dyn ScopedQueryOperation<S>,
24 ) -> Result<(), SQLError>;
25}
26pub trait ScopedQueryOperation<S: Clone + 'static> {
27 fn run(&mut self, context: &QueryContext<'_, S>) -> Result<(), SQLError>;
28}
29pub trait DirectionalQueryFactory<S: Clone + 'static> {
31 fn query_operator(
32 &self,
33 plan: QueryPlan,
34 params: Vec<SQLParam>,
35 scope: CteScope<S>,
36 schema: RowSchema,
37 ) -> Result<Box<dyn PhysicalOperator>, SQLError>;
38}
39pub trait CteFilterPlanning<S: Clone> {
40 fn output_filters(
41 &self,
42 plan: &QueryPlan,
43 scope: &CteScope<S>,
44 ) -> Result<BTreeMap<String, (String, ScalarExpr)>, SQLError>;
45}
46#[derive(Clone)]
47pub struct QueryContext<'a, S: Clone + 'static> {
48 pub generation: Option<&'a S>,
49 pub source: SourceContext<'a, S>,
50 pub snapshots: &'a dyn QuerySnapshots<S>,
51 pub directional: &'a dyn DirectionalQueryFactory<S>,
52 pub cte_filters: &'a dyn CteFilterPlanning<S>,
53}
54impl<S: Clone + 'static> Copy for QueryContext<'_, S> {}
55
56pub fn with_query_snapshot<S: Clone + 'static, T>(
57 snapshots: &dyn QuerySnapshots<S>,
58 snapshot: &S,
59 action: impl for<'scope> FnOnce(&QueryContext<'scope, S>) -> Result<T, SQLError>,
60) -> Result<T, SQLError> {
61 struct Operation<F, T> {
62 action: Option<F>,
63 result: Option<T>,
64 }
65 impl<S: Clone + 'static, F, T> ScopedQueryOperation<S> for Operation<F, T>
66 where
67 F: for<'scope> FnOnce(&QueryContext<'scope, S>) -> Result<T, SQLError>,
68 {
69 fn run(&mut self, context: &QueryContext<'_, S>) -> Result<(), SQLError> {
70 let action = self.action.take().ok_or_else(|| {
71 SQLError::Internal("statement snapshot operation was invoked more than once".into())
72 })?;
73 self.result = Some(action(context)?);
74 Ok(())
75 }
76 }
77 let mut operation = Operation {
78 action: Some(action),
79 result: None,
80 };
81 snapshots.with_snapshot(snapshot, &mut operation)?;
82 operation
83 .result
84 .ok_or_else(|| SQLError::Internal("statement snapshot operation was not invoked".into()))
85}