Skip to main content

uqa_engine/capabilities/
routine_execution.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7use crate::Engine;
8use uqa_core::Value;
9use uqa_execution::routines::{
10    context::{
11        RoutineExpressions, RoutinePortals, RoutineStatements, RoutineTransactions,
12        StatementResultCheck,
13    },
14    transaction::RoutineSessionId,
15    RoutineContext,
16};
17use uqa_sql::{
18    assignment::routines::RoutineValueContext,
19    ast::{ColumnType, Expr, FetchCursorStmt, Statement},
20    plan::{ExpressionPlan, UnifiedPlan},
21    SQLError, SQLParam, SQLResult,
22};
23impl Engine {
24    pub(crate) fn routine_session_id(&self) -> RoutineSessionId {
25        RoutineSessionId(std::sync::Arc::as_ptr(&self.session) as usize)
26    }
27    pub(crate) fn routine_execution_context(&self) -> RoutineContext<'_> {
28        RoutineContext {
29            expressions: self,
30            statements: self,
31            transactions: self,
32            portals: self,
33            session: self.routine_session_id(),
34            runtime: self.query_runtime_view(),
35        }
36    }
37}
38impl RoutineValueContext for Engine {
39    fn catalog_column_type(&self, name: &str) -> Option<ColumnType> {
40        uqa_execution::catalog::projection::resolve_catalog_column_type(
41            &self.catalog_execution(),
42            name,
43        )
44    }
45}
46impl RoutineExpressions for Engine {
47    fn column_type_name(&self, name: &str) -> Result<ColumnType, SQLError> {
48        uqa_execution::catalog::projection::resolve_catalog_column_type_name(
49            &self.catalog_execution(),
50            name,
51        )
52    }
53    fn evaluate(&self, expression: &Expr) -> Result<Value, SQLError> {
54        crate::capabilities::query_expressions::eval_lowered_expression(self, expression, None, &[])
55    }
56    fn evaluate_with_type(
57        &self,
58        expression: &Expr,
59    ) -> Result<(Value, Option<ColumnType>), SQLError> {
60        crate::capabilities::query_expressions::eval_lowered_expression_with_type(
61            self,
62            expression,
63            None,
64            &[],
65        )
66    }
67    fn expression_type(
68        &self,
69        plan: &ExpressionPlan,
70        params: &[SQLParam],
71    ) -> Result<Option<ColumnType>, SQLError> {
72        let mut scope = super::query_scope::new_for_current_routine(self);
73        scope.scalar_subqueries.clone_from(&plan.subqueries);
74        let hook = uqa_execution::query::relational::context::QueryExpressionFactory::bind_scope(
75            self, scope,
76        );
77        uqa_execution::scalar_type_with_resolver(
78            &plan.scalar,
79            &uqa_execution::RowSchema::default(),
80            params,
81            hook.as_ref(),
82        )
83    }
84}
85impl RoutineStatements for Engine {
86    fn body_input_context(
87        &self,
88    ) -> Option<uqa_execution::routines::sql_body::inputs::SQLRoutineInputContext<'_>> {
89        Some(
90            uqa_execution::routines::sql_body::inputs::SQLRoutineInputContext {
91                cache: self.session.routine_bodies.sql_inputs(),
92                analysis: self.prepared_definition_context(),
93            },
94        )
95    }
96
97    fn plpgsql_preparations(
98        &self,
99        definition: &uqa_sql::ast::CreateFunction,
100        parsed: &uqa_sql::plpgsql::PLpgSQLFunction,
101    ) -> std::sync::Arc<uqa_execution::routines::preparation::PLpgSQLPreparations> {
102        self.session
103            .routine_bodies
104            .plpgsql_preparations(definition, parsed)
105    }
106    fn analyze_static_plan(
107        &self,
108        plan: &mut UnifiedPlan,
109        parameters: &[SQLParam],
110    ) -> Result<uqa_sql::binding::statements::ProceduralPlanAnalysis, SQLError> {
111        uqa_sql::binding::statements::analyze_procedural_plan(
112            &self.statement_planning_context().analysis,
113            &uqa_sql::routines::resolution::RoutineOverloadContext { catalog: self },
114            self,
115            plan,
116            parameters,
117        )
118    }
119    fn parser_settings(&self) -> uqa_sql::parser::ParserSettings {
120        Engine::parser_settings(self)
121    }
122    fn execute_body_statement(
123        &self,
124        plan: UnifiedPlan,
125        params: &[SQLParam],
126        check: Option<StatementResultCheck<'_>>,
127    ) -> Result<SQLResult, SQLError> {
128        let context = self.compiled_statement_context();
129        match check {
130            Some(check) => uqa_execution::statement::compiled::execute_checked_plan(
131                &context, plan, params, check,
132            ),
133            None => uqa_execution::statement::compiled::execute_plan(&context, plan, params),
134        }
135    }
136
137    fn select_body_plan(
138        &self,
139        entry: &uqa_sql::prepared::entry::PreparedStatementPlan,
140        params: &[SQLParam],
141    ) -> Result<uqa_sql::prepared::planning::PreparedPlanSelection, SQLError> {
142        let _statement_thread = self.statement_thread_context().enter();
143        uqa_planner::statement_planning::prepared::selection::select_analyzed_entry(
144            &uqa_planner::statement_planning::prepared::selection::PreparedPlanningContext {
145                session: self,
146                analysis: self.prepared_definition_context(),
147                optimization: self,
148            },
149            entry,
150            params,
151        )
152    }
153    fn select_simple_expression_plan(
154        &self,
155        entry: &uqa_sql::prepared::entry::PreparedStatementPlan,
156        params: &[SQLParam],
157    ) -> Result<uqa_sql::prepared::planning::PreparedPlanSelection, SQLError> {
158        let _statement_thread = self.statement_thread_context().enter();
159        uqa_planner::statement_planning::prepared::selection::select_simple_expression_entry(
160            &uqa_planner::statement_planning::prepared::selection::PreparedPlanningContext {
161                session: self,
162                analysis: self.prepared_definition_context(),
163                optimization: self,
164            },
165            entry,
166            params,
167        )
168    }
169    fn execute_selected_body_plan(
170        &self,
171        plan: &UnifiedPlan,
172        params: &[SQLParam],
173    ) -> Result<SQLResult, SQLError> {
174        uqa_execution::statement::compiled::execute_selected_plan(
175            &self.compiled_statement_context(),
176            plan,
177            params,
178        )
179    }
180    fn execute_bound(
181        &self,
182        statement: Statement,
183        params: &[SQLParam],
184    ) -> Result<SQLResult, SQLError> {
185        uqa_execution::statement::compiled::execute(
186            &self.compiled_statement_context(),
187            statement,
188            params,
189        )
190    }
191    fn execute_text(&self, text: &str, params: &[SQLParam]) -> Result<SQLResult, SQLError> {
192        uqa_execution::statement::batch::execute_nested(
193            &self.batch_execution_context(),
194            text,
195            params,
196        )
197    }
198    fn optimize_plan(&self, plan: UnifiedPlan) -> Result<UnifiedPlan, SQLError> {
199        crate::capabilities::statement_planning::optimize_engine_plan(self, plan)
200    }
201    fn assertions_enabled(&self) -> bool {
202        self.plpgsql_asserts_enabled()
203    }
204    fn load_language_library(&self, language: &str) {
205        self.load_language(language);
206    }
207    fn with_statement_scope(
208        &self,
209        analyze: uqa_execution::routines::context::StatementScopeOperation<'_>,
210    ) -> Result<(), SQLError> {
211        let scope = super::query_scope::new_for_current_routine(self);
212        analyze(
213            self,
214            &uqa_execution::query::binding::binding_context(&scope)?,
215        )
216    }
217}
218impl RoutineTransactions for Engine {
219    fn depth(&self) -> usize {
220        self.transaction_depth()
221    }
222    fn begin(&self) -> Result<(), SQLError> {
223        self.begin()
224    }
225    fn commit(&self) -> Result<(), SQLError> {
226        self.commit()
227    }
228    fn rollback(&self) -> Result<(), SQLError> {
229        self.rollback()
230    }
231    fn finish_procedural_transaction(&self, commit: bool, chain: bool) -> Result<(), SQLError> {
232        self.finish_procedural_transaction(commit, chain)
233    }
234}
235impl RoutinePortals for Engine {
236    fn ensure_available(&self, name: &str) -> Result<(), SQLError> {
237        uqa_execution::statement::portal::declaration::ensure_plpgsql_session_portal_available(
238            self, name,
239        )
240    }
241    fn open(
242        &self,
243        params: &[SQLParam],
244        name: &str,
245        scroll: Option<bool>,
246        plan: &UnifiedPlan,
247        source_sql: &str,
248    ) -> Result<(), SQLError> {
249        uqa_execution::statement::portal::declaration::open_plpgsql_session_portal(
250            &self
251                .portal_execution_context()
252                .with_source_sql(Some(source_sql)),
253            params,
254            name,
255            scroll,
256            plan,
257        )
258    }
259    fn fetch(&self, request: &FetchCursorStmt) -> Result<SQLResult, SQLError> {
260        self.fetch_session_portal(request)
261    }
262    fn close(&self, name: &str) -> Result<(), SQLError> {
263        self.close_session_portal(name)
264    }
265    fn allocate_name(&self) -> String {
266        self.allocate_session_portal_name()
267    }
268    fn pin(&self, name: &str) -> Result<(), SQLError> {
269        self.pin_session_portal(name)
270    }
271    fn unpin(&self, name: &str) -> Result<(), SQLError> {
272        self.unpin_session_portal(name)
273    }
274}