Skip to main content

AggregateFunctionSetBuilder

Struct AggregateFunctionSetBuilder 

Source
pub struct AggregateFunctionSetBuilder { /* private fields */ }
Expand description

Builder for registering a DuckDB aggregate function set (multiple overloads).

Use this when one function name needs several signatures — either a variable number of arguments (one overload per arity) or different parameter types.

§Known DuckDB limitation

Every overload is a C-API aggregate, so on DuckDB before 2.0.0 each reads out of bounds under agg(x) OVER () and agg(x ORDER BY y) — a DuckDB C API defect, fixed in 2.0.0. See AggregateFunctionBuilder.

§ADR-5: Function sets for variadic signatures

DuckDB does not support true varargs for aggregate functions. For functions that accept 2–32 boolean conditions, register 31 overloads.

§Return types are per-overload

DuckDB resolves an aggregate overload from its parameter types and arity only; the return type plays no part in resolution. Each overload may therefore return a different type, set with AggregateOverloadBuilder::returns / AggregateOverloadBuilder::returns_logical. returns and returns_logical on this builder set a default applied to every overload that does not carry its own — convenient when all arities of a variadic aggregate share one return type.

Registration fails if an overload has neither its own return type nor a set-level default.

§Pitfall L6: Name must be set on each member

This builder calls duckdb_aggregate_function_set_name on EVERY individual function before adding it to the set. If you forget this call, DuckDB silently rejects the registration. Discovery of this bug required reading DuckDB’s own C++ test code at test/api/capi/test_capi_aggregate_functions.cpp.

§Examples

One return type shared by every arity — set it once on the set. Each overload needs its own parameters: overloads that accept the same arguments are refused at register.

use quack_rs::aggregate::{AggregateFunctionSetBuilder, AggregateOverloadBuilder};
use quack_rs::types::{LogicalType, TypeId};
use libduckdb_sys::{duckdb_aggregate_state, duckdb_connection, duckdb_data_chunk,
                    duckdb_function_info, duckdb_vector, idx_t};

/// # Safety
///
/// `con` must be a valid, open connection.
unsafe fn register_retention(
    con: duckdb_connection,
) -> Result<(), quack_rs::error::ExtensionError> {
    // SAFETY: `con` is valid per this function's contract.
    unsafe {
        AggregateFunctionSetBuilder::new("retention")
            .returns_logical(LogicalType::list(TypeId::Boolean))
            .overloads(2..=32, |n, builder: AggregateOverloadBuilder| {
                (0..n)
                    .fold(builder, |b, _| b.param(TypeId::Boolean))
                    .state_size(state_size)
                    .init(state_init)
                    .update(update)
                    .combine(combine)
                    .finalize(finalize)
                    .destructor(destroy)
            })
            .register(con)
    }
}

Different return types per overload — set them on each overload:

use quack_rs::aggregate::{AggregateFunctionSetBuilder, AggregateOverloadBuilder};
use quack_rs::types::TypeId;
// SAFETY: `con` is a valid, open connection.
unsafe {
    AggregateFunctionSetBuilder::new("my_agg")
        .overload(
            AggregateOverloadBuilder::new()
                .param(TypeId::Integer)
                .returns(TypeId::Integer)
                .state_size(state_size)
                .init(init)
                .update(update)
                .combine(combine)
                .finalize(int_finalize),
        )
        .overload(
            AggregateOverloadBuilder::new()
                .param(TypeId::Varchar)
                .returns(TypeId::Varchar)
                .state_size(state_size)
                .init(init)
                .update(update)
                .combine(combine)
                .finalize(str_finalize),
        )
        .register(con)
}

Implementations§

Source§

impl AggregateFunctionSetBuilder

Source

pub fn new(name: &str) -> Self

Creates a new builder for a function set with the given name.

§Panics

Panics if name contains an interior null byte.

Source

pub fn try_new(name: &str) -> Result<Self, ExtensionError>

Creates a new builder with function name validation.

§Errors

Returns ExtensionError if the name is invalid. See validate_function_name for the full set of rules.

Source

pub fn name(&self) -> &str

Returns the function set name.

Useful for introspection and for MockRegistrar.

Source

pub const fn returns(self, type_id: TypeId) -> Self

Sets the default return type, used by every overload that does not set its own with AggregateOverloadBuilder::returns / AggregateOverloadBuilder::returns_logical.

For complex return types like LIST(BIGINT), use returns_logical instead.

Source

pub fn returns_logical(self, logical_type: LogicalType) -> Self

