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
9use uqa_core::Value;
10use uqa_sql::SQLError;
11
12pub use uqa_sql::ast::FunctionVolatility as SQLFunctionVolatility;
13
14/// Execution properties declared for a Rust-backed SQL callback.
15///
16/// The default is deliberately conservative: callbacks registered through the
17/// original two-argument APIs are volatile and may mutate engine state. Callers
18/// must opt in to read-only execution explicitly.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct SQLFunctionOptions {
21    /// Whether optimizer rewrites may duplicate, eliminate, or reorder calls.
22    pub volatility: SQLFunctionVolatility,
23    /// Whether invoking the callback can mutate engine or session state.
24    pub may_mutate_engine: bool,
25}
26
27impl SQLFunctionOptions {
28    #[must_use]
29    pub const fn new(volatility: SQLFunctionVolatility, may_mutate_engine: bool) -> Self {
30        Self {
31            volatility,
32            may_mutate_engine,
33        }
34    }
35
36    /// Declare a callback that cannot mutate engine state.
37    #[must_use]
38    pub const fn read_only(volatility: SQLFunctionVolatility) -> Self {
39        Self::new(volatility, false)
40    }
41}
42
43impl Default for SQLFunctionOptions {
44    fn default() -> Self {
45        Self::new(SQLFunctionVolatility::Volatile, true)
46    }
47}
48
49pub struct RegisteredSQLFunction<F: ?Sized> {
50    pub function: std::sync::Arc<F>,
51    pub options: SQLFunctionOptions,
52}
53
54impl<F: ?Sized> RegisteredSQLFunction<F> {
55    pub fn new(function: std::sync::Arc<F>, options: SQLFunctionOptions) -> Self {
56        Self { function, options }
57    }
58}
59
60impl<F: ?Sized> Clone for RegisteredSQLFunction<F> {
61    fn clone(&self) -> Self {
62        Self {
63            function: self.function.clone(),
64            options: self.options,
65        }
66    }
67}
68
69/// Result shape returned by a registered SQL table function.
70#[derive(Debug, Clone, PartialEq)]
71pub struct SQLTableFunctionResult {
72    pub columns: Vec<String>,
73    pub rows: Vec<Vec<Value>>,
74}
75
76impl SQLTableFunctionResult {
77    pub fn new(
78        columns: impl IntoIterator<Item = impl Into<String>>,
79        rows: Vec<Vec<Value>>,
80    ) -> Self {
81        Self {
82            columns: columns.into_iter().map(Into::into).collect(),
83            rows,
84        }
85    }
86}
87
88/// Pull-based result returned by a registered SQL table function.
89///
90/// The iterator may report a late error after yielding earlier rows; the SQL
91/// physical pipeline propagates that error instead of turning it into an empty
92/// or truncated result.
93pub struct SQLTableFunctionStream {
94    pub columns: Vec<String>,
95    pub rows: Box<dyn Iterator<Item = Result<Vec<Value>, SQLError>> + Send>,
96}
97
98impl SQLTableFunctionStream {
99    pub fn new<I>(columns: impl IntoIterator<Item = impl Into<String>>, rows: I) -> Self
100    where
101        I: Iterator<Item = Result<Vec<Value>, SQLError>> + Send + 'static,
102    {
103        Self {
104            columns: columns.into_iter().map(Into::into).collect(),
105            rows: Box::new(rows),
106        }
107    }
108}
109
110impl From<SQLTableFunctionResult> for SQLTableFunctionStream {
111    fn from(result: SQLTableFunctionResult) -> Self {
112        Self {
113            columns: result.columns,
114            rows: Box::new(result.rows.into_iter().map(Ok)),
115        }
116    }
117}
118
119/// Rust implementation of a scalar SQL function.
120pub trait SQLScalarFunction: Send + Sync {
121    fn call(&self, args: &[Value]) -> Result<Value, SQLError>;
122}
123
124impl<F> SQLScalarFunction for F
125where
126    F: Fn(&[Value]) -> Result<Value, SQLError> + Send + Sync,
127{
128    fn call(&self, args: &[Value]) -> Result<Value, SQLError> {
129        self(args)
130    }
131}
132
133/// Rust implementation of a SQL table function used in `FROM`.
134pub trait SQLTableFunction: Send + Sync {
135    fn call(&self, _args: &[Value]) -> Result<SQLTableFunctionResult, SQLError> {
136        Err(SQLError::Unsupported(
137            "table function implements only the streaming call interface".into(),
138        ))
139    }
140
141    fn call_stream(&self, args: &[Value]) -> Result<SQLTableFunctionStream, SQLError> {
142        self.call(args).map(Into::into)
143    }
144}
145
146impl<F> SQLTableFunction for F
147where
148    F: Fn(&[Value]) -> Result<SQLTableFunctionResult, SQLError> + Send + Sync,
149{
150    fn call(&self, args: &[Value]) -> Result<SQLTableFunctionResult, SQLError> {
151        self(args)
152    }
153}
154
155/// Factory for per-group SQL aggregate state.
156pub trait SQLAggregateFunction: Send + Sync {
157    fn create_state(&self) -> Box<dyn SQLAggregateState>;
158}
159
160impl<F, S> SQLAggregateFunction for F
161where
162    F: Fn() -> S + Send + Sync,
163    S: SQLAggregateState + 'static,
164{
165    fn create_state(&self) -> Box<dyn SQLAggregateState> {
166        Box::new(self())
167    }
168}
169
170/// Per-group state for a registered SQL aggregate function.
171pub trait SQLAggregateState: Send {
172    fn observe(&mut self, args: &[Value]) -> Result<(), SQLError>;
173    fn finish(&self) -> Result<Value, SQLError>;
174}
175
176/// Typed lookup of registered aggregate factories during physical plan preparation.
177pub trait AggregateFunctionRegistry:
178    uqa_sql::FunctionTypeResolver + uqa_sql::plan::AggregateClassifier
179{
180    fn registered_aggregate_function(
181        &self,
182        name: &str,
183    ) -> Option<std::sync::Arc<dyn SQLAggregateFunction>>;
184}