Skip to main content

quack_rs/table/
bind_data.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//! Type-safe bind data management for table functions.
7//!
8//! [`FfiBindData<T>`] stores user-defined data during the `bind` phase of a table
9//! function and provides safe retrieval in the `init` and `scan` phases.
10//!
11//! # `DuckDB` table function lifecycle
12//!
13//! ```text
14//! bind  → stores bind_data (T)
15//! init  → reads bind_data to set up global state
16//! local_init → reads bind_data to set up per-thread state (optional)
17//! scan  → reads bind_data + init_data + local_init_data, fills output chunk
18//! ```
19//!
20//! # Example
21//!
22//! ```rust,no_run
23//! use quack_rs::table::FfiBindData;
24//! use libduckdb_sys::{duckdb_bind_info, duckdb_function_info};
25//!
26//! struct MyConfig { path: String }
27//!
28//! unsafe extern "C" fn my_bind(info: duckdb_bind_info) {
29//!     // store bind data
30//!     unsafe { FfiBindData::<MyConfig>::set(info, MyConfig { path: "data.csv".into() }); }
31//! }
32//!
33//! unsafe extern "C" fn my_scan(info: duckdb_function_info, _output: libduckdb_sys::duckdb_data_chunk) {
34//!     // retrieve bind data in scan
35//!     if let Some(cfg) = unsafe { FfiBindData::<MyConfig>::get_from_function(info) } {
36//!         let _ = &cfg.path;
37//!     }
38//! }
39//! ```
40
41use std::os::raw::c_void;
42
43use libduckdb_sys::{
44    duckdb_bind_info, duckdb_bind_set_bind_data, duckdb_function_get_bind_data,
45    duckdb_function_info, duckdb_init_get_bind_data, duckdb_init_info,
46};
47
48/// Type-safe bind data wrapper for `DuckDB` table functions.
49///
50/// `FfiBindData<T>` boxes a `T` on the heap during bind and provides
51/// safe access in subsequent phases. `DuckDB` owns the allocation lifetime
52/// and calls the provided `destroy` callback when the query is done.
53///
54/// # Memory model
55///
56/// - [`set`][FfiBindData::set] — boxes `T` via `Box::into_raw`, registers
57///   the pointer and the [`destroy`][FfiBindData::destroy] destructor with `DuckDB`.
58/// - `DuckDB` calls `destroy` when the bound plan is discarded, which drops the
59///   `Box<T>`. That is not necessarily the end of the first query: a prepared
60///   statement binds once and reuses the bind data for every `EXECUTE`, so treat
61///   it as immutable after bind and build per-execution state in `init`.
62/// - Retrieval methods borrow the `T` for the duration of the callback.
63pub struct FfiBindData<T: 'static> {
64    _marker: std::marker::PhantomData<T>,
65}
66
67impl<T: 'static> FfiBindData<T> {
68    /// Stores `data` as the bind data for this table function invocation.
69    ///
70    /// Call this inside your `bind` callback to save configuration that will
71    /// be accessed in `init` and `scan` callbacks.
72    ///
73    /// `T` must be `Send + Sync`. Bind data outlives the bind callback: a
74    /// prepared statement keeps it across executions, every `init` reads it,
75    /// and with [`InitInfo::set_max_threads`][crate::table::InitInfo::set_max_threads]
76    /// above 1 several scan threads read it at once. It is dropped on whichever
77    /// thread tears the plan down.
78    ///
79    /// # Safety
80    ///
81    /// - `info` must be a valid `duckdb_bind_info` provided by `DuckDB` in a bind callback.
82    /// - Must be called at most once per bind invocation; calling twice leaks the first allocation.
83    ///   The bind of a typed table function
84    ///   ([`TableFunctionBuilder::with_state`][crate::table::TableFunctionBuilder::with_state])
85    ///   sets the bind data itself after the closure returns, so a call from the
86    ///   closure (through [`BindInfo::as_raw`][crate::table::BindInfo::as_raw]) is
87    ///   the first of two.
88    pub unsafe fn set(info: duckdb_bind_info, data: T)
89    where
90        T: Send + Sync,
91    {
92        let raw = Box::into_raw(Box::new(data)).cast::<c_void>();
93        // SAFETY: info is valid; raw is a non-null heap allocation owned by DuckDB after this call.
94        unsafe {
95            duckdb_bind_set_bind_data(info, raw, Some(Self::destroy));
96        }
97    }
98
99    /// Always returns `None`.
100    ///
101    /// # Deprecated
102    ///
103    /// This method cannot work and never could. `DuckDB`'s C API has no
104    /// `duckdb_bind_get_bind_data`: the bind info exposes
105    /// `duckdb_bind_get_extra_info`, `duckdb_bind_get_parameter`,
106    /// `duckdb_bind_get_named_parameter` and the `set_*` calls, and nothing that
107    /// reads back what `duckdb_bind_set_bind_data` stored. Bind data is
108    /// write-only during bind and readable from `init` and `scan` onwards.
109    ///
110    /// Because it is safe and returns `Option`, a caller writing the natural
111    /// `if let Some(cfg) = get_from_bind(info)` silently takes the wrong branch
112    /// forever. Keep the value in a local instead, and use
113    /// [`get_from_init`][Self::get_from_init] /
114    /// [`get_from_function`][Self::get_from_function] in the later phases.
115    #[deprecated(
116        since = "0.16.0",
117        note = "always returns None — DuckDB has no duckdb_bind_get_bind_data. Keep the value \
118                in a local during bind; use get_from_init / get_from_function afterwards."
119    )]
120    // Deprecated and unconditionally `None` — DuckDB has no
121    // `duckdb_bind_get_bind_data` to call. The `-> Option<&T> with None` mutant
122    // is therefore the function itself: equivalent by construction, unkillable
123    // by any test.
124    #[cfg_attr(test, mutants::skip)]
125    pub const fn get_from_bind<'a>(info: duckdb_bind_info) -> Option<&'a T> {
126        // The C API has no `duckdb_bind_get_bind_data`: bind data is write-only
127        // during bind. This never calls DuckDB (in particular not
128        // `duckdb_bind_get_extra_info`, which reads the function's extra info,
129        // a different pointer) and exists only so old callers keep compiling.
130        let _ = info;
131        None
132    }
133
134    /// Retrieves a shared reference to the bind data from a global init callback.
135    ///
136    /// Returns `None` if no bind data was set or the pointer is null.
137    ///
138    /// # Safety
139    ///
140    /// - `info` must be a valid `duckdb_init_info`.
141    /// - `T` must be the type passed to [`set`][Self::set] for this function.
142    /// - No mutable reference to the same data must exist simultaneously.
143    /// - The returned reference is valid for the duration of the init callback.
144    pub unsafe fn get_from_init<'a>(info: duckdb_init_info) -> Option<&'a T> {
145        // SAFETY: info is valid per caller's contract.
146        let raw = unsafe { duckdb_init_get_bind_data(info) };
147        if raw.is_null() {
148            return None;
149        }
150        // SAFETY: raw was set by set() via Box::into_raw. It is non-null and valid.
151        // No mutable reference exists per caller's contract.
152        Some(unsafe { &*raw.cast::<T>() })
153    }
154
155    /// Retrieves a shared reference to the bind data from a scan callback.
156    ///
157    /// Returns `None` if no bind data was set or the pointer is null.
158    ///
159    /// # Safety
160    ///
161    /// - `info` must be a valid `duckdb_function_info` from a scan callback.
162    /// - `T` must be the type passed to [`set`][Self::set] for this function.
163    /// - No mutable reference to the same data must exist simultaneously.
164    /// - The returned reference is valid for the duration of the scan callback.
165    pub unsafe fn get_from_function<'a>(info: duckdb_function_info) -> Option<&'a T> {
166        // SAFETY: info is valid per caller's contract.
167        let raw = unsafe { duckdb_function_get_bind_data(info) };
168        if raw.is_null() {
169            return None;
170        }
171        // SAFETY: raw was set by set() via Box::into_raw. It is non-null and valid.
172        Some(unsafe { &*raw.cast::<T>() })
173    }
174
175    /// The destroy callback passed to `duckdb_bind_set_bind_data`.
176    ///
177    /// `DuckDB` calls this when the query is complete. It drops the `Box<T>`.
178    ///
179    /// # Pitfall L3: `T::drop` is user code
180    ///
181    /// `DuckDB` invokes this through an `extern "C"` function pointer with no
182    /// error channel, and Rust 1.81+ turns an unwind across `extern "C"` into a
183    /// process abort. The drop therefore runs under
184    /// [`catch_ffi_panic`][crate::callback::catch_ffi_panic]; a panicking
185    /// `Drop` impl costs the diagnostic, not the session.
186    ///
187    /// # Safety
188    ///
189    /// - `ptr` must have been allocated by [`set`][FfiBindData::set] via `Box::into_raw`.
190    /// - Must be called exactly once (`DuckDB` guarantees this for bind data destroyers).
191    pub unsafe extern "C" fn destroy(ptr: *mut c_void) {
192        if !ptr.is_null() {
193            // SAFETY: ptr was created by Box::into_raw(Box::<T>::new(...)) in set().
194            // DuckDB calls this exactly once. `T::drop` is arbitrary user code,
195            // so the unwind is contained here rather than aborting the process.
196            drop(crate::callback::catch_ffi_panic(|| unsafe {
197                drop(Box::from_raw(ptr.cast::<T>()));
198            }));
199        }
200    }
201}
202
203impl<T: 'static> core::fmt::Debug for FfiBindData<T> {
204    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
205        f.write_str("FfiBindData<")?;
206        f.write_str(core::any::type_name::<T>())?;
207        f.write_str(">")
208    }
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214
215    #[allow(dead_code)]
216    struct Config {
217        value: i32,
218    }
219
220    #[test]
221    fn destroy_null_is_noop() {
222        // Must not panic or crash
223        unsafe { FfiBindData::<Config>::destroy(std::ptr::null_mut()) };
224    }
225
226    #[test]
227    fn destroy_drops_the_boxed_value_exactly_once() {
228        use std::sync::atomic::{AtomicUsize, Ordering};
229        static DROPS: AtomicUsize = AtomicUsize::new(0);
230        struct Counted;
231        impl Drop for Counted {
232            fn drop(&mut self) {
233                DROPS.fetch_add(1, Ordering::SeqCst);
234            }
235        }
236        let raw = Box::into_raw(Box::new(Counted)).cast::<c_void>();
237        // SAFETY: raw is a valid Box-allocated `Counted`, destroyed once.
238        unsafe { FfiBindData::<Counted>::destroy(raw) };
239        assert_eq!(DROPS.load(Ordering::SeqCst), 1);
240    }
241
242    #[test]
243    #[allow(deprecated)]
244    fn get_from_bind_always_returns_none() {
245        // Pinned so the deprecation note stays truthful: DuckDB exposes no
246        // duckdb_bind_get_bind_data, so there is nothing this could return.
247        assert!(FfiBindData::<Config>::get_from_bind(std::ptr::null_mut()).is_none());
248    }
249}