Skip to main content

quack_rs/table/
typed.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//! Closure-based table functions with typed scan state.
7//!
8//! This module provides [`TypedTableFunctionBuilder`], a higher-level builder
9//! layered on top of [`TableFunctionBuilder`]. It lets extension authors write
10//! table functions using safe Rust closures instead of `unsafe extern "C" fn`
11//! trampolines for `bind`, `init`, and `scan`.
12//!
13//! # Motivation
14//!
15//! The raw [`TableFunctionBuilder`] API requires authors to write three
16//! hand-rolled `unsafe extern "C" fn` callbacks and manually shuttle state
17//! through [`FfiBindData`][crate::table::FfiBindData] /
18//! [`FfiInitData`][crate::table::FfiInitData]. For extensions that merely need
19//! "take some parameters at bind, stream rows until exhausted", that ceremony
20//! is largely accidental complexity. [`TypedTableFunctionBuilder`] collapses
21//! it to closures.
22//!
23//! # Two entry points
24//!
25//! | Constructor | Bind produces | Each execution starts from |
26//! |---|---|---|
27//! | [`TableFunctionBuilder::with_state`] | a template `S: Clone` | a clone of the template |
28//! | [`TableFunctionBuilder::with_bind_init`] | immutable bind data `B` | `init(&B)` |
29//!
30//! Use `with_state` when the scan state is cheap to clone. Use
31//! `with_bind_init` when it is not (it holds a file handle, a large buffer, a
32//! connection), or when the parameters and the cursor are naturally separate.
33//!
34//! ```rust,no_run
35//! use quack_rs::prelude::*;
36//!
37//! #[derive(Clone)]
38//! struct State { remaining: u64 }
39//!
40//! fn register(reg: &impl Registrar) -> ExtResult<()> {
41//!     let builder = TableFunctionBuilder::new("count_down")
42//!         .param(TypeId::BigInt)
43//!         .with_state::<State, _>(|bind| {
44//!             bind.add_result_column("n", TypeId::BigInt);
45//!             let raw = unsafe { bind.get_parameter_value(0) };
46//!             let n = raw.as_i64_or(0).max(0) as u64;
47//!             Ok(State { remaining: n })
48//!         })
49//!         .scan(|state, chunk| {
50//!             if state.remaining == 0 {
51//!                 unsafe { chunk.set_size(0) };
52//!                 return Ok(());
53//!             }
54//!             let mut writer = unsafe { chunk.writer(0) };
55//!             unsafe { writer.write_i64(0, state.remaining as i64) };
56//!             state.remaining -= 1;
57//!             unsafe { chunk.set_size(1) };
58//!             Ok(())
59//!         })
60//!         .build()?;
61//!     unsafe { reg.register_table(builder) }
62//! }
63//! ```
64//!
65//! # Design
66//!
67//! - The `bind` closure runs **once per bind** — once per query plan, not once
68//!   per execution. It receives a [`BindInfo`], declares the output schema,
69//!   and reads parameters.
70//! - `DuckDB` keeps that one bind result for the lifetime of the plan and runs
71//!   `init` against it **every time the plan executes**: each `EXECUTE` of a
72//!   prepared statement, each iteration of a recursive CTE that references the
73//!   function, and so on. The builder therefore never *moves* state out of the
74//!   bind result; each execution gets a fresh `S` (a clone of the template, or
75//!   the result of your `init` closure).
76//! - The `scan` closure runs repeatedly until it sets the output chunk size
77//!   to zero. It receives `&mut S` and a [`DataChunk`] for output.
78//! - Panics in user closures are caught via `std::panic::catch_unwind`; the
79//!   error is reported through `DuckDB` and the chunk size is forced to zero
80//!   to safely terminate the scan.
81//!
82//! # Threading
83//!
84//! Because `S` is only required to be `Send + 'static` (not `Sync`), the typed
85//! builder forces scans to execute on a single worker via
86//! [`InitInfo::set_max_threads`][crate::table::InitInfo::set_max_threads] with
87//! `1`. Extensions that want true multi-worker parallelism should continue to
88//! use the raw [`TableFunctionBuilder`] API and split state across
89//! `local_init`.
90//!
91//! # No projection pushdown
92//!
93//! The typed builder does not offer `projection_pushdown`,
94//! [`build`][TypedTableFunctionBuilder::build] returns an error if it was
95//! switched on on the raw builder before `with_state` / `with_bind_init`, and
96//! registering the builder `build` returns fails if it was switched on
97//! afterwards. So does replacing its `bind`, `init`, `local_init`, `scan` or
98//! `extra_info`: the typed callbacks read one another's data.
99//! With pushdown on,
100//! `DuckDB` hands the scan a chunk holding only the *projected* columns, in
101//! projection order, so `chunk.writer(0)` is no longer "the first declared
102//! column" — and the scan closure has no way to learn the mapping. A scan
103//! written against the declared schema would then write column `a`'s values
104//! into column `b`. Use the raw [`TableFunctionBuilder`] with
105//! [`InitInfo::projected_column_index`][crate::table::InitInfo::projected_column_index]
106//! when you need pushdown.
107//!
108//! ```rust,compile_fail
109//! use quack_rs::prelude::*;
110//!
111//! // Does not compile: the typed builder has no `projection_pushdown`.
112//! let _ = TableFunctionBuilder::new("two_cols")
113//!     .with_state(|_bind| Ok(0_u8))
114//!     .projection_pushdown(true);
115//! ```
116
117use std::sync::{Arc, Mutex, PoisonError};
118
119use crate::data_chunk::DataChunk;
120use crate::error::ExtensionError;
121use crate::table::builder::TableFunctionBuilder;
122use crate::table::info::BindInfo;
123use crate::types::{LogicalType, TypeId};
124
125mod trampolines;
126
127/// Produces a fresh scan state for one execution of a bound plan.
128///
129/// Stored as the table function's bind data. `DuckDB` may call `init` for the
130/// same bind data from any worker thread, hence `Send + Sync`.
131type StateFactory<S> = dyn Fn() -> Result<S, ExtensionError> + Send + Sync + 'static;
132
133/// Boxed bind closure signature stored inside [`TypedCallbacks`]: declares the
134/// schema, then returns the factory every later `init` draws its state from.
135type BindClosure<S> =
136    dyn Fn(&BindInfo) -> Result<Box<StateFactory<S>>, ExtensionError> + Send + Sync + 'static;
137
138/// Boxed scan closure signature stored inside [`TypedCallbacks`].
139type ScanClosure<S> =
140    dyn Fn(&mut S, &DataChunk) -> Result<(), ExtensionError> + Send + Sync + 'static;
141
142/// Heap-allocated bundle of user closures, stored as the table function's
143/// `extra_info` so it survives across FFI callbacks.
144struct TypedCallbacks<S: Send + 'static> {
145    bind: Box<BindClosure<S>>,
146    scan: Box<ScanClosure<S>>,
147}
148
149/// Closure-based builder for table functions with a typed, mutable scan state.
150///
151/// Obtain one via [`TableFunctionBuilder::with_state`] or
152/// [`TableFunctionBuilder::with_bind_init`]. Set a scan closure with
153/// [`scan`][Self::scan] and finish with [`build`][Self::build] to recover a
154/// fully-configured [`TableFunctionBuilder`] that can be passed to any
155/// [`Registrar`][crate::connection::Registrar].
156///
157/// # Example
158///
159/// See the [module-level docs][crate::table::typed] for a complete example.
160#[must_use]
161pub struct TypedTableFunctionBuilder<S: Send + 'static> {
162    inner: TableFunctionBuilder,
163    bind: Option<Box<BindClosure<S>>>,
164    scan: Option<Box<ScanClosure<S>>>,
165}
166
167impl TableFunctionBuilder {
168    /// Switches this builder into closure-based "typed state" mode, with the
169    /// scan state cloned from a template for every execution.
170    ///
171    /// The supplied `bind` closure runs once per bind (see the
172    /// [module docs][crate::table::typed] for what that means for prepared
173    /// statements). It must:
174    ///
175    /// - Declare the output schema via
176    ///   [`BindInfo::add_result_column`][crate::table::BindInfo::add_result_column]
177    ///   — at least one column. With `duckdb-1-5`, a bind that declares none
178    ///   is reported as an ordinary bind error instead of the `INTERNAL Error`
179    ///   `DuckDB` raises for it. Used as a `COPY … FROM` reader, it must
180    ///   instead declare none and read the target table's columns
181    ///   (`BindInfo::result_column_count`);
182    ///   with `duckdb-1-5` a column declared there fails the bind.
183    /// - Read parameters (positional or named) from the [`BindInfo`].
184    /// - Return the *template* scan state `S` on success, or an
185    ///   [`ExtensionError`] on failure. Errors are propagated to `DuckDB` via
186    ///   `duckdb_bind_set_error`.
187    ///
188    /// Every execution of the bound plan starts from `template.clone()`, so a
189    /// prepared statement executed twice scans the same rows twice. If `S` is
190    /// expensive or impossible to clone, use
191    /// [`with_bind_init`][Self::with_bind_init] instead.
192    ///
193    /// Continue building the function by calling [`scan`][TypedTableFunctionBuilder::scan].
194    ///
195    /// See the [module-level docs][crate::table::typed] for an end-to-end example.
196    pub fn with_state<S, F>(self, bind: F) -> TypedTableFunctionBuilder<S>
197    where
198        S: Clone + Send + 'static,
199        F: Fn(&BindInfo) -> Result<S, ExtensionError> + Send + Sync + 'static,
200    {
201        let bind: Box<BindClosure<S>> = Box::new(move |info| {
202            // `S` is `Send` but not necessarily `Sync`, and `init` may run on
203            // any thread, so the template sits behind a `Mutex`. `clone` takes
204            // `&S`, so a panic inside it cannot leave the template half
205            // modified: recovering from poison is sound.
206            let template = Mutex::new(bind(info)?);
207            let factory: Box<StateFactory<S>> = Box::new(move || {
208                Ok(template
209                    .lock()
210                    .unwrap_or_else(PoisonError::into_inner)
211                    .clone())
212            });
213            Ok(factory)
214        });
215        TypedTableFunctionBuilder {
216            inner: self,
217            bind: Some(bind),
218            scan: None,
219        }
220    }
221
222    /// Switches this builder into closure-based "typed state" mode, with
223    /// immutable bind data `B` and a fresh scan state `S` built from it for
224    /// every execution.
225    ///
226    /// - `bind` runs once per bind: declare the output schema with
227    ///   [`BindInfo::add_result_column`][crate::table::BindInfo::add_result_column],
228    ///   read parameters, and return the bind data `B`.
229    /// - `init` runs once per *execution* of the bound plan — every `EXECUTE`
230    ///   of a prepared statement, every re-scan inside a recursive CTE — and
231    ///   builds the scan state `S` from `&B`. This is where to open files or
232    ///   reset cursors.
233    ///
234    /// `B` must be `Send + Sync` because `DuckDB` may run `init` for the same
235    /// bind data on any worker thread. `S` need only be `Send`: scans are
236    /// serialised (see the [module docs][crate::table::typed]).
237    ///
238    /// Errors from either closure are reported to `DuckDB` (`bind` as a binder
239    /// error, `init` as an invalid-input error).
240    ///
241    /// # Example
242    ///
243    /// ```rust,no_run
244    /// use quack_rs::prelude::*;
245    ///
246    /// struct Params { n: i64 }
247    /// struct Cursor { next: i64, end: i64 }
248    ///
249    /// fn register(reg: &impl Registrar) -> ExtResult<()> {
250    ///     let builder = TableFunctionBuilder::new("count_up")
251    ///         .param(TypeId::BigInt)
252    ///         .with_bind_init(
253    ///             |bind| {
254    ///                 bind.add_result_column("n", TypeId::BigInt);
255    ///                 let n = unsafe { bind.get_parameter_value(0) }.as_i64_or(0);
256    ///                 Ok(Params { n })
257    ///             },
258    ///             |params: &Params| Ok(Cursor { next: 1, end: params.n }),
259    ///         )
260    ///         .scan(|cursor, chunk| {
261    ///             if cursor.next > cursor.end {
262    ///                 unsafe { chunk.set_size(0) };
263    ///                 return Ok(());
264    ///             }
265    ///             unsafe {
266    ///                 chunk.writer(0).write_i64(0, cursor.next);
267    ///                 chunk.set_size(1);
268    ///             }
269    ///             cursor.next += 1;
270    ///             Ok(())
271    ///         })
272    ///         .build()?;
273    ///     unsafe { reg.register_table(builder) }
274    /// }
275    /// ```
276    pub fn with_bind_init<B, S, FB, FI>(self, bind: FB, init: FI) -> TypedTableFunctionBuilder<S>
277    where
278        B: Send + Sync + 'static,
279        S: Send + 'static,
280        FB: Fn(&BindInfo) -> Result<B, ExtensionError> + Send + Sync + 'static,
281        FI: Fn(&B) -> Result<S, ExtensionError> + Send + Sync + 'static,
282    {
283        let init = Arc::new(init);
284        let bind: Box<BindClosure<S>> = Box::new(move |info| {
285            let bound = bind(info)?;
286            let init = Arc::clone(&init);
287            let factory: Box<StateFactory<S>> = Box::new(move || init(&bound));
288            Ok(factory)
289        });
290        TypedTableFunctionBuilder {
291            inner: self,
292            bind: Some(bind),
293            scan: None,
294        }
295    }
296}
297
298impl<S: Send + 'static> TypedTableFunctionBuilder<S> {
299    /// Sets the scan closure.
300    ///
301    /// The closure receives a mutable reference to the scan state for the
302    /// current execution, plus a [`DataChunk`] for the output chunk. It must
303    /// fill the chunk with zero or more output rows and set the chunk size via
304    /// [`DataChunk::set_size`] or a [`ChunkWriter`][crate::chunk_writer::ChunkWriter].
305    /// Returning with chunk size zero signals end-of-stream to `DuckDB`.
306    ///
307    /// Column `i` of the chunk is the `i`-th column declared in `bind`: the
308    /// typed builder never enables projection pushdown (and
309    /// [`build`][Self::build] refuses a raw builder that had it enabled).
310    ///
311    /// Errors are reported through `duckdb_function_set_error` and terminate
312    /// the scan.
313    pub fn scan<F>(mut self, f: F) -> Self
314    where
315        F: Fn(&mut S, &DataChunk) -> Result<(), ExtensionError> + Send + Sync + 'static,
316    {
317        self.scan = Some(Box::new(f));
318        self
319    }
320
321    /// Returns the underlying function name.
322    pub fn name(&self) -> &str {
323        self.inner.name()
324    }
325
326    /// Adds a positional parameter. Delegates to [`TableFunctionBuilder::param`].
327    pub fn param(mut self, type_id: TypeId) -> Self {
328        self.inner = self.inner.param(type_id);
329        self
330    }
331
332    /// Adds a positional parameter with a complex [`LogicalType`].
333    /// Delegates to [`TableFunctionBuilder::param_logical`].
334    pub fn param_logical(mut self, logical_type: LogicalType) -> Self {
335        self.inner = self.inner.param_logical(logical_type);
336        self
337    }
338
339    /// Adds a named parameter. Delegates to [`TableFunctionBuilder::named_param`].
340    pub fn named_param(mut self, name: &str, type_id: TypeId) -> Self {
341        self.inner = self.inner.named_param(name, type_id);
342        self
343    }
344
345    /// Adds a named parameter with a complex [`LogicalType`].
346    /// Delegates to [`TableFunctionBuilder::named_param_logical`].
347    pub fn named_param_logical(mut self, name: &str, logical_type: LogicalType) -> Self {
348        self.inner = self.inner.named_param_logical(name, logical_type);
349        self
350    }
351
352    /// Finalises the typed builder into a raw [`TableFunctionBuilder`] ready
353    /// for registration.
354    ///
355    /// The returned builder has its `bind`, `init`, and `scan` callbacks wired
356    /// to closure trampolines, and stores the user closures in `extra_info`
357    /// for the lifetime of the registered function.
358    ///
359    /// The closures are owned by the returned builder's `extra_info`: they are
360    /// handed to `DuckDB` on successful registration, and freed when the
361    /// builder is dropped otherwise — an unregistered builder does not leak.
362    ///
363    /// # Errors
364    ///
365    /// Returns an error if [`scan`][Self::scan] was never called (the bind
366    /// closure is always set at construction time), or if
367    /// [`projection_pushdown`][TableFunctionBuilder::projection_pushdown] was
368    /// enabled on the raw builder before it was turned into a typed one. The
369    /// typed scan closure writes columns in declaration order and cannot learn
370    /// the projection, so with pushdown on `SELECT b` would receive column
371    /// `a`'s values. Switching it off silently would change configuration the
372    /// caller asked for, so it is an error instead.
373    pub fn build(self) -> Result<TableFunctionBuilder, ExtensionError> {
374        if self.inner.projection_pushdown_enabled() {
375            return Err(ExtensionError::new(format!(
376                "typed table function '{}': projection_pushdown was enabled on the builder \
377                 before with_state/with_bind_init. The typed scan closure writes columns in \
378                 declaration order and cannot see the projection, so pushdown would put one \
379                 column's values under another's name. Remove projection_pushdown(true), or \
380                 use the raw TableFunctionBuilder with InitInfo::projected_column_index.",
381                self.inner.name()
382            )));
383        }
384        let bind = self
385            .bind
386            .ok_or_else(|| ExtensionError::new("typed table function: bind closure not set"))?;
387        let scan = self
388            .scan
389            .ok_or_else(|| ExtensionError::new("typed table function: scan closure not set"))?;
390        Ok(trampolines::wire(
391            self.inner,
392            TypedCallbacks::<S> { bind, scan },
393        ))
394    }
395}
396
397impl<S: Send + 'static> core::fmt::Debug for TypedTableFunctionBuilder<S> {
398    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
399        use crate::debug_repr::Callback;
400        f.debug_struct("TypedTableFunctionBuilder")
401            .field("state", &core::any::type_name::<S>())
402            .field("inner", &self.inner)
403            .field("bind", &Callback::of(&self.bind))
404            .field("scan", &Callback::of(&self.scan))
405            .finish()
406    }
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412    use std::sync::atomic::{AtomicUsize, Ordering};
413
414    #[derive(Clone)]
415    struct DummyState {
416        _rows: u64,
417    }
418
419    #[test]
420    fn with_state_produces_typed_builder() {
421        let typed = TableFunctionBuilder::new("demo")
422            .with_state::<DummyState, _>(|_bind| Ok(DummyState { _rows: 10 }));
423        assert_eq!(typed.name(), "demo");
424        assert!(typed.bind.is_some());
425        assert!(typed.scan.is_none());
426    }
427
428    #[test]
429    fn with_bind_init_produces_typed_builder() {
430        struct NotClone;
431        let typed = TableFunctionBuilder::new("demo")
432            .with_bind_init(|_bind| Ok(3_u64), |_n: &u64| Ok(NotClone));
433        assert_eq!(typed.name(), "demo");
434        assert!(typed.bind.is_some());
435        assert!(typed.scan.is_none());
436    }
437
438    unsafe extern "C" fn noop_bind(_: libduckdb_sys::duckdb_bind_info) {}
439    unsafe extern "C" fn noop_init(_: libduckdb_sys::duckdb_init_info) {}
440    unsafe extern "C" fn noop_scan(
441        _: libduckdb_sys::duckdb_function_info,
442        _: libduckdb_sys::duckdb_data_chunk,
443    ) {
444    }
445
446    #[test]
447    fn projection_pushdown_after_build_is_refused_at_registration() {
448        use crate::connection::Registrar;
449        use crate::testing::MockRegistrar;
450        let built = || {
451            TableFunctionBuilder::new("demo")
452                .with_state::<DummyState, _>(|_bind| Ok(DummyState { _rows: 10 }))
453                .scan(|_state, _chunk| Ok(()))
454                .build()
455                .expect("build")
456        };
457        let registrar = MockRegistrar::new();
458        // SAFETY: `MockRegistrar` never calls `DuckDB`.
459        let err = unsafe { registrar.register_table(built().projection_pushdown(true)) }
460            .expect_err("pushdown after build");
461        assert!(err.as_str().contains("after build()"), "{err}");
462        // SAFETY: as above.
463        unsafe { registrar.register_table(built().projection_pushdown(false)) }
464            .expect("pushdown off");
465        // A raw builder keeps pushdown.
466        let raw = TableFunctionBuilder::new("raw")
467            .bind(noop_bind)
468            .init(noop_init)
469            .scan(noop_scan)
470            .projection_pushdown(true);
471        // SAFETY: as above.
472        unsafe { registrar.register_table(raw) }.expect("raw pushdown");
473    }
474
475    #[test]
476    fn replacing_a_typed_functions_callbacks_after_build_is_refused() {
477        use crate::connection::Registrar;
478        use crate::testing::MockRegistrar;
479        let built = || {
480            TableFunctionBuilder::new("demo")
481                .with_state::<DummyState, _>(|_bind| Ok(DummyState { _rows: 10 }))
482                .scan(|_state, _chunk| Ok(()))
483                .build()
484                .expect("build")
485        };
486        let registrar = MockRegistrar::new();
487        for (what, builder) in [
488            ("bind", built().bind(noop_bind)),
489            ("init", built().init(noop_init)),
490            ("local_init", built().local_init(noop_init)),
491            ("scan", built().scan(noop_scan)),
492        ] {
493            // SAFETY: `MockRegistrar` never calls `DuckDB`.
494            let err = unsafe { registrar.register_table(builder) }.expect_err(what);
495            assert!(err.as_str().contains(what), "{what}: {err}");
496        }
497        // SAFETY: as above.
498        unsafe { registrar.register_table(built()) }.expect("untouched");
499    }
500
501    #[test]
502    fn build_without_scan_errors() {
503        let typed = TableFunctionBuilder::new("demo")
504            .with_state::<DummyState, _>(|_bind| Ok(DummyState { _rows: 10 }));
505        match typed.build() {
506            Err(e) => assert!(e.as_str().contains("scan closure not set")),
507            Ok(_) => panic!("expected error"),
508        }
509    }
510
511    #[test]
512    fn build_with_bind_and_scan_succeeds() {
513        let typed = TableFunctionBuilder::new("demo")
514            .param(TypeId::BigInt)
515            .with_state::<DummyState, _>(|_bind| Ok(DummyState { _rows: 10 }))
516            .scan(|_state, _chunk| Ok(()));
517        let builder = typed.build().expect("build should succeed");
518        assert_eq!(builder.name(), "demo");
519    }
520
521    #[test]
522    fn passthroughs_mutate_inner_builder() {
523        let typed = TableFunctionBuilder::new("demo")
524            .with_state::<DummyState, _>(|_| Ok(DummyState { _rows: 0 }))
525            .param(TypeId::Varchar)
526            .named_param("path", TypeId::Varchar);
527        // The inner builder's fields are private to `builder`; its `Debug`
528        // output is the observable record of what the passthroughs stored.
529        let inner = format!("{:?}", typed.inner);
530        assert!(inner.contains("params: [Varchar]"), "{inner}");
531        assert!(inner.contains("named_params: 1"), "{inner}");
532    }
533
534    #[test]
535    fn build_refuses_projection_pushdown_enabled_beforehand() {
536        let typed = TableFunctionBuilder::new("demo")
537            .projection_pushdown(true)
538            .with_state::<DummyState, _>(|_| Ok(DummyState { _rows: 0 }))
539            .scan(|_state, _chunk| Ok(()));
540        match typed.build() {
541            Err(e) => assert!(e.as_str().contains("projection_pushdown"), "{e}"),
542            Ok(_) => panic!("projection pushdown must be refused"),
543        }
544    }
545
546    /// The factories are what make repeated `init` calls against one bind
547    /// result work; exercise them without a live `DuckDB` by calling the
548    /// factory the bind closure would have stored.
549    #[test]
550    fn with_state_factory_hands_out_independent_clones() {
551        // SAFETY: a null bind info is never dereferenced by this closure.
552        let info = unsafe { BindInfo::new(std::ptr::null_mut()) };
553        let typed = TableFunctionBuilder::new("demo").with_state(|_| Ok(vec![1_u8, 2]));
554        let factory = (typed.bind.expect("bind set"))(&info).expect("bind ok");
555        let mut first = factory().expect("first");
556        first.push(3);
557        assert_eq!(first, vec![1, 2, 3]);
558        assert_eq!(factory().expect("second"), vec![1, 2]);
559    }
560
561    #[test]
562    fn with_bind_init_runs_init_once_per_factory_call() {
563        static INITS: AtomicUsize = AtomicUsize::new(0);
564        // SAFETY: a null bind info is never dereferenced by this closure.
565        let info = unsafe { BindInfo::new(std::ptr::null_mut()) };
566        let typed = TableFunctionBuilder::new("demo").with_bind_init(
567            |_| Ok(5_i64),
568            |n: &i64| {
569                INITS.fetch_add(1, Ordering::SeqCst);
570                Ok(*n * 2)
571            },
572        );
573        let factory = (typed.bind.expect("bind set"))(&info).expect("bind ok");
574        assert_eq!(factory().expect("first"), 10);
575        assert_eq!(factory().expect("second"), 10);
576        assert_eq!(INITS.load(Ordering::SeqCst), 2);
577    }
578}