Skip to main content

ScalarBindInfo

Struct ScalarBindInfo 

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

Ergonomic wrapper around the duckdb_bind_info handle provided to a scalar function bind callback (DuckDB 1.5.0+).

Provides access to function arguments, extra info, bind data storage, and error reporting.

Implementations§

Source§

impl ScalarBindInfo

Source

pub const unsafe fn new(info: RawScalarBindInfo) -> Self

Wraps the info DuckDB passes to a scalar function bind callback.

Breaking in 0.18.0: takes a RawScalarBindInfo, the argument type of ScalarBindFn, not a bare duckdb_bind_info.

§Safety

info must be the argument DuckDB passed to a scalar function bind callback that is still running.

Source

pub fn argument_count(&self) -> u64

Returns the number of arguments passed to the scalar function.

Source

pub unsafe fn get_argument(&self, index: u64) -> duckdb_expression

Returns the argument expression at index.

§Safety
  • index must be less than argument_count. The returned duckdb_expression handle is owned by the caller and must be used according to DuckDB expression API rules.
  • On DuckDB before v1.5.5 the argument must be one DuckDB can copy. Those releases copy the expression outside any try, and copying a scalar subquery (f((SELECT 1))) throws a C++ exception through this call, which aborts the process. argument checks the engine version for you.
Source

pub unsafe fn argument(&self, index: u64) -> Option<Expression>

Returns the argument at index as an RAII Expression, or None if DuckDB returns a null handle.

This is the ergonomic counterpart to get_argument: the returned Expression is destroyed automatically on drop and exposes safe accessors for the argument’s return type and constant folding.

Which expression that is depends on the engine. Up to DuckDB 1.5.x it is the argument as the query wrote it, before DuckDB casts it to the declared parameter type (the bind callback runs before CastToFunctionArguments in FunctionBinder::BindScalarFunction): for a BIGINT parameter, f(40 + 2) reports an INTEGER return type, and folds to an INTEGER value. From 2.0.0 the callback runs after the cast (FunctionBinder::ResolveFunction), so the same argument reports BIGINT and folds to a BIGINT. Code that must behave the same on both should read values with a casting getter such as Value::as_i64 rather than branch on the argument’s type.

§Asking for an argument can fail the query

DuckDB copies the argument’s expression to hand it out, and some expressions cannot be copied — a scalar subquery, as in f((SELECT 'x')), for one. duckdb_scalar_function_bind_get_argument then marks the bind as failed itself (scalar_function-c.cpp) and returns null, so the query fails whatever the callback does next, and the C API has no way to ask first. This returns None in that case and replaces DuckDB’s message — a raw JSON exception such as {"exception_type":"Serialization",…} — with one that says what happened. A bind callback that can do without an argument should not ask for it.

That holds from DuckDB v1.5.5. Releases v1.5.0 to v1.5.4 copy the expression outside any try, so the same subquery throws a C++ exception through the C API, which aborts a Rust process. On those releases (and on development builds that predate v1.5.5’s fix) this therefore asks for no argument at all: it fails the bind with a message saying why and returns None.

§Safety

index must be less than argument_count.

Source

pub unsafe fn get_extra_info(&self) -> *mut c_void

Retrieves the extra-info pointer previously set via ScalarFunctionBuilder::extra_info.

Returns a raw *mut c_void. Cast it back to your concrete type.

§Safety

The returned pointer is only valid as long as the scalar function is registered and DuckDB has not yet called the destructor.

Source

pub unsafe fn set_bind_data( &self, data: *mut c_void, destroy: duckdb_delete_callback_t, )

Stores per-query bind data that can later be retrieved during execution via ScalarFunctionInfo::get_bind_data.

Prefer ScalarBindData::set, which generates the destructor and the copy callback.

§Pair this with set_bind_data_copy

DuckDB copies a bound expression whenever it duplicates a plan — and when no copy callback is registered, the copy’s bind data is null, not a duplicate of yours. From DuckDB’s src/main/capi/scalar_function-c.cpp:

unique_ptr<FunctionData> Copy() const override {
    auto copy = make_uniq<CScalarFunctionBindData>(info);
    if (copy_callback) {
        copy->bind_data = copy_callback(bind_data);
        // ...
    }
    return std::move(copy);   // bind_data stays null without a callback
}

