Skip to main content

quack_rs/table/
info.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//! Ergonomic wrappers around `DuckDB` callback info handles.
7//!
8//! These types provide safe, chainable methods for the most common operations
9//! performed inside bind, init, and scan callbacks.
10
11use std::os::raw::c_void;
12use std::sync::atomic::{AtomicBool, Ordering};
13
14use libduckdb_sys::{
15    duckdb_bind_add_result_column, duckdb_bind_get_extra_info, duckdb_bind_get_named_parameter,
16    duckdb_bind_get_parameter, duckdb_bind_info, duckdb_bind_set_cardinality,
17    duckdb_bind_set_error, duckdb_function_get_extra_info, duckdb_function_info,
18    duckdb_function_set_error, duckdb_init_get_extra_info, duckdb_init_info, duckdb_init_set_error,
19    duckdb_value, idx_t,
20};
21#[cfg(feature = "duckdb-1-5")]
22use libduckdb_sys::{duckdb_client_context, duckdb_table_function_get_client_context};
23
24use crate::table::cstr::{error_cstring, str_to_cstring};
25use crate::types::{LogicalType, TypeId};
26use crate::value::Value;
27
28/// The message the table function wrappers report in place of an empty one.
29///
30/// [`BindInfo::set_error`], [`InitInfo::set_error`] and
31/// [`FunctionInfo::set_error`] substitute it for `""` (an interior NUL is
32/// replaced by `?`, so no other message is empty): `DuckDB` would otherwise report
33/// `Binder Error: ` followed by nothing, and the user would learn only that
34/// something failed.
35pub const EMPTY_ERROR_PLACEHOLDER: &str = "table function reported an error without a message";
36
37/// Helper wrapper around `duckdb_bind_info` for use inside bind callbacks.
38///
39/// Provides ergonomic methods for the most common bind operations.
40///
41/// # Example
42///
43/// ```rust,no_run
44/// use quack_rs::table::BindInfo;
45/// use quack_rs::types::TypeId;
46/// use libduckdb_sys::duckdb_bind_info;
47///
48/// unsafe extern "C" fn my_bind(info: duckdb_bind_info) {
49///     unsafe {
50///         BindInfo::new(info)
51///             .add_result_column("id",   TypeId::BigInt)
52///             .add_result_column("name", TypeId::Varchar)
53///             .set_cardinality(100, true);
54///     }
55/// }
56/// ```
57pub struct BindInfo {
58    info: duckdb_bind_info,
59    /// Whether [`set_error`][Self::set_error] has been called on this
60    /// wrapper. The typed bind trampoline reads it so its own "no columns
61    /// declared" error does not overwrite a more specific one (such as a
62    /// rejected column type). An `AtomicBool` rather than a `Cell` so the
63    /// wrapper stays `RefUnwindSafe`.
64    error_reported: AtomicBool,
65}
66
67impl BindInfo {
68    /// Wraps a raw `duckdb_bind_info`.
69    ///
70    /// # Safety
71    ///
72    /// `info` must be a valid `duckdb_bind_info` provided by `DuckDB` in a bind callback.
73    #[inline]
74    #[must_use]
75    pub const unsafe fn new(info: duckdb_bind_info) -> Self {
76        Self {
77            info,
78            error_reported: AtomicBool::new(false),
79        }
80    }
81
82    /// Whether [`set_error`][Self::set_error] was called through this wrapper.
83    ///
84    /// An error set by calling `duckdb_bind_set_error` on
85    /// [`as_raw`][Self::as_raw] directly is not seen.
86    // Only the typed trampoline's `duckdb-1-5` column check reads it.
87    #[cfg_attr(not(feature = "duckdb-1-5"), allow(dead_code))]
88    pub(crate) fn error_reported(&self) -> bool {
89        self.error_reported.load(Ordering::Relaxed)
90    }
91
92    /// Declares an output column with the given name and type.
93    ///
94    /// Call this once per output column in the order they will appear in the result.
95    ///
96    /// If `name` contains an interior null byte it is truncated at that point.
97    ///
98    /// # Rejected types
99    ///
100    /// A type that cannot be a result column is reported as a **bind error**
101    /// (via [`set_error`][Self::set_error]) naming the column, and the column
102    /// is not added:
103    ///
104    /// - `ANY` (and, through
105    ///   [`add_result_column_with_type`][Self::add_result_column_with_type],
106    ///   any type *containing* `ANY` or `INVALID`, such as `LIST(ANY)`).
107    ///   `duckdb_bind_add_result_column` would silently drop such a column,
108    ///   shifting the index of every column declared after it.
109    /// - A composite id (`List`, `Struct`, `Decimal`, ...) that needs its own
110    ///   [`LogicalType`] constructor; use `add_result_column_with_type`.
111    ///   (This used to panic.)
112    ///
113    /// The query then fails at bind time with that message, even if the bind
114    /// callback goes on to succeed.
115    ///
116    /// Do not call this in the bind of a `COPY … FROM` reader (see
117    /// `CopyFunctionBuilder::copy_from`, `duckdb-1-5`):
118    /// there the target table fixes the columns, and a declared one widens
119    /// every chunk the `INSERT` receives past the table.
120    pub fn add_result_column(&self, name: &str, type_id: TypeId) -> &Self {
121        match LogicalType::try_new(type_id) {
122            Ok(lt) => self.add_result_column_with_type(name, &lt),
123            Err(e) => {
124                self.set_error(&format!("add_result_column('{name}'): {e}"));
125                self
126            }
127        }
128    }
129
130    /// Number of result columns `DuckDB` already knows this table function must
131    /// produce.
132    ///
133    /// Zero for an ordinary table function, which is expected to declare its own
134    /// columns with
135    /// [`add_result_column`][Self::add_result_column]. Non-zero when the
136    /// function is driving a `COPY … FROM`: the target table's schema is fixed
137    /// before the bind callback runs, and `duckdb.h` is explicit that such a
138    /// function "should not define its own result columns using
139    /// `duckdb_bind_add_result_column`" and should read the expected schema from
140    /// here instead.
141    ///
142    /// Requires `duckdb-1-5`.
143    ///
144    /// # Example
145    ///
146    /// ```rust,no_run
147    /// use quack_rs::table::BindInfo;
148    ///
149    /// # fn demo(bind: &BindInfo) {
150    /// // A COPY ... FROM reader adapts to the table it is loading into.
151    /// for i in 0..bind.result_column_count() {
152    ///     let name = bind.result_column_name(i).unwrap_or_default();
153    ///     // SAFETY: `i` is in range.
154    ///     let ty = unsafe { bind.result_column_type(i) };
155    ///     let _ = (name, ty);
156    /// }
157    /// # }
158    /// ```
159    #[cfg(feature = "duckdb-1-5")]
160    #[cfg_attr(test, mutants::skip)] // FFI accessor — needs a live DuckDB bind callback
161    #[must_use]
162    pub fn result_column_count(&self) -> usize {
163        // SAFETY: `self.info` is valid per the constructor's contract.
164        usize::try_from(unsafe {
165            libduckdb_sys::duckdb_table_function_bind_get_result_column_count(self.info)
166        })
167        .unwrap_or(0)
168    }
169
170    /// Name of result column `index`, or `None` if it is out of range.
171    ///
172    /// The C API returns a **borrowed** pointer into `DuckDB`'s own storage —
173    /// `names[col_idx].c_str()` — which `duckdb.h` says "must not be destroyed"
174    /// and which is only valid "for the duration of the bind callback or until
175    /// the next call to `duckdb_bind_add_result_column`". This copies it, so the
176    /// returned `String` is not subject to either restriction (pitfall P11).
177    ///
178    /// Requires `duckdb-1-5`.
179    #[cfg(feature = "duckdb-1-5")]
180    #[cfg_attr(test, mutants::skip)] // FFI accessor — needs a live DuckDB bind callback
181    #[must_use]
182    pub fn result_column_name(&self, index: usize) -> Option<String> {
183        if index >= self.result_column_count() {
184            return None;
185        }
186        // SAFETY: `self.info` is valid and `index` is in range.
187        let ptr = unsafe {
188            libduckdb_sys::duckdb_table_function_bind_get_result_column_name(
189                self.info,
190                index as idx_t,
191            )
192        };
193        if ptr.is_null() {
194            return None;
195        }
196        // SAFETY: `ptr` is a NUL-terminated string DuckDB owns; it is copied
197        // here and never freed by this crate.
198        unsafe { std::ffi::CStr::from_ptr(ptr) }
199            .to_str()
200            .ok()
201            .map(str::to_owned)
202    }
203
204    /// Type of result column `index`, or `None` if it is out of range.
205    ///
206    /// Unlike [`result_column_name`][Self::result_column_name] this handle is
207    /// **owned** — `duckdb_table_function_bind_get_result_column_type` returns a
208    /// freshly allocated `LogicalType` — so it is wrapped in [`LogicalType`],
209    /// which destroys it on drop.
210    ///
211    /// Requires `duckdb-1-5`.
212    ///
213    /// # Safety
214    ///
215    /// Must be called during the bind callback, while `self.info` is live.
216    #[cfg(feature = "duckdb-1-5")]
217    #[cfg_attr(test, mutants::skip)] // FFI accessor — needs a live DuckDB bind callback
218    #[must_use]
219    pub unsafe fn result_column_type(&self, index: usize) -> Option<LogicalType> {
220        if index >= self.result_column_count() {
221            return None;
222        }
223        // SAFETY: `self.info` is valid and `index` is in range.
224        let raw = unsafe {
225            libduckdb_sys::duckdb_table_function_bind_get_result_column_type(
226                self.info,
227                index as idx_t,
228            )
229        };
230        if raw.is_null() {
231            return None;
232        }
233        // SAFETY: DuckDB returns a handle the caller owns and must destroy.
234        Some(unsafe { LogicalType::from_raw(raw) })
235    }
236
237    /// Adds an output column with a pre-built `LogicalType`.
238    ///
239    /// Use this when the column type is a complex type (LIST, STRUCT, MAP) built
240    /// via `LogicalType::list`, `LogicalType::struct_type`, or `LogicalType::map`.
241    ///
242    /// If `name` contains an interior null byte it is truncated at that point.
243    ///
244    /// A type containing `ANY` or `INVALID` is reported as a bind error rather
245    /// than added; see "Rejected types" on
246    /// [`add_result_column`][Self::add_result_column].
247    pub fn add_result_column_with_type(&self, name: &str, logical_type: &LogicalType) -> &Self {
248        // SAFETY: `logical_type` owns a live handle.
249        if unsafe { crate::table::type_check::contains_any_or_invalid(logical_type.as_raw()) } {
250            self.set_error(&format!(
251                "add_result_column('{name}'): a result column's type must not be or contain \
252                 ANY or INVALID; DuckDB would silently drop the column and shift every later one"
253            ));
254            return self;
255        }
256        let c_name = str_to_cstring(name);
257        // SAFETY: self.info is valid; logical_type.as_raw() is valid.
258        unsafe {
259            duckdb_bind_add_result_column(self.info, c_name.as_ptr(), logical_type.as_raw());
260        }
261        self
262    }
263
264    /// Sets a cardinality hint for the query optimizer.
265    ///
266    /// # What `is_exact` actually does
267    ///
268    /// `duckdb.h` describes `is_exact` as "whether or not the cardinality is
269    /// exact". `DuckDB` 2.0.0 implements that; every 1.x release up to and
270    /// including 1.5.6 implements it the other way round
271    /// (`src/main/capi/table_function-c.cpp`, `duckdb_bind_set_cardinality`):
272    ///
273    /// | `is_exact` | `NodeStatistics` recorded, 1.x | `NodeStatistics` recorded, 2.0.0 |
274    /// |---|---|---|
275    /// | `true`  | `NodeStatistics(rows)` — an **estimate only** | `NodeStatistics(rows, rows)` — the estimate **and** `max_cardinality = rows` |
276    /// | `false` | `NodeStatistics(rows, rows)` — the estimate **and** `max_cardinality = rows` | `NodeStatistics(rows)` — an **estimate only** |
277    ///
278    /// The estimate drives plan costing either way (`EXPLAIN` shows `~rows`
279    /// for both). The upper bound additionally feeds the optimizer's
280    /// statistics propagation for joins and set operations
281    /// (`src/optimizer/statistics/operator/propagate_join.cpp`), which treats
282    /// it as a limit. quack-rs passes the flag through unchanged, so the same
283    /// call records a bound on one engine and a plain estimate on the other.
284    /// For an extension that may load into either, the only safe call is one
285    /// whose `rows` the scan never exceeds — then a recorded bound is true
286    /// whichever flag records it. A guess the scan may exceed is safe with
287    /// `true` on 1.x and with `false` on 2.0.0 only: choose the flag by the
288    /// engine's version ([`crate::abi::engine_version`]) or set no hint.
289    ///
290    /// # The hint is clamped to `i64::MAX`
291    ///
292    /// `DuckDB` converts the hint to a signed 64-bit count when it estimates a
293    /// join, and a value above `i64::MAX` makes any query that joins or
294    /// cross-joins the function fail with `INTERNAL Error: Information loss on
295    /// integer cast` (measured on 1.5.6 with `u64::MAX`, the "unknown" a
296    /// careless caller passes). No table has that many rows, so a larger
297    /// `rows` is clamped to `i64::MAX` instead of being passed on.
298    pub fn set_cardinality(&self, rows: u64, is_exact: bool) -> &Self {
299        let rows = rows.min(i64::MAX as u64);
300        // SAFETY: self.info is valid.
301        unsafe {
302            duckdb_bind_set_cardinality(self.info, rows as idx_t, is_exact);
303        }
304        self
305    }
306
307    /// Reports an error from the bind callback.
308    ///
309    /// After calling this, `DuckDB` will abort query parsing and report the error.
310    ///
311    /// An interior null byte in `message` is replaced by `?`.
312    /// An empty message is replaced by [`EMPTY_ERROR_PLACEHOLDER`].
313    #[cfg_attr(test, mutants::skip)]
314    pub fn set_error(&self, message: &str) {
315        self.error_reported.store(true, Ordering::Relaxed);
316        let c_msg = error_cstring(message, EMPTY_ERROR_PLACEHOLDER);
317        // SAFETY: self.info is valid.
318        unsafe {
319            duckdb_bind_set_error(self.info, c_msg.as_ptr());
320        }
321    }
322
323    /// Returns the number of positional parameters passed to this function call.
324    #[cfg_attr(test, mutants::skip)]
325    #[must_use]
326    pub fn parameter_count(&self) -> usize {
327        // SAFETY: self.info is valid.
328        usize::try_from(unsafe { libduckdb_sys::duckdb_bind_get_parameter_count(self.info) })
329            .unwrap_or(0)
330    }
331
332    /// Returns the parameter value at the given positional index.
333    ///
334    /// # Safety
335    ///
336    /// - `index` must be less than [`parameter_count`][BindInfo::parameter_count].
337    /// - The caller is responsible for destroying the returned `duckdb_value`.
338    pub unsafe fn get_parameter(&self, index: u64) -> duckdb_value {
339        // SAFETY: `self.info` is the live `duckdb_bind_info` of the bind callback in
340        // progress, per the `# Safety` contract of `BindInfo::new`.
341        // `duckdb_bind_get_parameter` itself returns null for `index >= parameter_count`
342        // (table_function-c.cpp), so the index clause is belt-and-braces; otherwise it
343        // returns a fresh `new Value` that this function's `# Safety` clause makes the
344        // caller destroy.
345        unsafe { duckdb_bind_get_parameter(self.info, index) }
346    }
347
348    /// Returns the parameter value for the given named parameter.
349    ///
350    /// # Safety
351    ///
352    /// - `name` must correspond to a named parameter declared for this function.
353    /// - The caller is responsible for destroying the returned `duckdb_value`.
354    ///
355    /// If `name` contains an interior null byte it is truncated at that point.
356    pub unsafe fn get_named_parameter(&self, name: &str) -> duckdb_value {
357        let c_name = str_to_cstring(name);
358        // SAFETY: `self.info` is the live `duckdb_bind_info` of the bind callback in
359        // progress, per the `# Safety` contract of `BindInfo::new`. `c_name` is a
360        // NUL-terminated `CString` that outlives the call, and DuckDB only looks it up in
361        // `named_parameters`. The result is null (no such parameter) or a fresh `new Value`
362        // the caller must destroy, per this function's `# Safety` clause.
363        unsafe { duckdb_bind_get_named_parameter(self.info, c_name.as_ptr()) }
364    }
365
366    /// Returns the positional parameter at `index` as an owned [`Value`].
367    ///
368    /// The returned `Value` is RAII-managed — it will call `duckdb_destroy_value`
369    /// on drop, so the caller does not need to manually free it.
370    ///
371    /// # Safety
372    ///
373    /// `index` must be less than [`parameter_count`][BindInfo::parameter_count].
374    pub unsafe fn get_parameter_value(&self, index: u64) -> Value {
375        // SAFETY: index is valid per caller's contract.
376        let raw = unsafe { duckdb_bind_get_parameter(self.info, index) };
377        // SAFETY: raw is a fresh duckdb_value owned by us.
378        unsafe { Value::from_raw(raw) }
379    }
380
381    /// Returns the named parameter as an owned [`Value`].
382    ///
383    /// The returned `Value` is RAII-managed — it will call `duckdb_destroy_value`
384    /// on drop.
385    ///
386    /// # A parameter the caller did not supply
387    ///
388    /// Named parameters are optional in SQL. When the query does not pass
389    /// `name := ...`, `DuckDB` returns a null handle, and so does this: the
390    /// returned `Value` has [`is_null`][Value::is_null] `== true`. Test for
391    /// that, or read it with a defaulting accessor such as
392    /// [`as_i64_or`][Value::as_i64_or], before using a plain getter.
393    ///
394    /// # Safety
395    ///
396    /// `name` must correspond to a named parameter declared for this function.
397    ///
398    /// If `name` contains an interior null byte it is truncated at that point.
399    pub unsafe fn get_named_parameter_value(&self, name: &str) -> Value {
400        let c_name = str_to_cstring(name);
401        // SAFETY: name is valid per caller's contract.
402        let raw = unsafe { duckdb_bind_get_named_parameter(self.info, c_name.as_ptr()) };
403        // SAFETY: raw is a fresh duckdb_value owned by us.
404        unsafe { Value::from_raw(raw) }
405    }
406
407    /// Returns the extra info pointer set on the table function.
408    ///
409    /// # Safety
410    ///
411    /// The caller must ensure the returned pointer (if non-null) is used
412    /// according to its original type.
413    pub unsafe fn get_extra_info(&self) -> *mut c_void {
414        // SAFETY: `self.info` is the live `duckdb_bind_info` of the bind callback in
415        // progress, per the `# Safety` contract of `BindInfo::new`. DuckDB just returns the
416        // stored `extra_info` pointer; how it is used is the caller's obligation under this
417        // function's `# Safety` clause.
418        unsafe { duckdb_bind_get_extra_info(self.info) }
419    }
420
421    /// Returns the client context for this callback.
422    ///
423    /// The returned [`ClientContext`][crate::client_context::ClientContext] provides
424    /// access to the connection's catalog, configuration, and connection ID.
425    ///
426    /// # Safety
427    ///
428    /// The inner handle must be valid (requires `DuckDB` runtime), and the
429    /// returned context must not be used after the connection running this
430    /// query is closed — see
431    /// [`ClientContext`](crate::client_context::ClientContext#lifetime).
432    #[cfg(feature = "duckdb-1-5")]
433    pub unsafe fn get_client_context(&self) -> crate::client_context::ClientContext {
434        let mut ctx: duckdb_client_context = core::ptr::null_mut();
435        // SAFETY: `self.info` is the live `duckdb_bind_info` of the bind callback in
436        // progress, per the `# Safety` contract of `BindInfo::new`. `ctx` is a local
437        // out-parameter DuckDB writes a fresh `new CClientContextWrapper` into
438        // (table_function-c.cpp).
439        unsafe { duckdb_table_function_get_client_context(self.info, &raw mut ctx) };
440        // SAFETY: DuckDB wrote a non-null wrapper into `ctx` (it skips the write only for a
441        // null `info`, which `BindInfo::new`'s contract rules out), freshly allocated for
442        // us, so nothing else destroys it. That the connection outlives the returned
443        // context is this function's own `# Safety` clause, as `from_raw` requires.
444        unsafe { crate::client_context::ClientContext::from_raw(ctx) }
445    }
446
447    /// Returns the raw `duckdb_bind_info` handle.
448    #[must_use]
449    #[inline]
450    pub const fn as_raw(&self) -> duckdb_bind_info {
451        self.info
452    }
453}
454
455/// Helper wrapper around `duckdb_init_info` for use inside init callbacks.
456///
457/// Provides ergonomic methods for the most common init operations.
458pub struct InitInfo {
459    info: duckdb_init_info,
460}
461
462impl InitInfo {
463    /// Wraps a raw `duckdb_init_info`.
464    ///
465    /// # Safety
466    ///
467    /// `info` must be a valid `duckdb_init_info` provided by `DuckDB`.
468    #[inline]
469    #[must_use]
470    pub const unsafe fn new(info: duckdb_init_info) -> Self {
471        Self { info }
472    }
473
474    /// Returns the number of projected (requested) columns.
475    ///
476    /// Only valid when projection pushdown is enabled for the table function.
477    #[cfg_attr(test, mutants::skip)]
478    #[must_use]
479    pub fn projected_column_count(&self) -> usize {
480        // SAFETY: self.info is valid.
481        usize::try_from(unsafe { libduckdb_sys::duckdb_init_get_column_count(self.info) })
482            .unwrap_or(0)
483    }
484
485    /// Returns the declared column index at the given projection position, or
486    /// `None` when `projection_idx` is not less than
487    /// [`projected_column_count`][Self::projected_column_count].
488    ///
489    /// Only meaningful when projection pushdown is enabled.
490    ///
491    /// `duckdb_init_get_column_index` answers an out-of-range position with
492    /// `0` — indistinguishable from "the first declared column" — so the range
493    /// check happens here.
494    #[cfg_attr(test, mutants::skip)]
495    #[must_use]
496    pub fn projected_column_index(&self, projection_idx: usize) -> Option<usize> {
497        if projection_idx >= self.projected_column_count() {
498            return None;
499        }
500        // SAFETY: self.info is valid and `projection_idx` is in range.
501        usize::try_from(unsafe {
502            libduckdb_sys::duckdb_init_get_column_index(self.info, projection_idx as idx_t)
503        })
504        .ok()
505    }
506
507    /// Sets the maximum number of threads for parallel scanning.
508    ///
509    /// The default is 1. Above 1, `DuckDB` may call the scan callback from up
510    /// to `n` threads **at the same time**, whether or not `local_init` is set
511    /// (`local_init` only gives each thread its own state; it is not what
512    /// enables parallelism). All of those calls share the one global init
513    /// data and the one bind data, so after raising this, the scan must not
514    /// use [`FfiInitData::get_mut`][crate::table::FfiInitData::get_mut]; keep
515    /// shared mutable state behind a `Mutex` or atomics instead.
516    #[cfg_attr(test, mutants::skip)]
517    pub fn set_max_threads(&self, n: u64) {
518        // SAFETY: self.info is valid.
519        unsafe { libduckdb_sys::duckdb_init_set_max_threads(self.info, n as idx_t) };
520    }
521
522    /// Reports an error from the init callback.
523    ///
524    /// An interior null byte in `message` is replaced by `?`.
525    /// An empty message is replaced by [`EMPTY_ERROR_PLACEHOLDER`].
526    #[cfg_attr(test, mutants::skip)]
527    pub fn set_error(&self, message: &str) {
528        let c_msg = error_cstring(message, EMPTY_ERROR_PLACEHOLDER);
529        // SAFETY: self.info is valid.
530        unsafe { duckdb_init_set_error(self.info, c_msg.as_ptr()) };
531    }
532
533    /// Returns the extra info pointer set on the table function.
534    ///
535    /// # Safety
536    ///
537    /// The caller must ensure the returned pointer (if non-null) is used
538    /// according to its original type.
539    pub unsafe fn get_extra_info(&self) -> *mut c_void {
540        // SAFETY: `self.info` is the live `duckdb_init_info` of the init callback in
541        // progress, per the `# Safety` contract of `InitInfo::new`. DuckDB just returns the
542        // stored `extra_info` pointer; how it is used is the caller's obligation under this
543        // function's `# Safety` clause.
544        unsafe { duckdb_init_get_extra_info(self.info) }
545    }
546
547    /// Returns the raw `duckdb_init_info` handle.
548    #[must_use]
549    #[inline]
550    pub const fn as_raw(&self) -> duckdb_init_info {
551        self.info
552    }
553}
554
555/// Helper wrapper around `duckdb_function_info` for use inside scan callbacks.
556pub struct FunctionInfo {
557    info: duckdb_function_info,
558}
559
560impl FunctionInfo {
561    /// Wraps a raw `duckdb_function_info`.
562    ///
563    /// # Safety
564    ///
565    /// `info` must be a valid `duckdb_function_info` provided by `DuckDB` in a scan callback.
566    #[inline]
567    #[must_use]
568    pub const unsafe fn new(info: duckdb_function_info) -> Self {
569        Self { info }
570    }
571
572    /// Reports an error from the scan callback.
573    ///
574    /// `DuckDB` will abort the query and propagate this as a SQL error.
575    ///
576    /// An interior null byte in `message` is replaced by `?`.
577    /// An empty message is replaced by [`EMPTY_ERROR_PLACEHOLDER`].
578    #[cfg_attr(test, mutants::skip)]
579    pub fn set_error(&self, message: &str) {
580        let c_msg = error_cstring(message, EMPTY_ERROR_PLACEHOLDER);
581        // SAFETY: self.info is valid.
582        unsafe { duckdb_function_set_error(self.info, c_msg.as_ptr()) };
583    }
584
585    /// Returns the extra info pointer set on the table function.
586    ///
587    /// # Safety
588    ///
589    /// The caller must ensure the returned pointer (if non-null) is used
590    /// according to its original type.
591    pub unsafe fn get_extra_info(&self) -> *mut c_void {
592        // SAFETY: `self.info` is the live `duckdb_function_info` of the scan callback in
593        // progress, per the `# Safety` contract of `FunctionInfo::new`. DuckDB just returns
594        // the stored `extra_info` pointer; how it is used is the caller's obligation under
595        // this function's `# Safety` clause.
596        unsafe { duckdb_function_get_extra_info(self.info) }
597    }
598
599    /// Returns the raw `duckdb_function_info` handle.
600    #[must_use]
601    #[inline]
602    pub const fn as_raw(&self) -> duckdb_function_info {
603        self.info
604    }
605}
606
607crate::debug_repr::impl_handle_debug!(BindInfo.info, InitInfo.info, FunctionInfo.info);
608
609#[cfg(test)]
610mod tests {
611    use super::BindInfo;
612
613    /// A fresh wrapper has reported no error, so the typed bind trampoline
614    /// still raises its own "declared no result columns" error for a bind that
615    /// declared nothing. (The other direction needs `set_error`, which calls
616    /// `duckdb_bind_set_error`; see `.cargo/mutants.toml`.)
617    #[test]
618    fn a_fresh_bind_info_has_reported_no_error() {
619        // SAFETY: the handle is only stored, never passed to DuckDB.
620        let info = unsafe { BindInfo::new(std::ptr::null_mut()) };
621        assert!(!info.error_reported());
622    }
623}