Skip to main content

quack_rs/scalar/builder/
overload.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2026 Tom F. <https://github.com/tomtom215/>
3// My way of giving something small back to the open source community
4// and encouraging more Rust development!
5
6//! One overload within a [`ScalarFunctionSetBuilder`].
7//!
8//! Split out of `set.rs` so both files stay inside the 500-line guideline in
9//! `CONTRIBUTING.md`, mirroring `aggregate/builder/overload.rs`.
10//!
11//! [`ScalarFunctionSetBuilder`]: super::ScalarFunctionSetBuilder
12
13use std::os::raw::c_void;
14
15use libduckdb_sys::duckdb_delete_callback_t;
16
17use crate::error::ExtensionError;
18use crate::types::{LogicalType, NullHandling, TypeId};
19
20use super::single::ScalarFn;
21#[cfg(feature = "duckdb-1-5")]
22use super::single::{ScalarBindFn, ScalarInitFn};
23
24/// Specification for one overload within a scalar function set: the owned,
25/// post-build form of [`ScalarOverloadBuilder`].
26pub(super) struct ScalarOverloadSpec {
27    pub(super) params: Vec<TypeId>,
28    pub(super) logical_params: Vec<(usize, LogicalType)>,
29    pub(super) return_type: Option<TypeId>,
30    pub(super) return_logical: Option<LogicalType>,
31    pub(super) function: Option<ScalarFn>,
32    pub(super) null_handling: NullHandling,
33    pub(super) extra_info: Option<crate::extra_info::ExtraInfo>,
34    pub(super) varargs: Option<super::signature::Varargs>,
35    pub(super) volatile: bool,
36    #[cfg(feature = "duckdb-1-5")]
37    pub(super) bind: Option<ScalarBindFn>,
38    #[cfg(feature = "duckdb-1-5")]
39    pub(super) init: Option<ScalarInitFn>,
40    /// The name a closure-built overload was built under
41    /// ([`ScalarFunctionSetBuilder::overload_typed`]), checked against the
42    /// set's.
43    ///
44    /// [`ScalarFunctionSetBuilder::overload_typed`]: super::ScalarFunctionSetBuilder::overload_typed
45    pub(super) built_as: Option<String>,
46}
47
48impl ScalarOverloadSpec {
49    /// The overload a closure-built function's builder describes, with its
50    /// signature, callback, `extra_info` and stability as they are.
51    pub(super) fn from_function(function: super::ScalarFunctionBuilder) -> Self {
52        Self {
53            built_as: Some(function.name().to_owned()),
54            params: function.params,
55            logical_params: function.logical_params,
56            return_type: function.return_type,
57            return_logical: function.return_logical,
58            function: function.function,
59            null_handling: function.null_handling,
60            extra_info: function.extra_info,
61            varargs: function.varargs,
62            volatile: function.volatile,
63            #[cfg(feature = "duckdb-1-5")]
64            bind: function.bind,
65            #[cfg(feature = "duckdb-1-5")]
66            init: function.init,
67        }
68    }
69
70    /// Checks that overload `index` has everything registration needs,
71    /// without any `DuckDB` call.
72    pub(super) fn check_complete(&self, index: usize) -> Result<(), ExtensionError> {
73        if self.return_type.is_none() && self.return_logical.is_none() {
74            return Err(ExtensionError::new(format!(
75                "overload {index} has no return type: call `returns` or `returns_logical`"
76            )));
77        }
78        if self.function.is_none() {
79            return Err(ExtensionError::new(format!(
80                "overload {index} has no function callback: call `function`"
81            )));
82        }
83        Ok(())
84    }
85}
86
87/// A builder for one overload within a [`ScalarFunctionSetBuilder`].
88///
89/// [`ScalarFunctionSetBuilder`]: super::ScalarFunctionSetBuilder
90#[must_use]
91pub struct ScalarOverloadBuilder {
92    pub(super) params: Vec<TypeId>,
93    pub(super) logical_params: Vec<(usize, LogicalType)>,
94    pub(super) return_type: Option<TypeId>,
95    pub(super) return_logical: Option<LogicalType>,
96    pub(super) function: Option<ScalarFn>,
97    pub(super) null_handling: NullHandling,
98    pub(super) extra_info: Option<crate::extra_info::ExtraInfo>,
99    pub(super) varargs: Option<super::signature::Varargs>,
100    pub(super) volatile: bool,
101    #[cfg(feature = "duckdb-1-5")]
102    pub(super) bind: Option<ScalarBindFn>,
103    #[cfg(feature = "duckdb-1-5")]
104    pub(super) init: Option<ScalarInitFn>,
105}
106
107impl ScalarOverloadBuilder {
108    /// Creates a new `ScalarOverloadBuilder`.
109    pub fn new() -> Self {
110        Self {
111            params: Vec::new(),
112            logical_params: Vec::new(),
113            return_type: None,
114            return_logical: None,
115            function: None,
116            null_handling: NullHandling::DefaultNullHandling,
117            extra_info: None,
118            varargs: None,
119            volatile: false,
120            #[cfg(feature = "duckdb-1-5")]
121            bind: None,
122            #[cfg(feature = "duckdb-1-5")]
123            init: None,
124        }
125    }
126
127    /// Adds a positional parameter to this overload.
128    ///
129    /// For complex types like `LIST(BIGINT)`, use
130    /// [`param_logical`][Self::param_logical].
131    pub fn param(mut self, type_id: TypeId) -> Self {
132        self.params.push(type_id);
133        self
134    }
135
136    /// Adds a positional parameter with a complex [`LogicalType`].
137    ///
138    /// Use this for parameterized types that [`TypeId`] cannot express, such as
139    /// `LIST(BIGINT)`, `MAP(VARCHAR, INTEGER)`, or `STRUCT(...)`.
140    #[cfg_attr(test, mutants::skip)] // position arithmetic tested via E2E
141    pub fn param_logical(mut self, logical_type: LogicalType) -> Self {
142        let position = self.params.len() + self.logical_params.len();
143        self.logical_params.push((position, logical_type));
144        self
145    }
146
147    /// Sets the return type for this overload.
148    ///
149    /// For complex return types like `LIST(BIGINT)`, use
150    /// [`returns_logical`][Self::returns_logical] instead.
151    pub const fn returns(mut self, type_id: TypeId) -> Self {
152        self.return_type = Some(type_id);
153        self
154    }
155
156    /// Sets the return type to a complex [`LogicalType`] for this overload.
157    ///
158    /// Use this for parameterized return types that [`TypeId`] cannot express,
159    /// such as `LIST(BOOLEAN)`, `LIST(TIMESTAMP)`, `MAP(VARCHAR, INTEGER)`, etc.
160    ///
161    /// If both `returns` and `returns_logical` are called, the logical type takes
162    /// precedence.
163    #[cfg_attr(test, mutants::skip)] // tested via E2E
164    pub fn returns_logical(mut self, logical_type: LogicalType) -> Self {
165        self.return_logical = Some(logical_type);
166        self
167    }
168
169    /// Sets the scalar function callback for this overload.
170    pub fn function(mut self, f: ScalarFn) -> Self {
171        self.function = Some(f);
172        self
173    }
174
175    /// Marks this overload as accepting variadic arguments of the given type,
176    /// after its fixed parameters.
177    ///
178    /// Mirrors [`ScalarFunctionBuilder::varargs`][super::ScalarFunctionBuilder::varargs],
179    /// including the error from `register` for a composite `type_id`.
180    #[cfg_attr(test, mutants::skip)] // tested via E2E
181    pub fn varargs(mut self, type_id: TypeId) -> Self {
182        self.varargs = Some(super::signature::Varargs::Id(type_id));
183        self
184    }
185
186    /// Marks this overload as accepting variadic arguments with a complex type.
187    ///
188    /// Mirrors
189    /// [`ScalarFunctionBuilder::varargs_logical`][super::ScalarFunctionBuilder::varargs_logical].
190    #[cfg_attr(test, mutants::skip)] // tested via E2E
191    pub fn varargs_logical(mut self, logical_type: LogicalType) -> Self {
192        self.varargs = Some(super::signature::Varargs::Logical(logical_type));
193        self
194    }
195
196    /// Marks this overload as volatile: re-evaluated for every row even when
197    /// its arguments are constant.
198    ///
199    /// Mirrors [`ScalarFunctionBuilder::volatile`][super::ScalarFunctionBuilder::volatile].
200    /// Each overload of a set has its own stability.
201    pub const fn volatile(mut self) -> Self {
202        self.volatile = true;
203        self
204    }
205
206    /// Sets a bind callback for this overload (`DuckDB` 1.5.0+).
207    ///
208    /// Mirrors [`ScalarFunctionBuilder::bind`][super::ScalarFunctionBuilder::bind].
209    ///
210    /// Guard it against panics with
211    /// [`scalar_bind_callback!`](crate::scalar_bind_callback), **not**
212    /// `table_bind_callback!`. The compiler refuses the table macro here — its
213    /// function takes a table function's bind info, not a
214    /// [`RawScalarBindInfo`](crate::scalar::RawScalarBindInfo) — because a
215    /// table callback reports a panic through `duckdb_bind_set_error`, which
216    /// would write past the smaller scalar bind info and corrupt the stack.
217    #[cfg(feature = "duckdb-1-5")]
218    pub fn bind(mut self, f: ScalarBindFn) -> Self {
219        self.bind = Some(f);
220        self
221    }
222
223    /// Sets an init callback for this overload (`DuckDB` 1.5.0+).
224    ///
225    /// Mirrors [`ScalarFunctionBuilder::init`][super::ScalarFunctionBuilder::init].
226    ///
227    /// Guard it against panics with
228    /// [`scalar_init_callback!`](crate::scalar_init_callback), **not**
229    /// `table_init_callback!`. The compiler refuses the table macro here — its
230    /// function takes a table function's init info, not a
231    /// [`RawScalarInitInfo`](crate::scalar::RawScalarInitInfo) — because a
232    /// table callback reports a panic through `duckdb_init_set_error`, which
233    /// would write past the smaller scalar init info and corrupt the stack.
234    #[cfg(feature = "duckdb-1-5")]
235    pub fn init(mut self, f: ScalarInitFn) -> Self {
236        self.init = Some(f);
237        self
238    }
239
240    /// Sets the NULL handling behaviour for this overload.
241    ///
242    /// Under either setting the callback receives NULL rows. With the default,
243    /// [`DefaultNullHandling`][NullHandling::DefaultNullHandling], the callback
244    /// **promises** NULL-in-NULL-out and must keep that promise itself —
245    /// `DuckDB` does not write NULL for it (pitfall L8; see [`NullHandling`] and
246    /// [`DataChunk::propagate_nulls`][crate::data_chunk::DataChunk::propagate_nulls]).
247    /// [`SpecialNullHandling`][NullHandling::SpecialNullHandling] declares that
248    /// it may return non-NULL for NULL input.
249    pub const fn null_handling(mut self, handling: NullHandling) -> Self {
250        self.null_handling = handling;
251        self
252    }
253
254    /// Attaches arbitrary data to this overload.
255    ///
256    /// The data pointer is available inside the callback via
257    /// `duckdb_function_get_extra_info`. The `destroy` callback is called by
258    /// `DuckDB` when the function is dropped to free the data.
259    ///
260    /// # Safety
261    ///
262    /// - `data` must stay valid until `destroy` frees it (with no `destroy`,
263    ///   for as long as the database lives), and `destroy` must be able to
264    ///   free it exactly once with no one else freeing it — so one pointer
265    ///   must not be given to two builders or overloads, each of which hands
266    ///   its `destroy` to `DuckDB` separately.
267    /// - The pointee must be `Send + Sync`. `DuckDB` hands the same pointer to
268    ///   the callbacks on every thread that executes the function, possibly at
269    ///   the same moment, and `destroy` runs on whichever thread releases the
270    ///   function — or, if the builder is dropped unregistered, the thread
271    ///   that drops it.
272    /// - `destroy` must not unwind: it is an `extern "C" fn`, so a panic
273    ///   escaping it aborts the process. Wrap a body that can panic in
274    ///   [`catch_ffi_panic`][crate::callback::catch_ffi_panic].
275    ///
276    /// The typical pattern is to box your data:
277    /// `Box::into_raw(Box::new(my_data)).cast()`.
278    pub unsafe fn extra_info(
279        mut self,
280        data: *mut c_void,
281        destroy: duckdb_delete_callback_t,
282    ) -> Self {
283        // SAFETY: forwarded from this method's own contract.
284        self.extra_info = Some(unsafe { crate::extra_info::ExtraInfo::new(data, destroy) });
285        self
286    }
287
288    /// Consumes this builder into the owned spec the set stores.
289    pub(super) fn into_spec(self) -> ScalarOverloadSpec {
290        ScalarOverloadSpec {
291            params: self.params,
292            logical_params: self.logical_params,
293            return_type: self.return_type,
294            return_logical: self.return_logical,
295            function: self.function,
296            null_handling: self.null_handling,
297            extra_info: self.extra_info,
298            varargs: self.varargs,
299            volatile: self.volatile,
300            #[cfg(feature = "duckdb-1-5")]
301            bind: self.bind,
302            #[cfg(feature = "duckdb-1-5")]
303            init: self.init,
304            built_as: None,
305        }
306    }
307}
308
309impl Default for ScalarOverloadBuilder {
310    fn default() -> Self {
311        Self::new()
312    }
313}
314
315impl core::fmt::Debug for ScalarOverloadBuilder {
316    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
317        use crate::debug_repr::Callback;
318        let mut s = f.debug_struct("ScalarOverloadBuilder");
319        s.field("params", &self.params)
320            .field("logical_params", &self.logical_params.len())
321            .field("return_type", &self.return_type)
322            .field("return_logical", &self.return_logical)
323            .field("function", &Callback::of(&self.function))
324            .field("null_handling", &self.null_handling)
325            .field("extra_info", &Callback::of(&self.extra_info))
326            .field("varargs", &self.varargs)
327            .field("volatile", &self.volatile);
328        #[cfg(feature = "duckdb-1-5")]
329        s.field("bind", &Callback::of(&self.bind))
330            .field("init", &Callback::of(&self.init));
331        s.finish()
332    }
333}