Skip to main content

uqa_engine/capabilities/
statements.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Compose statement contexts over the current Engine state without owning plan dispatch.
8
9use crate::{session::StatementReadSnapshot, Engine};
10use uqa_execution::statement::context::{
11    self, StatementEffects, StatementExecutionContext, StatementValidationContext,
12};
13impl Engine {
14    pub(crate) fn statement_execution_context(
15        &self,
16    ) -> StatementExecutionContext<'_, StatementReadSnapshot> {
17        let runtime = self.query_runtime_view();
18        StatementExecutionContext {
19            diagnostics: self,
20            validation: StatementValidationContext {
21                session: self,
22                rules: self,
23                effects: self,
24                transactions: self,
25                aliases: self,
26            },
27            runtime: context::StatementRuntime {
28                cancellation: runtime.cancellation,
29                notices: runtime.notices,
30            },
31            queries: self,
32            mutations: self,
33            schemas: context::schemas::SchemaStatements {
34                creation: self,
35                removal: self,
36                tables_as: self,
37                views: self,
38                view_alteration: self,
39                foreign_alteration: self,
40                sequence_creation: self,
41                sequence_alteration: self,
42                owners: self,
43                renames: self,
44                inputs: self,
45            },
46            routines: context::routines::RoutineStatements {
47                resolution: self,
48                inputs: self,
49                transactions: self,
50            },
51            prepared: context::session::PreparedStatements {
52                state: self,
53                arguments: self,
54                definitions: self.prepared_registration_context(),
55                plans: self,
56            },
57            settings: self,
58            notifications: self,
59            controls: self,
60            portals: self.portal_execution_context(),
61            roles: self.role_execution_context(),
62            events: self.event_lifecycle_context(),
63            foreign: self,
64            table_privileges: self,
65            explain: uqa_planner::explain::run_explain_with_physical,
66            physical_explain: self,
67        }
68    }
69}
70
71impl context::PhysicalExplainPlanning for Engine {
72    fn physical_explain_plan(
73        &self,
74        body: &uqa_sql::plan::UnifiedPlan,
75        params: &[uqa_sql::SQLParam],
76    ) -> Result<uqa_sql::result::ExplainPhysicalPlan, uqa_sql::SQLError> {
77        let catalog = self.catalog_read_view();
78        let resolution = self.session_execution_view().relation_name_resolution();
79        uqa_planner::explain::physical_plan(
80            uqa_planner::explain::PhysicalExplainContext {
81                retrieval: self,
82                statistics: self,
83                validate_source: &|source_resolution, name| {
84                    uqa_execution::catalog::foreign::reference::validate_query_source(
85                        &catalog,
86                        source_resolution,
87                        name,
88                    )
89                },
90                filters: uqa_planner::filter_pushdown::context::FilterPushdownContext {
91                    volatility: self,
92                    correlation: uqa_sql::binding::correlation::CorrelationContext {
93                        catalog: &catalog,
94                        resolution: &resolution,
95                        scoped_relations: None,
96                    },
97                    optimizer: &|plan| super::statement_planning::optimize_engine_plan(self, plan),
98                },
99                evaluate: &|expression, params| {
100                    uqa_execution::eval_scalar(
101                        expression,
102                        &uqa_execution::ScalarEvalContext::new(None, params),
103                    )
104                },
105            },
106            body,
107            params,
108        )
109    }
110}
111impl context::StatementExecutionInputs<StatementReadSnapshot> for Engine {
112    fn regex_cache(&self) -> Option<std::sync::Arc<uqa_sql::expr::RegexCache>> {
113        Some(self.session_regex_cache())
114    }
115    fn parser_settings(&self) -> uqa_sql::parser::ParserSettings {
116        Engine::parser_settings(self)
117    }
118
119    fn transaction_timestamp_micros(&self) -> Option<i64> {
120        self.session_transaction_clock_micros()
121    }
122
123    fn temporal_date_order(&self) -> Option<uqa_core::TemporalDateOrder> {
124        Some(uqa_sql::semantics::parameters::datestyle::date_order(
125            &self.session.setting("DateStyle"),
126        ))
127    }
128
129    fn temporal_interval_style(&self) -> Option<uqa_core::TemporalIntervalStyle> {
130        Some(self.session.interval_style())
131    }
132
133    fn diagnostic_search_path(&self) -> Option<Vec<String>> {
134        Some(self.session.state.read().search_path.clone())
135    }
136
137    fn notification_subscriptions_required(&self) -> bool {
138        Engine::notification_subscriptions_required(self)
139    }
140
141    fn statement_timeout(&self) -> Option<std::time::Duration> {
142        let milliseconds = self
143            .session
144            .setting("statement_timeout")
145            .parse::<u64>()
146            .ok()?;
147        (milliseconds != 0).then(|| std::time::Duration::from_millis(milliseconds))
148    }
149
150    fn statement_execution_context(&self) -> StatementExecutionContext<'_, StatementReadSnapshot> {
151        Engine::statement_execution_context(self)
152    }
153}
154
155impl StatementEffects for Engine {
156    fn query_effect_context(&self) -> uqa_sql::semantics::effects::QueryEffectContext<'_> {
157        Engine::query_effect_context(self)
158    }
159}
160mod queries;
161mod routines;
162mod schemas;
163mod session;
164
165impl Engine {
166    pub(crate) fn compiled_statement_context(
167        &self,
168    ) -> uqa_execution::statement::compiled::CompiledStatementContext<
169        '_,
170        crate::session::StatementReadSnapshot,
171    > {
172        uqa_execution::statement::compiled::CompiledStatementContext {
173            aggregates: self,
174            planning: self,
175            statements: self,
176            cancellation: &self.runtime.cancellation,
177        }
178    }
179}
180
181impl context::StatementDiagnostics for Engine {
182    fn diagnostics_scope(
183        &self,
184    ) -> Result<uqa_execution::query::diagnostics::DiagnosticsScope, uqa_sql::SQLError> {
185        self.runtime
186            .diagnostics
187            .enter(self.query_retention_control()?)
188            .map_err(|error| {
189                uqa_execution::storage_errors::storage_error("retain EXPLAIN diagnostics", &error)
190            })
191    }
192}