Skip to main content

uqa_engine/capabilities/
prepared.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Adapt current routine scope and session parameter metadata to prepared-statement services.
8
9use crate::{capabilities::ScopedEngineHook, Engine};
10use uqa_execution::query::prepared::{
11    ArgumentBindingContext, PreparedArgumentScopes, ScopedArgumentOperation,
12};
13use uqa_execution::scalar::plan::PhysicalEvalContext;
14use uqa_sql::{
15    plan::{ExpressionPlan, UnifiedPlan},
16    prepared::arguments::ArgumentValidationContext,
17    SQLError, SQLParam,
18};
19
20impl Engine {
21    pub(crate) fn note_prepared_relation_change(&self, relation: &uqa_core::RelationIdentity) {
22        self.mutation_coordinator()
23            .note_prepared_relation_change(relation);
24    }
25
26    pub(crate) fn note_prepared_table_change(&self, table: &crate::TableState) {
27        self.mutation_coordinator()
28            .note_prepared_table_change(table);
29    }
30
31    pub(crate) fn note_prepared_catalog_change(
32        &self,
33        change: uqa_execution::statement::prepared::invalidation::PreparedCatalogChange,
34    ) {
35        self.mutation_coordinator()
36            .note_prepared_catalog_change(change);
37    }
38
39    pub(crate) fn prepared_definition_context(
40        &self,
41    ) -> uqa_sql::prepared::definition::PreparedDefinitionContext<'_> {
42        uqa_sql::prepared::definition::PreparedDefinitionContext {
43            types: self,
44            routines: self,
45            procedures: self,
46            scopes: self,
47            session: self,
48            aliases: self,
49        }
50    }
51
52    pub(crate) fn prepared_registration_context(
53        &self,
54    ) -> uqa_execution::statement::prepared::PreparedRegistrationContext<'_> {
55        uqa_execution::statement::prepared::PreparedRegistrationContext {
56            analysis: self.prepared_definition_context(),
57            aggregates: self,
58            registry: self,
59            transaction_timestamp_micros: self.session_transaction_clock_micros(),
60            interval_style: Some(self.session.interval_style()),
61            date_order: Some(uqa_sql::semantics::parameters::datestyle::date_order(
62                &self.session.setting("DateStyle"),
63            )),
64            cancellation: &self.runtime.cancellation,
65            clock: uqa_sql::expr::clock_timestamp_micros,
66        }
67    }
68}
69
70impl uqa_sql::prepared::utility::PreparedSessionMetadata for Engine {
71    fn show_result_schema(&self, name: &str) -> Result<uqa_sql::RowSchema, SQLError> {
72        uqa_execution::statement::show::show_schema(self, name)
73    }
74    fn show_result_schema_with_control(
75        &self,
76        name: &str,
77        control: &uqa_core::memory::ProductionControl<'_>,
78    ) -> Result<uqa_sql::RowSchema, SQLError> {
79        uqa_execution::statement::show::show_schema_with_control(self, name, control)
80    }
81    fn portal_result_schema(&self, name: &str) -> Option<uqa_sql::RowSchema> {
82        self.session
83            .portals
84            .lock()
85            .get(name)
86            .map(|portal| portal.schema.clone())
87    }
88    fn prepared_result_schema(&self, name: &str) -> Option<uqa_sql::RowSchema> {
89        self.session
90            .prepared
91            .read()
92            .get(name)
93            .and_then(|entry| entry.result_schema.clone())
94    }
95}
96
97impl PreparedArgumentScopes for Engine {
98    fn with_scope(
99        &self,
100        parameters: &[SQLParam],
101        operation: &mut ScopedArgumentOperation<'_>,
102    ) -> Result<Vec<SQLParam>, SQLError> {
103        let scope = super::query_scope::new_for_current_routine(self)?;
104        let hook = ScopedEngineHook::new(self, &scope);
105        let evaluation = PhysicalEvalContext::new(None, parameters)
106            .with_function_hook(&hook)
107            .with_subquery_runner(&hook);
108        let cast_type = |name: &str| {
109            uqa_execution::catalog::projection::resolve_catalog_column_type(
110                &self.catalog_execution(),
111                name,
112            )
113        };
114        let mut analyze_type = |argument: &ExpressionPlan| {
115            uqa_execution::query::binding::analyze_expression_plan_type(
116                self, argument, parameters, &scope,
117            )
118        };
119        operation(ArgumentBindingContext {
120            validation: ArgumentValidationContext {
121                aggregates: self,
122                volatility: self,
123                cast_type: &cast_type,
124                routines: self,
125                parameters,
126            },
127            assignment: self,
128            analyze_type: &mut analyze_type,
129            evaluation,
130        })
131    }
132}
133
134struct PreparedDefinitionWrite<'a> {
135    entries: parking_lot::RwLockWriteGuard<
136        'a,
137        uqa_core::memory::OwnedMap<
138            uqa_core::memory::Produced<String>,
139            uqa_sql::prepared::entry::PreparedStatementPlan,
140        >,
141    >,
142    _memory: Option<uqa_core::memory::MemoryReservation>,
143}
144
145impl uqa_execution::statement::prepared::PreparedDefinitionWrite for PreparedDefinitionWrite<'_> {
146    fn insert(
147        &mut self,
148        name: uqa_core::memory::Produced<String>,
149        definition: uqa_sql::prepared::entry::PreparedStatementPlan,
150        control: &uqa_core::memory::ProductionControl<'_>,
151    ) -> Result<(), SQLError> {
152        control.check()?;
153        match control.budget() {
154            Some(budget) => {
155                self.entries.insert_budgeted(name, definition, budget)?;
156            }
157            None => {
158                self.entries.insert(name, definition);
159            }
160        }
161        Ok(())
162    }
163}
164
165impl uqa_execution::statement::prepared::PreparedDefinitionRegistry for Engine {
166    fn production_resources(&self) -> Result<uqa_core::memory::OwnedProductionControl, SQLError> {
167        <Self as uqa_execution::routines::context::RoutineStatements>::planning_resources(self)
168    }
169    fn write_definitions(
170        &self,
171        control: &uqa_core::memory::ProductionControl<'_>,
172    ) -> Result<Box<dyn uqa_execution::statement::prepared::PreparedDefinitionWrite + '_>, SQLError>
173    {
174        let memory = control.reserve(size_of::<PreparedDefinitionWrite<'_>>())?;
175        Ok(Box::new(PreparedDefinitionWrite {
176            entries: self.session.prepared.write(),
177            _memory: memory,
178        }))
179    }
180}
181
182impl uqa_planner::statement_planning::prepared::selection::PreparedPlanSession for Engine {
183    fn prepared_entry(
184        &self,
185        name: &str,
186    ) -> Option<uqa_sql::prepared::entry::PreparedStatementPlan> {
187        self.session.prepared.read().get(name).cloned()
188    }
189    fn plan_cache_mode(&self) -> Result<String, SQLError> {
190        self.show_variable("plan_cache_mode")
191    }
192    fn plan_cache_mode_with_control(
193        &self,
194        control: &uqa_core::memory::ProductionControl<'_>,
195    ) -> Result<uqa_core::memory::Produced<String>, SQLError> {
196        control.check()?;
197        if let Some(mode) = self
198            .session
199            .state
200            .read()
201            .session_vars
202            .get("plan_cache_mode")
203        {
204            return Ok(control.copy_text(mode)?);
205        }
206        if let Some(mode) = self
207            .session
208            .parameters
209            .lock()
210            .client_setting_with_control("plan_cache_mode", control)?
211        {
212            return Ok(control.copy_text(mode)?);
213        }
214        uqa_sql::semantics::parameters::catalog::find_parameter("plan_cache_mode")
215            .expect("defined plan policy")
216            .boot_setting_with_control(control)
217    }
218    fn publish_usage(
219        &self,
220        name: &str,
221        logical_plan: &uqa_sql::plan::SharedExecutablePlan,
222        update: uqa_sql::prepared::planning::PreparedPlanUpdate,
223    ) {
224        if let Some(current) = self.session.prepared.write().get_mut(name) {
225            if current.logical_plan.ptr_eq(logical_plan) {
226                current.record_execution(update);
227            }
228        }
229    }
230}
231
232impl uqa_planner::statement_planning::prepared::selection::PreparedPlanOptimization for Engine {
233    fn planning_resources(&self) -> Result<uqa_core::memory::OwnedProductionControl, SQLError> {
234        <Self as uqa_execution::routines::context::RoutineStatements>::planning_resources(self)
235    }
236    fn optimize_plan(
237        &self,
238        plan: uqa_sql::plan::MutableExecutablePlan,
239        control: &uqa_core::memory::ProductionControl<'_>,
240    ) -> Result<uqa_sql::plan::SharedExecutablePlan, SQLError> {
241        uqa_planner::statement_planning::executable::optimize_owned_with_control(
242            &self.statement_planning_context(),
243            plan,
244            control,
245        )?
246        .into_shared(control)
247    }
248    fn estimate_plan(
249        &self,
250        plan: &UnifiedPlan,
251        control: &uqa_core::memory::ProductionControl<'_>,
252    ) -> Result<uqa_planner::plan_cost::PlanCost, SQLError> {
253        uqa_planner::statement_planning::estimate_plan_with_control(
254            self.statement_statistics_context(),
255            plan,
256            control,
257        )
258    }
259}
260
261impl uqa_sql::prepared::planning::PreparedPlanProvider for Engine {
262    fn plan_for_execution(
263        &self,
264        name: &str,
265        parameters: &[SQLParam],
266    ) -> Result<Option<uqa_sql::plan::SharedExecutablePlan>, SQLError> {
267        uqa_planner::statement_planning::prepared::selection::select_plan(
268            &uqa_planner::statement_planning::prepared::selection::PreparedPlanningContext {
269                session: self,
270                analysis: self.prepared_definition_context(),
271                optimization: self,
272            },
273            name,
274            parameters,
275        )
276    }
277}