Skip to main content

uqa_engine/capabilities/
routine_catalog.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Bind routine lookup and restoration to query snapshots, live registry guards, and catalog storage.
8
9use crate::{open::CatalogRestoreMode, Arc, CatalogFacade, Engine, StorageBackendResult};
10use uqa_execution::routines::{
11    catalog,
12    restoration::{self, PendingSQLFunctionRestore, RoutineRestoreContext, RoutineRestoreSchemas},
13};
14use uqa_sql::{
15    ast::FunctionBinding,
16    routines::{
17        lifecycle::{lookup, names, RoutineRegistry},
18        SQLUserFunction,
19    },
20    SQLError,
21};
22
23impl Engine {
24    pub(crate) fn visible_sql_function_setness_with_control(
25        &self,
26        name: &str,
27        control: &uqa_core::memory::ProductionControl<'_>,
28    ) -> Result<uqa_sql::routines::VisibleFunctionSetness, SQLError> {
29        let Some(keys) = names::routine_lookup_keys_for_analysis_with_control(self, name, control)?
30        else {
31            return Ok(uqa_sql::routines::VisibleFunctionSetness::default());
32        };
33        self.with_routine_lookup_registry(|registry| {
34            lookup::visible_function_setness_by_keys_with_control(
35                registry,
36                keys.iter().map(String::as_str),
37                control,
38            )
39        })
40    }
41
42    fn with_routine_lookup_registry<T>(&self, lookup: impl FnOnce(&RoutineRegistry) -> T) -> T {
43        let live_registry;
44        let registry = if let Some(snapshot) = self.query_sql_function_snapshots.as_ref() {
45            snapshot.as_ref()
46        } else {
47            live_registry = self.durable.sql_user_functions.read();
48            &live_registry
49        };
50        lookup(registry)
51    }
52    pub(crate) fn sql_routine_volatility_with_control(
53        &self,
54        name: &str,
55        binding: Option<&FunctionBinding>,
56        control: &uqa_core::memory::ProductionControl<'_>,
57    ) -> Result<Option<uqa_sql::ast::FunctionVolatility>, SQLError> {
58        if let Some(binding) = binding {
59            return self.with_routine_lookup_registry(|registry| {
60                lookup::bound_routine_volatility_with_control(registry, binding, control)
61            });
62        }
63        let Some(keys) = names::routine_volatility_lookup_keys_with_control(self, name, control)?
64        else {
65            return Ok(None);
66        };
67        self.with_routine_lookup_registry(|registry| {
68            lookup::routine_volatility_by_keys_with_control(
69                registry,
70                keys.iter().map(String::as_str),
71                control,
72            )
73        })
74    }
75
76    pub(crate) fn lookup_visible_sql_functions(
77        &self,
78        name: &str,
79    ) -> Result<Option<Vec<Arc<SQLUserFunction>>>, SQLError> {
80        let keys = names::routine_lookup_keys(self, name)?;
81        Ok(self.with_routine_lookup_registry(|registry| {
82            lookup::lookup_sql_functions_by_keys(registry, keys)
83        }))
84    }
85    pub(crate) fn lookup_visible_sql_functions_for_analysis(
86        &self,
87        name: &str,
88    ) -> Result<Option<Vec<Arc<SQLUserFunction>>>, SQLError> {
89        let Some(keys) = names::routine_lookup_keys_for_analysis(self, name)? else {
90            return Ok(None);
91        };
92        Ok(self.with_routine_lookup_registry(|registry| {
93            lookup::lookup_sql_functions_by_keys(registry, keys)
94        }))
95    }
96
97    pub(crate) fn has_visible_sql_function_candidates_with_control(
98        &self,
99        name: &str,
100        control: &uqa_core::memory::ProductionControl<'_>,
101    ) -> Result<bool, SQLError> {
102        let keys = uqa_sql::routines::lifecycle::names::routine_lookup_keys_with_control(
103            self, name, control,
104        )?;
105        self.with_routine_lookup_registry(|registry| {
106            for key in keys.iter() {
107                control.check()?;
108                if registry.get(key).is_some_and(|entries| !entries.is_empty()) {
109                    return Ok(true);
110                }
111            }
112            Ok(false)
113        })
114    }
115
116    pub(crate) fn visible_sql_function_returns_set_with_control(
117        &self,
118        name: &str,
119        control: &uqa_core::memory::ProductionControl<'_>,
120    ) -> Result<bool, SQLError> {
121        let Some(keys) = names::routine_lookup_keys_for_analysis_with_control(self, name, control)?
122        else {
123            return Ok(false);
124        };
125        self.with_routine_lookup_registry(|registry| {
126            lookup::visible_function_returns_set_by_keys_with_control(
127                registry,
128                keys.iter().map(String::as_str),
129                control,
130            )
131        })
132    }
133    pub(crate) fn lookup_bound_sql_functions(
134        &self,
135        name: &str,
136    ) -> Option<Vec<Arc<SQLUserFunction>>> {
137        let keys = std::iter::once(name.to_string());
138        self.with_routine_lookup_registry(|registry| {
139            lookup::lookup_sql_functions_by_keys(registry, keys)
140        })
141    }
142    pub(crate) fn lookup_bound_sql_functions_by_binding(
143        &self,
144        binding: &FunctionBinding,
145    ) -> Option<Vec<Arc<SQLUserFunction>>> {
146        self.with_routine_lookup_registry(|registry| {
147            lookup::lookup_bound_sql_functions_by_binding(registry, binding)
148        })
149    }
150    pub(crate) fn lookup_sql_routine_candidates(
151        &self,
152        name: &str,
153    ) -> Result<Option<Vec<Arc<SQLUserFunction>>>, SQLError> {
154        let keys = names::routine_lookup_keys(self, name)?;
155        Ok(self.with_routine_lookup_registry(|registry| {
156            lookup::lookup_sql_routine_candidates_by_keys(registry, keys)
157        }))
158    }
159    pub(crate) fn lookup_sql_routine_candidates_with_control(
160        &self,
161        name: &str,
162        control: &uqa_core::memory::ProductionControl<'_>,
163    ) -> Result<Option<uqa_core::memory::Produced<Vec<Arc<SQLUserFunction>>>>, SQLError> {
164        let keys = names::routine_lookup_keys_with_control(self, name, control)?;
165        self.with_routine_lookup_registry(|registry| {
166            lookup::lookup_sql_routine_candidates_by_keys_with_control(
167                registry,
168                keys.iter().map(String::as_str),
169                control,
170            )
171        })
172    }
173    pub(crate) fn lookup_bound_sql_routine_candidates_by_binding(
174        &self,
175        binding: &FunctionBinding,
176    ) -> Option<Vec<Arc<SQLUserFunction>>> {
177        self.with_routine_lookup_registry(|registry| {
178            lookup::lookup_bound_sql_routine_candidates_by_binding(registry, binding)
179        })
180    }
181    pub(crate) fn select_bound_function_with_control(
182        &self,
183        binding: &FunctionBinding,
184        control: &uqa_core::memory::ProductionControl<'_>,
185    ) -> Result<Option<Arc<SQLUserFunction>>, SQLError> {
186        self.with_routine_lookup_registry(|registry| {
187            lookup::select_bound_function_with_control(
188                registry.values().flat_map(|overloads| overloads.iter()),
189                binding,
190                control,
191            )
192        })
193    }
194    pub(crate) fn select_bound_routine_with_control(
195        &self,
196        binding: &FunctionBinding,
197        kind: uqa_sql::routines::resolution::RoutineCallKind,
198        control: &uqa_core::memory::ProductionControl<'_>,
199    ) -> Result<Option<Arc<SQLUserFunction>>, SQLError> {
200        self.with_routine_lookup_registry(|registry| {
201            lookup::select_bound_routine_with_control(
202                registry.values().flat_map(|overloads| overloads.iter()),
203                binding,
204                kind,
205                control,
206            )
207        })
208    }
209    pub(crate) fn persist_sql_functions_snapshot(
210        &self,
211        registry: &RoutineRegistry,
212    ) -> Result<(), SQLError> {
213        catalog::persist_sql_functions_snapshot(self.storage.catalog.as_deref(), registry)
214    }
215    fn routine_restore_context(&self) -> RoutineRestoreContext<'_> {
216        RoutineRestoreContext {
217            registry: self,
218            roles: self,
219            publication: self,
220            schemas: self,
221            definition: self.routine_definition_context(),
222        }
223    }
224    pub(crate) fn install_sql_function_restore_placeholders(
225        &self,
226        catalog: &dyn CatalogFacade,
227        mode: CatalogRestoreMode,
228    ) -> StorageBackendResult<Option<PendingSQLFunctionRestore>> {
229        restoration::install_sql_function_restore_placeholders(
230            &self.routine_restore_context(),
231            catalog,
232            mode.allows_migration(),
233        )
234    }
235    pub(crate) fn finalize_sql_function_restore(
236        &self,
237        pending: PendingSQLFunctionRestore,
238        mode: CatalogRestoreMode,
239    ) -> StorageBackendResult<()> {
240        restoration::finalize_sql_function_restore(
241            &self.routine_restore_context(),
242            pending,
243            mode.allows_migration(),
244        )
245    }
246}
247impl RoutineRestoreSchemas for Engine {
248    fn routine_schema_exists(&self, schema: &str) -> bool {
249        self.durable.schemas.read().contains_key(schema)
250    }
251    fn routine_user_type_identity(&self, type_name: &str) -> Option<String> {
252        uqa_execution::catalog::projection::resolve_catalog_column_type(
253            &self.catalog_execution(),
254            type_name,
255        )
256        .and_then(|ty| ty.user_type_identity())
257    }
258}