Skip to main content

uqa_engine/
prepared.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7use super::Engine;
8use crate::transactions::prepared::PreparedOperation;
9use std::sync::{Arc, Weak};
10use uqa_sql::{ColumnType, RowSchema, SQLError, SQLParam, SQLResult};
11
12/// A session-owned prepared definition's identity. Removing and recreating its catalog name never rebinds this handle.
13pub struct PreparedStatement {
14    name: String,
15    source: Arc<uqa_sql::Statement>,
16    owner: Weak<crate::state::SessionContext>,
17    definition: Weak<()>,
18}
19
20/// Preparation-time parameter and positional result descriptors.
21pub struct PreparedStatementDescription {
22    pub parameter_types: Vec<Option<ColumnType>>,
23    pub result_schema: Option<RowSchema>,
24}
25
26impl PreparedStatement {
27    fn matches(&self, engine: &Engine, entry: &super::PreparedStatementPlan) -> bool {
28        self.owner.ptr_eq(&Arc::downgrade(&engine.session))
29            && self
30                .definition
31                .ptr_eq(&Arc::downgrade(&entry.definition_identity))
32    }
33
34    fn invalid(&self) -> SQLError {
35        uqa_sql::prepared::statement_error("26000", &self.name, "does not exist")
36    }
37}
38
39impl Engine {
40    /// Prepare native SQL with optional explicit parameter declarations. Definitions survive transaction rollback and are removed by finalize, DEALLOCATE or DISCARD ALL.
41    pub fn prepare_statement(
42        &self,
43        sql: &str,
44        declared: &[ColumnType],
45    ) -> Result<PreparedStatement, SQLError> {
46        self.with_prepared_registration(
47            |engine| {
48                uqa_execution::statement::prepared::parse_host_sql(
49                    sql,
50                    engine.parser_settings(),
51                    &engine.runtime.notices,
52                    &engine.runtime.cancellation,
53                )
54            },
55            |engine, source| {
56                let name = loop {
57                    let identity = engine
58                        .session
59                        .next_prepared_handle
60                        .fetch_update(
61                            std::sync::atomic::Ordering::Relaxed,
62                            std::sync::atomic::Ordering::Relaxed,
63                            |value| value.checked_add(1),
64                        )
65                        .map_err(|_| SQLError::Routine {
66                            sqlstate: "54000".into(),
67                            message: "prepared statement identity space exhausted".into(),
68                        })?;
69                    let name = format!("__uqa_prepared_{identity}");
70                    if !engine.session.prepared.read().contains_key(&name) {
71                        break name;
72                    }
73                };
74                uqa_execution::statement::prepared::register_host_statement(
75                    &engine.prepared_registration_context(),
76                    name.clone(),
77                    &source,
78                    sql,
79                    declared,
80                )?;
81                let registry = engine.session.prepared.read();
82                let entry = registry.get(&name).expect("published prepared definition");
83                Ok(PreparedStatement {
84                    name,
85                    source,
86                    owner: Arc::downgrade(&engine.session),
87                    definition: Arc::downgrade(&entry.definition_identity),
88                })
89            },
90        )
91    }
92
93    pub fn validate_prepared_statement(
94        &self,
95        statement: &PreparedStatement,
96    ) -> Result<(), SQLError> {
97        let _gate = self.lock_statement_gate();
98        if self
99            .session
100            .prepared
101            .read()
102            .get(&statement.name)
103            .is_some_and(|entry| statement.matches(self, entry))
104        {
105            Ok(())
106        } else {
107            Err(statement.invalid())
108        }
109    }
110
111    pub fn describe_prepared_statement(
112        &self,
113        statement: &PreparedStatement,
114    ) -> Result<PreparedStatementDescription, SQLError> {
115        let _statement = self.lock_statement_gate();
116        let (_execution, nested) = crate::queries::SQLExecutionScope::enter(self);
117        self.run_prepared_operation(
118            || {
119                let registry = self.session.prepared.read();
120                let entry = registry
121                    .get(&statement.name)
122                    .filter(|entry| statement.matches(self, entry))
123                    .ok_or_else(|| statement.invalid())?;
124                Ok((
125                    PreparedOperation::Describe {
126                        returns_rows: entry.result_schema.is_some(),
127                        outermost: !nested,
128                        requires_analysis: uqa_sql::prepared::utility::requires_analysis(
129                            &entry.source_plan,
130                        ),
131                    },
132                    entry.clone(),
133                ))
134            },
135            |entry| {
136                if let Some(definition) =
137                    uqa_planner::statement_planning::prepared::selection::describe_entry_with_control(
138                        &self.prepared_definition_context(),
139                        &entry,
140                        &<Self as uqa_execution::routines::context::RoutineStatements>::planning_resources(self)?.control(),
141                    )?
142                {
143                    let mut registry = self.session.prepared.write();
144                    let current = registry
145                        .get_mut(&statement.name)
146                        .filter(|current| statement.matches(self, current))
147                        .ok_or_else(|| statement.invalid())?;
148                    if current.logical_plan.ptr_eq(&entry.logical_plan) {
149                        current.record_analysis(definition);
150                    }
151                }
152                Ok(PreparedStatementDescription {
153                    parameter_types: entry.parameter_types.to_vec(),
154                    result_schema: entry.result_schema,
155                })
156            },
157        )
158    }
159
160    pub fn execute_prepared_statement(
161        &self,
162        statement: &PreparedStatement,
163        params: &[SQLParam],
164    ) -> Result<SQLResult, SQLError> {
165        self.run_prepared_operation(
166            || {
167                let registry = self.session.prepared.read();
168                let entry = registry
169                    .get(&statement.name)
170                    .filter(|entry| statement.matches(self, entry))
171                    .ok_or_else(|| statement.invalid())?;
172                uqa_sql::prepared::validate_host_parameter_count(
173                    &statement.name,
174                    params.len(),
175                    entry.parameter_types.len(),
176                )?;
177                Ok((
178                    PreparedOperation::Bind {
179                        statement: Arc::clone(&statement.source),
180                        parameter_count: params.len(),
181                    },
182                    entry.source_sql.clone(),
183                ))
184            },
185            |sql| {
186                self.execute_compiled_prepared(
187                    &statement.name,
188                    Arc::clone(&statement.source),
189                    sql.as_ref().map(|sql| sql.as_str()),
190                    params,
191                )
192            },
193        )
194    }
195
196    /// An invalidated handle is harmless to release and cannot remove a replacement definition.
197    pub fn finalize_prepared_statement(&self, statement: &PreparedStatement) {
198        let _gate = self.lock_statement_gate();
199        let mut registry = self.session.prepared.write();
200        if registry
201            .get(&statement.name)
202            .is_some_and(|entry| statement.matches(self, entry))
203        {
204            registry.remove(&statement.name);
205        }
206    }
207
208    pub fn register_prepared(
209        &self,
210        name: String,
211        definition: uqa_sql::ast::Statement,
212    ) -> Result<(), uqa_sql::SQLError> {
213        self.with_prepared_registration(
214            |_| Ok(Arc::new(definition)),
215            |engine, definition| {
216                uqa_execution::statement::prepared::register_statement(
217                    &engine.prepared_registration_context(),
218                    name,
219                    definition.as_ref().clone(),
220                )
221            },
222        )
223    }
224
225    pub(crate) fn prepared_parameter_types(
226        &self,
227        name: &str,
228    ) -> Option<Vec<Option<uqa_sql::ast::ColumnType>>> {
229        self.session
230            .prepared
231            .read()
232            .get(name)
233            .map(|entry| entry.parameter_types.to_vec())
234    }
235
236    /// Retain the current generic executable, or its analyzed input before planning, without copying the plan tree.
237    pub fn lookup_prepared(&self, name: &str) -> Option<uqa_sql::plan::SharedExecutablePlan> {
238        self.session.prepared.read().get(name).map(|entry| {
239            entry
240                .plan
241                .clone()
242                .unwrap_or_else(|| entry.logical_plan.clone())
243        })
244    }
245
246    /// Invalidate executable plans without removing connection-owned definitions.
247    /// Catalog changes are checked when each statement is next executed, so a
248    /// dropped dependency cannot make unrelated commands or rollback fail.
249    pub(crate) fn invalidate_prepared_plans(&self) {
250        uqa_execution::statement::prepared::invalidation::invalidate_execution_plans_with_routines(
251            self.session.prepared.write().values_mut(),
252            &self.session.routine_bodies,
253        );
254    }
255
256    /// Read original input syntax again after a binding dependency changes.
257    pub(crate) fn invalidate_prepared_analysis(&self) {
258        uqa_execution::statement::prepared::invalidation::PreparedCatalogChange::GlobalCatalog
259            .invalidate_with_routines(
260                self.session.prepared.write().values_mut(),
261                &self.session.routine_bodies,
262            );
263    }
264
265    pub fn deallocate_prepared(&self, name: Option<&str>) {
266        let _gate = self.lock_statement_gate();
267        match name {
268            Some(name) => {
269                self.session.prepared.write().remove(name);
270            }
271            None => self.session.prepared.write().clear(),
272        }
273    }
274}