Skip to main content

uqa_execution/statement/batch/
context.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Deferred execution inputs and session-owned cache, transaction and lock state.
8
9use crate::{
10    row_locks::retry_cache::RowLockRetryCache,
11    statement::{
12        context::{StatementEffects, StatementExecutionInputs, StatementRuntime},
13        transactions::StatementTransactions,
14    },
15};
16use std::sync::Arc;
17use uqa_sql::{
18    ast::TransactionStmt,
19    plan::{AggregateClassifier, ExecutablePlanOptimizer, UnifiedPlan},
20    SQLError, SQLParam, Statement,
21};
22
23/// Cancel the statement that begins now once the session's `statement_timeout` passes, as `PostgreSQL`'s `start_xact_command` enables the timeout for each statement of a query and `finish_xact_command` disables it; the returned deadline disarms when the statement ends.
24pub fn statement_deadline<S: Clone + 'static>(
25    context: &BatchExecutionContext<'_, S>,
26) -> Option<uqa_core::CancellationDeadline> {
27    let timeout = context.statements.statement_timeout()?;
28    Some(
29        context
30            .runtime
31            .cancellation
32            .deadline(timeout, uqa_core::CancellationReason::StatementTimeout),
33    )
34}
35
36/// Owned cache contents after the session has validated its catalog epochs.
37pub struct CachedStatement {
38    pub statement: Arc<Statement>,
39    pub logical_plan: Arc<UnifiedPlan>,
40    pub optimized_plan: Option<Arc<UnifiedPlan>>,
41    pub parser: uqa_sql::parser::ParserMetadata,
42}
43
44impl CachedStatement {
45    /// Optimized entries were analyzed without parameters; any supplied inputs require native binding, including inputs the query does not reference.
46    pub(crate) fn optimized_plan_for(&self, params: &[SQLParam]) -> Option<&Arc<UnifiedPlan>> {
47        if params.is_empty() {
48            self.optimized_plan.as_ref()
49        } else {
50            None
51        }
52    }
53}
54
55pub trait StatementCache {
56    /// Look up analysis after the statement's snapshot and writer refreshes, with current catalog and scope validation. Ordinary cache implementations may decline this capability.
57    fn cached_sql_analysis(
58        &self,
59        _sql: &str,
60    ) -> Option<Arc<uqa_sql::binding::statements::AnalyzedStatement>> {
61        None
62    }
63    fn cache_sql_analysis(
64        &self,
65        _sql: &str,
66        _analysis: Option<Arc<uqa_sql::binding::statements::AnalyzedStatement>>,
67    ) {
68    }
69
70    fn cached_sql_statement(&self, sql: &str) -> Option<CachedStatement>;
71    fn cache_sql_statement(
72        &self,
73        sql: String,
74        statement: Arc<Statement>,
75        logical_plan: Arc<UnifiedPlan>,
76        parser: uqa_sql::parser::ParserMetadata,
77    );
78    fn cache_optimized_sql_plan(&self, sql: &str, optimized_plan: Arc<UnifiedPlan>);
79}
80
81/// Transaction state changes requested at the native scheduler's boundaries.
82pub trait BatchTransactions: StatementTransactions {
83    fn begin_simple_query_transaction(&self) -> Result<(), SQLError>;
84    fn promote_simple_query_transaction(&self) -> Result<(), SQLError>;
85    fn run_transaction_statement(&self, statement: TransactionStmt) -> Result<(), SQLError>;
86    /// Admit and run one operation in the existing transaction. The owner rejects failed or unresolved frames before invoking the callback, invokes it exactly once on admission, and owns error and unwind cleanup.
87    fn with_active_transaction(
88        &self,
89        operation: &mut dyn FnMut() -> Result<(), SQLError>,
90    ) -> Result<(), SQLError>;
91    fn prepare_explicit_statement_snapshot(&self, sets_snapshot: bool) -> Result<(), SQLError>;
92    fn prepare_explicit_transaction_writer(&self) -> Result<bool, SQLError>;
93    fn begin_implicit_statement_transaction(&self, read_only: bool) -> Result<(), SQLError>;
94}
95
96pub(in crate::statement) fn with_active_transaction<T>(
97    transactions: &dyn BatchTransactions,
98    operation: impl FnOnce() -> Result<T, SQLError>,
99) -> Result<T, SQLError> {
100    let mut operation = Some(operation);
101    let mut result = None;
102    transactions.with_active_transaction(&mut || {
103        let operation = operation.take().ok_or_else(|| {
104            SQLError::Internal("transaction owner invoked its operation more than once".into())
105        })?;
106        result = Some(operation()?);
107        Ok(())
108    })?;
109    result.ok_or_else(|| {
110        SQLError::Internal("transaction owner did not invoke its admitted operation".into())
111    })
112}
113
114/// Retain the session's row-lock frame until the current loop iteration exits.
115pub trait RowLockStatementGuard {}
116
117pub trait BatchRowLocks {
118    fn begin_row_lock_statement(&self) -> Box<dyn RowLockStatementGuard + '_>;
119    fn statement_row_lock_cache(&self) -> Result<Arc<RowLockRetryCache>, SQLError>;
120}
121
122pub struct BatchExecutionContext<'a, S: Clone + 'static> {
123    pub runtime: StatementRuntime<'a>,
124    pub persistent_backend: bool,
125    pub statements: &'a dyn StatementExecutionInputs<S>,
126    pub cache: &'a dyn StatementCache,
127    pub aggregates: &'a dyn AggregateClassifier,
128    pub effects: &'a dyn StatementEffects,
129    pub planning: &'a dyn ExecutablePlanOptimizer,
130    pub transactions: &'a dyn BatchTransactions,
131    pub row_locks: &'a dyn BatchRowLocks,
132}