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