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    /// The session-owned compiled regex cache, shared by its nested statements and workers.
69    fn regex_cache(&self) -> Option<std::sync::Arc<uqa_sql::expr::RegexCache>> {
70        None
71    }
72    fn statement_execution_context(&self) -> StatementExecutionContext<'_, S>;
73    /// The live transaction start, or the current message's start outside a transaction. `None` preserves the calling statement's clock without capturing execution inputs.
74    fn transaction_timestamp_micros(&self) -> Option<i64> {
75        None
76    }
77    /// The live session order for ambiguous date inputs. None preserves a caller's input context.
78    fn temporal_date_order(&self) -> Option<uqa_core::TemporalDateOrder> {
79        None
80    }
81    /// The live interval input/output style; None preserves a caller's context.
82    fn temporal_interval_style(&self) -> Option<uqa_core::TemporalIntervalStyle> {
83        None
84    }
85    /// 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.
86    fn statement_timeout(&self) -> Option<std::time::Duration>;
87    /// Capture scanner settings at the SQL message boundary, before its first SET can execute.
88    fn parser_settings(&self) -> uqa_sql::parser::ParserSettings {
89        uqa_sql::parser::ParserSettings::default()
90    }
91    /// Read the live host policy without capturing the statement's catalog/execution inputs.
92    fn notification_subscriptions_required(&self) -> bool {
93        false
94    }
95
96    /// The session search path, which diagnostics use to qualify types it does not include. `None` leaves type names unqualified.
97    fn diagnostic_search_path(&self) -> Option<Vec<String>> {
98        None
99    }
100}
101
102/// 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.
103pub(super) fn statement_thread_scope<S: Clone + 'static>(
104    statements: &dyn StatementExecutionInputs<S>,
105    cancellation: &uqa_core::CancellationToken,
106) -> super::thread_scope::StatementThreadScope {
107    super::thread_context::StatementThreadContext {
108        retained_rows: crate::query::sources::retained_source::RetainedRowContext::current(),
109        regex_cache: statements.regex_cache(),
110        temporal_input: uqa_sql::expr::TemporalInputContext {
111            transaction_clock_micros: statements
112                .transaction_timestamp_micros()
113                .or_else(uqa_sql::expr::transaction_clock_micros),
114            interval_style: statements
115                .temporal_interval_style()
116                .unwrap_or_else(uqa_sql::expr::temporal_interval_style),
117            date_order: statements
118                .temporal_date_order()
119                .unwrap_or_else(uqa_sql::expr::temporal_date_order),
120        },
121        cancellation: Some(cancellation.clone()),
122    }
123    .enter()
124}
125
126pub trait StatementMutationInputs<S: Clone + 'static> {
127    fn mutation_context(&self) -> crate::mutation::entry::MutationEntryContext<'_, S>;
128    /// Borrow read services for expression initialization without entering a writable command.
129    fn mutation_initialization_context(
130        &self,
131    ) -> crate::mutation::statement::context::MutationStatementContext<'_, S>;
132}
133
134#[derive(Clone)]
135pub struct StatementExecutionContext<'a, S: Clone + 'static> {
136    pub diagnostics: &'a dyn StatementDiagnostics,
137    pub validation: StatementValidationContext<'a>,
138    pub runtime: StatementRuntime<'a>,
139    pub queries: &'a dyn queries::StatementQueryContexts<S>,
140    pub mutations: &'a dyn StatementMutationInputs<S>,
141    pub schemas: schemas::SchemaStatements<'a, S>,
142    pub routines: routines::RoutineStatements<'a>,
143    pub prepared: session::PreparedStatements<'a>,
144    pub settings: &'a dyn session::StatementSettings,
145    pub notifications: &'a dyn session::StatementNotifications,
146    pub controls: &'a dyn session::StatementControl,
147    pub portals: super::portal::context::PortalExecutionContext<'a, S>,
148    pub roles: crate::catalog::security::role_lifecycle::context::RoleExecutionContext<'a>,
149    pub events: crate::schema::events::context::EventLifecycleContext<'a>,
150    pub foreign: &'a dyn crate::schema::foreign_creation::entry::ForeignCreationTransactions,
151    pub table_privileges: &'a dyn crate::catalog::security::table_grants::TableGrantInputs,
152    pub explain: PhysicalExplainRenderer,
153    pub physical_explain: &'a dyn PhysicalExplainPlanning,
154}