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