Skip to main content

Module state

Module state 

Source
Expand description

Typed bind data and per-thread local state for scalar functions. Typed bind data and per-thread local state for scalar functions (DuckDB 1.5.0+).

ScalarBindInfo::set_bind_data and ScalarInitInfo::set_state take a raw pointer and a duckdb_delete_callback_t, which means every extension that wants bind data writes its own:

ⓘ
unsafe extern "C" fn drop_bind(ptr: *mut c_void) {
    if !ptr.is_null() {
        drop(unsafe { Box::from_raw(ptr.cast::<BindData>()) });  // aborts if
    }                                                           // Drop panics
}

That is the hazard FfiState and FfiBindData exist to remove for aggregates and table functions: an unwind out of an extern "C" fn is a process abort on Rust 1.81+, and BindData’s Drop is arbitrary user code. ScalarBindData and ScalarLocalState are the same thing for scalar functions — the destructor is generated, panic-safe, and impossible to forget.

§Lifecycle

bind        → ScalarBindData::<T>::set(&bind_info, value)
init        → ScalarBindData::<T>::get_from_init(&init_info)   (read)
              ScalarLocalState::<S>::set(&init_info, state)    (per thread)
execute     → ScalarBindData::<T>::get(&function_info)         (read)
              ScalarLocalState::<S>::get_mut(&function_info)   (read/write)

§Example

use quack_rs::scalar::state::ScalarBindData;
use quack_rs::scalar::{ScalarBindInfo, ScalarFunctionInfo};

#[derive(Clone)]
struct Factor(i64);

unsafe extern "C" fn my_bind(info: quack_rs::scalar::RawScalarBindInfo) {
    // SAFETY: DuckDB passes a valid bind info.
    let bind = unsafe { ScalarBindInfo::new(info) };
    ScalarBindData::set(&bind, Factor(10));
}

quack_rs::scalar_callback!(my_func, |info, input, output| {
    // SAFETY: DuckDB passes a valid function info.
    let fninfo = unsafe { ScalarFunctionInfo::new(info) };
    // SAFETY: `my_bind` stored a `Factor`, and nothing else did.
    let factor = unsafe { ScalarBindData::<Factor>::get(&fninfo) };
    let _ = factor.map(|f| f.0);
});

§Thread safety

DuckDB hands the same bind data to every thread executing the query (CAPIScalarFunction in src/main/capi/scalar_function-c.cpp reads it through the shared bound expression), so bind data must be Send + Sync. Local state is per thread but may be freed on a different thread from the one that created it, so it must be Send. Both bounds are enforced:

ⓘ
fn bind(info: &ScalarBindInfo) {
    // `Rc` is neither `Send` nor `Sync`: rejected.
    ScalarBindData::set(info, std::rc::Rc::new(1_i64));
}
ⓘ
fn init(info: &ScalarInitInfo) {
    // `Rc` is not `Send`: rejected.
    ScalarLocalState::set(info, std::rc::Rc::new(1_i64));
}

Structs§

ScalarBindData
Type-safe bind data for a DuckDB scalar function.
ScalarLocalState
Type-safe per-thread local state for a DuckDB scalar function.