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
98pub(super) fn temporal_input_scope<S: Clone + 'static>(
99    statements: &dyn StatementExecutionInputs<S>,
100) -> uqa_sql::expr::TemporalInputScope {
101    uqa_sql::expr::TemporalInputContext {
102        transaction_clock_micros: statements.transaction_timestamp_micros(),
103        interval_style: statements
104            .temporal_interval_style()
105            .unwrap_or_else(uqa_sql::expr::temporal_interval_style),
106        date_order: statements
107            .temporal_date_order()
108            .unwrap_or_else(uqa_sql::expr::temporal_date_order),
109    }
110    .enter()
111}
112
113pub trait StatementMutationInputs<S: Clone + 'static> {
114    fn mutation_context(&self) -> crate::mutation::entry::MutationEntryContext<'_, S>;
115    /// Borrow read services for expression initialization without entering a writable command.
116    fn mutation_initialization_context(
117        &self,
118    ) -> crate::mutation::statement::context::MutationStatementContext<'_, S>;
119}
120
121#[derive(Clone)]
122pub struct StatementExecutionContext<'a, S: Clone + 'static> {
123    pub diagnostics: &'a dyn StatementDiagnostics,
124    pub validation: StatementValidationContext<'a>,
125    pub runtime: StatementRuntime<'a>,
126    pub queries: &'a dyn queries::StatementQueryContexts<S>,
127    pub mutations: &'a dyn StatementMutationInputs<S>,
128    pub schemas: schemas::SchemaStatements<'a, S>,
129    pub routines: routines::RoutineStatements<'a>,
130    pub prepared: session::PreparedStatements<'a>,
131    pub settings: &'a dyn session::StatementSettings,
132    pub notifications: &'a dyn session::StatementNotifications,
133    pub controls: &'a dyn session::StatementControl,
134    pub portals: super::portal::context::PortalExecutionContext<'a, S>,
135    pub roles: crate::catalog::security::role_lifecycle::context::RoleExecutionContext<'a>,
136    pub events: crate::schema::events::context::EventLifecycleContext<'a>,
137    pub foreign: &'a dyn crate::schema::foreign_creation::entry::ForeignCreationTransactions,
138    pub table_privileges: &'a dyn crate::catalog::security::table_grants::TableGrantInputs,
139    pub explain: PhysicalExplainRenderer,
140    pub physical_explain: &'a dyn PhysicalExplainPlanning,
141}