Skip to main content

quack_rs/aggregate/builder/
set.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
6use std::ffi::CString;
7
8use libduckdb_sys::{
9    duckdb_add_aggregate_function_to_set, duckdb_aggregate_function_set_destructor,
10    duckdb_aggregate_function_set_extra_info, duckdb_aggregate_function_set_functions,
11    duckdb_aggregate_function_set_name, duckdb_aggregate_function_set_return_type,
12    duckdb_aggregate_function_set_special_handling, duckdb_connection,
13    duckdb_create_aggregate_function, duckdb_create_aggregate_function_set,
14    duckdb_destroy_aggregate_function, duckdb_destroy_aggregate_function_set,
15    duckdb_register_aggregate_function_set, DuckDBSuccess,
16};
17
18use super::overload::{AggregateOverloadBuilder, OverloadSpec};
19use crate::error::ExtensionError;
20use crate::scalar::builder::signature::{merged_params, reject_duplicate_overloads};
21use crate::types::logical_type::SlotCheck;
22use crate::types::{LogicalType, NullHandling, TypeId};
23use crate::validate::validate_function_name;
24
25/// Builder for registering a `DuckDB` aggregate function set (multiple overloads).
26///
27/// Use this when one function name needs several signatures — either a variable
28/// number of arguments (one overload per arity) or different parameter types.
29///
30/// # Known `DuckDB` limitation
31///
32/// Every overload is a C-API aggregate, so on `DuckDB` before 2.0.0 each
33/// reads out of bounds under `agg(x) OVER ()` and `agg(x ORDER BY y)` — a
34/// `DuckDB` C API defect, fixed in 2.0.0. See
35/// [`AggregateFunctionBuilder`][crate::aggregate::AggregateFunctionBuilder#known-duckdb-limitation].
36///
37/// # ADR-5: Function sets for variadic signatures
38///
39/// `DuckDB` does not support true varargs for aggregate functions. For functions
40/// that accept 2–32 boolean conditions, register 31 overloads.
41///
42/// # Return types are per-overload
43///
44/// `DuckDB` resolves an aggregate overload from its **parameter types and arity
45/// only**; the return type plays no part in resolution. Each overload may
46/// therefore return a different type, set with
47/// [`AggregateOverloadBuilder::returns`] /
48/// [`AggregateOverloadBuilder::returns_logical`]. [`returns`][Self::returns] and
49/// [`returns_logical`][Self::returns_logical] on *this* builder set a **default**
50/// applied to every overload that does not carry its own — convenient when all
51/// arities of a variadic aggregate share one return type.
52///
53/// Registration fails if an overload has neither its own return type nor a
54/// set-level default.
55///
56/// # Pitfall L6: Name must be set on each member
57///
58/// This builder calls `duckdb_aggregate_function_set_name` on EVERY individual
59/// function before adding it to the set. If you forget this call, `DuckDB`
60/// silently rejects the registration. Discovery of this bug required reading
61/// `DuckDB`'s own C++ test code at
62/// `test/api/capi/test_capi_aggregate_functions.cpp`.
63///
64/// # Examples
65///
66/// One return type shared by every arity — set it once on the set. Each
67/// overload needs its own parameters: overloads that accept the same
68/// arguments are refused at `register`.
69///
70/// ```rust,no_run
71/// use quack_rs::aggregate::{AggregateFunctionSetBuilder, AggregateOverloadBuilder};
72/// use quack_rs::types::{LogicalType, TypeId};
73/// use libduckdb_sys::{duckdb_aggregate_state, duckdb_connection, duckdb_data_chunk,
74///                     duckdb_function_info, duckdb_vector, idx_t};
75///
76/// # unsafe extern "C" fn state_size(_: duckdb_function_info) -> idx_t { 8 }
77/// # unsafe extern "C" fn state_init(_: duckdb_function_info, _: duckdb_aggregate_state) {}
78/// # unsafe extern "C" fn update(_: duckdb_function_info, _: duckdb_data_chunk,
79/// #     _: *mut duckdb_aggregate_state) {}
80/// # unsafe extern "C" fn combine(_: duckdb_function_info, _: *mut duckdb_aggregate_state,
81/// #     _: *mut duckdb_aggregate_state, _: idx_t) {}
82/// # unsafe extern "C" fn finalize(_: duckdb_function_info, _: *mut duckdb_aggregate_state,
83/// #     _: duckdb_vector, _: idx_t, _: idx_t) {}
84/// # unsafe extern "C" fn destroy(_: *mut duckdb_aggregate_state, _: idx_t) {}
85/// /// # Safety
86/// ///
87/// /// `con` must be a valid, open connection.
88/// unsafe fn register_retention(
89///     con: duckdb_connection,
90/// ) -> Result<(), quack_rs::error::ExtensionError> {
91///     // SAFETY: `con` is valid per this function's contract.
92///     unsafe {
93///         AggregateFunctionSetBuilder::new("retention")
94///             .returns_logical(LogicalType::list(TypeId::Boolean))
95///             .overloads(2..=32, |n, builder: AggregateOverloadBuilder| {
96///                 (0..n)
97///                     .fold(builder, |b, _| b.param(TypeId::Boolean))
98///                     .state_size(state_size)
99///                     .init(state_init)
100///                     .update(update)
101///                     .combine(combine)
102///                     .finalize(finalize)
103///                     .destructor(destroy)
104///             })
105///             .register(con)
106///     }
107/// }
108/// ```
109///
110/// Different return types per overload — set them on each overload:
111///
112/// ```rust,no_run
113/// use quack_rs::aggregate::{AggregateFunctionSetBuilder, AggregateOverloadBuilder};
114/// use quack_rs::types::TypeId;
115/// # use libduckdb_sys::{duckdb_aggregate_state, duckdb_connection, duckdb_data_chunk,
116/// #                     duckdb_function_info, duckdb_vector, idx_t};
117/// # unsafe extern "C" fn state_size(_: duckdb_function_info) -> idx_t { 8 }
118/// # unsafe extern "C" fn init(_: duckdb_function_info, _: duckdb_aggregate_state) {}
119/// # unsafe extern "C" fn update(_: duckdb_function_info, _: duckdb_data_chunk,
120/// #     _: *mut duckdb_aggregate_state) {}
121/// # unsafe extern "C" fn combine(_: duckdb_function_info, _: *mut duckdb_aggregate_state,
122/// #     _: *mut duckdb_aggregate_state, _: idx_t) {}
123/// # unsafe extern "C" fn int_finalize(_: duckdb_function_info, _: *mut duckdb_aggregate_state,
124/// #     _: duckdb_vector, _: idx_t, _: idx_t) {}
125/// # unsafe extern "C" fn str_finalize(_: duckdb_function_info, _: *mut duckdb_aggregate_state,
126/// #     _: duckdb_vector, _: idx_t, _: idx_t) {}
127/// # unsafe fn demo(con: duckdb_connection) -> Result<(), quack_rs::error::ExtensionError> {
128/// // SAFETY: `con` is a valid, open connection.
129/// unsafe {
130///     AggregateFunctionSetBuilder::new("my_agg")
131///         .overload(
132///             AggregateOverloadBuilder::new()
133///                 .param(TypeId::Integer)
134///                 .returns(TypeId::Integer)
135///                 .state_size(state_size)
136///                 .init(init)
137///                 .update(update)
138///                 .combine(combine)
139///                 .finalize(int_finalize),
140///         )
141///         .overload(
142///             AggregateOverloadBuilder::new()
143///                 .param(TypeId::Varchar)
144///                 .returns(TypeId::Varchar)
145///                 .state_size(state_size)
146///                 .init(init)
147///                 .update(update)
148///                 .combine(combine)
149///                 .finalize(str_finalize),
150///         )
151///         .register(con)
152/// }
153/// # }
154/// ```
155#[must_use]
156pub struct AggregateFunctionSetBuilder {
157    pub(super) name: CString,
158    pub(super) return_type: Option<TypeId>,
159    pub(super) return_logical: Option<LogicalType>,
160    pub(super) overloads: Vec<OverloadSpec>,
161}
162
163impl AggregateFunctionSetBuilder {
164    /// Creates a new builder for a function set with the given name.
165    ///
166    /// # Panics
167    ///
168    /// Panics if `name` contains an interior null byte.
169    pub fn new(name: &str) -> Self {
170        Self {
171            name: CString::new(name).expect("function name must not contain null bytes"),
172            return_type: None,
173            return_logical: None,
174            overloads: Vec::new(),
175        }
176    }
177
178    /// Creates a new builder with function name validation.
179    ///
180    /// # Errors
181    ///
182    /// Returns `ExtensionError` if the name is invalid.
183    /// See [`validate_function_name`] for the full set of rules.
184    pub fn try_new(name: &str) -> Result<Self, ExtensionError> {
185        validate_function_name(name)?;
186        let c_name = CString::new(name)
187            .map_err(|_| ExtensionError::new("function name contains interior null byte"))?;
188        Ok(Self {
189            name: c_name,
190            return_type: None,
191            return_logical: None,
192            overloads: Vec::new(),
193        })
194    }
195
196    /// Returns the function set name.
197    ///
198    /// Useful for introspection and for [`MockRegistrar`][crate::testing::MockRegistrar].
199    pub fn name(&self) -> &str {
200        self.name.to_str().unwrap_or("")
201    }
202
203    /// Sets the **default** return type, used by every overload that does not
204    /// set its own with [`AggregateOverloadBuilder::returns`] /
205    /// [`AggregateOverloadBuilder::returns_logical`].
206    ///
207    /// For complex return types like `LIST(BIGINT)`, use
208    /// [`returns_logical`][Self::returns_logical] instead.
209    pub const fn returns(mut self, type_id: TypeId) -> Self {
210        self.return_type = Some(type_id);
211        self
212    }
213
214    /// Sets the **default** return type to a complex [`LogicalType`], used by
215    /// every overload that does not set its own.
216    ///
217    /// Use this for parameterized return types that [`TypeId`] cannot express,
218    /// such as `LIST(BOOLEAN)`, `LIST(TIMESTAMP)`, `MAP(VARCHAR, INTEGER)`, etc.
219    ///
220    /// If both `returns` and `returns_logical` are called, the logical type takes
221    /// precedence.
222    ///
223    /// # Example
224    ///
225    /// ```rust,no_run
226    /// use quack_rs::aggregate::AggregateFunctionSetBuilder;
227    /// use quack_rs::types::{LogicalType, TypeId};
228    ///
229    /// // AggregateFunctionSetBuilder::new("retention")
230    /// //     .returns_logical(LogicalType::list(TypeId::Boolean))
231    /// //     .overloads(2..=32, |n, builder| {
232    /// //         (0..n).fold(builder, |b, _| b.param(TypeId::Boolean))
233    /// //             .state_size(my_state_size)
234    /// //             .init(my_init)
235    /// //             .update(my_update)
236    /// //             .combine(my_combine)
237    /// //             .finalize(my_finalize)
238    /// //     });
239    /// ```
240    pub fn returns_logical(mut self, logical_type: LogicalType) -> Self {
241        self.return_logical = Some(logical_type);
242        self
243    }
244
245    /// Adds a single, fully-configured overload to this function set.
246    ///
247    /// Use this when overloads differ in more than arity — different parameter
248    /// types, different return types, or different callbacks. For a family of
249    /// arities that share a shape, [`overloads`][Self::overloads] is shorter.
250    ///
251    /// The two may be mixed; overloads are registered in the order added.
252    ///
253    /// # Example
254    ///
255    /// ```rust,no_run
256    /// use quack_rs::aggregate::{AggregateFunctionSetBuilder, AggregateOverloadBuilder};
257    /// use quack_rs::types::TypeId;
258    ///
259    /// // AggregateFunctionSetBuilder::new("my_agg")
260    /// //     .overload(
261    /// //         AggregateOverloadBuilder::new()
262    /// //             .param(TypeId::Integer)
263    /// //             .returns(TypeId::Integer)
264    /// //             .state_size(state_size)
265    /// //             .init(init)
266    /// //             .update(update)
267    /// //             .combine(combine)
268    /// //             .finalize(finalize),
269    /// //     );
270    /// ```
271    pub fn overload(mut self, builder: AggregateOverloadBuilder) -> Self {
272        self.overloads.push(builder.into_spec());
273        self
274    }
275
276    /// Adds overloads for each arity in `range`, using the given builder closure.
277    ///
278    /// The closure receives:
279    /// - `n`: the number of parameters for this overload
280    /// - A fresh [`AggregateOverloadBuilder`] for configuring callbacks
281    ///
282    /// Each overload may set its own return type; any that does not falls back
283    /// to the set-level default from [`returns`][Self::returns] /
284    /// [`returns_logical`][Self::returns_logical].
285    ///
286    /// # Example
287    ///
288    /// ```rust,no_run
289    /// use quack_rs::aggregate::AggregateFunctionSetBuilder;
290    /// use quack_rs::types::TypeId;
291    ///
292    /// // AggregateFunctionSetBuilder::new("retention")
293    /// //     .returns(TypeId::BigInt)
294    /// //     .overloads(2..=32, |n, builder| {
295    /// //         let builder = builder
296    /// //             .state_size(my_state_size)
297    /// //             .init(my_init)
298    /// //             .update(my_update)
299    /// //             .combine(my_combine)
300    /// //             .finalize(my_finalize);
301    /// //         // `n` booleans as params
302    /// //         (0..n).fold(builder, |b, _| b.param(TypeId::Boolean))
303    /// //     });
304    /// ```
305    pub fn overloads<F>(mut self, range: std::ops::RangeInclusive<usize>, f: F) -> Self
306    where
307        F: Fn(usize, AggregateOverloadBuilder) -> AggregateOverloadBuilder,
308    {
309        for n in range {
310            self.overloads
311                .push(f(n, AggregateOverloadBuilder::new()).into_spec());
312        }
313        self
314    }
315
316    /// The completeness checks that need no `DuckDB` call: at least one
317    /// overload, each with a return type (its own or the set's) and every
318    /// required callback. [`MockRegistrar`][crate::testing::MockRegistrar]
319    /// runs them too.
320    pub(crate) fn check_parts(&self) -> Result<(), ExtensionError> {
321        if self.overloads.is_empty() {
322            return Err(ExtensionError::new("no overloads added to function set"));
323        }
324        let has_default_return = self.return_type.is_some() || self.return_logical.is_some();
325        for (i, overload) in self.overloads.iter().enumerate() {
326            overload.check_complete(i, has_default_return)?;
327        }
328        Ok(())
329    }
330
331    /// Refuses a type [`register`][Self::register] refuses before its first
332    /// `DuckDB` call; `slot` checks each `TypeId` (see [`SlotCheck`]).
333    pub(crate) fn check_types(&self, slot: SlotCheck) -> Result<(), ExtensionError> {
334        if let Some(id) = self.return_type {
335            slot(id, "aggregate function set return type")?;
336        }
337        for (i, overload) in self.overloads.iter().enumerate() {
338            for (j, id) in overload.params.iter().enumerate() {
339                slot(*id, &format!("overload {i} parameter {j}"))?;
340            }
341            if let Some(id) = overload.return_type {
342                slot(id, &format!("overload {i} return type"))?;
343            }
344            // The overload's own return type, else the set-level default.
345            let (id, logical) =
346                if overload.return_logical.is_some() || overload.return_type.is_some() {
347                    (overload.return_type, overload.return_logical.as_ref())
348                } else {
349                    (self.return_type, self.return_logical.as_ref())
350                };
351            crate::table::type_check::refuse_any_return(
352                &format!("overload {i} return type"),
353                id,
354                logical,
355            )?;
356        }
357        Ok(())
358    }
359
360    /// Registers the function set on the given connection.
361    ///
362    /// # Pitfall L6
363    ///
364    /// This method calls `duckdb_aggregate_function_set_name` on EVERY individual
365    /// function in the set. Omitting this call causes silent registration failure.
366    ///
367    /// # Errors
368    ///
369    /// Returns `ExtensionError` if:
370    /// - No overloads were added.
371    /// - A parameter or return type was given as a bare composite
372    ///   [`TypeId`] (`DECIMAL`, `ENUM`, `LIST`, `STRUCT`, `MAP`, `ARRAY`,
373    ///   `UNION`), which carries parameters a `TypeId` cannot express. Build
374    ///   it as a [`LogicalType`] and use the `*_logical` method; the error
375    ///   names the slot.
376    /// - An overload has neither its own return type nor a set-level default,
377    ///   or is missing a required callback. The error names the overload's
378    ///   index, and is reported before any `DuckDB` handle is allocated.
379    /// - Two overloads accept the same call — argument types `DuckDB`'s
380    ///   overload resolution cannot tell apart. It tells `DECIMAL`, `MAP` and
381    ///   `ENUM` parameters apart by type alone, also inside a `LIST`, `ARRAY`,
382    ///   `STRUCT` or `UNION`, so `DECIMAL(4,1)` and `DECIMAL(18,3)` collide;
383    ///   `LIST(INTEGER)` and `LIST(VARCHAR)` do not. `DuckDB` itself would
384    ///   accept such a set and then fail every such call with "Could not
385    ///   choose a best candidate function".
386    /// - `DuckDB` reports registration failure.
387    ///
388    /// # Name collisions
389    ///
390    /// An aggregate can neither extend nor replace an existing catalog entry:
391    /// registration fails if the name is already taken by any scalar function,
392    /// aggregate function or macro, built-in or not — including an earlier
393    /// registration of this same aggregate. (`DuckDB` registers with
394    /// `ALTER_ON_CONFLICT`, and turning the create into an alter is not
395    /// implemented for aggregates: `CreateInfo::GetAlterInfo` throws.) The C
396    /// API reports only a failure, so after one quack-rs looks the name up in
397    /// `duckdb_functions()` and the error names the entry that holds it; a
398    /// registration that succeeds scans nothing.
399    ///
400    /// # Safety
401    ///
402    /// - `con` must be a valid, open `duckdb_connection`.
403    /// - In each overload, the `state_size`, `init` and `destructor` callbacks,
404    ///   and the ones that read the state, must describe the same state; see
405    ///   [`AggregateOverloadBuilder::ffi_state`].
406    #[allow(clippy::too_many_lines)]
407    pub unsafe fn register(self, con: duckdb_connection) -> Result<(), ExtensionError> {
408        // Validate everything before allocating any DuckDB handle. The checks
409        // that need no DuckDB call come first, so a missing callback is
410        // reported by index without touching the engine.
411        self.check_parts()?;
412        self.check_types(LogicalType::check_slot)?;
413        let signatures: Vec<_> = self
414            .overloads
415            .iter()
416            .map(|o| merged_params(&o.params, &o.logical_params))
417            .collect();
418        // SAFETY: every logical parameter is a live `LogicalType` owned by this
419        // builder, and the caller's contract means the C API is initialised.
420        unsafe { reject_duplicate_overloads(&self.name.to_string_lossy(), &signatures)? };
421
422        // Resolve the set-level *default* return type once, if one was given.
423        // Overloads that carry their own return type never consult it.
424        let default_ret_lt: Option<LogicalType> = if let Some(lt) = self.return_logical {
425            Some(lt)
426        } else if let Some(id) = self.return_type {
427            Some(LogicalType::for_slot(
428                id,
429                "aggregate function set return type",
430            )?)
431        } else {
432            None
433        };
434
435        // SAFETY: Creates a new aggregate function set handle.
436        let mut set = unsafe { duckdb_create_aggregate_function_set(self.name.as_ptr()) };
437
438        let mut register_error: Option<ExtensionError> = None;
439
440        for (i, overload) in self.overloads.iter().enumerate() {
441            // Resolve this overload's return type: its own LogicalType, then its
442            // own TypeId, then the set-level default. `_ret_lt_owner` keeps a
443            // `LogicalType` built from a bare `TypeId` alive until the
444            // `set_return_type` call below has copied it. This `else` arm and
445            // the missing-callback ones below cannot run: every overload was
446            // checked before the set was created.
447            let (_ret_lt_owner, ret_raw) = if let Some(ref lt) = overload.return_logical {
448                (None, lt.as_raw())
449            } else if let Some(id) = overload.return_type {
450                let lt = LogicalType::new(id);
451                let raw = lt.as_raw();
452                (Some(lt), raw)
453            } else if let Some(ref lt) = default_ret_lt {
454                (None, lt.as_raw())
455            } else {
456                register_error = Some(ExtensionError::new(format!(
457                    "overload {i} has no return type"
458                )));
459                break;
460            };
461
462            let (Some(state_size), Some(init), Some(update), Some(combine), Some(finalize)) = (
463                overload.state_size,
464                overload.init,
465                overload.update,
466                overload.combine,
467                overload.finalize,
468            ) else {
469                register_error = Some(ExtensionError::new(format!(
470                    "overload {i} is missing a required callback"
471                )));
472                break;
473            };
474
475            // SAFETY: Creates a new aggregate function handle for this overload.
476            let mut func = unsafe { duckdb_create_aggregate_function() };
477
478            // PITFALL L6: CRITICAL — must call this on EACH function, not just the set.
479            // Without this, duckdb_register_aggregate_function_set silently returns DuckDBError.
480            // Discovered by reading DuckDB's test/api/capi/test_capi_aggregate_functions.cpp.
481            // SAFETY: `func` is the handle `duckdb_create_aggregate_function` just
482            // returned, not yet destroyed; it is null only if allocating its info threw,
483            // and `duckdb_aggregate_function_set_name` null-checks both arguments
484            // (aggregate_function-c.cpp). `self.name` is a `CString`, so NUL-terminated
485            // and live for the call, and DuckDB copies it into `AggregateFunction::name`.
486            unsafe {
487                duckdb_aggregate_function_set_name(func, self.name.as_ptr());
488            }
489
490            // Add parameters: merge simple TypeId params and complex LogicalType params
491            // in the order they were added (tracked by position).
492            {
493                let mut simple_idx = 0;
494                let mut logical_idx = 0;
495                let total = overload.params.len() + overload.logical_params.len();
496                for pos in 0..total {
497                    if logical_idx < overload.logical_params.len()
498                        && overload.logical_params[logical_idx].0 == pos
499                    {
500                        // SAFETY: func and logical type handle are valid.
501                        unsafe {
502                            libduckdb_sys::duckdb_aggregate_function_add_parameter(
503                                func,
504                                overload.logical_params[logical_idx].1.as_raw(),
505                            );
506                        }
507                        logical_idx += 1;
508                    } else if simple_idx < overload.params.len() {
509                        let lt = LogicalType::new(overload.params[simple_idx]);
510                        // SAFETY: func and lt.as_raw() are valid handles.
511                        unsafe {
512                            libduckdb_sys::duckdb_aggregate_function_add_parameter(
513                                func,
514                                lt.as_raw(),
515                            );
516                        }
517                        simple_idx += 1;
518                    }
519                }
520            }
521
522            // Set this overload's return type.
523            // SAFETY: func and ret_raw are valid; `_ret_lt_owner` keeps ret_raw's
524            // owner alive across this call when the type was built from a TypeId.
525            unsafe {
526                duckdb_aggregate_function_set_return_type(func, ret_raw);
527            }
528
529            // Set callbacks
530            // SAFETY: func is a valid aggregate function handle, and each
531            // callback was checked to be Some above. The pointers are
532            // `extern "C" fn` items with 'static lifetime, so they outlive the
533            // registration.
534            unsafe {
535                duckdb_aggregate_function_set_functions(
536                    func,
537                    Some(state_size),
538                    Some(init),
539                    Some(update),
540                    Some(combine),
541                    Some(finalize),
542                );
543            }
544
545            // Always register a destructor, a no-op if none was given (see
546            // `callbacks::no_op_destroy`).
547            let dtor = overload
548                .destructor
549                .unwrap_or(crate::aggregate::callbacks::no_op_destroy);
550            // SAFETY: func is valid and `dtor` is a 'static `extern "C" fn`.
551            unsafe {
552                duckdb_aggregate_function_set_destructor(func, Some(dtor));
553            }
554
555            // Set special NULL handling if requested
556            if overload.null_handling == NullHandling::SpecialNullHandling {
557                // SAFETY: func is a valid aggregate function handle.
558                unsafe {
559                    duckdb_aggregate_function_set_special_handling(func);
560                }
561            }
562
563            // Set extra info if provided
564            if let Some(info) = &overload.extra_info {
565                // SAFETY: func is valid; data and destroy are provided by caller.
566                unsafe {
567                    duckdb_aggregate_function_set_extra_info(func, info.data(), info.destroy());
568                    // DuckDB owns the allocation from here: the set's copy of
569                    // this function frees it, even if registration fails.
570                    info.mark_transferred();
571                }
572            }
573
574            // Add this function to the set
575            // SAFETY: set and func are valid handles.
576            unsafe {
577                duckdb_add_aggregate_function_to_set(set, func);
578            }
579
580            // SAFETY: func was created above and ownership transferred to the set.
581            unsafe {
582                duckdb_destroy_aggregate_function(&raw mut func);
583            }
584        }
585
586        if register_error.is_none() {
587            // SAFETY: con is valid and set is fully configured.
588            let result = unsafe { duckdb_register_aggregate_function_set(con, set) };
589            if result != DuckDBSuccess {
590                let name = self.name.to_string_lossy();
591                // SAFETY: `con` is valid per this function's contract.
592                let reason = unsafe { super::collision::taken_name_reason(con, &name) };
593                register_error = Some(ExtensionError::new(format!(
594                    "duckdb_register_aggregate_function_set failed for '{name}': {hint}",
595                    hint = reason
596                        .as_deref()
597                        .unwrap_or(crate::error::REGISTRATION_FAILURE_HINT)
598                )));
599            }
600        }
601
602        // SAFETY: set was created above and must be destroyed.
603        unsafe {
604            duckdb_destroy_aggregate_function_set(&raw mut set);
605        }
606
607        register_error.map_or(Ok(()), Err)
608    }
609}
610
611impl core::fmt::Debug for AggregateFunctionSetBuilder {
612    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
613        f.debug_struct("AggregateFunctionSetBuilder")
614            .field("name", &self.name)
615            .field("return_type", &self.return_type)
616            .field("return_logical", &self.return_logical)
617            .field("overloads", &self.overloads.len())
618            .finish()
619    }
620}