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