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 ExplainRenderer =
22    fn(&UnifiedPlan, bool, Option<&str>, Option<&ExplainAnalysis>) -> Result<SQLResult, SQLError>;
23
24pub type PhysicalExplainRenderer = fn(
25    &UnifiedPlan,
26    bool,
27    Option<&str>,
28    Option<&ExplainAnalysis>,
29    &ExplainPhysicalPlan,
30) -> Result<SQLResult, SQLError>;
31
32/// Capture physical facts before an optional execution without invoking the explained query.
33pub trait PhysicalExplainPlanning: Sync {
34    fn physical_explain_plan(
35        &self,
36        body: &UnifiedPlan,
37        params: &[SQLParam],
38    ) -> Result<ExplainPhysicalPlan, SQLError>;
39}
40
41pub trait StatementDiagnostics: Sync {
42    fn diagnostics_scope(&self) -> Result<crate::query::diagnostics::DiagnosticsScope, SQLError>;
43}
44
45pub trait StatementEffects {
46    fn query_effect_context(&self) -> QueryEffectContext<'_>;
47}
48
49/// Cancellation and diagnostics for the top-level statement boundary.
50#[derive(Clone, Copy)]
51pub struct StatementRuntime<'a> {
52    pub cancellation: &'a uqa_core::CancellationToken,
53    pub notices: &'a crate::query::NoticeQueue,
54}
55
56#[derive(Clone, Copy)]
57pub struct StatementValidationContext<'a> {
58    pub session: &'a dyn CatalogSession,
59    pub rules: &'a dyn RuleCatalog,
60    pub effects: &'a dyn StatementEffects,
61    pub transactions: &'a dyn super::transactions::StatementTransactions,
62    /// Reads the objects the statement's `reg*` constants name, as their input functions read them when the statement is analyzed.
63    pub aliases: &'a dyn uqa_sql::schema::dependencies::oid_alias::OidAliasInput,
64}
65
66/// Capture live subsystem inputs only when a statement is ready to execute.
67pub trait StatementExecutionInputs<S: Clone + 'static> {
68    fn statement_execution_context(&self) -> StatementExecutionContext<'_, S>;
69    /// The live transaction start, or the current message's start outside a transaction. `None` preserves the calling statement's clock without capturing execution inputs.
70    fn transaction_timestamp_micros(&self) -> Option<i64> {
71        None
72    }
73    /// The live session order for ambiguous date inputs. None preserves a caller's input context.
74    fn temporal_date_order(&self) -> Option<uqa_core::TemporalDateOrder> {
75        None
76    }
77    /// The live interval input/output style; None preserves a caller's context.
78    fn temporal_interval_style(&self) -> Option<uqa_core::TemporalIntervalStyle> {
79        None
80    }
81    /// 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.
82    fn statement_timeout(&self) -> Option<std::time::Duration>;
83    /// Capture scanner settings at the SQL message boundary, before its first SET can execute.
84    fn parser_settings(&self) -> uqa_sql::parser::ParserSettings {
85        uqa_sql::parser::ParserSettings::default()
86    }
87    /// Read the live host policy without capturing the statement's catalog/execution inputs.
88    fn notification_subscriptions_required(&self) -> bool {
89        false
90    }
91
92    /// The session search path, which diagnostics use to qualify types it does not include. `None` leaves type names unqualified.
93    fn diagnostic_search_path(&self) -> Option<Vec<String>> {
94        None
95    }
96}
97
98/// 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.
99pub(super) fn statement_thread_scope<S: Clone + 'static>(
100    statements: &dyn StatementExecutionInputs<S>,
101    cancellation: &uqa_core::CancellationToken,
102) -> super::thread_scope::StatementThreadScope {
103    super::thread_context::StatementThreadContext {
104        temporal_input: uqa_sql::expr::TemporalInputContext {
105            transaction_clock_micros: statements
106                .transaction_timestamp_micros()
107                .or_else(uqa_sql::expr::transaction_clock_micros),
108            interval_style: statements
109                .temporal_interval_style()
110                .unwrap_or_else(uqa_sql::expr::temporal_interval_style),
111            date_order: statements
112                .temporal_date_order()
113                .unwrap_or_else(uqa_sql::expr::temporal_date_order),
114        },
115        cancellation: Some(cancellation.clone()),
116    }
117    .enter()
118}
119
120pub trait StatementMutationInputs<S: Clone + 'static> {
121    fn mutation_context(&self) -> crate::mutation::entry::MutationEntryContext<'_, S>;
122    /// Borrow read services for expression initialization without entering a writable command.
123    fn mutation_initialization_context(
124        &self,
125    ) -> crate::mutation::statement::context::MutationStatementContext<'_, S>;
126}
127
128#[derive(Clone)]
129pub struct StatementExecutionContext<'a, S: Clone + 'static> {
130    pub diagnostics: &'a dyn StatementDiagnostics,
131    pub validation: StatementValidationContext<'a>,
132    pub runtime: StatementRuntime<'a>,
133    pub queries: &'a dyn queries::StatementQueryContexts<S>,
134    pub mutations: &'a dyn StatementMutationInputs<S>,
135    pub schemas: schemas::SchemaStatements<'a, S>,
136    pub routines: routines::RoutineStatements<'a>,
137    pub prepared: session::PreparedStatements<'a>,
138    pub settings: &'a dyn session::StatementSettings,
139    pub notifications: &'a dyn session::StatementNotifications,
140    pub controls: &'a dyn session::StatementControl,
141    pub portals: super::portal::context::PortalExecutionContext<'a, S>,
142    pub roles: crate::catalog::security::role_lifecycle::context::RoleExecutionContext<'a>,
143    pub events: crate::schema::events::context::EventLifecycleContext<'a>,
144    pub foreign: &'a dyn crate::schema::foreign_creation::entry::ForeignCreationTransactions,
145    pub table_privileges: &'a dyn crate::catalog::security::table_grants::TableGrantInputs,
146    pub explain: PhysicalExplainRenderer,
147    pub physical_explain: &'a dyn PhysicalExplainPlanning,
148}