Skip to main content

uqa_execution/statement/
context.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Compose native statement execution from its query, schema, routine and session inputs.
8
9use crate::catalog::services::CatalogSession;
10use uqa_sql::{
11    plan::UnifiedPlan,
12    result::{ExplainAnalysis, ExplainPhysicalPlan},
13    semantics::{effects::QueryEffectContext, rules::RuleCatalog},
14    SQLError, SQLParam, SQLResult,
15};
16pub mod queries;
17pub mod routines;
18pub mod schemas;
19pub mod session;
20
21pub type PhysicalExplainRenderer = fn(
22    &UnifiedPlan,
23    &uqa_sql::explain::ExplainSettings,
24    Option<&ExplainAnalysis>,
25    &ExplainPhysicalPlan,
26    &uqa_core::memory::ProductionControl<'_>,
27) -> Result<SQLResult, SQLError>;
28
29/// Capture physical facts before an optional execution without invoking the explained query.
30pub trait PhysicalExplainPlanning: Sync {
31    /// Optimize the already analyzed body only after the command has interpreted its options.
32    fn plan_explained_statement(
33        &self,
34        body: uqa_sql::plan::PlanRef<'_>,
35    ) -> Result<uqa_sql::plan::OwnedExecutablePlan, SQLError>;
36    fn explained_plan_estimates(
37        &self,
38        body: &UnifiedPlan,
39        params: &[SQLParam],
40        control: &uqa_core::memory::ProductionControl<'_>,
41    ) -> Result<
42        uqa_core::memory::Produced<Vec<uqa_sql::result::explain::ExplainNodeEstimate>>,
43        SQLError,
44    >;
45    fn physical_explain_plan(
46        &self,
47        body: &UnifiedPlan,
48        params: &[SQLParam],
49        costs: bool,
50        control: &uqa_core::memory::ProductionControl<'_>,
51    ) -> Result<uqa_core::memory::Produced<ExplainPhysicalPlan>, SQLError>;
52}
53
54pub trait StatementDiagnostics: Sync {
55    fn diagnostics_control(
56        &self,
57    ) -> Result<uqa_storage::read_control::StorageReadControl, SQLError>;
58    fn diagnostics_scope(
59        &self,
60        timing: Option<bool>,
61        io: uqa_core::io_usage::IOOptions,
62    ) -> Result<crate::query::diagnostics::DiagnosticsScope, SQLError>;
63}
64
65pub trait StatementEffects {
66    fn query_effect_context(&self) -> QueryEffectContext<'_>;
67}
68
69/// Cancellation and diagnostics for the top-level statement boundary.
70#[derive(Clone, Copy)]
71pub struct StatementRuntime<'a> {
72    pub cancellation: &'a uqa_core::CancellationToken,
73    pub notices: &'a crate::query::NoticeQueue,
74}
75
76#[derive(Clone, Copy)]
77pub struct StatementValidationContext<'a> {
78    pub session: &'a dyn CatalogSession,
79    pub rules: &'a dyn RuleCatalog,
80    pub effects: &'a dyn StatementEffects,
81    pub transactions: &'a dyn super::transactions::StatementTransactions,
82}
83
84/// Capture live subsystem inputs only when a statement is ready to execute.
85pub trait StatementExecutionInputs<S: Clone + 'static> {
86    fn io_context(&self) -> uqa_core::io_usage::IOContext {
87        uqa_core::io_usage::IOContext::current()
88    }
89    /// The session-owned compiled regex cache, shared by its nested statements and workers.
90    fn regex_cache(&self) -> Option<std::sync::Arc<uqa_sql::expr::RegexCache>> {
91        None
92    }
93    fn statement_execution_context(&self) -> StatementExecutionContext<'_, S>;
94    /// The live transaction start, or the current message's start outside a transaction. `None` preserves the calling statement's clock without capturing execution inputs.
95    fn transaction_timestamp_micros(&self) -> Option<i64> {
96        None
97    }
98    /// The live session order for ambiguous date inputs. None preserves a caller's input context.
99    fn temporal_date_order(&self) -> Option<uqa_core::TemporalDateOrder> {
100        None
101    }
102    /// The live interval input/output style; None preserves a caller's context.
103    fn temporal_interval_style(&self) -> Option<uqa_core::TemporalIntervalStyle> {
104        None
105    }
106    /// The session's `statement_timeout`, which a statement starts with; `None` lets a statement run without a limit. Reading it captures none of the statement's execution inputs.
107    fn statement_timeout(&self) -> Option<std::time::Duration>;
108    /// Capture scanner settings at the SQL message boundary, before its first SET can execute.
109    fn parser_settings(&self) -> uqa_sql::parser::ParserSettings {
110        uqa_sql::parser::ParserSettings::default()
111    }
112    /// Read the live host policy without capturing the statement's catalog/execution inputs.
113    fn notification_subscriptions_required(&self) -> bool {
114        false
115    }
116
117    /// The session search path, which diagnostics use to qualify types it does not include. `None` leaves type names unqualified.
118    fn diagnostic_search_path(&self) -> Option<Vec<String>> {
119        None
120    }
121}
122
123/// Enter the session's live temporal input and the statement's `cancellation` on the invoking thread for the statement's analysis, planning and execution, without capturing its execution inputs.
124pub(super) fn statement_thread_scope<S: Clone + 'static>(
125    statements: &dyn StatementExecutionInputs<S>,
126    cancellation: &uqa_core::CancellationToken,
127) -> super::thread_scope::StatementThreadScope {
128    super::thread_context::StatementThreadContext {
129        retained_rows: crate::query::sources::retained_source::RetainedRowContext::current(),
130        io: statements.io_context(),
131        regex_cache: statements.regex_cache(),
132        temporal_input: uqa_sql::expr::TemporalInputContext {
133            transaction_clock_micros: statements
134                .transaction_timestamp_micros()
135                .or_else(uqa_sql::expr::transaction_clock_micros),
136            interval_style: statements
137                .temporal_interval_style()
138                .unwrap_or_else(uqa_sql::expr::temporal_interval_style),
139            date_order: statements
140                .temporal_date_order()
141                .unwrap_or_else(uqa_sql::expr::temporal_date_order),
142        },
143        cancellation: Some(cancellation.clone()),
144    }
145    .enter()
146}
147
148pub trait StatementMutationInputs<S: Clone + 'static>:
149    crate::mutation::returning::ReturningInputs<S>
150{
151    fn mutation_context(&self) -> crate::mutation::entry::MutationEntryContext<'_, S>;
152    /// Borrow read services for expression initialization without entering a writable command.
153    fn mutation_initialization_context(
154        &self,
155    ) -> crate::mutation::statement::context::MutationStatementContext<'_, S>;
156}
157
158#[derive(Clone)]
159pub struct StatementExecutionContext<'a, S: Clone + 'static> {
160    pub diagnostics: &'a dyn StatementDiagnostics,
161    pub validation: StatementValidationContext<'a>,
162    pub runtime: StatementRuntime<'a>,
163    pub queries: &'a dyn queries::StatementQueryContexts<S>,
164    pub mutations: &'a dyn StatementMutationInputs<S>,
165    pub schemas: schemas::SchemaStatements<'a, S>,
166    pub routines: routines::RoutineStatements<'a>,
167    pub prepared: session::PreparedStatements<'a>,
168    pub settings: &'a dyn session::StatementSettings,
169    pub notifications: &'a dyn session::StatementNotifications,
170    pub controls: &'a dyn session::StatementControl,
171    pub portals: super::portal::context::PortalExecutionContext<'a, S>,
172    pub roles: crate::catalog::security::role_lifecycle::context::RoleExecutionContext<'a>,
173    pub events: crate::schema::events::context::EventLifecycleContext<'a>,
174    pub foreign: &'a dyn crate::schema::foreign_creation::entry::ForeignCreationTransactions,
175    pub table_privileges: &'a dyn crate::catalog::security::table_grants::TableGrantInputs,
176    pub explain: PhysicalExplainRenderer,
177    pub physical_explain: &'a dyn PhysicalExplainPlanning,
178}