quack_rs/aggregate/builder/single/register.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//! [`AggregateFunctionBuilder::register`].
7
8use libduckdb_sys::{
9 duckdb_aggregate_function_set_destructor, duckdb_aggregate_function_set_extra_info,
10 duckdb_aggregate_function_set_functions, duckdb_aggregate_function_set_name,
11 duckdb_aggregate_function_set_return_type, duckdb_aggregate_function_set_special_handling,
12 duckdb_connection, duckdb_create_aggregate_function, duckdb_destroy_aggregate_function,
13 duckdb_register_aggregate_function, DuckDBSuccess,
14};
15
16use super::AggregateFunctionBuilder;
17use crate::error::ExtensionError;
18use crate::types::{LogicalType, NullHandling};
19
20impl AggregateFunctionBuilder {
21 /// Registers the aggregate function on the given connection.
22 ///
23 /// # Errors
24 ///
25 /// Returns `ExtensionError` if:
26 /// - The return type was not set.
27 /// - Any required callback was not set.
28 /// - A parameter or return type was given as a bare composite
29 /// [`TypeId`][crate::types::TypeId] (`DECIMAL`, `ENUM`, `LIST`, `STRUCT`, `MAP`, `ARRAY`,
30 /// `UNION`), which carries parameters a `TypeId` cannot express. Build
31 /// it as a [`LogicalType`] and use the `*_logical` method; the error
32 /// names the slot.
33 /// - `DuckDB` reports a registration failure.
34 ///
35 /// # Name collisions
36 ///
37 /// An aggregate can neither extend nor replace an existing catalog entry:
38 /// registration fails if the name is already taken by any scalar function,
39 /// aggregate function or macro, built-in or not — including an earlier
40 /// registration of this same aggregate. (`DuckDB` registers with
41 /// `ALTER_ON_CONFLICT`, and turning the create into an alter is not
42 /// implemented for aggregates: `CreateInfo::GetAlterInfo` throws.) The C
43 /// API reports only a failure, so after one quack-rs looks the name up in
44 /// `duckdb_functions()` and the error names the entry that holds it; a
45 /// registration that succeeds scans nothing.
46 ///
47 /// # Safety
48 ///
49 /// - `con` must be a valid, open `duckdb_connection`.
50 /// - The `state_size`, `init` and `destructor` callbacks, and the ones
51 /// that read the state, must describe the same state; see
52 /// [`ffi_state`][Self::ffi_state].
53 #[allow(clippy::too_many_lines)]
54 pub unsafe fn register(self, con: duckdb_connection) -> Result<(), ExtensionError> {
55 // See `ScalarFunctionBuilder::register` -- validate before allocating.
56 self.check_parts()?;
57 self.check_types(LogicalType::check_slot)?;
58 // Resolve return type: prefer explicit LogicalType over TypeId.
59 let ret_lt = if let Some(lt) = self.return_logical {
60 lt
61 } else if let Some(id) = self.return_type {
62 LogicalType::for_slot(id, "aggregate function return type")?
63 } else {
64 return Err(ExtensionError::new("return type not set"));
65 };
66
67 let state_size = self
68 .state_size
69 .ok_or_else(|| ExtensionError::new("state_size callback not set"))?;
70 let init = self
71 .init
72 .ok_or_else(|| ExtensionError::new("init callback not set"))?;
73 let update = self
74 .update
75 .ok_or_else(|| ExtensionError::new("update callback not set"))?;
76 let combine = self
77 .combine
78 .ok_or_else(|| ExtensionError::new("combine callback not set"))?;
79 let finalize = self
80 .finalize
81 .ok_or_else(|| ExtensionError::new("finalize callback not set"))?;
82
83 // SAFETY: duckdb_create_aggregate_function allocates a new function handle.
84 let mut func = unsafe { duckdb_create_aggregate_function() };
85
86 // SAFETY: func is a valid newly created function handle.
87 unsafe {
88 duckdb_aggregate_function_set_name(func, self.name.as_ptr());
89 }
90
91 // Add parameters: merge simple TypeId params and complex LogicalType params
92 // in the order they were added (tracked by position).
93 {
94 let mut simple_idx = 0;
95 let mut logical_idx = 0;
96 let total = self.params.len() + self.logical_params.len();
97 for pos in 0..total {
98 if logical_idx < self.logical_params.len()
99 && self.logical_params[logical_idx].0 == pos
100 {
101 // SAFETY: func and logical type handle are valid.
102 unsafe {
103 libduckdb_sys::duckdb_aggregate_function_add_parameter(
104 func,
105 self.logical_params[logical_idx].1.as_raw(),
106 );
107 }
108 logical_idx += 1;
109 } else if simple_idx < self.params.len() {
110 let lt = LogicalType::new(self.params[simple_idx]);
111 // SAFETY: func and lt.as_raw() are valid.
112 unsafe {
113 libduckdb_sys::duckdb_aggregate_function_add_parameter(func, lt.as_raw());
114 }
115 simple_idx += 1;
116 }
117 }
118 }
119
120 // Set return type
121 // SAFETY: func and ret_lt.as_raw() are valid.
122 unsafe {
123 duckdb_aggregate_function_set_return_type(func, ret_lt.as_raw());
124 }
125
126 // Set callbacks
127 // SAFETY: All function pointers are valid extern "C" fn pointers.
128 unsafe {
129 duckdb_aggregate_function_set_functions(
130 func,
131 Some(state_size),
132 Some(init),
133 Some(update),
134 Some(combine),
135 Some(finalize),
136 );
137 }
138
139 // Always register a destructor, a no-op if none was given: without one
140 // DuckDB streams running-frame windows through a path that gives C API
141 // aggregates wrong answers (see `callbacks::no_op_destroy`).
142 let dtor = self
143 .destructor
144 .unwrap_or(crate::aggregate::callbacks::no_op_destroy);
145 // SAFETY: dtor is a valid extern "C" fn pointer.
146 unsafe {
147 duckdb_aggregate_function_set_destructor(func, Some(dtor));
148 }
149
150 // Set special NULL handling if requested
151 if self.null_handling == NullHandling::SpecialNullHandling {
152 // SAFETY: func is a valid aggregate function handle.
153 unsafe {
154 duckdb_aggregate_function_set_special_handling(func);
155 }
156 }
157
158 // Set extra info if provided
159 if let Some(info) = self.extra_info {
160 // SAFETY: func is valid; data and destroy are provided by caller.
161 unsafe {
162 duckdb_aggregate_function_set_extra_info(func, info.data(), info.destroy());
163 // DuckDB owns the allocation from here.
164 info.mark_transferred();
165 }
166 }
167
168 // Register
169 // SAFETY: con is a valid open connection, func is fully configured.
170 let result = unsafe { duckdb_register_aggregate_function(con, func) };
171
172 // SAFETY: func was created above and must be destroyed after use.
173 unsafe {
174 duckdb_destroy_aggregate_function(&raw mut func);
175 }
176
177 if result == DuckDBSuccess {
178 Ok(())
179 } else {
180 let name = self.name.to_string_lossy();
181 // SAFETY: `con` is valid per this function's contract.
182 let reason = unsafe { super::super::collision::taken_name_reason(con, &name) };
183 Err(ExtensionError::new(format!(
184 "duckdb_register_aggregate_function failed for '{name}': {hint}",
185 hint = reason
186 .as_deref()
187 .unwrap_or(crate::error::REGISTRATION_FAILURE_HINT)
188 )))
189 }
190 }
191}