The execute callback then sees a null pointer from ScalarFunctionInfo::get_bind_data on the copied expression. That is a silent wrong answer, not a crash, so always register a copy callback alongside any bind data you rely on at execution time.

Written up as Pitfall L10.

§Calling it twice

A second call overwrites the pointer and destructor without running the first destructor: the first value is leaked. So is a value an earlier ScalarBindData::set stored (only a second ScalarBindData::set through the same wrapper frees it).

§Identical calls share bind data

DuckDB merges two calls with the same arguments without comparing their bind data, so the value stored here must depend only on the arguments, their types and extra_info — or the function must be volatile. See ScalarBindData.

§Safety

data must point to valid memory. destroy will be called by DuckDB to free the data when the query finishes. The typical pattern is to box your data: Box::into_raw(Box::new(my_data)).cast(). DuckDB reads the data from every executing thread at once, so it must be safe to share across threads (Sync) and to free from any of them (Send).

A copy callback registered earlier in this bind — by set_bind_data_copy, or by ScalarBindData::set — stays in effect: this call replaces only the pointer and the destructor (duckdb_scalar_function_set_bind_data), and DuckDB applies the old copy callback to the new data whenever it copies the expression. So data must be of the type that callback expects, or a matching copy callback must be registered after this call.

Source

pub unsafe fn set_bind_data_copy(&self, copy: duckdb_copy_callback_t)

Registers the callback DuckDB uses to duplicate the bind data set by set_bind_data when it copies a bound expression.

Without this, a copied expression carries null bind data — see set_bind_data for the upstream code that does it. Registering a copy callback is therefore not an optimisation; it is what makes bind data survive.

copy receives the pointer passed to set_bind_data and must return a pointer to an independently owned duplicate. DuckDB frees the duplicate with the same destroy callback given to set_bind_data, so the two must agree on ownership — returning the same pointer twice is a double free.

§Order

DuckDB stores the copy callback on the same bind-data slot, so call this after set_bind_data within one bind callback.

§Example
use std::os::raw::c_void;

struct MyBindData {
    pattern: String,
}

unsafe extern "C" fn destroy(data: *mut c_void) {
    if !data.is_null() {
        drop(unsafe { Box::from_raw(data.cast::<MyBindData>()) });
    }
}

unsafe extern "C" fn copy(data: *mut c_void) -> *mut c_void {
    if data.is_null() {
        return std::ptr::null_mut();
    }
    // Clone into a fresh allocation; `destroy` frees each one once.
    let src = unsafe { &*data.cast::<MyBindData>() };
    let dup = Box::new(MyBindData {
        pattern: src.pattern.clone(),
    });
    Box::into_raw(dup).cast()
}

// Inside a bind callback holding a `ScalarBindInfo`:
// let boxed = Box::new(MyBindData { pattern: "%x%".to_owned() });
// unsafe {
//     bind_info.set_bind_data(Box::into_raw(boxed).cast(), Some(destroy));
//     bind_info.set_bind_data_copy(Some(copy));
// }
§Safety

copy must return a pointer that is valid to free with the destroy callback registered by set_bind_data, and must not alias the pointer it was given. It must not unwind: it runs across an FFI boundary, so wrap any panicking work in catch_ffi_panic and return null on failure.

Source

pub fn set_error(&self, message: &str)

Reports an error from the scalar function bind callback, causing DuckDB to abort the current query.

An interior NUL byte in message is replaced with ? (see message_to_c_string), and an empty message by EMPTY_ERROR_PLACEHOLDER, since DuckDB would otherwise report only an error-type prefix.

Source

pub unsafe fn get_client_context(&self) -> ClientContext

Returns the client context for this callback.

The returned ClientContext provides access to the connection’s catalog, configuration, and connection ID.

§Safety

The inner handle must be valid (requires DuckDB runtime), and the returned context must not be used after the connection running this query is closed — see ClientContext.

Source

pub const fn as_raw(&self) -> duckdb_bind_info

Returns the raw duckdb_bind_info handle.

Trait Implementations§

Source§

impl Debug for ScalarBindInfo

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.