Skip to main content

quack_rs/scalar/
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 wrapper around `duckdb_function_info` for scalar function callbacks.
7
8use std::os::raw::c_void;
9
10#[cfg(feature = "duckdb-1-5")]
11use libduckdb_sys::{
12    duckdb_bind_info, duckdb_client_context, duckdb_copy_callback_t, duckdb_delete_callback_t,
13    duckdb_expression, duckdb_init_info, duckdb_scalar_function_bind_get_argument,
14    duckdb_scalar_function_bind_get_argument_count, duckdb_scalar_function_bind_get_extra_info,
15    duckdb_scalar_function_bind_set_error, duckdb_scalar_function_get_bind_data,
16    duckdb_scalar_function_get_client_context, duckdb_scalar_function_get_state,
17    duckdb_scalar_function_init_get_bind_data, duckdb_scalar_function_init_get_client_context,
18    duckdb_scalar_function_init_get_extra_info, duckdb_scalar_function_init_set_error,
19    duckdb_scalar_function_init_set_state, duckdb_scalar_function_set_bind_data,
20    duckdb_scalar_function_set_bind_data_copy,
21};
22use libduckdb_sys::{
23    duckdb_function_info, duckdb_scalar_function_get_extra_info, duckdb_scalar_function_set_error,
24};
25
26#[cfg(feature = "duckdb-1-5")]
27use crate::expression::Expression;
28
29/// What the scalar `set_error` methods report when given an empty message:
30/// `DuckDB` would otherwise show only an error-type prefix such as
31/// `Invalid Input Error: `.
32pub const EMPTY_ERROR_PLACEHOLDER: &str = "scalar function reported an error without a message";
33
34/// Ergonomic wrapper around the `duckdb_function_info` handle provided to a
35/// scalar function callback.
36///
37/// Provides access to extra info and error reporting.
38///
39/// # Example
40///
41/// ```rust,no_run
42/// use quack_rs::scalar::ScalarFunctionInfo;
43/// use libduckdb_sys::{duckdb_function_info, duckdb_data_chunk, duckdb_vector};
44///
45/// unsafe extern "C" fn my_func(
46///     info: duckdb_function_info,
47///     _input: duckdb_data_chunk,
48///     _output: duckdb_vector,
49/// ) {
50///     let info = unsafe { ScalarFunctionInfo::new(info) };
51///     let _extra = unsafe { info.get_extra_info() };
52///     // ... use extra info ...
53/// }
54/// ```
55pub struct ScalarFunctionInfo {
56    info: duckdb_function_info,
57}
58
59impl ScalarFunctionInfo {
60    /// Wraps a raw `duckdb_function_info` provided by `DuckDB` inside a scalar
61    /// function callback.
62    ///
63    /// # Safety
64    ///
65    /// `info` must be a valid `duckdb_function_info` passed by `DuckDB` to a
66    /// scalar function callback.
67    #[inline]
68    #[must_use]
69    pub const unsafe fn new(info: duckdb_function_info) -> Self {
70        Self { info }
71    }
72
73    /// Retrieves the extra-info pointer previously set via
74    /// [`ScalarFunctionBuilder::extra_info`][crate::scalar::ScalarFunctionBuilder::extra_info].
75    ///
76    /// Returns a raw `*mut c_void`. Cast it back to your concrete type.
77    ///
78    /// # Safety
79    ///
80    /// The returned pointer is only valid as long as the scalar function is
81    /// registered and `DuckDB` has not yet called the destructor.
82    #[must_use]
83    pub unsafe fn get_extra_info(&self) -> *mut c_void {
84        // SAFETY: self.info is valid per constructor contract.
85        unsafe { duckdb_scalar_function_get_extra_info(self.info) }
86    }
87
88    /// Reports an error from the scalar function callback, causing `DuckDB`
89    /// to abort the current query.
90    ///
91    /// An interior NUL byte in `message` is replaced with `?`
92    /// (see [`message_to_c_string`][crate::callback::message_to_c_string]),
93    /// and an empty message by [`EMPTY_ERROR_PLACEHOLDER`], since `DuckDB`
94    /// would otherwise report only an error-type prefix.
95    #[cfg_attr(test, mutants::skip)]
96    pub fn set_error(&self, message: &str) {
97        let c_msg = crate::table::cstr::error_cstring(message, EMPTY_ERROR_PLACEHOLDER);
98        // SAFETY: self.info is valid per constructor contract.
99        unsafe {
100            duckdb_scalar_function_set_error(self.info, c_msg.as_ptr());
101        }
102    }
103
104    /// Returns the raw `duckdb_function_info` handle.
105    #[must_use]
106    #[inline]
107    pub const fn as_raw(&self) -> duckdb_function_info {
108        self.info
109    }
110
111    /// Retrieves the bind data pointer previously set via
112    /// [`ScalarBindInfo::set_bind_data`] during the bind callback.
113    ///
114    /// Returns a raw `*mut c_void`. Cast it back to your concrete type.
115    ///
116    /// # Safety
117    ///
118    /// The returned pointer is only valid as long as `DuckDB` has not yet called
119    /// the destructor registered with [`ScalarBindInfo::set_bind_data`].
120    #[cfg(feature = "duckdb-1-5")]
121    #[must_use]
122    pub unsafe fn get_bind_data(&self) -> *mut c_void {
123        // SAFETY: self.info is valid per constructor contract.
124        unsafe { duckdb_scalar_function_get_bind_data(self.info) }
125    }
126
127    /// Retrieves the per-thread state pointer previously set via
128    /// [`ScalarInitInfo::set_state`] during the init callback.
129    ///
130    /// Returns a raw `*mut c_void`. Cast it back to your concrete type.
131    ///
132    /// # Safety
133    ///
134    /// The returned pointer is only valid as long as `DuckDB` has not yet called
135    /// the destructor registered with [`ScalarInitInfo::set_state`].
136    #[cfg(feature = "duckdb-1-5")]
137    #[must_use]
138    pub unsafe fn get_state(&self) -> *mut c_void {
139        // SAFETY: self.info is valid per constructor contract.
140        unsafe { duckdb_scalar_function_get_state(self.info) }
141    }
142}
143
144/// The argument `DuckDB` passes to a scalar function **bind** callback: a
145/// `duckdb_bind_info`, in a type of its own.
146///
147/// A table function's bind callback receives a `duckdb_bind_info` too, but
148/// `DuckDB` casts it to a different, larger struct, so a callback written for
149/// one kind of function corrupts memory when registered on the other (a
150/// table bind's `duckdb_bind_set_error` writes past the scalar bind info).
151/// With its own argument type, [`ScalarBindFn`][crate::scalar::ScalarBindFn]
152/// no longer accepts a table callback, and a scalar callback no longer fits a
153/// table function's `bind`. `#[repr(transparent)]`, so the C ABI is the
154/// pointer's.
155///
156/// ```rust,compile_fail
157/// use quack_rs::scalar::ScalarFunctionBuilder;
158/// quack_rs::table_bind_callback!(table_bind, |_info| {});
159/// // Does not compile: a table bind callback takes a `duckdb_bind_info`.
160/// let _ = ScalarFunctionBuilder::new("f").bind(table_bind);
161/// ```
162#[cfg(feature = "duckdb-1-5")]
163#[repr(transparent)]
164#[derive(Clone, Copy, Debug)]
165pub struct RawScalarBindInfo(pub duckdb_bind_info);
166
167/// The argument `DuckDB` passes to a scalar function **init** callback; see
168/// [`RawScalarBindInfo`] for why it has a type of its own.
169///
170/// ```rust,compile_fail
171/// use quack_rs::scalar::ScalarFunctionBuilder;
172/// quack_rs::table_init_callback!(table_init, |_info| {});
173/// // Does not compile: a table init callback takes a `duckdb_init_info`.
174/// let _ = ScalarFunctionBuilder::new("f").init(table_init);
175/// ```
176#[cfg(feature = "duckdb-1-5")]
177#[repr(transparent)]
178#[derive(Clone, Copy, Debug)]
179pub struct RawScalarInitInfo(pub duckdb_init_info);
180
181/// Ergonomic wrapper around the `duckdb_bind_info` handle provided to a
182/// scalar function bind callback (`DuckDB` 1.5.0+).
183///
184/// Provides access to function arguments, extra info, bind data storage,
185/// and error reporting.
186#[cfg(feature = "duckdb-1-5")]
187pub struct ScalarBindInfo {
188    info: duckdb_bind_info,
189    /// The value the last [`ScalarBindData::set`][crate::scalar::ScalarBindData::set]
190    /// through this wrapper stored, with its destructor, so that a second
191    /// `set` can free it: `DuckDB` overwrites the pointer without running the
192    /// destructor (`duckdb_scalar_function_set_bind_data`, read at v1.5.6 and
193    /// v2.0.0). Cleared by [`set_bind_data`][Self::set_bind_data], whose
194    /// pointers are the caller's.
195    typed: core::cell::Cell<Option<TypedBindData>>,
196}
197
198/// A bind-data pointer and the destructor that frees it.
199#[cfg(feature = "duckdb-1-5")]
200pub(crate) type TypedBindData = (*mut c_void, unsafe extern "C" fn(*mut c_void));
201
202#[cfg(feature = "duckdb-1-5")]
203impl ScalarBindInfo {
204    /// Wraps the info `DuckDB` passes to a scalar function bind callback.
205    ///
206    /// **Breaking** in 0.18.0: takes a [`RawScalarBindInfo`], the argument type
207    /// of [`ScalarBindFn`][crate::scalar::ScalarBindFn], not a bare
208    /// `duckdb_bind_info`.
209    ///
210    /// # Safety
211    ///
212    /// `info` must be the argument `DuckDB` passed to a scalar function bind
213    /// callback that is still running.
214    #[inline]
215    #[must_use]
216    pub const unsafe fn new(info: RawScalarBindInfo) -> Self {
217        Self {
218            info: info.0,
219            typed: core::cell::Cell::new(None),
220        }
221    }
222
223    /// Records `stored` as the value [`ScalarBindData::set`][crate::scalar::ScalarBindData::set]
224    /// just stored through this wrapper, returning the one it replaced.
225    pub(crate) fn replace_typed_bind_data(&self, stored: TypedBindData) -> Option<TypedBindData> {
226        self.typed.replace(Some(stored))
227    }
228
229    /// Forgets the recorded value, returning it.
230    pub(crate) fn take_typed_bind_data(&self) -> Option<TypedBindData> {
231        self.typed.take()
232    }
233
234    /// Returns the number of arguments passed to the scalar function.
235    #[cfg_attr(test, mutants::skip)]
236    #[must_use]
237    pub fn argument_count(&self) -> u64 {
238        // SAFETY: self.info is valid per constructor contract.
239        unsafe { duckdb_scalar_function_bind_get_argument_count(self.info) }
240    }
241
242    /// Returns the argument expression at `index`.
243    ///
244    /// # Safety
245    ///
246    /// - `index` must be less than [`argument_count`][Self::argument_count].
247    ///   The returned `duckdb_expression` handle is owned by the caller and
248    ///   must be used according to `DuckDB` expression API rules.
249    /// - On `DuckDB` before v1.5.5 the argument must be one `DuckDB` can copy.
250    ///   Those releases copy the expression outside any `try`, and copying a
251    ///   scalar subquery (`f((SELECT 1))`) throws a C++ exception through
252    ///   this call, which aborts the process. [`argument`][Self::argument]
253    ///   checks the engine version for you.
254    #[must_use]
255    pub unsafe fn get_argument(&self, index: u64) -> duckdb_expression {
256        // SAFETY: self.info is valid per constructor contract; caller guarantees index.
257        unsafe { duckdb_scalar_function_bind_get_argument(self.info, index) }
258    }
259
260    /// Returns the argument at `index` as an RAII [`Expression`], or `None` if
261    /// `DuckDB` returns a null handle.
262    ///
263    /// This is the ergonomic counterpart to [`get_argument`][Self::get_argument]:
264    /// the returned [`Expression`] is destroyed automatically on drop and exposes
265    /// safe accessors for the argument's return type and constant folding.
266    ///
267    /// Which expression that is depends on the engine. Up to `DuckDB` 1.5.x
268    /// it is the argument as the query wrote it, before `DuckDB` casts it to
269    /// the declared parameter type (the bind callback runs before
270    /// `CastToFunctionArguments` in `FunctionBinder::BindScalarFunction`):
271    /// for a `BIGINT` parameter, `f(40 + 2)` reports an `INTEGER` return type,
272    /// and folds to an `INTEGER` value. From 2.0.0 the callback runs after the
273    /// cast (`FunctionBinder::ResolveFunction`), so the same argument reports
274    /// `BIGINT` and folds to a `BIGINT`. Code that must behave the same on
275    /// both should read values with a casting getter such as
276    /// [`Value::as_i64`][crate::value::Value::as_i64] rather than branch on
277    /// the argument's type.
278    ///
279    /// # Asking for an argument can fail the query
280    ///
281    /// `DuckDB` copies the argument's expression to hand it out, and some
282    /// expressions cannot be copied — a scalar subquery, as in
283    /// `f((SELECT 'x'))`, for one. `duckdb_scalar_function_bind_get_argument`
284    /// then marks the bind as failed itself (`scalar_function-c.cpp`) and
285    /// returns null, so the query fails whatever the callback does next, and
286    /// the C API has no way to ask first. This returns `None` in that case and
287    /// replaces `DuckDB`'s message — a raw JSON exception such as
288    /// `{"exception_type":"Serialization",…}` — with one that says what
289    /// happened. A bind callback that can do without an argument should not
290    /// ask for it.
291    ///
292    /// That holds from `DuckDB` v1.5.5. Releases v1.5.0 to v1.5.4 copy the
293    /// expression outside any `try`, so the same subquery throws a C++
294    /// exception through the C API, which aborts a Rust process. On those
295    /// releases (and on development builds that predate v1.5.5's fix) this
296    /// therefore asks for no argument at all: it fails the bind with a message
297    /// saying why and returns `None`.
298    ///
299    /// # Safety
300    ///
301    /// `index` must be less than [`argument_count`][Self::argument_count].
302    #[must_use]
303    pub unsafe fn argument(&self, index: u64) -> Option<Expression> {
304        // SAFETY: a bind callback runs with the dispatch table initialised.
305        let engine = unsafe { crate::abi::engine_version() };
306        if !engine
307            .as_deref()
308            .is_some_and(get_argument_catches_copy_failures)
309        {
310            self.set_error(&format!(
311                "argument {index} of this scalar function cannot be inspected at bind time on \
312                 DuckDB {}: before v1.5.5, DuckDB aborts the process when the argument is a \
313                 scalar subquery, and there is no way to tell first. Upgrade to DuckDB v1.5.5 \
314                 or later, or do not inspect arguments in the bind callback",
315                engine.as_deref().unwrap_or("(unknown version)")
316            ));
317            return None;
318        }
319        // SAFETY: self.info is valid per constructor contract; caller guarantees index.
320        // The engine catches a failed copy (checked above), so nothing throws.
321        let raw = unsafe { duckdb_scalar_function_bind_get_argument(self.info, index) };
322        if raw.is_null() {
323            // DuckDB returns null without an error only for an index out of
324            // range; for any other index a null means the copy threw and the
325            // bind is already failed. Its error is a plain assignment, so this
326            // message replaces the JSON one.
327            if index < self.argument_count() {
328                self.set_error(&format!(
329                    "argument {index} of this scalar function cannot be inspected at bind \
330                     time: DuckDB could not copy its expression (a scalar subquery cannot be \
331                     copied), and it fails the query when a bind callback asks for such an \
332                     argument"
333                ));
334            }
335            None
336        } else {
337            // SAFETY: raw is a non-null, owned duckdb_expression handle.
338            Some(unsafe { Expression::from_raw(raw) })
339        }
340    }
341
342    /// Retrieves the extra-info pointer previously set via
343    /// [`ScalarFunctionBuilder::extra_info`][crate::scalar::ScalarFunctionBuilder::extra_info].
344    ///
345    /// Returns a raw `*mut c_void`. Cast it back to your concrete type.
346    ///
347    /// # Safety
348    ///
349    /// The returned pointer is only valid as long as the scalar function is
350    /// registered and `DuckDB` has not yet called the destructor.
351    #[must_use]
352    pub unsafe fn get_extra_info(&self) -> *mut c_void {
353        // SAFETY: self.info is valid per constructor contract.
354        unsafe { duckdb_scalar_function_bind_get_extra_info(self.info) }
355    }
356
357    /// Stores per-query bind data that can later be retrieved during execution
358    /// via [`ScalarFunctionInfo::get_bind_data`].
359    ///
360    /// Prefer [`ScalarBindData::set`][crate::scalar::ScalarBindData::set],
361    /// which generates the destructor *and* the copy callback.
362    ///
363    /// # Pair this with [`set_bind_data_copy`][Self::set_bind_data_copy]
364    ///
365    /// `DuckDB` copies a bound expression whenever it duplicates a plan — and
366    /// when no copy callback is registered, the copy's bind data is **null**,
367    /// not a duplicate of yours. From `DuckDB`'s
368    /// `src/main/capi/scalar_function-c.cpp`:
369    ///
370    /// ```cpp
371    /// unique_ptr<FunctionData> Copy() const override {
372    ///     auto copy = make_uniq<CScalarFunctionBindData>(info);
373    ///     if (copy_callback) {
374    ///         copy->bind_data = copy_callback(bind_data);
375    ///         // ...
376    ///     }
377    ///     return std::move(copy);   // bind_data stays null without a callback
378    /// }
379    /// ```
380    ///
381    /// The execute callback then sees a null pointer from
382    /// [`ScalarFunctionInfo::get_bind_data`] on the copied expression. That is
383    /// a **silent wrong answer**, not a crash, so always register a copy
384    /// callback alongside any bind data you rely on at execution time.
385    ///
386    /// Written up as [Pitfall L10](https://quack-rs.com/reference/pitfalls.html#l10-scalar-bind-data-is-dropped-when-duckdb-copies-the-expression).
387    ///
388    /// # Calling it twice
389    ///
390    /// A second call overwrites the pointer and destructor without running the
391    /// first destructor: the first value is leaked. So is a value an earlier
392    /// [`ScalarBindData::set`][crate::scalar::ScalarBindData::set] stored
393    /// (only a second `ScalarBindData::set` through the same wrapper frees
394    /// it).
395    ///
396    /// # Identical calls share bind data
397    ///
398    /// `DuckDB` merges two calls with the same arguments without comparing
399    /// their bind data, so the value stored here must depend only on the
400    /// arguments, their types and `extra_info` — or the function must be
401    /// volatile. See [`ScalarBindData`][crate::scalar::ScalarBindData].
402    ///
403    /// # Safety
404    ///
405    /// `data` must point to valid memory. `destroy` will be called by `DuckDB`
406    /// to free the data when the query finishes. The typical pattern is to box
407    /// your data: `Box::into_raw(Box::new(my_data)).cast()`. `DuckDB` reads the
408    /// data from every executing thread at once, so it must be safe to share
409    /// across threads (`Sync`) and to free from any of them (`Send`).
410    ///
411    /// A copy callback registered earlier in this bind — by
412    /// [`set_bind_data_copy`][Self::set_bind_data_copy], or by
413    /// [`ScalarBindData::set`][crate::scalar::ScalarBindData::set] — stays in
414    /// effect: this call replaces only the pointer and the destructor
415    /// (`duckdb_scalar_function_set_bind_data`), and `DuckDB` applies the old
416    /// copy callback to the new `data` whenever it copies the expression. So
417    /// `data` must be of the type that callback expects, or a matching copy
418    /// callback must be registered after this call.
419    pub unsafe fn set_bind_data(&self, data: *mut c_void, destroy: duckdb_delete_callback_t) {
420        // What this replaces is no longer a value `ScalarBindData::set` may
421        // free: the caller may hand the same pointer back.
422        self.typed.set(None);
423        // SAFETY: self.info is valid per constructor contract.
424        unsafe {
425            duckdb_scalar_function_set_bind_data(self.info, data, destroy);
426        }
427    }
428
429    /// Registers the callback `DuckDB` uses to duplicate the bind data set by
430    /// [`set_bind_data`][Self::set_bind_data] when it copies a bound
431    /// expression.
432    ///
433    /// Without this, a copied expression carries **null** bind data — see
434    /// [`set_bind_data`][Self::set_bind_data] for the upstream code that does
435    /// it. Registering a copy callback is therefore not an optimisation; it is
436    /// what makes bind data survive.
437    ///
438    /// `copy` receives the pointer passed to `set_bind_data` and must return a
439    /// pointer to an **independently owned** duplicate. `DuckDB` frees the
440    /// duplicate with the same `destroy` callback given to `set_bind_data`, so
441    /// the two must agree on ownership — returning the same pointer twice is a
442    /// double free.
443    ///
444    /// # Order
445    ///
446    /// `DuckDB` stores the copy callback on the same bind-data slot, so call
447    /// this **after** [`set_bind_data`][Self::set_bind_data] within one bind
448    /// callback.
449    ///
450    /// # Example
451    ///
452    /// ```rust,no_run
453    /// use std::os::raw::c_void;
454    ///
455    /// struct MyBindData {
456    ///     pattern: String,
457    /// }
458    ///
459    /// unsafe extern "C" fn destroy(data: *mut c_void) {
460    ///     if !data.is_null() {
461    ///         drop(unsafe { Box::from_raw(data.cast::<MyBindData>()) });
462    ///     }
463    /// }
464    ///
465    /// unsafe extern "C" fn copy(data: *mut c_void) -> *mut c_void {
466    ///     if data.is_null() {
467    ///         return std::ptr::null_mut();
468    ///     }
469    ///     // Clone into a fresh allocation; `destroy` frees each one once.
470    ///     let src = unsafe { &*data.cast::<MyBindData>() };
471    ///     let dup = Box::new(MyBindData {
472    ///         pattern: src.pattern.clone(),
473    ///     });
474    ///     Box::into_raw(dup).cast()
475    /// }
476    ///
477    /// // Inside a bind callback holding a `ScalarBindInfo`:
478    /// // let boxed = Box::new(MyBindData { pattern: "%x%".to_owned() });
479    /// // unsafe {
480    /// //     bind_info.set_bind_data(Box::into_raw(boxed).cast(), Some(destroy));
481    /// //     bind_info.set_bind_data_copy(Some(copy));
482    /// // }
483    /// ```
484    ///
485    /// # Safety
486    ///
487    /// `copy` must return a pointer that is valid to free with the `destroy`
488    /// callback registered by [`set_bind_data`][Self::set_bind_data], and must
489    /// not alias the pointer it was given. It must not unwind: it runs across
490    /// an FFI boundary, so wrap any panicking work in
491    /// [`catch_ffi_panic`][crate::callback::catch_ffi_panic] and return null on
492    /// failure.
493    pub unsafe fn set_bind_data_copy(&self, copy: duckdb_copy_callback_t) {
494        // SAFETY: self.info is valid per constructor contract; `copy` is either
495        // None or a function pointer whose contract the caller upholds.
496        unsafe {
497            duckdb_scalar_function_set_bind_data_copy(self.info, copy);
498        }
499    }
500
501    /// Reports an error from the scalar function bind callback, causing
502    /// `DuckDB` to abort the current query.
503    ///
504    /// An interior NUL byte in `message` is replaced with `?`
505    /// (see [`message_to_c_string`][crate::callback::message_to_c_string]),
506    /// and an empty message by [`EMPTY_ERROR_PLACEHOLDER`], since `DuckDB`
507    /// would otherwise report only an error-type prefix.
508    #[cfg_attr(test, mutants::skip)]
509    pub fn set_error(&self, message: &str) {
510        let c_msg = crate::table::cstr::error_cstring(message, EMPTY_ERROR_PLACEHOLDER);
511        // SAFETY: self.info is valid per constructor contract.
512        unsafe {
513            duckdb_scalar_function_bind_set_error(self.info, c_msg.as_ptr());
514        }
515    }
516
517    /// Returns the client context for this callback.
518    ///
519    /// The returned [`ClientContext`][crate::client_context::ClientContext] provides
520    /// access to the connection's catalog, configuration, and connection ID.
521    ///
522    /// # Safety
523    ///
524    /// The inner handle must be valid (requires `DuckDB` runtime), and the
525    /// returned context must not be used after the connection running this
526    /// query is closed — see
527    /// [`ClientContext`](crate::client_context::ClientContext#lifetime).
528    pub unsafe fn get_client_context(&self) -> crate::client_context::ClientContext {
529        let mut ctx: duckdb_client_context = core::ptr::null_mut();
530        // SAFETY: self.info is a valid bind-info handle per this fn's contract;
531        // the call writes the client-context handle into `ctx`.
532        unsafe { duckdb_scalar_function_get_client_context(self.info, &raw mut ctx) };
533        // SAFETY: `ctx` was just populated by DuckDB with a client-context handle.
534        unsafe { crate::client_context::ClientContext::from_raw(ctx) }
535    }
536
537    /// Returns the raw `duckdb_bind_info` handle.
538    #[cfg_attr(test, mutants::skip)]
539    #[must_use]
540    #[inline]
541    pub const fn as_raw(&self) -> duckdb_bind_info {
542        self.info
543    }
544}
545
546/// Ergonomic wrapper around the `duckdb_init_info` handle provided to a
547/// scalar function init callback (`DuckDB` 1.5.0+).
548///
549/// Provides access to extra info, bind data, per-thread state storage,
550/// and error reporting.
551#[cfg(feature = "duckdb-1-5")]
552pub struct ScalarInitInfo {
553    info: duckdb_init_info,
554}
555
556#[cfg(feature = "duckdb-1-5")]
557impl ScalarInitInfo {
558    /// Wraps the info `DuckDB` passes to a scalar function init callback.
559    ///
560    /// **Breaking** in 0.18.0: takes a [`RawScalarInitInfo`], the argument type
561    /// of [`ScalarInitFn`][crate::scalar::ScalarInitFn], not a bare
562    /// `duckdb_init_info`.
563    ///
564    /// # Safety
565    ///
566    /// `info` must be the argument `DuckDB` passed to a scalar function init
567    /// callback that is still running.
568    #[inline]
569    #[must_use]
570    pub const unsafe fn new(info: RawScalarInitInfo) -> Self {
571        Self { info: info.0 }
572    }
573
574    /// Retrieves the extra-info pointer previously set via
575    /// [`ScalarFunctionBuilder::extra_info`][crate::scalar::ScalarFunctionBuilder::extra_info].
576    ///
577    /// Returns a raw `*mut c_void`. Cast it back to your concrete type.
578    ///
579    /// # Safety
580    ///
581    /// The returned pointer is only valid as long as the scalar function is
582    /// registered and `DuckDB` has not yet called the destructor.
583    #[must_use]
584    pub unsafe fn get_extra_info(&self) -> *mut c_void {
585        // SAFETY: self.info is valid per constructor contract.
586        unsafe { duckdb_scalar_function_init_get_extra_info(self.info) }
587    }
588
589    /// Retrieves the bind data pointer previously set via
590    /// [`ScalarBindInfo::set_bind_data`] during the bind callback.
591    ///
592    /// Returns a raw `*mut c_void`. Cast it back to your concrete type.
593    ///
594    /// # Safety
595    ///
596    /// The returned pointer is only valid as long as `DuckDB` has not yet called
597    /// the destructor registered with [`ScalarBindInfo::set_bind_data`].
598    #[must_use]
599    pub unsafe fn get_bind_data(&self) -> *mut c_void {
600        // SAFETY: self.info is valid per constructor contract.
601        unsafe { duckdb_scalar_function_init_get_bind_data(self.info) }
602    }
603
604    /// Stores per-thread state that can later be retrieved during execution
605    /// via [`ScalarFunctionInfo::get_state`].
606    ///
607    /// A second call overwrites the pointer and destructor without running the
608    /// first destructor: the first value is leaked.
609    ///
610    /// # Safety
611    ///
612    /// `state` must point to valid memory. `destroy` will be called by `DuckDB`
613    /// to free the state when the thread finishes. The typical pattern is to box
614    /// your data: `Box::into_raw(Box::new(my_state)).cast()`.
615    pub unsafe fn set_state(&self, state: *mut c_void, destroy: duckdb_delete_callback_t) {
616        // SAFETY: self.info is valid per constructor contract.
617        unsafe {
618            duckdb_scalar_function_init_set_state(self.info, state, destroy);
619        }
620    }
621
622    /// Reports an error from the scalar function init callback, causing
623    /// `DuckDB` to abort the current query.
624    ///
625    /// An interior NUL byte in `message` is replaced with `?`
626    /// (see [`message_to_c_string`][crate::callback::message_to_c_string]),
627    /// and an empty message by [`EMPTY_ERROR_PLACEHOLDER`], since `DuckDB`
628    /// would otherwise report only an error-type prefix.
629    #[cfg_attr(test, mutants::skip)]
630    pub fn set_error(&self, message: &str) {
631        let c_msg = crate::table::cstr::error_cstring(message, EMPTY_ERROR_PLACEHOLDER);
632        // SAFETY: self.info is valid per constructor contract.
633        unsafe {
634            duckdb_scalar_function_init_set_error(self.info, c_msg.as_ptr());
635        }
636    }
637
638    /// Returns the client context for this callback.
639    ///
640    /// The returned [`ClientContext`][crate::client_context::ClientContext] provides
641    /// access to the connection's catalog, configuration, and connection ID.
642    ///
643    /// # Safety
644    ///
645    /// The inner handle must be valid (requires `DuckDB` runtime), and the
646    /// returned context must not be used after the connection running this
647    /// query is closed — see
648    /// [`ClientContext`](crate::client_context::ClientContext#lifetime).
649    pub unsafe fn get_client_context(&self) -> crate::client_context::ClientContext {
650        let mut ctx: duckdb_client_context = core::ptr::null_mut();
651        // SAFETY: self.info is a valid init-info handle per this fn's contract;
652        // the call writes the client-context handle into `ctx`.
653        unsafe { duckdb_scalar_function_init_get_client_context(self.info, &raw mut ctx) };
654        // SAFETY: `ctx` was just populated by DuckDB with a client-context handle.
655        unsafe { crate::client_context::ClientContext::from_raw(ctx) }
656    }
657
658    /// Returns the raw `duckdb_init_info` handle.
659    #[cfg_attr(test, mutants::skip)]
660    #[must_use]
661    #[inline]
662    pub const fn as_raw(&self) -> duckdb_init_info {
663        self.info
664    }
665}
666
667crate::debug_repr::impl_handle_debug!(ScalarFunctionInfo.info);
668
669#[cfg(feature = "duckdb-1-5")]
670crate::debug_repr::impl_handle_debug!(ScalarBindInfo.info, ScalarInitInfo.info);
671
672/// Whether `duckdb_scalar_function_bind_get_argument` in the engine reporting
673/// `engine` catches a failed copy of the argument. It does from v1.5.5: the
674/// function body has no `try` at tags v1.5.0 to v1.5.4 and one at v1.5.5
675/// (`src/main/capi/scalar_function-c.cpp`). A pre-release or development build
676/// (`v1.5.5-dev42`) precedes its release, so it counts only if its base is
677/// later than v1.5.5; an engine version that does not parse does not count.
678#[cfg(feature = "duckdb-1-5")]
679fn get_argument_catches_copy_failures(engine: &str) -> bool {
680    const FIXED: (u64, u64, u64) = (1, 5, 5);
681    let (base, pre_release) = engine
682        .split_once('-')
683        .map_or((engine, false), |(b, _)| (b, true));
684    crate::abi::parse_version(base).is_some_and(|version| {
685        if pre_release {
686            version > FIXED
687        } else {
688            version >= FIXED
689        }
690    })
691}
692
693#[cfg(test)]
694mod tests {
695
696    /// `duckdb_scalar_function_bind_get_argument` has no `try` at `DuckDB` tags
697    /// v1.5.0 to v1.5.4 and one at v1.5.5, so only v1.5.5 and later, or a
698    /// development build of a later release, may be asked for an argument.
699    #[cfg(feature = "duckdb-1-5")]
700    #[test]
701    fn only_engines_that_catch_a_failed_copy_are_asked_for_an_argument() {
702        use super::get_argument_catches_copy_failures as catches;
703        for engine in [
704            "v1.5.5",
705            "v1.5.6",
706            "v1.6.0",
707            "v2.0.0",
708            "v1.5.6-dev42",
709            "1.5.5",
710        ] {
711            assert!(catches(engine), "{engine}");
712        }
713        for engine in [
714            "v1.5.0",
715            "v1.5.4",
716            "v1.4.4",
717            "v1.5.5-dev42",
718            "v1.5.5-rc1",
719            "0d3cd0e22e",
720            "",
721        ] {
722            assert!(!catches(engine), "{engine}");
723        }
724    }
725    use super::*;
726
727    #[test]
728    fn scalar_function_info_as_raw_roundtrip() {
729        let raw = std::ptr::null_mut();
730        let info = unsafe { ScalarFunctionInfo::new(raw) };
731        assert_eq!(info.as_raw(), raw);
732    }
733
734    #[cfg(feature = "duckdb-1-5")]
735    #[test]
736    fn scalar_bind_info_as_raw_roundtrip() {
737        let raw = std::ptr::null_mut();
738        let info = unsafe { ScalarBindInfo::new(RawScalarBindInfo(raw)) };
739        assert_eq!(info.as_raw(), raw);
740    }
741
742    #[cfg(feature = "duckdb-1-5")]
743    #[test]
744    fn scalar_init_info_as_raw_roundtrip() {
745        let raw = std::ptr::null_mut();
746        let info = unsafe { ScalarInitInfo::new(RawScalarInitInfo(raw)) };
747        assert_eq!(info.as_raw(), raw);
748    }
749}