Skip to main content

quack_rs/scalar/builder/
single.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::cell::RefCell;
7use std::ffi::CString;
8
9#[cfg(feature = "duckdb-1-5")]
10use libduckdb_sys::{
11    duckdb_bind_info, duckdb_init_info, duckdb_scalar_function_set_bind,
12    duckdb_scalar_function_set_init,
13};
14use std::os::raw::c_void;
15
16use libduckdb_sys::{
17    duckdb_connection, duckdb_create_scalar_function, duckdb_data_chunk, duckdb_delete_callback_t,
18    duckdb_destroy_scalar_function, duckdb_function_info, duckdb_register_scalar_function,
19    duckdb_scalar_function_add_parameter, duckdb_scalar_function_set_extra_info,
20    duckdb_scalar_function_set_function, duckdb_scalar_function_set_name,
21    duckdb_scalar_function_set_return_type, duckdb_scalar_function_set_special_handling,
22    duckdb_scalar_function_set_volatile, duckdb_vector, DuckDBSuccess,
23};
24
25use crate::error::ExtensionError;
26use crate::types::logical_type::SlotCheck;
27use crate::types::{LogicalType, NullHandling, TypeId};
28use crate::validate::validate_function_name;
29
30/// The scalar function bind callback signature (`DuckDB` 1.5.0+).
31///
32/// Called once during query planning. Use this to inspect arguments and
33/// allocate per-query state via `duckdb_scalar_function_set_bind_data`.
34///
35/// **Breaking** in 0.18.0: the argument is a
36/// [`RawScalarBindInfo`][crate::scalar::RawScalarBindInfo], so that a table
37/// function's bind callback, which `DuckDB` passes a different struct, cannot
38/// be registered here.
39#[cfg(feature = "duckdb-1-5")]
40pub type ScalarBindFn = unsafe extern "C" fn(info: crate::scalar::RawScalarBindInfo);
41
42/// The scalar function init callback signature (`DuckDB` 1.5.0+).
43///
44/// Called once per thread before execution begins. Use this to allocate
45/// per-thread local state via `duckdb_scalar_function_init_set_state`.
46///
47/// **Breaking** in 0.18.0: the argument is a
48/// [`RawScalarInitInfo`][crate::scalar::RawScalarInitInfo]; see
49/// [`ScalarBindFn`].
50#[cfg(feature = "duckdb-1-5")]
51pub type ScalarInitFn = unsafe extern "C" fn(info: crate::scalar::RawScalarInitInfo);
52
53/// `f` as the callback type `duckdb_scalar_function_set_bind` takes.
54#[cfg(feature = "duckdb-1-5")]
55pub(super) const fn raw_bind(f: ScalarBindFn) -> unsafe extern "C" fn(duckdb_bind_info) {
56    // SAFETY: `RawScalarBindInfo` is `#[repr(transparent)]` over
57    // `duckdb_bind_info`, so the two function pointer types have the same ABI
58    // and `DuckDB` calls `f` with exactly the argument it declares.
59    unsafe { core::mem::transmute::<ScalarBindFn, unsafe extern "C" fn(duckdb_bind_info)>(f) }
60}
61
62/// `f` as the callback type `duckdb_scalar_function_set_init` takes.
63#[cfg(feature = "duckdb-1-5")]
64pub(super) const fn raw_init(f: ScalarInitFn) -> unsafe extern "C" fn(duckdb_init_info) {
65    // SAFETY: as in `raw_bind`, for `RawScalarInitInfo` over
66    // `duckdb_init_info`.
67    unsafe { core::mem::transmute::<ScalarInitFn, unsafe extern "C" fn(duckdb_init_info)>(f) }
68}
69
70/// The scalar function callback signature.
71///
72/// This function is called once per data chunk. It receives:
73/// - `info`: Function metadata (use for extra data or error reporting)
74/// - `input`: The input data chunk containing all parameter columns
75/// - `output`: The output vector to write results into
76pub type ScalarFn = unsafe extern "C" fn(
77    info: duckdb_function_info,
78    input: duckdb_data_chunk,
79    output: duckdb_vector,
80);
81
82/// Builder for registering a single `DuckDB` scalar function.
83///
84/// # Example
85///
86/// ```rust,no_run
87/// use quack_rs::scalar::ScalarFunctionBuilder;
88/// use quack_rs::types::TypeId;
89/// use libduckdb_sys::{duckdb_connection, duckdb_function_info, duckdb_data_chunk,
90///                     duckdb_vector};
91///
92/// unsafe extern "C" fn double_it(
93///     _info: duckdb_function_info,
94///     _input: duckdb_data_chunk,
95///     _output: duckdb_vector,
96/// ) {
97///     // Read from input, write doubled values to output
98/// }
99///
100/// // fn register(con: duckdb_connection) -> Result<(), quack_rs::error::ExtensionError> {
101/// //     unsafe {
102/// //         ScalarFunctionBuilder::new("double_it")
103/// //             .param(TypeId::BigInt)
104/// //             .returns(TypeId::BigInt)
105/// //             .function(double_it)
106/// //             .register(con)
107/// //     }
108/// // }
109/// ```
110#[must_use]
111pub struct ScalarFunctionBuilder {
112    pub(super) name: CString,
113    pub(super) params: Vec<TypeId>,
114    pub(super) logical_params: Vec<(usize, LogicalType)>,
115    pub(super) return_type: Option<TypeId>,
116    pub(super) return_logical: Option<LogicalType>,
117    pub(super) function: Option<ScalarFn>,
118    pub(super) null_handling: NullHandling,
119    pub(super) extra_info: Option<crate::extra_info::ExtraInfo>,
120    pub(super) varargs: Option<super::signature::Varargs>,
121    pub(super) volatile: bool,
122    #[cfg(feature = "duckdb-1-5")]
123    pub(super) bind: Option<ScalarBindFn>,
124    #[cfg(feature = "duckdb-1-5")]
125    pub(super) init: Option<ScalarInitFn>,
126}
127
128impl ScalarFunctionBuilder {
129    /// Creates a new builder for a scalar function with the given name.
130    ///
131    /// # Panics
132    ///
133    /// Panics if `name` contains an interior null byte.
134    pub fn new(name: &str) -> Self {
135        Self {
136            name: CString::new(name).expect("function name must not contain null bytes"),
137            params: Vec::new(),
138            logical_params: Vec::new(),
139            return_type: None,
140            return_logical: None,
141            function: None,
142            null_handling: NullHandling::DefaultNullHandling,
143            extra_info: None,
144            varargs: None,
145            volatile: false,
146            #[cfg(feature = "duckdb-1-5")]
147            bind: None,
148            #[cfg(feature = "duckdb-1-5")]
149            init: None,
150        }
151    }
152
153    /// Creates a new builder with function name validation.
154    ///
155    /// Unlike [`new`][Self::new], this method validates the function name against
156    /// `DuckDB` naming conventions and returns an error instead of panicking.
157    ///
158    /// # Errors
159    ///
160    /// Returns `ExtensionError` if the name is invalid.
161    /// See [`validate_function_name`] for the full set of rules.
162    pub fn try_new(name: &str) -> Result<Self, ExtensionError> {
163        validate_function_name(name)?;
164        let c_name = CString::new(name)
165            .map_err(|_| ExtensionError::new("function name contains interior null byte"))?;
166        Ok(Self {
167            name: c_name,
168            params: Vec::new(),
169            logical_params: Vec::new(),
170            return_type: None,
171            return_logical: None,
172            function: None,
173            null_handling: NullHandling::DefaultNullHandling,
174            extra_info: None,
175            varargs: None,
176            volatile: false,
177            #[cfg(feature = "duckdb-1-5")]
178            bind: None,
179            #[cfg(feature = "duckdb-1-5")]
180            init: None,
181        })
182    }
183
184    /// Returns the function name.
185    ///
186    /// Useful for introspection and for [`MockRegistrar`][crate::testing::MockRegistrar].
187    pub fn name(&self) -> &str {
188        self.name.to_str().unwrap_or("")
189    }
190
191    /// Adds a positional parameter with the given type.
192    ///
193    /// Call this once per parameter in order. For complex types like
194    /// `LIST(BIGINT)` or `MAP(VARCHAR, INTEGER)`, use [`param_logical`][Self::param_logical].
195    pub fn param(mut self, type_id: TypeId) -> Self {
196        self.params.push(type_id);
197        self
198    }
199
200    /// Adds a positional parameter with a complex [`LogicalType`].
201    ///
202    /// Use this for parameterized types that [`TypeId`] cannot express, such as
203    /// `LIST(BIGINT)`, `MAP(VARCHAR, INTEGER)`, or `STRUCT(...)`.
204    ///
205    /// The parameter position is determined by the total number of `param` and
206    /// `param_logical` calls made so far.
207    #[cfg_attr(test, mutants::skip)] // position arithmetic tested via E2E
208    pub fn param_logical(mut self, logical_type: LogicalType) -> Self {
209        let position = self.params.len() + self.logical_params.len();
210        self.logical_params.push((position, logical_type));
211        self
212    }
213
214    /// Sets the return type for this function.
215    ///
216    /// For complex return types like `LIST(BIGINT)`, use
217    /// [`returns_logical`][Self::returns_logical] instead.
218    pub const fn returns(mut self, type_id: TypeId) -> Self {
219        self.return_type = Some(type_id);
220        self
221    }
222
223    /// Sets the return type to a complex [`LogicalType`].
224    ///
225    /// Use this for parameterized return types that [`TypeId`] cannot express,
226    /// such as `LIST(BOOLEAN)`, `LIST(TIMESTAMP)`, `MAP(VARCHAR, INTEGER)`, etc.
227    ///
228    /// If both `returns` and `returns_logical` are called, the logical type takes
229    /// precedence.
230    pub fn returns_logical(mut self, logical_type: LogicalType) -> Self {
231        self.return_logical = Some(logical_type);
232        self
233    }
234
235    /// Sets the scalar function callback.
236    pub fn function(mut self, f: ScalarFn) -> Self {
237        self.function = Some(f);
238        self
239    }
240
241    /// Marks this function as accepting variadic arguments of the given type.
242    ///
243    /// After the fixed positional parameters, `DuckDB` will accept any number of
244    /// additional arguments that match the given type. Maps to
245    /// `duckdb_scalar_function_set_varargs`, part of the stable C API since
246    /// v1.2.0, so no feature flag is needed.
247    ///
248    /// A composite `type_id` (see [`TypeId::is_composite`]) makes
249    /// [`register`][Self::register] return an error naming the varargs slot;
250    /// use [`varargs_logical`][Self::varargs_logical] for those types.
251    #[cfg_attr(test, mutants::skip)] // tested via E2E
252    pub fn varargs(mut self, type_id: TypeId) -> Self {
253        self.varargs = Some(super::signature::Varargs::Id(type_id));
254        self
255    }
256
257    /// Marks this function as accepting variadic arguments with a complex type.
258    ///
259    /// Identical to [`varargs`][Self::varargs] but accepts a [`LogicalType`]
260    /// for parameterized types.
261    #[cfg_attr(test, mutants::skip)] // tested via E2E
262    pub fn varargs_logical(mut self, logical_type: LogicalType) -> Self {
263        self.varargs = Some(super::signature::Varargs::Logical(logical_type));
264        self
265    }
266
267    /// Marks this function as volatile.
268    ///
269    /// Volatile functions are re-evaluated for every row, even when called with
270    /// the same arguments (e.g. `random()`). Non-volatile functions may be
271    /// optimized by `DuckDB` to only execute once for constant arguments.
272    /// Maps to `duckdb_scalar_function_set_volatile`, part of the stable C API
273    /// since v1.2.0, so no feature flag is needed.
274    #[cfg_attr(test, mutants::skip)] // tested via E2E
275    pub const fn volatile(mut self) -> Self {
276        self.volatile = true;
277        self
278    }
279
280    /// Sets a bind callback for this scalar function (`DuckDB` 1.5.0+).
281    ///
282    /// The bind callback is invoked once during query planning. It can inspect
283    /// the function arguments and store per-query data with
284    /// `ScalarBindInfo::set_bind_data` (`duckdb_scalar_function_set_bind_data`).
285    /// This data can later be retrieved during execution with
286    /// `ScalarFunctionInfo::get_bind_data` (`duckdb_scalar_function_get_bind_data`).
287    ///
288    /// Guard it against panics with
289    /// [`scalar_bind_callback!`](crate::scalar_bind_callback), **not**
290    /// `table_bind_callback!`. The compiler refuses the table macro here — its
291    /// function takes a table function's bind info, not a
292    /// [`RawScalarBindInfo`](crate::scalar::RawScalarBindInfo) — because a
293    /// table callback reports a panic through `duckdb_bind_set_error`, which
294    /// would write past the smaller scalar bind info and corrupt the stack.
295    #[cfg(feature = "duckdb-1-5")]
296    #[cfg_attr(test, mutants::skip)] // DuckDB 1.5+ feature, tested via E2E
297    pub fn bind(mut self, f: ScalarBindFn) -> Self {
298        self.bind = Some(f);
299        self
300    }
301
302    /// Sets an init callback for this scalar function (`DuckDB` 1.5.0+).
303    ///
304    /// The init callback is invoked once per thread before execution begins.
305    /// Use it to allocate per-thread local state via
306    /// `duckdb_scalar_function_init_set_state`. The state pointer can later be
307    /// retrieved during execution via `duckdb_scalar_function_get_state`.
308    ///
309    /// Guard it against panics with
310    /// [`scalar_init_callback!`](crate::scalar_init_callback), **not**
311    /// `table_init_callback!`. The compiler refuses the table macro here — its
312    /// function takes a table function's init info, not a
313    /// [`RawScalarInitInfo`](crate::scalar::RawScalarInitInfo) — because a
314    /// table callback reports a panic through `duckdb_init_set_error`, which
315    /// would write past the smaller scalar init info and corrupt the stack.
316    #[cfg(feature = "duckdb-1-5")]
317    #[cfg_attr(test, mutants::skip)] // DuckDB 1.5+ feature, tested via E2E
318    pub fn init(mut self, f: ScalarInitFn) -> Self {
319        self.init = Some(f);
320        self
321    }
322
323    /// Sets the NULL handling behaviour for this function.
324    ///
325    /// Under either setting the callback receives NULL rows. With the default,
326    /// [`DefaultNullHandling`][NullHandling::DefaultNullHandling], the callback
327    /// **promises** NULL-in-NULL-out and must keep that promise itself —
328    /// `DuckDB` does not write NULL for it (pitfall L8; see [`NullHandling`] and
329    /// [`DataChunk::propagate_nulls`][crate::data_chunk::DataChunk::propagate_nulls]).
330    /// [`SpecialNullHandling`][NullHandling::SpecialNullHandling] declares that
331    /// it may return non-NULL for NULL input.
332    pub const fn null_handling(mut self, handling: NullHandling) -> Self {
333        self.null_handling = handling;
334        self
335    }
336
337    /// Attaches arbitrary data to this scalar function.
338    ///
339    /// The data pointer is available inside the callback via
340    /// `duckdb_function_get_extra_info`. The `destroy` callback is called by
341    /// `DuckDB` when the function is dropped to free the data.
342    ///
343    /// # Safety
344    ///
345    /// - `data` must stay valid until `destroy` frees it (with no `destroy`,
346    ///   for as long as the database lives), and `destroy` must be able to
347    ///   free it exactly once with no one else freeing it — so one pointer
348    ///   must not be given to two builders or overloads, each of which hands
349    ///   its `destroy` to `DuckDB` separately.
350    /// - The pointee must be `Send + Sync`. `DuckDB` hands the same pointer to
351    ///   the callbacks on every thread that executes the function, possibly at
352    ///   the same moment, and `destroy` runs on whichever thread releases the
353    ///   function — or, if the builder is dropped unregistered, the thread
354    ///   that drops it.
355    /// - `destroy` must not unwind: it is an `extern "C" fn`, so a panic
356    ///   escaping it aborts the process. Wrap a body that can panic in
357    ///   [`catch_ffi_panic`][crate::callback::catch_ffi_panic].
358    /// - The pointee must be the type the installed function reads it as. A
359    ///   closure-built function reads its own `extra_info`, so the builder
360    ///   inside a [`TypedScalarFunctionBuilder`][crate::scalar::TypedScalarFunctionBuilder]
361    ///   must not be given another.
362    ///
363    /// The typical pattern is to box your data:
364    /// `Box::into_raw(Box::new(my_data)).cast()`.
365    pub unsafe fn extra_info(
366        mut self,
367        data: *mut c_void,
368        destroy: duckdb_delete_callback_t,
369    ) -> Self {
370        // SAFETY: forwarded from this method's own contract.
371        self.extra_info = Some(unsafe { crate::extra_info::ExtraInfo::new(data, destroy) });
372        self
373    }
374
375    /// Checks everything that needs no `DuckDB` call, returning the callback.
376    ///
377    /// Composite `TypeId`s are rejected before any `DuckDB` handle exists, so
378    /// the diagnostic names the offending slot instead of surfacing as an
379    /// opaque `duckdb_register_scalar_function failed`. See
380    /// `TypeId::is_composite`.
381    /// The completeness checks that need no `DuckDB` call: a return type and
382    /// a function callback. [`MockRegistrar`][crate::testing::MockRegistrar]
383    /// runs them too, so a builder it accepts is not refused at `LOAD` for a
384    /// missing part.
385    pub(crate) fn check_parts(&self) -> Result<(), ExtensionError> {
386        if self.return_logical.is_none() && self.return_type.is_none() {
387            return Err(ExtensionError::new("return type not set"));
388        }
389        if self.function.is_none() {
390            return Err(ExtensionError::new("function callback not set"));
391        }
392        Ok(())
393    }
394
395    /// Refuses a type [`register`][Self::register] refuses before its first
396    /// `DuckDB` call; `slot` checks each `TypeId` (see [`SlotCheck`]).
397    pub(crate) fn check_types(&self, slot: SlotCheck) -> Result<(), ExtensionError> {
398        for (i, id) in self.params.iter().enumerate() {
399            slot(*id, &format!("scalar function parameter {i}"))?;
400        }
401        if let Some(id) = self.return_type {
402            slot(id, "scalar function return type")?;
403        }
404        if let Some(ref varargs) = self.varargs {
405            varargs.check(slot, "scalar function varargs")?;
406        }
407        crate::table::type_check::refuse_any_return(
408            "scalar function return type",
409            self.return_type,
410            self.return_logical.as_ref(),
411        )
412    }
413
414    fn check_complete(&self) -> Result<ScalarFn, ExtensionError> {
415        self.check_parts()?;
416        self.check_types(LogicalType::check_slot)?;
417        self.function
418            .ok_or_else(|| ExtensionError::new("function callback not set"))
419    }
420
421    /// This function's signature, rendered as `duckdb_functions()` prints it
422    /// (`None` if a type is not rendered), labelled for error messages.
423    fn rendered_signature(&self) -> Vec<(String, Option<super::collision::Rendered>)> {
424        let mut signature = super::signature::merged_params(&self.params, &self.logical_params);
425        if let Some(ref varargs) = self.varargs {
426            signature.push(varargs.param_ref());
427        }
428        // SAFETY: every logical parameter is a live handle owned by this
429        // builder, and rendering one needs only the C API, which the
430        // `register` caller's contract initialises.
431        let rendered = unsafe { super::collision::render_signature(&signature) };
432        vec![(String::from("scalar function"), rendered)]
433    }
434
435    /// Registers the scalar function on the given connection.
436    ///
437    /// # Errors
438    ///
439    /// Returns `ExtensionError` if:
440    /// - The return type was not set.
441    /// - The function callback was not set.
442    /// - A parameter, varargs or return type was given as a bare composite
443    ///   [`TypeId`] (`DECIMAL`, `ENUM`, `LIST`, `STRUCT`, `MAP`, `ARRAY`,
444    ///   `UNION`), which carries parameters a `TypeId` cannot express. Build
445    ///   it as a [`LogicalType`] and use the `*_logical` method; the error
446    ///   names the slot.
447    /// - A scalar function with this name and parameter types already exists
448    ///   (see "Name collisions").
449    /// - `DuckDB` reports a registration failure.
450    ///
451    /// # Name collisions
452    ///
453    /// `DuckDB` registers scalar functions with `ALTER_ON_CONFLICT`
454    /// (`duckdb_register_scalar_function_set` in `scalar_function-c.cpp`), so a
455    /// **scalar** function that already has this name — built-in or not — never
456    /// makes `DuckDB` refuse the registration. A new signature is added as an
457    /// overload. One with the same parameter types as an existing overload
458    /// either **silently replaces it** for every connection to the database
459    /// (same return type: `FunctionSet::MergeFunctionSet` with
460    /// `override = true`) or makes every call ambiguous ("Could not choose a
461    /// best candidate function", different return type). Registering
462    /// `abs(BIGINT)` would change the built-in `abs` for `BIGINT`.
463    ///
464    /// quack-rs therefore refuses, before registering, when
465    /// `duckdb_functions()` already lists a scalar with this name whose
466    /// parameter and varargs types accept the same call — the same types, or,
467    /// with varargs, the same types at some argument count (`f(BIGINT)` beside
468    /// an existing `f(BIGINT, BIGINT...)`: `DuckDB` would find `f(1)`
469    /// ambiguous). Types are compared as `DuckDB` prints them, aliases
470    /// included, so `abs(myint)` for `CREATE TYPE myint AS INTEGER` is its own
471    /// overload — except that a `DECIMAL` or `MAP` is compared by type alone,
472    /// at any depth, as `DuckDB`'s overload resolution compares it:
473    /// `round(DECIMAL(18,3))` beside the built-in `round(DECIMAL)` would make
474    /// every `round` of a `DECIMAL` ambiguous, so it is refused. The check
475    /// covers every parameter type except `STRUCT`,
476    /// `UNION`, `ENUM` and the `SQLNULL` / literal pseudo-types; a signature
477    /// containing one of those is registered unchecked. `DuckDB` itself
478    /// refuses a name that belongs to an aggregate function or a macro (such
479    /// as the built-in `list_sum`).
480    ///
481    /// # Cost
482    ///
483    /// Each call lists the catalog once — one scan of `duckdb_functions()`,
484    /// 17–21 ms per call in a release build against `DuckDB` 1.5.5 (measured
485    /// over 300 registrations). Registering through the entry point's
486    /// [`Connection`](crate::connection::Connection) instead (its
487    /// [`Registrar`](crate::connection::Registrar) methods) lists the catalog
488    /// once per extension load: 300 registrations took 19–36 ms in all.
489    ///
490    /// # Safety
491    ///
492    /// `con` must be a valid, open `duckdb_connection`.
493    pub unsafe fn register(self, con: duckdb_connection) -> Result<(), ExtensionError> {
494        // SAFETY: forwarded from this function's own contract.
495        unsafe { self.register_with(con, None) }
496    }
497
498    /// [`register`][Self::register], checking signatures against `snapshot`
499    /// (listed on first use) instead of listing the catalog for this call.
500    ///
501    /// # Safety
502    ///
503    /// As [`register`][Self::register].
504    pub(crate) unsafe fn register_with(
505        self,
506        con: duckdb_connection,
507        snapshot: Option<&RefCell<Option<super::collision::ExistingScalars>>>,
508    ) -> Result<(), ExtensionError> {
509        let function = self.check_complete()?;
510        let name = self.name.to_string_lossy().into_owned();
511        let rendered = self.rendered_signature();
512        // SAFETY: `con` is valid per this function's contract.
513        unsafe { super::collision::refuse_taken_signatures(con, snapshot, &name, &rendered)? };
514
515        // Resolve return type: prefer explicit LogicalType over TypeId. One of
516        // the two is set, checked above.
517        let ret_lt = match (self.return_logical, self.return_type) {
518            (Some(lt), _) => lt,
519            (None, Some(id)) => LogicalType::for_slot(id, "scalar function return type")?,
520            (None, None) => return Err(ExtensionError::new("return type not set")),
521        };
522
523        // SAFETY: duckdb_create_scalar_function allocates a new function handle.
524        let mut func = unsafe { duckdb_create_scalar_function() };
525
526        // SAFETY: func is a valid newly created function handle.
527        unsafe {
528            duckdb_scalar_function_set_name(func, self.name.as_ptr());
529        }
530
531        // Add parameters: merge simple TypeId params and complex LogicalType params
532        // in the order they were added (tracked by position).
533        {
534            let mut simple_idx = 0;
535            let mut logical_idx = 0;
536            let total = self.params.len() + self.logical_params.len();
537            for pos in 0..total {
538                if logical_idx < self.logical_params.len()
539                    && self.logical_params[logical_idx].0 == pos
540                {
541                    // SAFETY: func and logical type handle are valid.
542                    unsafe {
543                        duckdb_scalar_function_add_parameter(
544                            func,
545                            self.logical_params[logical_idx].1.as_raw(),
546                        );
547                    }
548                    logical_idx += 1;
549                } else if simple_idx < self.params.len() {
550                    let lt = LogicalType::new(self.params[simple_idx]);
551                    // SAFETY: func and lt.as_raw() are valid.
552                    unsafe {
553                        duckdb_scalar_function_add_parameter(func, lt.as_raw());
554                    }
555                    simple_idx += 1;
556                }
557            }
558        }
559
560        // Set return type
561        // SAFETY: func and ret_lt.as_raw() are valid.
562        unsafe {
563            duckdb_scalar_function_set_return_type(func, ret_lt.as_raw());
564        }
565
566        // Set callback
567        // SAFETY: function is a valid extern "C" fn pointer.
568        unsafe {
569            duckdb_scalar_function_set_function(func, Some(function));
570        }
571
572        // Set extra info if provided
573        if let Some(info) = self.extra_info {
574            // SAFETY: func is valid; data and destroy are provided by caller.
575            unsafe {
576                duckdb_scalar_function_set_extra_info(func, info.data(), info.destroy());
577                // DuckDB owns the allocation from here; `ExtraInfo::drop` must
578                // not free it as well.
579                info.mark_transferred();
580            }
581        }
582
583        // Set bind callback if configured (`DuckDB` 1.5.0+)
584        #[cfg(feature = "duckdb-1-5")]
585        if let Some(bind_fn) = self.bind {
586            // SAFETY: func is a valid scalar function handle.
587            unsafe {
588                duckdb_scalar_function_set_bind(func, Some(raw_bind(bind_fn)));
589            }
590        }
591
592        // Set init callback if configured (`DuckDB` 1.5.0+)
593        #[cfg(feature = "duckdb-1-5")]
594        if let Some(init_fn) = self.init {
595            // SAFETY: func is a valid scalar function handle.
596            unsafe {
597                duckdb_scalar_function_set_init(func, Some(raw_init(init_fn)));
598            }
599        }
600
601        // Set varargs type if configured (stable C API since v1.2.0)
602        if let Some(ref varargs) = self.varargs {
603            // SAFETY: func is a valid scalar function handle, and the varargs
604            // type was checked above.
605            unsafe { varargs.set_on(func) };
606        }
607
608        // Set volatile flag if configured (stable C API since v1.2.0)
609        if self.volatile {
610            // SAFETY: func is a valid scalar function handle.
611            unsafe {
612                duckdb_scalar_function_set_volatile(func);
613            }
614        }
615
616        // Set special NULL handling if requested
617        if self.null_handling == NullHandling::SpecialNullHandling {
618            // SAFETY: func is a valid scalar function handle.
619            unsafe {
620                duckdb_scalar_function_set_special_handling(func);
621            }
622        }
623
624        // Register
625        // SAFETY: con is a valid open connection, func is fully configured.
626        let result = unsafe { duckdb_register_scalar_function(con, func) };
627
628        // SAFETY: func was created above and must be destroyed after use.
629        unsafe {
630            duckdb_destroy_scalar_function(&raw mut func);
631        }
632
633        if result == DuckDBSuccess {
634            super::collision::record_registered(snapshot, &name, rendered);
635            Ok(())
636        } else {
637            Err(ExtensionError::new(format!(
638                "duckdb_register_scalar_function failed for '{name}': {hint}",
639                hint = crate::error::REGISTRATION_FAILURE_HINT
640            )))
641        }
642    }
643}
644
645impl core::fmt::Debug for ScalarFunctionBuilder {
646    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
647        use crate::debug_repr::Callback;
648        let mut s = f.debug_struct("ScalarFunctionBuilder");
649        s.field("name", &self.name)
650            .field("params", &self.params)
651            .field("logical_params", &self.logical_params.len())
652            .field("return_type", &self.return_type)
653            .field("return_logical", &self.return_logical)
654            .field("function", &Callback::of(&self.function))
655            .field("null_handling", &self.null_handling)
656            .field("extra_info", &Callback::of(&self.extra_info))
657            .field("varargs", &self.varargs)
658            .field("volatile", &self.volatile);
659        #[cfg(feature = "duckdb-1-5")]
660        s.field("bind", &Callback::of(&self.bind))
661            .field("init", &Callback::of(&self.init));
662        s.finish()
663    }
664}
665
666#[cfg(test)]
667mod tests {
668    use super::super::collision::Rendered;
669    use super::ScalarFunctionBuilder;
670    use crate::types::TypeId;
671
672    /// Signatures given as `TypeId`s render with no `DuckDB` call, in the
673    /// notation `duckdb_functions()` prints, labelled for the error message.
674    #[test]
675    fn a_type_id_signature_renders_as_the_catalog_prints_it() {
676        let builder = ScalarFunctionBuilder::new("f")
677            .param(TypeId::BigInt)
678            .param(TypeId::TimestampTz)
679            .varargs(TypeId::Varchar);
680        assert_eq!(
681            builder.rendered_signature(),
682            vec![(
683                String::from("scalar function"),
684                Some(Rendered {
685                    fixed: vec![
686                        String::from("BIGINT"),
687                        String::from("TIMESTAMP WITH TIME ZONE")
688                    ],
689                    varargs: Some(String::from("VARCHAR")),
690                })
691            )]
692        );
693    }
694}