Skip to main content

uqa_engine/
sql_registry.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7use super::{
8    Arc, Engine, RegisteredSQLFunction, SQLAggregateFactory, SQLError, SQLFunctionOptions,
9    SQLFunctionVolatility, SQLScalarFunction, SQLTableFunction, Value,
10};
11
12mod owner;
13mod retained;
14pub(crate) use owner::Registry;
15pub use owner::{SQLFunctionRegistration, SQLFunctionRegistrationError};
16
17impl Engine {
18    /// Install immutable host invocation data for this session. Public sibling
19    /// sessions start empty; internal readers and portal workers inherit it.
20    pub fn install_sql_function_context(
21        &self,
22        context: crate::SQLFunctionContext,
23    ) -> Result<(), SQLFunctionRegistrationError> {
24        let _gate = self
25            .runtime
26            .statement_gate
27            .try_lock_idle()
28            .ok_or(SQLFunctionRegistrationError::Busy)?;
29        self.runtime
30            .function_context
31            .set(context)
32            .map_err(|_| SQLError::Routine {
33                sqlstate: "55000".into(),
34                message: "SQL function context is already installed for this session".into(),
35            })?;
36        Ok(())
37    }
38
39    fn normalize_sql_function_name(name: &str) -> std::result::Result<String, SQLError> {
40        let normalized = name.trim().to_ascii_lowercase();
41        if normalized.is_empty() {
42            return Err(SQLError::TypeMismatch(
43                "SQL function name cannot be empty".into(),
44            ));
45        }
46        Ok(normalized)
47    }
48
49    pub fn register_scalar_function<F>(
50        &self,
51        name: &str,
52        function: F,
53    ) -> std::result::Result<(), SQLError>
54    where
55        F: SQLScalarFunction + 'static,
56    {
57        self.register_scalar_function_with_options(name, SQLFunctionOptions::default(), function)
58    }
59
60    /// Register a Rust scalar callback with explicit optimizer and transaction
61    /// properties.
62    pub fn register_scalar_function_with_options<F>(
63        &self,
64        name: &str,
65        options: SQLFunctionOptions,
66        function: F,
67    ) -> std::result::Result<(), SQLError>
68    where
69        F: SQLScalarFunction + 'static,
70    {
71        self.register_scalar_function_retained(name, options, function)
72            .map(drop)
73            .map_err(Into::into)
74    }
75
76    /// Register a callback and return its independent retirement handle.
77    pub fn register_scalar_function_retained<F>(
78        &self,
79        name: &str,
80        options: SQLFunctionOptions,
81        function: F,
82    ) -> Result<SQLFunctionRegistration, SQLFunctionRegistrationError>
83    where
84        F: SQLScalarFunction + 'static,
85    {
86        Self::validate_sql_function_options(options)?;
87        let name = Self::normalize_sql_function_name(name)?;
88        self.extensions
89            .functions
90            .register_scalar(name, Arc::new(function), options)
91    }
92
93    pub fn register_table_function<F>(
94        &self,
95        name: &str,
96        function: F,
97    ) -> std::result::Result<(), SQLError>
98    where
99        F: SQLTableFunction + 'static,
100    {
101        self.register_table_function_with_options(name, SQLFunctionOptions::default(), function)
102    }
103
104    /// Register a Rust table callback with explicit optimizer and transaction
105    /// properties.
106    pub fn register_table_function_with_options<F>(
107        &self,
108        name: &str,
109        options: SQLFunctionOptions,
110        function: F,
111    ) -> std::result::Result<(), SQLError>
112    where
113        F: SQLTableFunction + 'static,
114    {
115        self.register_table_function_retained(name, options, function)
116            .map(drop)
117            .map_err(Into::into)
118    }
119
120    /// Register a callback and return its independent retirement handle.
121    pub fn register_table_function_retained<F>(
122        &self,
123        name: &str,
124        options: SQLFunctionOptions,
125        function: F,
126    ) -> Result<SQLFunctionRegistration, SQLFunctionRegistrationError>
127    where
128        F: SQLTableFunction + 'static,
129    {
130        Self::validate_sql_function_options(options)?;
131        let name = Self::normalize_sql_function_name(name)?;
132        self.extensions
133            .functions
134            .register_table(name, retained::Table::wrap(function), options)
135    }
136
137    pub fn register_aggregate_function<F>(
138        &self,
139        name: &str,
140        function: F,
141    ) -> std::result::Result<(), SQLError>
142    where
143        F: SQLAggregateFactory + 'static,
144    {
145        self.register_aggregate_function_with_options(name, SQLFunctionOptions::default(), function)
146    }
147
148    /// Register a Rust aggregate callback with explicit optimizer and
149    /// transaction properties.
150    pub fn register_aggregate_function_with_options<F>(
151        &self,
152        name: &str,
153        options: SQLFunctionOptions,
154        function: F,
155    ) -> std::result::Result<(), SQLError>
156    where
157        F: SQLAggregateFactory + 'static,
158    {
159        self.register_aggregate_function_retained(name, options, function)
160            .map(drop)
161            .map_err(Into::into)
162    }
163
164    /// Register a callback and return its independent retirement handle.
165    pub fn register_aggregate_function_retained<F>(
166        &self,
167        name: &str,
168        options: SQLFunctionOptions,
169        function: F,
170    ) -> Result<SQLFunctionRegistration, SQLFunctionRegistrationError>
171    where
172        F: SQLAggregateFactory + 'static,
173    {
174        Self::validate_sql_function_options(options)?;
175        let name = Self::normalize_sql_function_name(name)?;
176        self.extensions.functions.register_aggregate(
177            name,
178            retained::Aggregate::wrap(function),
179            options,
180        )
181    }
182
183    fn validate_sql_function_options(options: SQLFunctionOptions) -> Result<(), SQLError> {
184        if options.may_mutate_engine && options.volatility != SQLFunctionVolatility::Volatile {
185            return Err(SQLError::TypeMismatch(
186                "a callback that may mutate engine state must be VOLATILE".into(),
187            ));
188        }
189        Ok(())
190    }
191
192    pub(crate) fn call_registered_scalar_function(
193        &self,
194        name: &str,
195        args: &[Value],
196    ) -> Option<std::result::Result<Value, SQLError>> {
197        let registration = self.query_runtime_view().lookup_scalar_function(name)?;
198        Some(
199            uqa_sql::expr::enums::render_host_arguments(Some(self), args).and_then(|args| {
200                registration
201                    .function
202                    .call_with_context(self.query_runtime_view().function_context, &args)
203            }),
204        )
205    }
206
207    pub(crate) fn has_registered_scalar_functions(&self) -> bool {
208        self.query_runtime_view().has_scalar_functions()
209    }
210
211    pub(crate) fn has_registered_scalar_function(&self, name: &str) -> bool {
212        self.query_runtime_view().has_scalar_function(name)
213    }
214
215    pub(crate) fn has_registered_table_function(&self, name: &str) -> bool {
216        self.query_runtime_view().has_table_function(name)
217    }
218
219    pub(crate) fn has_registered_aggregate_function(&self, name: &str) -> bool {
220        self.query_runtime_view().has_aggregate_function(name)
221    }
222
223    pub(crate) fn registered_aggregate_function(
224        &self,
225        name: &str,
226    ) -> Option<Arc<dyn SQLAggregateFactory>> {
227        self.query_runtime_view()
228            .lookup_aggregate_function(name)
229            .map(|registration| {
230                Arc::new(retained::BoundAggregate {
231                    function: registration.function,
232                    context: self.query_runtime_view().function_context.clone(),
233                }) as Arc<dyn SQLAggregateFactory>
234            })
235    }
236
237    pub(crate) fn registered_runtime_function_may_mutate_engine(&self, name: &str) -> bool {
238        self.registered_runtime_function_options(name)
239            .into_iter()
240            .flatten()
241            .any(|options| options.may_mutate_engine)
242    }
243
244    pub(crate) fn registered_runtime_function_volatility(
245        &self,
246        name: &str,
247    ) -> Option<SQLFunctionVolatility> {
248        let mut volatility = None;
249        for options in self
250            .registered_runtime_function_options(name)
251            .into_iter()
252            .flatten()
253        {
254            volatility = Some(match (volatility, options.volatility) {
255                (_, SQLFunctionVolatility::Volatile)
256                | (Some(SQLFunctionVolatility::Volatile), _) => SQLFunctionVolatility::Volatile,
257                (_, SQLFunctionVolatility::Stable) | (Some(SQLFunctionVolatility::Stable), _) => {
258                    SQLFunctionVolatility::Stable
259                }
260                _ => SQLFunctionVolatility::Immutable,
261            });
262        }
263        volatility
264    }
265
266    fn registered_runtime_function_options(&self, name: &str) -> [Option<SQLFunctionOptions>; 3] {
267        self.query_runtime_view().registered_function_options(name)
268    }
269}
270
271#[cfg(test)]
272mod tests;