pub struct ScalarFunctionBuilder { /* private fields */ }Expand description
Builder for registering a single DuckDB scalar function.
§Example
use quack_rs::scalar::ScalarFunctionBuilder;
use quack_rs::types::TypeId;
use libduckdb_sys::{duckdb_connection, duckdb_function_info, duckdb_data_chunk,
duckdb_vector};
unsafe extern "C" fn double_it(
_info: duckdb_function_info,
_input: duckdb_data_chunk,
_output: duckdb_vector,
) {
// Read from input, write doubled values to output
}
// fn register(con: duckdb_connection) -> Result<(), quack_rs::error::ExtensionError> {
// unsafe {
// ScalarFunctionBuilder::new("double_it")
// .param(TypeId::BigInt)
// .returns(TypeId::BigInt)
// .function(double_it)
// .register(con)
// }
// }Implementations§
Source§impl ScalarFunctionBuilder
impl ScalarFunctionBuilder
Sourcepub fn new(name: &str) -> Self
pub fn new(name: &str) -> Self
Creates a new builder for a scalar function with the given name.
§Panics
Panics if name contains an interior null byte.
Sourcepub fn try_new(name: &str) -> Result<Self, ExtensionError>
pub fn try_new(name: &str) -> Result<Self, ExtensionError>
Creates a new builder with function name validation.
Unlike new, this method validates the function name against
DuckDB naming conventions and returns an error instead of panicking.
§Errors
Returns ExtensionError if the name is invalid.
See validate_function_name for the full set of rules.
Sourcepub fn name(&self) -> &str
pub fn name(&self) -> &str
Returns the function name.
Useful for introspection and for MockRegistrar.
Sourcepub fn param(self, type_id: TypeId) -> Self
pub fn param(self, type_id: TypeId) -> Self
Adds a positional parameter with the given type.
Call this once per parameter in order. For complex types like
LIST(BIGINT) or MAP(VARCHAR, INTEGER), use param_logical.
Sourcepub fn param_logical(self, logical_type: LogicalType) -> Self
pub fn param_logical(self, logical_type: LogicalType) -> Self
Adds a positional parameter with a complex LogicalType.
Use this for parameterized types that TypeId cannot express, such as
LIST(BIGINT), MAP(VARCHAR, INTEGER), or STRUCT(...).
The parameter position is determined by the total number of param and
param_logical calls made so far.
Sourcepub const fn returns(self, type_id: TypeId) -> Self
pub const fn returns(self, type_id: TypeId) -> Self
Sets the return type for this function.
For complex return types like LIST(BIGINT), use
returns_logical instead.
Sourcepub fn returns_logical(self, logical_type: LogicalType) -> Self
pub fn returns_logical(self, logical_type: LogicalType) -> Self
Sets the return type to a complex LogicalType.
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.
Sourcepub fn varargs(self, type_id: TypeId) -> Self
pub fn varargs(self, type_id: TypeId) -> Self
Marks this function as accepting variadic arguments of the given type.
After the fixed positional parameters, DuckDB will accept any number of
additional arguments that match the given type. Maps to
duckdb_scalar_function_set_varargs, part of the stable C API since
v1.2.0, so no feature flag is needed.
A composite type_id (see TypeId::is_composite) makes
register return an error naming the varargs slot;
use varargs_logical for those types.
Sourcepub fn varargs_logical(self, logical_type: LogicalType) -> Self
pub fn varargs_logical(self, logical_type: LogicalType) -> Self
Marks this function as accepting variadic arguments with a complex type.
Identical to varargs but accepts a LogicalType
for parameterized types.
Sourcepub const fn volatile(self) -> Self
pub const fn volatile(self) -> Self
Marks this function as volatile.
Volatile functions are re-evaluated for every row, even when called with
the same arguments (e.g. random()). Non-volatile functions may be
optimized by DuckDB to only execute once for constant arguments.
Maps to duckdb_scalar_function_set_volatile, part of the stable C API
since v1.2.0, so no feature flag is needed.
Sourcepub fn bind(self, f: ScalarBindFn) -> Self
pub fn bind(self, f: ScalarBindFn) -> Self
Sets a bind callback for this scalar function (DuckDB 1.5.0+).
The bind callback is invoked once during query planning. It can inspect
the function arguments and store per-query data with
ScalarBindInfo::set_bind_data (duckdb_scalar_function_set_bind_data).
This data can later be retrieved during execution with
ScalarFunctionInfo::get_bind_data (duckdb_scalar_function_get_bind_data).
Guard it against panics with
scalar_bind_callback!, not
table_bind_callback!. The compiler refuses the table macro here — its
function takes a table function’s bind info, not a
RawScalarBindInfo — because a
table callback reports a panic through duckdb_bind_set_error, which
would write past the smaller scalar bind info and corrupt the stack.
Sourcepub fn init(self, f: ScalarInitFn) -> Self
pub fn init(self, f: ScalarInitFn) -> Self
Sets an init callback for this scalar function (DuckDB 1.5.0+).
The init callback is invoked once per thread before execution begins.
Use it to allocate per-thread local state via
duckdb_scalar_function_init_set_state. The state pointer can later be
retrieved during execution via duckdb_scalar_function_get_state.
Guard it against panics with
scalar_init_callback!, not
table_init_callback!. The compiler refuses the table macro here — its
function takes a table function’s init info, not a
RawScalarInitInfo — because a
table callback reports a panic through duckdb_init_set_error, which
would write past the smaller scalar init info and corrupt the stack.
Sourcepub const fn null_handling(self, handling: NullHandling) -> Self
pub const fn null_handling(self, handling: NullHandling) -> Self
Sets the NULL handling behaviour for this function.
Under either setting the callback receives NULL rows. With the default,
DefaultNullHandling, the callback
promises NULL-in-NULL-out and must keep that promise itself —
DuckDB does not write NULL for it (pitfall L8; see NullHandling and
DataChunk::propagate_nulls).
SpecialNullHandling declares that
it may return non-NULL for NULL input.
Sourcepub unsafe fn extra_info(
self,
data: *mut c_void,
destroy: duckdb_delete_callback_t,
) -> Self
pub unsafe fn extra_info( self, data: *mut c_void, destroy: duckdb_delete_callback_t, ) -> Self
Attaches arbitrary data to this scalar function.
The data pointer is available inside the callback via
duckdb_function_get_extra_info. The destroy callback is called by
DuckDB when the function is dropped to free the data.
§Safety
datamust stay valid untildestroyfrees it (with nodestroy, for as long as the database lives), anddestroymust be able to free it exactly once with no one else freeing it — so one pointer must not be given to two builders or overloads, each of which hands itsdestroytoDuckDBseparately.- The pointee must be
Send + Sync.DuckDBhands the same pointer to the callbacks on every thread that executes the function, possibly at the same moment, anddestroyruns on whichever thread releases the function — or, if the builder is dropped unregistered, the thread that drops it. destroymust not unwind: it is anextern "C" fn, so a panic escaping it aborts the process. Wrap a body that can panic incatch_ffi_panic.- The pointee must be the type the installed function reads it as. A
closure-built function reads its own
extra_info, so the builder inside aTypedScalarFunctionBuildermust not be given another.
The typical pattern is to box your data:
Box::into_raw(Box::new(my_data)).cast().
Sourcepub unsafe fn register(
self,
con: duckdb_connection,
) -> Result<(), ExtensionError>
pub unsafe fn register( self, con: duckdb_connection, ) -> Result<(), ExtensionError>
Registers the scalar function on the given connection.
§Errors
Returns ExtensionError if:
- The return type was not set.
- The function callback was not set.
- A parameter, varargs or return type was given as a bare composite
TypeId(DECIMAL,ENUM,LIST,STRUCT,MAP,ARRAY,UNION), which carries parameters aTypeIdcannot express. Build it as aLogicalTypeand use the*_logicalmethod; the error names the slot. - A scalar function with this name and parameter types already exists (see “Name collisions”).
DuckDBreports a registration failure.
§Name collisions
DuckDB registers scalar functions with ALTER_ON_CONFLICT
(duckdb_register_scalar_function_set in scalar_function-c.cpp), so a
scalar function that already has this name — built-in or not — never
makes DuckDB refuse the registration. A new signature is added as an
overload. One with the same parameter types as an existing overload
either silently replaces it for every connection to the database
(same return type: FunctionSet::MergeFunctionSet with
override = true) or makes every call ambiguous (“Could not choose a
best candidate function”, different return type). Registering
abs(BIGINT) would change the built-in abs for BIGINT.
quack-rs therefore refuses, before registering, when
duckdb_functions() already lists a scalar with this name whose
parameter and varargs types accept the same call — the same types, or,
with varargs, the same types at some argument count (f(BIGINT) beside
an existing f(BIGINT, BIGINT...): DuckDB would find f(1)
ambiguous). Types are compared as DuckDB prints them, aliases
included, so abs(myint) for CREATE TYPE myint AS INTEGER is its own
overload — except that a DECIMAL or MAP is compared by type alone,
at any depth, as DuckDB’s overload resolution compares it:
round(DECIMAL(18,3)) beside the built-in round(DECIMAL) would make
every round of a DECIMAL ambiguous, so it is refused. The check
covers every parameter type except STRUCT,
UNION, ENUM and the SQLNULL / literal pseudo-types; a signature
containing one of those is registered unchecked. DuckDB itself
refuses a name that belongs to an aggregate function or a macro (such
as the built-in list_sum).
§Cost
Each call lists the catalog once — one scan of duckdb_functions(),
17–21 ms per call in a release build against DuckDB 1.5.5 (measured
over 300 registrations). Registering through the entry point’s
Connection instead (its
Registrar methods) lists the catalog
once per extension load: 300 registrations took 19–36 ms in all.
§Safety
con must be a valid, open duckdb_connection.
Source§impl ScalarFunctionBuilder
impl ScalarFunctionBuilder
Sourcepub fn try_map1<A, R, E, F>(
name: &str,
f: F,
) -> Result<TypedScalarFunctionBuilder, ExtensionError>
pub fn try_map1<A, R, E, F>( name: &str, f: F, ) -> Result<TypedScalarFunctionBuilder, ExtensionError>
A unary scalar function from a fallible closure, with SQL NULL propagation.
Like map1, but the closure returns Result<R, E>.
Ok(v) writes v; return Ok(None) (with R = Option<_>) for SQL
NULL. A row whose argument is NULL yields NULL without calling the
closure, exactly as in map1.
§What an Err does
The first Err in a chunk stops processing that chunk: no later row is
passed to the closure. Its Display text is reported through the
scalar function’s set_error, and DuckDB fails the whole query with
that message. Rows already written into the result vector are
discarded with the rest of the query — the statement returns an error,
never a partial result. (A client that is streaming a result may
already have fetched earlier chunks before the failing one is computed;
the fetch that reaches the failing chunk returns the error.)
A panic in the closure is reported the same way.
§Errors
Returns an error if name is not a valid SQL identifier.
§Example
use quack_rs::scalar::ScalarFunctionBuilder;
// SAFETY: `con` is the connection DuckDB handed the entry point.
unsafe {
ScalarFunctionBuilder::try_map1("checked_square", |x: i64| {
x.checked_mul(x).ok_or_else(|| format!("{x} squared overflows BIGINT"))
})?
.register(con)
}Sourcepub fn try_map2<A, B, R, E, F>(
name: &str,
f: F,
) -> Result<TypedScalarFunctionBuilder, ExtensionError>where
A: ScalarValue,
B: ScalarValue,
R: ScalarOut,
E: Display,
F: Fn(A, B) -> Result<R, E> + Send + Sync + 'static,
pub fn try_map2<A, B, R, E, F>(
name: &str,
f: F,
) -> Result<TypedScalarFunctionBuilder, ExtensionError>where
A: ScalarValue,
B: ScalarValue,
R: ScalarOut,
E: Display,
F: Fn(A, B) -> Result<R, E> + Send + Sync + 'static,
A binary scalar function from a fallible closure, with SQL NULL propagation.
Like map2, with Err handled as in
try_map1. A row with either argument NULL yields
NULL without calling the closure.
§Errors
Returns an error if name is not a valid SQL identifier.
§Example
use quack_rs::scalar::ScalarFunctionBuilder;
// SAFETY: `con` is the connection DuckDB handed the entry point.
unsafe {
ScalarFunctionBuilder::try_map2("strict_div", |a: i64, b: i64| {
a.checked_div(b).ok_or("strict_div: division by zero")
})?
.register(con)
}Sourcepub fn try_map1_str<R, E, F>(
name: &str,
f: F,
) -> Result<TypedScalarFunctionBuilder, ExtensionError>
pub fn try_map1_str<R, E, F>( name: &str, f: F, ) -> Result<TypedScalarFunctionBuilder, ExtensionError>
A VARCHAR-argument scalar function from a fallible closure, with SQL
NULL propagation.
Like map1_str — the closure borrows the string
straight out of the vector — with Err handled as in
try_map1.
§Errors
Returns an error if name is not a valid SQL identifier.
§Example
use quack_rs::scalar::ScalarFunctionBuilder;
// SAFETY: `con` is the connection DuckDB handed the entry point.
unsafe {
// '' is NULL, 'x@y' is 'y', anything else fails the query.
ScalarFunctionBuilder::try_map1_str("email_domain", |s: &str| {
if s.is_empty() {
return Ok(None);
}
match s.split_once('@') {
Some((_, domain)) => Ok(Some(domain.to_owned())),
None => Err(format!("not an email address: {s:?}")),
}
})?
.register(con)
}Sourcepub fn try_map2_str<R, E, F>(
name: &str,
f: F,
) -> Result<TypedScalarFunctionBuilder, ExtensionError>
pub fn try_map2_str<R, E, F>( name: &str, f: F, ) -> Result<TypedScalarFunctionBuilder, ExtensionError>
A two-VARCHAR scalar function from a fallible closure, with SQL NULL
propagation.
Like map2_str, with Err handled as in
try_map1.
§Errors
Returns an error if name is not a valid SQL identifier.
§Example
use quack_rs::scalar::ScalarFunctionBuilder;
// SAFETY: `con` is the connection DuckDB handed the entry point.
unsafe {
ScalarFunctionBuilder::try_map2_str("field", |line: &str, key: &str| {
line.split(',')
.find_map(|kv| kv.strip_prefix(key)?.strip_prefix('='))
.map(str::to_owned)
.ok_or_else(|| format!("no field {key:?}"))
})?
.register(con)
}Source§impl ScalarFunctionBuilder
impl ScalarFunctionBuilder
Sourcepub fn map3<A, B, C, R, F>(
name: &str,
f: F,
) -> Result<TypedScalarFunctionBuilder, ExtensionError>where
A: ScalarValue,
B: ScalarValue,
C: ScalarValue,
R: ScalarOut,
F: Fn(A, B, C) -> R + Send + Sync + 'static,
pub fn map3<A, B, C, R, F>(
name: &str,
f: F,
) -> Result<TypedScalarFunctionBuilder, ExtensionError>where
A: ScalarValue,
B: ScalarValue,
C: ScalarValue,
R: ScalarOut,
F: Fn(A, B, C) -> R + Send + Sync + 'static,
A ternary scalar function from a safe closure, with SQL NULL propagation.
A row with any argument NULL yields NULL without calling the closure.
Return Option<R> to produce NULL for other rows too.
§Errors
Returns an error if name is not a valid SQL identifier.
§Example
use quack_rs::scalar::ScalarFunctionBuilder;
// SAFETY: `con` is the connection DuckDB handed the entry point.
unsafe {
ScalarFunctionBuilder::map3("lerp", |a: f64, b: f64, t: f64| a + (b - a) * t)?
.register(con)
}Sourcepub fn try_map3<A, B, C, R, E, F>(
name: &str,
f: F,
) -> Result<TypedScalarFunctionBuilder, ExtensionError>where
A: ScalarValue,
B: ScalarValue,
C: ScalarValue,
R: ScalarOut,
E: Display,
F: Fn(A, B, C) -> Result<R, E> + Send + Sync + 'static,
pub fn try_map3<A, B, C, R, E, F>(
name: &str,
f: F,
) -> Result<TypedScalarFunctionBuilder, ExtensionError>where
A: ScalarValue,
B: ScalarValue,
C: ScalarValue,
R: ScalarOut,
E: Display,
F: Fn(A, B, C) -> Result<R, E> + Send + Sync + 'static,
A ternary scalar function from a fallible closure, with SQL NULL propagation.
Like map3, with Err handled as in
try_map1: the first Err stops the chunk and fails
the query with its Display text.
§Errors
Returns an error if name is not a valid SQL identifier.
§Example
use quack_rs::scalar::ScalarFunctionBuilder;
// SAFETY: `con` is the connection DuckDB handed the entry point.
unsafe {
ScalarFunctionBuilder::try_map3("strict_clamp", |x: i64, lo: i64, hi: i64| {
if lo > hi {
Err(format!("strict_clamp: empty range [{lo}, {hi}]"))
} else {
Ok(x.clamp(lo, hi))
}
})?
.register(con)
}Source§impl ScalarFunctionBuilder
impl ScalarFunctionBuilder
Sourcepub fn map1<A, R, F>(
name: &str,
f: F,
) -> Result<TypedScalarFunctionBuilder, ExtensionError>
pub fn map1<A, R, F>( name: &str, f: F, ) -> Result<TypedScalarFunctionBuilder, ExtensionError>
A unary scalar function from a safe closure, with SQL NULL propagation.
Parameter and return types come from the closure’s signature. A row whose argument is NULL yields NULL without calling the closure.
§Errors
Returns an error if name is not a valid SQL identifier.
§Example
use quack_rs::scalar::ScalarFunctionBuilder;
// SAFETY: `con` is the connection DuckDB handed the entry point.
unsafe { ScalarFunctionBuilder::map1("double_it", |x: i64| x * 2)?.register(con) }Sourcepub fn map2<A, B, R, F>(
name: &str,
f: F,
) -> Result<TypedScalarFunctionBuilder, ExtensionError>
pub fn map2<A, B, R, F>( name: &str, f: F, ) -> Result<TypedScalarFunctionBuilder, ExtensionError>
A binary scalar function from a safe closure, with SQL NULL propagation.
A row with either argument NULL yields NULL without calling the closure.
§Errors
Returns an error if name is not a valid SQL identifier.
Sourcepub fn map1_opt<A, R, F>(
name: &str,
f: F,
) -> Result<TypedScalarFunctionBuilder, ExtensionError>
pub fn map1_opt<A, R, F>( name: &str, f: F, ) -> Result<TypedScalarFunctionBuilder, ExtensionError>
A unary scalar function that sees NULLs.
Registers
SpecialNullHandling,
so DuckDB neither expects nor asserts NULL-in-NULL-out. The closure
receives None for a NULL argument and returning None writes NULL —
which is what coalesce-like and is_null-like functions need.
§Errors
Returns an error if name is not a valid SQL identifier.
Sourcepub fn map2_opt<A, B, R, F>(
name: &str,
f: F,
) -> Result<TypedScalarFunctionBuilder, ExtensionError>where
A: ScalarValue,
B: ScalarValue,
R: ScalarOut,
F: Fn(Option<A>, Option<B>) -> Option<R> + Send + Sync + 'static,
pub fn map2_opt<A, B, R, F>(
name: &str,
f: F,
) -> Result<TypedScalarFunctionBuilder, ExtensionError>where
A: ScalarValue,
B: ScalarValue,
R: ScalarOut,
F: Fn(Option<A>, Option<B>) -> Option<R> + Send + Sync + 'static,
Sourcepub fn map1_str<R, F>(
name: &str,
f: F,
) -> Result<TypedScalarFunctionBuilder, ExtensionError>
pub fn map1_str<R, F>( name: &str, f: F, ) -> Result<TypedScalarFunctionBuilder, ExtensionError>
A VARCHAR-argument scalar function from a safe closure, with SQL NULL
propagation.
The closure borrows the string straight out of the vector — no allocation
per row. VARCHAR needs its own constructor because the argument is a
borrow with the chunk’s lifetime, which a plain type parameter cannot
express.
§Errors
Returns an error if name is not a valid SQL identifier.
§Example
use quack_rs::scalar::ScalarFunctionBuilder;
// SAFETY: `con` is the connection DuckDB handed the entry point.
unsafe {
ScalarFunctionBuilder::map1_str("word_count", |s: &str| {
s.split_whitespace().count() as i64
})?
.register(con)
}