Skip to main content

quack_rs/aggregate/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 an [`AggregateFunctionSetBuilder`].
7//!
8//! Split out of `set.rs` so both files stay inside the 500-line guideline in
9//! `CONTRIBUTING.md`.
10//!
11//! [`AggregateFunctionSetBuilder`]: super::AggregateFunctionSetBuilder
12
13use std::os::raw::c_void;
14
15use libduckdb_sys::duckdb_delete_callback_t;
16
17use crate::aggregate::callbacks::{
18    CombineFn, DestroyFn, FinalizeFn, StateInitFn, StateSizeFn, UpdateFn,
19};
20use crate::error::ExtensionError;
21use crate::types::{LogicalType, NullHandling, TypeId};
22
23/// Specification for one overload within a function set.
24///
25/// This is the owned, post-build form of [`AggregateOverloadBuilder`]; the
26/// builder is consumed into one of these when it is handed to
27/// [`AggregateFunctionSetBuilder::overload`] or produced by
28/// [`AggregateFunctionSetBuilder::overloads`].
29///
30/// [`AggregateFunctionSetBuilder::overload`]: super::AggregateFunctionSetBuilder::overload
31/// [`AggregateFunctionSetBuilder::overloads`]: super::AggregateFunctionSetBuilder::overloads
32pub(super) struct OverloadSpec {
33    pub(super) params: Vec<TypeId>,
34    pub(super) logical_params: Vec<(usize, LogicalType)>,
35    pub(super) return_type: Option<TypeId>,
36    pub(super) return_logical: Option<LogicalType>,
37    pub(super) state_size: Option<StateSizeFn>,
38    pub(super) init: Option<StateInitFn>,
39    pub(super) update: Option<UpdateFn>,
40    pub(super) combine: Option<CombineFn>,
41    pub(super) finalize: Option<FinalizeFn>,
42    pub(super) destructor: Option<DestroyFn>,
43    pub(super) null_handling: NullHandling,
44    pub(super) extra_info: Option<crate::extra_info::ExtraInfo>,
45}
46
47impl OverloadSpec {
48    /// Checks that overload `index` has a return type (its own, or the set's
49    /// default when `has_default_return`) and every required callback,
50    /// without any `DuckDB` call.
51    pub(super) fn check_complete(
52        &self,
53        index: usize,
54        has_default_return: bool,
55    ) -> Result<(), ExtensionError> {
56        if self.return_type.is_none() && self.return_logical.is_none() && !has_default_return {
57            return Err(ExtensionError::new(format!(
58                "overload {index} has no return type and the function set has no default \
59                 return type: call `returns`/`returns_logical` on the overload, or on \
60                 the set to cover every overload"
61            )));
62        }
63        let missing = [
64            ("state_size", self.state_size.is_none()),
65            ("init", self.init.is_none()),
66            ("update", self.update.is_none()),
67            ("combine", self.combine.is_none()),
68            ("finalize", self.finalize.is_none()),
69        ]
70        .into_iter()
71        .find_map(|(name, absent)| absent.then_some(name));
72        if let Some(callback) = missing {
73            return Err(ExtensionError::new(format!(
74                "overload {index} has no {callback} callback: call `{callback}`"
75            )));
76        }
77        // Last, as for a single function.
78        if self.params.is_empty() && self.logical_params.is_empty() {
79            return Err(super::zero_parameter_error(
80                &format!("overload {index}"),
81                &format!("<function>_{index}"),
82            ));
83        }
84        Ok(())
85    }
86}
87
88/// A builder for one overload within an [`AggregateFunctionSetBuilder`].
89///
90/// Obtain one either from the closure passed to
91/// [`AggregateFunctionSetBuilder::overloads`] (one per arity in a range) or by
92/// calling [`AggregateOverloadBuilder::new`] and handing it to
93/// [`AggregateFunctionSetBuilder::overload`].
94///
95/// # Return types
96///
97/// An overload may carry its own return type via [`returns`][Self::returns] or
98/// [`returns_logical`][Self::returns_logical]. `DuckDB` resolves an aggregate
99/// overload from the **parameter types and arity only** — the return type takes
100/// no part in resolution — so overloads in one set are free to return different
101/// types, exactly as `DuckDB`'s own `arg_max` does:
102///
103/// ```text
104/// arg_max(ANY, ANY)      -> ANY
105/// arg_max(ANY, ANY, ANY) -> ANY[]
106/// ```
107///
108/// If an overload sets no return type, the set-level default from
109/// [`AggregateFunctionSetBuilder::returns`] /
110/// [`AggregateFunctionSetBuilder::returns_logical`] applies. Registration fails
111/// if an overload has neither.
112///
113/// [`AggregateFunctionSetBuilder`]: super::AggregateFunctionSetBuilder
114/// [`AggregateFunctionSetBuilder::overload`]: super::AggregateFunctionSetBuilder::overload
115/// [`AggregateFunctionSetBuilder::overloads`]: super::AggregateFunctionSetBuilder::overloads
116/// [`AggregateFunctionSetBuilder::returns`]: super::AggregateFunctionSetBuilder::returns
117/// [`AggregateFunctionSetBuilder::returns_logical`]: super::AggregateFunctionSetBuilder::returns_logical
118///
119/// # Example
120///
121/// Two overloads under one name with **different** return types:
122///
123/// ```rust,no_run
124/// use quack_rs::aggregate::{AggregateFunctionSetBuilder, AggregateOverloadBuilder};
125/// use quack_rs::types::TypeId;
126///
127/// // AggregateFunctionSetBuilder::new("my_agg")
128/// //     .overload(
129/// //         AggregateOverloadBuilder::new()
130/// //             .param(TypeId::Integer)
131/// //             .returns(TypeId::Integer)
132/// //             .state_size(int_state_size)
133/// //             .init(int_init)
134/// //             .update(int_update)
135/// //             .combine(int_combine)
136/// //             .finalize(int_finalize),
137/// //     )
138/// //     .overload(
139/// //         AggregateOverloadBuilder::new()
140/// //             .param(TypeId::Varchar)
141/// //             .returns(TypeId::Varchar)
142/// //             .state_size(str_state_size)
143/// //             .init(str_init)
144/// //             .update(str_update)
145/// //             .combine(str_combine)
146/// //             .finalize(str_finalize),
147/// //     )
148/// //     .register(con)
149/// ```
150#[must_use]
151pub struct AggregateOverloadBuilder {
152    pub(super) params: Vec<TypeId>,
153    pub(super) logical_params: Vec<(usize, LogicalType)>,
154    pub(super) return_type: Option<TypeId>,
155    pub(super) return_logical: Option<LogicalType>,
156    pub(super) state_size: Option<StateSizeFn>,
157    pub(super) init: Option<StateInitFn>,
158    pub(super) update: Option<UpdateFn>,
159    pub(super) combine: Option<CombineFn>,
160    pub(super) finalize: Option<FinalizeFn>,
161    pub(super) destructor: Option<DestroyFn>,
162    pub(super) null_handling: NullHandling,
163    pub(super) extra_info: Option<crate::extra_info::ExtraInfo>,
164}
165
166impl AggregateOverloadBuilder {
167    /// Creates a new `AggregateOverloadBuilder` with no parameters, no return
168    /// type and no callbacks set.
169    pub fn new() -> Self {
170        Self {
171            params: Vec::new(),
172            logical_params: Vec::new(),
173            return_type: None,
174            return_logical: None,
175            state_size: None,
176            init: None,
177            update: None,
178            combine: None,
179            finalize: None,
180            destructor: None,
181            null_handling: NullHandling::DefaultNullHandling,
182            extra_info: None,
183        }
184    }
185
186    /// Adds a positional parameter to this overload.
187    ///
188    /// For complex types like `LIST(BIGINT)`, use
189    /// [`param_logical`][Self::param_logical].
190    pub fn param(mut self, type_id: TypeId) -> Self {
191        self.params.push(type_id);
192        self
193    }
194
195    /// Adds a positional parameter with a complex [`LogicalType`].
196    ///
197    /// Use this for parameterized types that [`TypeId`] cannot express, such as
198    /// `LIST(BIGINT)`, `MAP(VARCHAR, INTEGER)`, or `STRUCT(...)`.
199    #[cfg_attr(test, mutants::skip)] // position arithmetic tested via E2E
200    pub fn param_logical(mut self, logical_type: LogicalType) -> Self {
201        let position = self.params.len() + self.logical_params.len();
202        self.logical_params.push((position, logical_type));
203        self
204    }
205
206    /// Sets the return type for **this overload only**, overriding any
207    /// set-level default.
208    ///
209    /// For complex return types like `LIST(BIGINT)`, use
210    /// [`returns_logical`][Self::returns_logical] instead.
211    pub const fn returns(mut self, type_id: TypeId) -> Self {
212        self.return_type = Some(type_id);
213        self
214    }
215
216    /// Sets the return type for **this overload only** to a complex
217    /// [`LogicalType`], overriding any set-level default.
218    ///
219    /// Use this for parameterized return types that [`TypeId`] cannot express,
220    /// such as `LIST(BOOLEAN)`, `MAP(VARCHAR, INTEGER)`, or `STRUCT(...)`.
221    ///
222    /// If both `returns` and `returns_logical` are called on the same overload,
223    /// the logical type takes precedence.
224    // Building a `LogicalType` calls `duckdb_create_logical_type`, which panics
225    // without a live dispatch table, so no `--lib` test can assert on what this
226    // stores. Covered end-to-end instead, by the DECIMAL(18,2) overload in
227    // `one_aggregate_set_serves_overloads_with_different_return_types`. Same
228    // reasoning as `ScalarOverloadBuilder::returns_logical`.
229    #[cfg_attr(test, mutants::skip)] // tested via E2E
230    pub fn returns_logical(mut self, logical_type: LogicalType) -> Self {
231        self.return_logical = Some(logical_type);
232        self
233    }
234
235    /// Installs [`FfiState<T>`][crate::aggregate::FfiState]'s `state_size`,
236    /// `init` and `destructor` callbacks together, so they cannot describe
237    /// different states (setting them one by one, a size callback for one `T`
238    /// with an init callback for another wrote past `DuckDB`'s allocation).
239    /// `update`, `combine` and `finalize` still read the state through
240    /// `FfiState::<T>::with_state` / `with_state_mut` with the same `T`.
241    pub const fn ffi_state<T: crate::aggregate::AggregateState>(self) -> Self {
242        self.state_size(crate::aggregate::FfiState::<T>::size_callback)
243            .init(crate::aggregate::FfiState::<T>::init_callback)
244            .destructor(crate::aggregate::FfiState::<T>::destroy_callback)
245    }
246
247    /// Sets the `state_size` callback for this overload.
248    ///
249    /// The `state_size`, `init` and `destructor` callbacks must describe the
250    /// same state: `DuckDB` allocates what `state_size` returns and hands that
251    /// allocation to `init` and, later, to `destructor` and the other
252    /// callbacks. [`FfiState<A>`][crate::aggregate::FfiState]'s size callback
253    /// with `FfiState<B>`'s init callback writes a `B` into space sized for an
254    /// `A`, past the allocation when `B` is larger. Prefer
255    /// [`ffi_state`][Self::ffi_state], which installs all three for one `T`.
256    pub const fn state_size(mut self, f: StateSizeFn) -> Self {
257        self.state_size = Some(f);
258        self
259    }
260
261    /// Sets the `init` callback for this overload.
262    ///
263    /// The `state_size`, `init` and `destructor` callbacks must describe the
264    /// same state: `DuckDB` allocates what `state_size` returns and hands that
265    /// allocation to `init` and, later, to `destructor` and the other
266    /// callbacks. [`FfiState<A>`][crate::aggregate::FfiState]'s size callback
267    /// with `FfiState<B>`'s init callback writes a `B` into space sized for an
268    /// `A`, past the allocation when `B` is larger. Prefer
269    /// [`ffi_state`][Self::ffi_state], which installs all three for one `T`.
270    pub const fn init(mut self, f: StateInitFn) -> Self {
271        self.init = Some(f);
272        self
273    }
274
275    /// Sets the `update` callback for this overload.
276    pub const fn update(mut self, f: UpdateFn) -> Self {
277        self.update = Some(f);
278        self
279    }
280
281    /// Sets the `combine` callback for this overload.
282    pub const fn combine(mut self, f: CombineFn) -> Self {
283        self.combine = Some(f);
284        self
285    }
286
287    /// Sets the `finalize` callback for this overload.
288    pub const fn finalize(mut self, f: FinalizeFn) -> Self {
289        self.finalize = Some(f);
290        self
291    }
292
293    /// Sets the optional destructor callback for this overload.
294    ///
295    /// When none is set, `register` installs a no-op destructor rather than
296    /// none at all. `DuckDB` evaluates an aggregate without a state destructor
297    /// as a *streaming* window for running frames
298    /// (`agg(x) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`), and
299    /// through the C API that path feeds `update` the first row of each chunk
300    /// in place of every later one — a wrong answer with no error (Pitfall
301    /// L13). The cost is the streaming shortcut: such windows are evaluated by
302    /// `DuckDB`'s general window operator instead.
303    pub const fn destructor(mut self, f: DestroyFn) -> Self {
304        self.destructor = Some(f);
305        self
306    }
307
308    /// Sets the NULL handling behaviour for this overload.
309    ///
310    /// This does **not** decide whether `update` sees NULL rows: it receives
311    /// every row under either setting, so an aggregate that ignores NULLs must
312    /// skip rows whose
313    /// [`VectorReader::is_valid`][crate::vector::VectorReader::is_valid] is
314    /// false. [`SpecialNullHandling`][NullHandling::SpecialNullHandling]
315    /// declares that the aggregate may return non-NULL for NULL input; see
316    /// [`NullHandling`] for the one planner decision that reads it.
317    pub const fn null_handling(mut self, handling: NullHandling) -> Self {
318        self.null_handling = handling;
319        self
320    }
321
322    /// Attaches arbitrary data to this overload.
323    ///
324    /// Mirrors
325    /// [`AggregateFunctionBuilder::extra_info`][super::AggregateFunctionBuilder::extra_info]:
326    /// the pointer is available inside this overload's callbacks via
327    /// [`AggregateFunctionInfo::get_extra_info`][crate::aggregate::AggregateFunctionInfo::get_extra_info],
328    /// and `destroy` frees it exactly once — by `DuckDB` once registration has
329    /// handed it over (whether or not registration then succeeds), or by the
330    /// builder if it is dropped, or registration is rejected, before that.
331    ///
332    /// # Safety
333    ///
334    /// - `data` must stay valid until `destroy` frees it (with no `destroy`,
335    ///   for as long as the database lives), and `destroy` must be able to
336    ///   free it exactly once with no one else freeing it — so one pointer
337    ///   must not be given to two builders or overloads, each of which hands
338    ///   its `destroy` to `DuckDB` separately.
339    /// - The pointee must be `Send + Sync`. `DuckDB` hands the same pointer to
340    ///   the callbacks on every thread that executes the function, possibly at
341    ///   the same moment, and `destroy` runs on whichever thread releases the
342    ///   function — or, if the builder is dropped unregistered, the thread
343    ///   that drops it.
344    /// - `destroy` must not unwind: it is an `extern "C" fn`, so a panic
345    ///   escaping it aborts the process. Wrap a body that can panic in
346    ///   [`catch_ffi_panic`][crate::callback::catch_ffi_panic].
347    ///
348    /// The typical pattern is to box your data:
349    /// `Box::into_raw(Box::new(my_data)).cast()`.
350    pub unsafe fn extra_info(
351        mut self,
352        data: *mut c_void,
353        destroy: duckdb_delete_callback_t,
354    ) -> Self {
355        // SAFETY: forwarded from this method's own contract.
356        self.extra_info = Some(unsafe { crate::extra_info::ExtraInfo::new(data, destroy) });
357        self
358    }
359
360    /// Attaches `value` as this overload's extra info: the safe, typed form
361    /// of [`extra_info`][Self::extra_info], read back with
362    /// [`AggregateFunctionInfo::extra_info_ref`][crate::aggregate::AggregateFunctionInfo::extra_info_ref].
363    /// See
364    /// [`AggregateFunctionBuilder::extra_info_typed`][crate::aggregate::AggregateFunctionBuilder::extra_info_typed]
365    /// for the ownership and threading rules and an example.
366    pub fn extra_info_typed<T: Send + Sync + 'static>(self, value: T) -> Self {
367        let (data, destroy) = crate::extra_info::into_tagged(value);
368        // SAFETY: `into_tagged` returns a fresh allocation, used by no one
369        // else, and the destructor that frees it exactly once without
370        // unwinding; `T: Send + Sync`.
371        unsafe { self.extra_info(data, Some(destroy)) }
372    }
373
374    /// Consumes this builder into the owned spec the set stores.
375    pub(super) fn into_spec(self) -> OverloadSpec {
376        OverloadSpec {
377            params: self.params,
378            logical_params: self.logical_params,
379            return_type: self.return_type,
380            return_logical: self.return_logical,
381            state_size: self.state_size,
382            init: self.init,
383            update: self.update,
384            combine: self.combine,
385            finalize: self.finalize,
386            destructor: self.destructor,
387            null_handling: self.null_handling,
388            extra_info: self.extra_info,
389        }
390    }
391}
392
393impl Default for AggregateOverloadBuilder {
394    fn default() -> Self {
395        Self::new()
396    }
397}
398
399impl core::fmt::Debug for AggregateOverloadBuilder {
400    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
401        use crate::debug_repr::Callback;
402        f.debug_struct("AggregateOverloadBuilder")
403            .field("params", &self.params)
404            .field("logical_params", &self.logical_params.len())
405            .field("return_type", &self.return_type)
406            .field("return_logical", &self.return_logical)
407            .field("state_size", &Callback::of(&self.state_size))
408            .field("init", &Callback::of(&self.init))
409            .field("update", &Callback::of(&self.update))
410            .field("combine", &Callback::of(&self.combine))
411            .field("finalize", &Callback::of(&self.finalize))
412            .field("destructor", &Callback::of(&self.destructor))
413            .field("null_handling", &self.null_handling)
414            .field("extra_info", &Callback::of(&self.extra_info))
415            .finish()
416    }
417}