Skip to main content

uqa_execution/
functions.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Runtime contracts for scalar, table, and aggregate extensions.
8
9pub use crate::row_stream::{SQLRowSource, SQLRowStream};
10use uqa_core::Value;
11use uqa_sql::SQLError;
12
13pub use uqa_sql::ast::FunctionVolatility as SQLFunctionVolatility;
14
15/// Host-owned invocation data belonging to the calling session. Registrations
16/// are shared across sessions; this data travels with execution, including
17/// worker and retained-portal execution, instead of with the registered code.
18/// Hosts should store weak session references here to avoid ownership cycles.
19#[derive(Clone, Default)]
20pub struct SQLFunctionContext(Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>);
21
22impl SQLFunctionContext {
23    #[must_use]
24    pub const fn empty() -> Self {
25        Self(None)
26    }
27
28    #[must_use]
29    pub fn new<T: Send + Sync + 'static>(data: T) -> Self {
30        Self(Some(std::sync::Arc::new(data)))
31    }
32
33    #[must_use]
34    pub fn get<T: 'static>(&self) -> Option<&T> {
35        self.0.as_ref()?.downcast_ref()
36    }
37}
38
39/// Execution properties declared for a Rust-backed SQL callback.
40///
41/// The default is deliberately conservative: callbacks registered through the
42/// original two-argument APIs are volatile and may mutate engine state. Callers
43/// must opt in to read-only execution explicitly.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct SQLFunctionOptions {
46    /// Whether optimizer rewrites may duplicate, eliminate, or reorder calls.
47    pub volatility: SQLFunctionVolatility,
48    /// Whether invoking the callback can mutate engine or session state.
49    pub may_mutate_engine: bool,
50}
51
52impl SQLFunctionOptions {
53    #[must_use]
54    pub const fn new(volatility: SQLFunctionVolatility, may_mutate_engine: bool) -> Self {
55        Self {
56            volatility,
57            may_mutate_engine,
58        }
59    }
60
61    /// Declare a callback that cannot mutate engine state.
62    #[must_use]
63    pub const fn read_only(volatility: SQLFunctionVolatility) -> Self {
64        Self::new(volatility, false)
65    }
66}
67
68impl Default for SQLFunctionOptions {
69    fn default() -> Self {
70        Self::new(SQLFunctionVolatility::Volatile, true)
71    }
72}
73
74pub struct RegisteredSQLFunction<F: ?Sized> {
75    pub function: std::sync::Arc<F>,
76    pub options: SQLFunctionOptions,
77}
78
79impl<F: ?Sized> RegisteredSQLFunction<F> {
80    pub fn new(function: std::sync::Arc<F>, options: SQLFunctionOptions) -> Self {
81        Self { function, options }
82    }
83}
84
85impl<F: ?Sized> Clone for RegisteredSQLFunction<F> {
86    fn clone(&self) -> Self {
87        Self {
88            function: self.function.clone(),
89            options: self.options,
90        }
91    }
92}
93
94/// Result shape returned by a registered SQL table function.
95#[derive(Debug, Clone, PartialEq)]
96pub struct SQLTableFunctionResult {
97    pub columns: Vec<String>,
98    pub rows: Vec<Vec<Value>>,
99}
100
101impl SQLTableFunctionResult {
102    pub fn new(
103        columns: impl IntoIterator<Item = impl Into<String>>,
104        rows: Vec<Vec<Value>>,
105    ) -> Self {
106        Self {
107            columns: columns.into_iter().map(Into::into).collect(),
108            rows,
109        }
110    }
111}
112
113/// Pull-based result returned by a registered SQL table function.
114///
115/// The iterator may report a late error after yielding earlier rows; the SQL
116/// physical pipeline propagates that error instead of turning it into an empty
117/// or truncated result.
118pub struct SQLTableFunctionStream {
119    pub columns: Vec<String>,
120    pub rows: SQLRowStream<'static, Vec<Value>>,
121}
122
123impl SQLTableFunctionStream {
124    pub fn new<I>(columns: impl IntoIterator<Item = impl Into<String>>, rows: I) -> Self
125    where
126        I: Iterator<Item = Result<Vec<Value>, SQLError>> + Send + 'static,
127    {
128        Self {
129            columns: columns.into_iter().map(Into::into).collect(),
130            rows: SQLRowStream::new(rows),
131        }
132    }
133
134    /// Transfer a scan with fallible cleanup to the execution pipeline.
135    pub fn from_source(
136        columns: impl IntoIterator<Item = impl Into<String>>,
137        rows: impl SQLRowSource<Vec<Value>> + 'static,
138    ) -> Self {
139        Self {
140            columns: columns.into_iter().map(Into::into).collect(),
141            rows: SQLRowStream::from_source(rows),
142        }
143    }
144}
145
146impl From<SQLTableFunctionResult> for SQLTableFunctionStream {
147    fn from(result: SQLTableFunctionResult) -> Self {
148        Self {
149            columns: result.columns,
150            rows: SQLRowStream::new(result.rows.into_iter().map(Ok)),
151        }
152    }
153}
154
155/// Rust implementation of a scalar SQL function.
156pub trait SQLScalarFunction: Send + Sync {
157    fn call(&self, _args: &[Value]) -> Result<Value, SQLError> {
158        Err(SQLError::Unsupported(
159            "scalar function requires an invocation context".into(),
160        ))
161    }
162
163    fn call_with_context(
164        &self,
165        _context: &SQLFunctionContext,
166        args: &[Value],
167    ) -> Result<Value, SQLError> {
168        self.call(args)
169    }
170}
171
172impl<F> SQLScalarFunction for F
173where
174    F: Fn(&[Value]) -> Result<Value, SQLError> + Send + Sync,
175{
176    fn call(&self, args: &[Value]) -> Result<Value, SQLError> {
177        self(args)
178    }
179}
180
181/// Rust implementation of a SQL table function used in `FROM`.
182pub trait SQLTableFunction: Send + Sync {
183    /// Stable, nonempty output names, independent of argument values and scan creation.
184    /// A declared descriptor permits binding correlated and empty sources
185    /// without executing the callback. Every call must return these columns
186    /// in this order. `None` retains the runtime-described call interface.
187    fn output_columns(&self) -> Option<&[String]> {
188        None
189    }
190
191    fn call(&self, _args: &[Value]) -> Result<SQLTableFunctionResult, SQLError> {
192        Err(SQLError::Unsupported(
193            "table function implements only the streaming call interface".into(),
194        ))
195    }
196
197    fn call_stream(&self, args: &[Value]) -> Result<SQLTableFunctionStream, SQLError> {
198        self.call(args).map(Into::into)
199    }
200
201    fn call_with_context(
202        &self,
203        _context: &SQLFunctionContext,
204        args: &[Value],
205    ) -> Result<SQLTableFunctionResult, SQLError> {
206        self.call(args)
207    }
208
209    fn call_stream_with_context(
210        &self,
211        _context: &SQLFunctionContext,
212        args: &[Value],
213    ) -> Result<SQLTableFunctionStream, SQLError> {
214        self.call_stream(args)
215    }
216}
217
218impl<F> SQLTableFunction for F
219where
220    F: Fn(&[Value]) -> Result<SQLTableFunctionResult, SQLError> + Send + Sync,
221{
222    fn call(&self, args: &[Value]) -> Result<SQLTableFunctionResult, SQLError> {
223        self(args)
224    }
225}
226
227/// Infallible factory retained for existing Rust aggregate implementations.
228///
229/// Every implementation also implements [`SQLAggregateFactory`]. A callback
230/// whose state creation can fail implements that fallible interface directly.
231pub trait SQLAggregateFunction: Send + Sync {
232    fn create_state(&self) -> Box<dyn SQLAggregateState>;
233}
234
235/// Fallible creation of an independent SQL aggregate state.
236///
237/// Execution propagates creation failure before observing or finishing that
238/// state, including a global aggregate over an empty input. A failed factory
239/// remains responsible for resources it allocated before returning the error.
240pub trait SQLAggregateFactory: Send + Sync {
241    fn try_create_state(&self) -> Result<Box<dyn SQLAggregateState>, SQLError> {
242        Err(SQLError::Unsupported(
243            "aggregate factory requires an invocation context".into(),
244        ))
245    }
246
247    fn try_create_state_with_context(
248        &self,
249        _context: &SQLFunctionContext,
250    ) -> Result<Box<dyn SQLAggregateState>, SQLError> {
251        self.try_create_state()
252    }
253}
254
255impl<F: SQLAggregateFunction + ?Sized> SQLAggregateFactory for F {
256    fn try_create_state(&self) -> Result<Box<dyn SQLAggregateState>, SQLError> {
257        Ok(self.create_state())
258    }
259}
260
261impl<F, S> SQLAggregateFunction for F
262where
263    F: Fn() -> S + Send + Sync,
264    S: SQLAggregateState + 'static,
265{
266    fn create_state(&self) -> Box<dyn SQLAggregateState> {
267        Box::new(self())
268    }
269}
270
271/// Per-group state for a registered SQL aggregate function.
272pub trait SQLAggregateState: Send {
273    fn observe(&mut self, args: &[Value]) -> Result<(), SQLError>;
274    fn finish(&self) -> Result<Value, SQLError>;
275
276    /// Release host resources after the last observation or value read. Execution
277    /// calls this once, including on failure, before completing the statement.
278    /// Resources must be released even when cleanup returns an error. `finish`
279    /// remains non-consuming because a window can read the same state repeatedly.
280    /// Existing Rust states may retain ordinary infallible `Drop` cleanup.
281    fn close(&mut self) -> Result<(), SQLError> {
282        Ok(())
283    }
284}
285
286/// Typed lookup of registered aggregate factories during physical plan preparation.
287pub trait AggregateFunctionRegistry:
288    uqa_sql::FunctionTypeResolver + uqa_sql::plan::AggregateClassifier
289{
290    fn registered_aggregate_function(
291        &self,
292        name: &str,
293    ) -> Option<std::sync::Arc<dyn SQLAggregateFactory>>;
294}