Sets the default return type to a complex LogicalType, used by every overload that does not set its own.

Use this for parameterized return types that TypeId cannot express, such as LIST(BOOLEAN), LIST(TIMESTAMP), MAP(VARCHAR, INTEGER), etc.

If both returns and returns_logical are called, the logical type takes precedence.

§Example
use quack_rs::aggregate::AggregateFunctionSetBuilder;
use quack_rs::types::{LogicalType, TypeId};

// AggregateFunctionSetBuilder::new("retention")
//     .returns_logical(LogicalType::list(TypeId::Boolean))
//     .overloads(2..=32, |n, builder| {
//         (0..n).fold(builder, |b, _| b.param(TypeId::Boolean))
//             .state_size(my_state_size)
//             .init(my_init)
//             .update(my_update)
//             .combine(my_combine)
//             .finalize(my_finalize)
//     });
Source

pub fn overload(self, builder: AggregateOverloadBuilder) -> Self

Adds a single, fully-configured overload to this function set.

Use this when overloads differ in more than arity — different parameter types, different return types, or different callbacks. For a family of arities that share a shape, overloads is shorter.

The two may be mixed; overloads are registered in the order added.

§Example
use quack_rs::aggregate::{AggregateFunctionSetBuilder, AggregateOverloadBuilder};
use quack_rs::types::TypeId;

// AggregateFunctionSetBuilder::new("my_agg")
//     .overload(
//         AggregateOverloadBuilder::new()
//             .param(TypeId::Integer)
//             .returns(TypeId::Integer)
//             .state_size(state_size)
//             .init(init)
//             .update(update)
//             .combine(combine)
//             .finalize(finalize),
//     );
Source

pub fn overloads<F>(self, range: RangeInclusive<usize>, f: F) -> Self

Adds overloads for each arity in range, using the given builder closure.

The closure receives:

Each overload may set its own return type; any that does not falls back to the set-level default from returns / returns_logical.

§Example
use quack_rs::aggregate::AggregateFunctionSetBuilder;
use quack_rs::types::TypeId;

// AggregateFunctionSetBuilder::new("retention")
//     .returns(TypeId::BigInt)
//     .overloads(2..=32, |n, builder| {
//         let builder = builder
//             .state_size(my_state_size)
//             .init(my_init)
//             .update(my_update)
//             .combine(my_combine)
//             .finalize(my_finalize);
//         // `n` booleans as params
//         (0..n).fold(builder, |b, _| b.param(TypeId::Boolean))
//     });
Source

pub unsafe fn register( self, con: duckdb_connection, ) -> Result<(), ExtensionError>

Registers the function set on the given connection.

§Pitfall L6

This method calls duckdb_aggregate_function_set_name on EVERY individual function in the set. Omitting this call causes silent registration failure.

§Errors

Returns ExtensionError if:

  • No overloads were added.
  • A parameter or return type was given as a bare composite TypeId (DECIMAL, ENUM, LIST, STRUCT, MAP, ARRAY, UNION), which carries parameters a TypeId cannot express. Build it as a LogicalType and use the *_logical method; the error names the slot.
  • An overload has neither its own return type nor a set-level default, or is missing a required callback. The error names the overload’s index, and is reported before any DuckDB handle is allocated.
  • Two overloads accept the same call — argument types DuckDB’s overload resolution cannot tell apart. It tells DECIMAL, MAP and ENUM parameters apart by type alone, also inside a LIST, ARRAY, STRUCT or UNION, so DECIMAL(4,1) and DECIMAL(18,3) collide; LIST(INTEGER) and LIST(VARCHAR) do not. DuckDB itself would accept such a set and then fail every such call with “Could not choose a best candidate function”.
  • DuckDB reports registration failure.
§Name collisions

An aggregate can neither extend nor replace an existing catalog entry: registration fails if the name is already taken by any scalar function, aggregate function or macro, built-in or not — including an earlier registration of this same aggregate. (DuckDB registers with ALTER_ON_CONFLICT, and turning the create into an alter is not implemented for aggregates: CreateInfo::GetAlterInfo throws.) The C API reports only a failure, so after one quack-rs looks the name up in duckdb_functions() and the error names the entry that holds it; a registration that succeeds scans nothing.

§Safety
  • con must be a valid, open duckdb_connection.
  • In each overload, the state_size, init and destructor callbacks, and the ones that read the state, must describe the same state; see AggregateOverloadBuilder::ffi_state.

Trait Implementations§

Source§

impl Debug for AggregateFunctionSetBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.