Skip to main content

uqa_engine/capabilities/
routine_definitions.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Bind routine definition analysis to current catalog data and compilation namespaces.
8
9use crate::Engine;
10use uqa_sql::{
11    ast::{ColumnDef, ColumnType},
12    binding::{snapshot::BindingSnapshot, stored_relations::StoredQueryNamespace},
13    plpgsql::PlpgsqlCatalog,
14    routines::{
15        compilation::{RoutineCompilationCatalog, RoutineCompilationContext, RoutineParserCatalog},
16        declaration::RoutineTypeCatalog,
17        merge_columns::StoredMergeColumnCatalog,
18        regclass::RoutineRegclassCatalog,
19    },
20    SQLError,
21};
22
23impl Engine {
24    pub(crate) fn routine_compilation_context(&self) -> RoutineCompilationContext<'_> {
25        RoutineCompilationContext {
26            types: self,
27            parsers: self,
28            catalog: self,
29            routines: self,
30            relations: self,
31            sequences: self,
32            merge: self,
33            regroles: self,
34        }
35    }
36}
37impl RoutineTypeCatalog for Engine {
38    fn try_describe_table(&self, name: &str) -> Result<Option<Vec<ColumnDef>>, String> {
39        Engine::describe_table_in_execution(self, name).map_err(|error| error.to_string())
40    }
41    fn resolve_catalog_column_type(&self, name: &str) -> Option<ColumnType> {
42        uqa_execution::catalog::projection::resolve_catalog_column_type(
43            &self.catalog_execution(),
44            name,
45        )
46    }
47    fn resolve_catalog_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 resolve_catalog_user_type_by_oid(&self, oid: u32) -> Option<ColumnType> {
54        uqa_execution::catalog::projection::resolve_catalog_user_type_by_oid(
55            &self.catalog_execution(),
56            oid,
57        )
58    }
59    fn format_type(&self, ty: &ColumnType) -> Result<String, SQLError> {
60        uqa_execution::catalog::projection::format_type_name(&self.catalog_execution(), ty)
61    }
62    fn format_type_oid(&self, oid: u32) -> Result<String, SQLError> {
63        uqa_execution::catalog::projection::format_type_object(
64            &self.catalog_execution(),
65            i64::from(oid),
66        )
67        .map_err(SQLError::Internal)?
68        .ok_or_else(|| SQLError::Internal(format!("cache lookup failed for type {oid}")))
69    }
70    fn composite_types(&self) -> Option<&dyn uqa_sql::expr::composites::CompositeTypeCatalog> {
71        Some(self)
72    }
73    fn require_type_usage(&self, ty: &ColumnType) -> Result<(), SQLError> {
74        uqa_execution::catalog::security::type_inquiry::require_type_usage(
75            &self.catalog_execution(),
76            ty,
77        )
78    }
79}
80impl uqa_execution::routines::invocation::bodies::RoutineBodySession for Engine {
81    fn retain_routine_body(
82        &self,
83        function: &uqa_sql::routines::SQLUserFunction,
84        body: uqa_sql::routines::CompiledFunctionBody,
85    ) -> Result<(), SQLError> {
86        self.session.routine_bodies.retain(function, body)
87    }
88}
89impl StoredMergeColumnCatalog for Engine {
90    fn stored_merge_target_definitions(&self, table: &str) -> Option<Vec<ColumnDef>> {
91        self.table_entries()
92            .into_iter()
93            .find(|(name, _)| name == table)
94            .map(|(_, table)| table.columns.read().clone())
95    }
96}
97impl RoutineParserCatalog for Engine {
98    fn parser_settings(&self) -> uqa_sql::parser::ParserSettings {
99        Engine::parser_settings(self)
100    }
101
102    fn parser_notice(&self, notice: uqa_sql::SQLNotice) {
103        self.runtime.notices.push(notice);
104    }
105
106    fn plpgsql_catalog(&self) -> Result<PlpgsqlCatalog, SQLError> {
107        uqa_execution::catalog::projection::plpgsql_catalog(&self.catalog_execution())
108    }
109}
110impl RoutineCompilationCatalog for Engine {
111    fn has_registered_aggregate_function(&self, name: &str) -> bool {
112        Engine::has_registered_aggregate_function(self, name)
113    }
114    fn binding_snapshot(&self) -> Result<BindingSnapshot, SQLError> {
115        let scope = super::query_scope::new_for_catalog_binding(self);
116        uqa_execution::query::binding::binding_context(&scope).map(Into::into)
117    }
118    fn stored_query_namespace(&self) -> StoredQueryNamespace {
119        StoredQueryNamespace {
120            temporary_schema: self.temporary_schema_name(),
121            transition_relations:
122                uqa_execution::mutation::triggers::current_transition_relation_names(),
123        }
124    }
125}
126impl RoutineRegclassCatalog for Engine {
127    fn resolve_routine_regclass(&self, reference: &str) -> Result<Option<i64>, SQLError> {
128        uqa_execution::catalog::projection::resolve_regclass_oid(
129            &self.catalog_execution(),
130            reference,
131        )
132    }
133}
134
135use uqa_core::RelationIdentity;
136use uqa_execution::routines::{
137    compilation::{RoutineCompilationSession, StoredRoutineCompilationContext},
138    definition::RoutineDefinitionContext,
139    rewrites::{self, RoutineRewriteContext},
140};
141
142impl Engine {
143    pub(crate) fn routine_definition_context(&self) -> RoutineDefinitionContext<'_> {
144        RoutineDefinitionContext {
145            compilation: self.stored_routine_compilation_context(),
146            sources: self,
147            regclasses: self,
148        }
149    }
150    pub(crate) fn stored_routine_compilation_context(&self) -> StoredRoutineCompilationContext<'_> {
151        StoredRoutineCompilationContext {
152            analysis: self.routine_compilation_context(),
153            session: self,
154        }
155    }
156    pub(crate) fn routine_rewrite_context(&self) -> RoutineRewriteContext<'_> {
157        RoutineRewriteContext {
158            registry: self,
159            publication: self,
160            compilation: self.stored_routine_compilation_context(),
161            columns: self.stored_column_binding_context(),
162            changes: self,
163        }
164    }
165    pub(crate) fn rewrite_routine_relation_references(
166        &self,
167        from: &RelationIdentity,
168        to: &RelationIdentity,
169    ) -> Result<(), SQLError> {
170        rewrites::rewrite_routine_relation_references(&self.routine_rewrite_context(), from, to)
171    }
172    pub(crate) fn rewrite_routine_column_references(
173        &self,
174        relation: &RelationIdentity,
175        from: &str,
176        to: &str,
177    ) -> Result<(), SQLError> {
178        rewrites::rewrite_routine_column_references(
179            &self.routine_rewrite_context(),
180            relation,
181            from,
182            to,
183        )
184    }
185}
186impl RoutineCompilationSession for Engine {
187    fn routine_search_path(&self) -> Vec<String> {
188        crate::session::effective_search_path(&self.session.state.read())
189    }
190    fn replace_routine_search_path(&self, path: Vec<String>) -> Vec<String> {
191        std::mem::replace(&mut self.session.state.write().search_path, path)
192    }
193    fn restore_routine_search_path(&self, path: Vec<String>) {
194        self.session.state.write().search_path = path;
195    }
196    fn routine_settings_scope(
197        &self,
198        settings: &[(String, String)],
199    ) -> Result<Box<dyn RoutineConfigurationGuard + '_>, SQLError> {
200        let scope = self.routine_invocation_state_guard(!settings.is_empty(), false);
201        for (name, value) in settings {
202            self.set_configured_parameter(name, value)?;
203        }
204        Ok(Box::new(scope))
205    }
206}
207
208use uqa_execution::routines::{
209    catalog::RoutineMutationContext,
210    configuration::{RoutineConfigurationGuard, RoutineConfigurationSession},
211    registration::RoutineRegistrationContext,
212};
213use uqa_sql::routines::registration::RoutineSupportAuthority;
214
215impl RoutineSupportAuthority for Engine {
216    fn current_user_is_superuser(&self) -> bool {
217        Engine::current_user_is_superuser(self)
218    }
219}
220impl RoutineConfigurationGuard for crate::roles::RoutineSessionStateGuard<'_> {}
221impl RoutineConfigurationSession for Engine {
222    fn routine_configuration_guard(&self) -> Box<dyn RoutineConfigurationGuard + '_> {
223        Box::new(self.routine_config_state_guard())
224    }
225    fn set_routine_variable(&self, name: &str, value: &str) -> Result<(), SQLError> {
226        self.set_variable(name, value)
227    }
228    fn show_routine_variable(&self, name: &str) -> Result<String, SQLError> {
229        self.show_variable(name)
230    }
231    fn routine_variable_name(&self, name: &str) -> Result<String, SQLError> {
232        self.session_execution_view()
233            .show_parameter(name)
234            .map(|(name, _)| name)
235    }
236    fn load_language_library(&self, language: &str) {
237        self.load_language(language);
238    }
239}
240impl Engine {
241    pub(crate) fn routine_mutation_context(&self) -> RoutineMutationContext<'_> {
242        RoutineMutationContext {
243            writer: self,
244            names: self,
245            roles: self,
246            registry: self,
247            publication: self,
248            changes: self,
249        }
250    }
251    pub(crate) fn routine_registration_context(&self) -> RoutineRegistrationContext<'_> {
252        RoutineRegistrationContext {
253            catalog: self.routine_mutation_context(),
254            namespace: self.relation_creation_context(),
255            definition: self.routine_definition_context(),
256            support: self,
257            configuration: self,
258            overloads: uqa_sql::routines::resolution::RoutineOverloadContext { catalog: self },
259            session: self,
260            bodies: self,
261        }
262    }
263}