Skip to main content

quack_rs/
callback.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//! Panic-safe callback wrapper macros for `DuckDB` extension callbacks.
7//!
8//! Every `DuckDB` callback is an `unsafe extern "C" fn`, and a Rust panic that
9//! reaches that boundary aborts the process — taking the user's `DuckDB` session,
10//! and any application embedding it, with it. These macros wrap the body in
11//! [`std::panic::catch_unwind`] and route the panic message to whichever
12//! `set_error` `DuckDB` provides for that callback kind, so a bug in extension
13//! code becomes an ordinary SQL error.
14//!
15//! # Macros
16//!
17//! | Macro | Wraps | Reports through |
18//! |-------|-------|-----------------|
19//! | `scalar_callback!` | scalar function execution | `duckdb_scalar_function_set_error` |
20//! | `table_bind_callback!` | table function bind | `duckdb_bind_set_error` |
21//! | `table_init_callback!` | table function init / local init | `duckdb_init_set_error` |
22//! | `scalar_bind_callback!` | scalar function bind (`duckdb-1-5`) | `duckdb_scalar_function_bind_set_error` |
23//! | `scalar_init_callback!` | scalar function init (`duckdb-1-5`) | `duckdb_scalar_function_init_set_error` |
24//! | `table_scan_callback!` | table function scan | `duckdb_function_set_error`, then chunk size 0 |
25//! | `aggregate_update_callback!` | aggregate update | `duckdb_aggregate_function_set_error` |
26//! | `aggregate_combine_callback!` | aggregate combine | `duckdb_aggregate_function_set_error` |
27//! | `aggregate_finalize_callback!` | aggregate finalize | `duckdb_aggregate_function_set_error` |
28//! | `aggregate_destroy_callback!` | aggregate state destructor | *(no error channel — panic is swallowed)* |
29//! | `cast_callback!` | cast function | `duckdb_cast_function_set_error`, returns `false` |
30//! | `replacement_scan_callback!` | replacement scan | `duckdb_replacement_scan_set_error` |
31//!
32//! # `panic = "abort"`
33//!
34//! `catch_unwind` cannot catch anything when the crate is built with
35//! `panic = "abort"`, which silently disables everything in this module. Keep
36//! extension crates on `panic = "unwind"` — the quack-rs scaffold generates that,
37//! and [`entry_point!`][crate::entry_point!] and
38//! [`entry_point_v2!`][crate::entry_point_v2!] refuse to compile without it.
39//!
40//! # What no guard can catch
41//!
42//! Some failures abort the process, and with it the `DuckDB` host, whatever
43//! quack-rs does: a panic raised while another panic is already unwinding (a
44//! `Drop` that panics during the unwind: Rust prints "panic in a destructor
45//! during cleanup" and aborts), a panic hook that itself panics, and running
46//! out of memory (Rust's default allocation-error handler aborts, also when
47//! the allocation is the one that formats a panic's message). A caught panic is
48//! still reported by the panic hook, which by default prints it to stderr.
49//!
50//! # The body returns `()`
51//!
52//! A body runs under `catch_unwind`, and its value is discarded. So
53//! every body except `cast_callback!`'s (which returns the cast's `bool`) must
54//! have type `()`: a body that used `?` would otherwise compile, and the error
55//! it returned would be dropped without being reported.
56//!
57//! ```rust,compile_fail,E0308
58//! quack_rs::scalar_callback!(parse_or_drop, |info, input, output| {
59//!     let _n: i64 = "not a number".parse()?; // dropped, not reported
60//!     Ok::<(), std::num::ParseIntError>(())
61//! });
62//! ```
63//!
64//! Report such an error with the callback's `set_error` instead.
65//!
66//! # The body is not an `unsafe` context
67//!
68//! The generated function is an `unsafe extern "C" fn`, but the body is
69//! expanded as an ordinary nested `fn`, so an unsafe operation in it needs its
70//! own `unsafe` block, as anywhere else in safe code. Until the fifth audit the
71//! body was a closure inside the `unsafe fn` and inherited its unsafe context:
72//! on edition 2021 this compiled with no `unsafe` keyword and no warning.
73//!
74//! ```rust,compile_fail,E0133
75//! quack_rs::scalar_callback!(reads_a_raw_pointer, |info, input, output| {
76//!     let _ = (info, output);
77//!     let _first_byte = *input.cast::<u8>();
78//! });
79//! ```
80//!
81//! ```rust,compile_fail,E0133
82//! quack_rs::cast_callback!(casts_by_hand, |info, count, input, output| {
83//!     let _ = (info, count, output);
84//!     *input.cast::<u8>() == 0
85//! });
86//! ```
87//!
88//! # Example: Scalar callback
89//!
90//! ```rust,no_run
91//! use quack_rs::data_chunk::DataChunk;
92//! use quack_rs::vector::VectorWriter;
93//!
94//! quack_rs::scalar_callback!(my_func, |info, input, output| {
95//!     let chunk = unsafe { DataChunk::from_raw(input) };
96//!     let reader = unsafe { chunk.reader(0) }; // once per chunk, not per row
97//!     let mut writer = unsafe { VectorWriter::from_vector(output) };
98//!     for row in 0..chunk.size() {
99//!         let val = unsafe { reader.read_i64(row) };
100//!         unsafe { writer.write_i64(row, val * 2) };
101//!     }
102//! });
103//! ```
104//!
105//! # Example: Table scan callback
106//!
107//! ```rust,no_run
108//! use quack_rs::data_chunk::DataChunk;
109//!
110//! quack_rs::table_scan_callback!(my_scan, |info, output| {
111//!     let chunk = unsafe { DataChunk::from_raw(output) };
112//!     let mut writer = unsafe { chunk.writer(0) };
113//!     unsafe { writer.write_i64(0, 42) };
114//!     unsafe { chunk.set_size(1) };
115//! });
116//! ```
117
118mod payload;
119
120pub use payload::{drop_panic_payload, take_panic_message, MAX_NESTED_PAYLOAD_DROPS};
121
122/// Generates a panic-safe `unsafe extern "C"` scalar function callback.
123///
124/// The macro emits a function with signature:
125/// ```text
126/// unsafe extern "C" fn $name(
127///     info: duckdb_function_info,
128///     input: duckdb_data_chunk,
129///     output: duckdb_vector,
130/// )
131/// ```
132///
133/// The body is wrapped in `std::panic::catch_unwind`. If the closure panics,
134/// the error is reported via `duckdb_scalar_function_set_error` and the
135/// function returns without unwinding across the FFI boundary.
136///
137/// # Parameters
138///
139/// - `$name` — the name of the generated function
140/// - `$body` — a closure with signature `|info: duckdb_function_info, input: duckdb_data_chunk, output: duckdb_vector|`
141///
142/// # Example
143///
144/// ```rust,no_run
145/// quack_rs::scalar_callback!(double_it, |info, input, output| {
146///     let chunk = unsafe { quack_rs::data_chunk::DataChunk::from_raw(input) };
147///     let reader = unsafe { chunk.reader(0) }; // once per chunk, not per row
148///     let mut writer = unsafe { quack_rs::vector::VectorWriter::from_vector(output) };
149///     for row in 0..chunk.size() {
150///         let val = unsafe { reader.read_i64(row) };
151///         unsafe { writer.write_i64(row, val * 2) };
152///     }
153/// });
154/// ```
155#[macro_export]
156macro_rules! scalar_callback {
157    ($name:ident, |$info:ident, $input:ident, $output:ident| $body:block) => {
158        /// Scalar function callback (generated by `scalar_callback!`).
159        ///
160        /// # Safety
161        ///
162        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
163        /// Panics are caught and reported via `duckdb_scalar_function_set_error`.
164        #[allow(unused_unsafe)]
165        pub unsafe extern "C" fn $name(
166            $info: ::libduckdb_sys::duckdb_function_info,
167            $input: ::libduckdb_sys::duckdb_data_chunk,
168            $output: ::libduckdb_sys::duckdb_vector,
169        ) {
170            // The body is an ordinary `fn`, so it is not an `unsafe` context:
171            // unsafe operations in it need their own `unsafe` block.
172            #[inline]
173            fn __quack_rs_body($info: ::libduckdb_sys::duckdb_function_info, $input: ::libduckdb_sys::duckdb_data_chunk, $output: ::libduckdb_sys::duckdb_vector) $body
174            let result =
175                ::std::panic::catch_unwind::<_, ()>(::std::panic::AssertUnwindSafe(|| __quack_rs_body($info, $input, $output)));
176            if let Err(panic) = result {
177                let c_msg = $crate::callback::panic_c_message(panic);
178                // SAFETY: `info` is the pointer DuckDB passed in; `c_msg` outlives the call.
179                unsafe {
180                    ::libduckdb_sys::duckdb_scalar_function_set_error($info, c_msg.as_ptr());
181                }
182            }
183        }
184    };
185}
186
187/// Generates a panic-safe `unsafe extern "C"` table function scan callback.
188///
189/// The macro emits a function with signature:
190/// ```text
191/// unsafe extern "C" fn $name(
192///     info: duckdb_function_info,
193///     output: duckdb_data_chunk,
194/// )
195/// ```
196///
197/// The body is wrapped in `std::panic::catch_unwind`. If the closure panics,
198/// the output chunk size is set to 0 (signaling end of stream) to prevent
199/// undefined behaviour from unwinding across the FFI boundary.
200///
201/// # Parameters
202///
203/// - `$name` — the name of the generated function
204/// - `$body` — a closure with signature `|info: duckdb_function_info, output: duckdb_data_chunk|`
205///
206/// # Example
207///
208/// ```rust,no_run
209/// quack_rs::table_scan_callback!(my_scan, |info, output| {
210///     let chunk = unsafe { quack_rs::data_chunk::DataChunk::from_raw(output) };
211///     let mut writer = unsafe { chunk.writer(0) };
212///     unsafe { writer.write_i64(0, 42) };
213///     unsafe { chunk.set_size(1) };
214/// });
215/// ```
216#[macro_export]
217macro_rules! table_scan_callback {
218    ($name:ident, |$info:ident, $output:ident| $body:block) => {
219        /// Table function scan callback (generated by `table_scan_callback!`).
220        ///
221        /// # Safety
222        ///
223        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
224        /// Panics are caught; on panic the output chunk size is set to 0.
225        #[allow(unused_unsafe)]
226        pub unsafe extern "C" fn $name(
227            $info: ::libduckdb_sys::duckdb_function_info,
228            $output: ::libduckdb_sys::duckdb_data_chunk,
229        ) {
230            // The body is an ordinary `fn`, so it is not an `unsafe` context:
231            // unsafe operations in it need their own `unsafe` block.
232            #[inline]
233            fn __quack_rs_body($info: ::libduckdb_sys::duckdb_function_info, $output: ::libduckdb_sys::duckdb_data_chunk) $body
234            let result =
235                ::std::panic::catch_unwind::<_, ()>(::std::panic::AssertUnwindSafe(|| __quack_rs_body($info, $output)));
236            if let Err(panic) = result {
237                let c_msg = $crate::callback::panic_c_message(panic);
238                // SAFETY: `info` and `output` are the pointers DuckDB passed in.
239                unsafe {
240                    ::libduckdb_sys::duckdb_function_set_error($info, c_msg.as_ptr());
241                    // Signal end-of-stream so the scan terminates.
242                    ::libduckdb_sys::duckdb_data_chunk_set_size($output, 0);
243                }
244            }
245        }
246    };
247}
248
249/// Generates a panic-safe `unsafe extern "C"` table function **bind** callback.
250///
251/// Emits `unsafe extern "C" fn $name(info: duckdb_bind_info)`. A panic is
252/// reported through `duckdb_bind_set_error`, which fails the query during
253/// planning rather than aborting the process.
254///
255/// **Table functions only.** `duckdb_bind_set_error` casts its argument to the
256/// table function's info struct, which is much larger than a scalar
257/// function's: used on a scalar function, it wrote past the scalar bind info
258/// (SIGSEGV in testing). A scalar callback takes a
259/// `RawScalarBindInfo` (feature `duckdb-1-5`), so the compiler
260/// refuses this macro's output there. Use `scalar_bind_callback!` (feature
261/// `duckdb-1-5`) for scalar functions.
262///
263/// # Example
264///
265/// ```rust,no_run
266/// quack_rs::table_bind_callback!(my_bind, |info| {
267///     let bind = unsafe { quack_rs::table::BindInfo::new(info) };
268///     bind.add_result_column("n", quack_rs::types::TypeId::BigInt);
269/// });
270/// ```
271#[macro_export]
272macro_rules! table_bind_callback {
273    ($name:ident, |$info:ident| $body:block) => {
274        /// Table function bind callback (generated by `table_bind_callback!`).
275        ///
276        /// # Safety
277        ///
278        /// Called by DuckDB. `info` is provided by the DuckDB runtime.
279        #[allow(unused_unsafe)]
280        pub unsafe extern "C" fn $name($info: ::libduckdb_sys::duckdb_bind_info) {
281            // The body is an ordinary `fn`, so it is not an `unsafe` context:
282            // unsafe operations in it need their own `unsafe` block.
283            #[inline]
284            fn __quack_rs_body($info: ::libduckdb_sys::duckdb_bind_info) $body
285            let result =
286                ::std::panic::catch_unwind::<_, ()>(::std::panic::AssertUnwindSafe(|| __quack_rs_body($info)));
287            if let Err(panic) = result {
288                let c_msg = $crate::callback::panic_c_message(panic);
289                // SAFETY: `info` is the pointer DuckDB passed in.
290                unsafe {
291                    ::libduckdb_sys::duckdb_bind_set_error($info, c_msg.as_ptr());
292                }
293            }
294        }
295    };
296}
297
298/// Generates a panic-safe `unsafe extern "C"` table function **init** callback.
299///
300/// Emits `unsafe extern "C" fn $name(info: duckdb_init_info)`. Use it for both
301/// the global `init` and the per-thread `local_init` callback — they share a
302/// signature. A panic is reported through `duckdb_init_set_error`.
303///
304/// **Table functions only.** `duckdb_init_set_error` casts its argument to the
305/// table function's info struct, which is much larger than a scalar
306/// function's: used on a scalar function, it wrote past the scalar init info
307/// (SIGSEGV in testing). A scalar callback takes a
308/// `RawScalarInitInfo` (feature `duckdb-1-5`), so the compiler
309/// refuses this macro's output there. Use `scalar_init_callback!` (feature
310/// `duckdb-1-5`) for scalar functions.
311///
312/// # Example
313///
314/// ```rust,no_run
315/// quack_rs::table_init_callback!(my_init, |info| {
316///     let init = unsafe { quack_rs::table::InitInfo::new(info) };
317///     init.set_max_threads(1);
318/// });
319/// ```
320#[macro_export]
321macro_rules! table_init_callback {
322    ($name:ident, |$info:ident| $body:block) => {
323        /// Table function init callback (generated by `table_init_callback!`).
324        ///
325        /// # Safety
326        ///
327        /// Called by DuckDB. `info` is provided by the DuckDB runtime.
328        #[allow(unused_unsafe)]
329        pub unsafe extern "C" fn $name($info: ::libduckdb_sys::duckdb_init_info) {
330            // The body is an ordinary `fn`, so it is not an `unsafe` context:
331            // unsafe operations in it need their own `unsafe` block.
332            #[inline]
333            fn __quack_rs_body($info: ::libduckdb_sys::duckdb_init_info) $body
334            let result =
335                ::std::panic::catch_unwind::<_, ()>(::std::panic::AssertUnwindSafe(|| __quack_rs_body($info)));
336            if let Err(panic) = result {
337                let c_msg = $crate::callback::panic_c_message(panic);
338                // SAFETY: `info` is the pointer DuckDB passed in.
339                unsafe {
340                    ::libduckdb_sys::duckdb_init_set_error($info, c_msg.as_ptr());
341                }
342            }
343        }
344    };
345}
346
347/// Generates a panic-safe `unsafe extern "C"` **scalar function bind** callback
348/// (`duckdb-1-5`).
349///
350/// Emits `unsafe extern "C" fn $name(info: RawScalarBindInfo)`, for
351/// [`ScalarFunctionBuilder::bind`](crate::scalar::ScalarFunctionBuilder::bind).
352/// A panic is reported through `duckdb_scalar_function_bind_set_error`, which
353/// fails the query during planning. The argument type keeps the callback out
354/// of a table function's `bind`, and [`table_bind_callback!`](crate::table_bind_callback)'s
355/// output out of this one.
356///
357/// # Example
358///
359/// ```rust,no_run
360/// quack_rs::scalar_bind_callback!(my_bind, |info| {
361///     let bind = unsafe { quack_rs::scalar::ScalarBindInfo::new(info) };
362///     assert!(bind.argument_count() > 0, "needs an argument");
363/// });
364/// ```
365#[cfg(feature = "duckdb-1-5")]
366#[macro_export]
367macro_rules! scalar_bind_callback {
368    ($name:ident, |$info:ident| $body:block) => {
369        /// Scalar function bind callback (generated by `scalar_bind_callback!`).
370        ///
371        /// # Safety
372        ///
373        /// Called by DuckDB. `info` is provided by the DuckDB runtime.
374        #[allow(unused_unsafe)]
375        pub unsafe extern "C" fn $name($info: $crate::scalar::RawScalarBindInfo) {
376            // The body is an ordinary `fn`, so it is not an `unsafe` context:
377            // unsafe operations in it need their own `unsafe` block.
378            #[inline]
379            fn __quack_rs_body($info: $crate::scalar::RawScalarBindInfo) $body
380            let result =
381                ::std::panic::catch_unwind::<_, ()>(::std::panic::AssertUnwindSafe(|| __quack_rs_body($info)));
382            if let Err(panic) = result {
383                let c_msg = $crate::callback::panic_c_message(panic);
384                // SAFETY: `info` is the scalar bind info DuckDB passed in.
385                unsafe {
386                    ::libduckdb_sys::duckdb_scalar_function_bind_set_error($info.0, c_msg.as_ptr());
387                }
388            }
389        }
390    };
391}
392
393/// Generates a panic-safe `unsafe extern "C"` **scalar function init** callback
394/// (`duckdb-1-5`).
395///
396/// Emits `unsafe extern "C" fn $name(info: RawScalarInitInfo)`, for
397/// [`ScalarFunctionBuilder::init`](crate::scalar::ScalarFunctionBuilder::init).
398/// A panic is reported through `duckdb_scalar_function_init_set_error`. The
399/// argument type keeps the callback out of a table function's `init`, and
400/// [`table_init_callback!`](crate::table_init_callback)'s output out of this
401/// one.
402///
403/// # Example
404///
405/// ```rust,no_run
406/// quack_rs::scalar_init_callback!(my_init, |info| {
407///     let _ = info;
408/// });
409/// ```
410#[cfg(feature = "duckdb-1-5")]
411#[macro_export]
412macro_rules! scalar_init_callback {
413    ($name:ident, |$info:ident| $body:block) => {
414        /// Scalar function init callback (generated by `scalar_init_callback!`).
415        ///
416        /// # Safety
417        ///
418        /// Called by DuckDB. `info` is provided by the DuckDB runtime.
419        #[allow(unused_unsafe)]
420        pub unsafe extern "C" fn $name($info: $crate::scalar::RawScalarInitInfo) {
421            // The body is an ordinary `fn`, so it is not an `unsafe` context:
422            // unsafe operations in it need their own `unsafe` block.
423            #[inline]
424            fn __quack_rs_body($info: $crate::scalar::RawScalarInitInfo) $body
425            let result =
426                ::std::panic::catch_unwind::<_, ()>(::std::panic::AssertUnwindSafe(|| __quack_rs_body($info)));
427            if let Err(panic) = result {
428                let c_msg = $crate::callback::panic_c_message(panic);
429                // SAFETY: `info` is the scalar init info DuckDB passed in.
430                unsafe {
431                    ::libduckdb_sys::duckdb_scalar_function_init_set_error($info.0, c_msg.as_ptr());
432                }
433            }
434        }
435    };
436}
437
438/// Generates a panic-safe `unsafe extern "C"` aggregate **update** callback.
439///
440/// Emits
441/// `unsafe extern "C" fn $name(info: duckdb_function_info, input: duckdb_data_chunk, states: *mut duckdb_aggregate_state)`.
442/// A panic is reported through `duckdb_aggregate_function_set_error`.
443///
444/// Aggregate callbacks run on `DuckDB`'s worker threads, so an unguarded panic
445/// here aborts the process from a thread the user never sees.
446///
447/// # Example
448///
449/// ```rust,no_run
450/// quack_rs::aggregate_update_callback!(my_update, |info, input, states| {
451///     let _ = (input, states);
452/// });
453/// ```
454#[macro_export]
455macro_rules! aggregate_update_callback {
456    ($name:ident, |$info:ident, $input:ident, $states:ident| $body:block) => {
457        /// Aggregate update callback (generated by `aggregate_update_callback!`).
458        ///
459        /// # Safety
460        ///
461        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
462        #[allow(unused_unsafe)]
463        pub unsafe extern "C" fn $name(
464            $info: ::libduckdb_sys::duckdb_function_info,
465            $input: ::libduckdb_sys::duckdb_data_chunk,
466            $states: *mut ::libduckdb_sys::duckdb_aggregate_state,
467        ) {
468            // The body is an ordinary `fn`, so it is not an `unsafe` context:
469            // unsafe operations in it need their own `unsafe` block.
470            #[inline]
471            fn __quack_rs_body($info: ::libduckdb_sys::duckdb_function_info, $input: ::libduckdb_sys::duckdb_data_chunk, $states: *mut ::libduckdb_sys::duckdb_aggregate_state) $body
472            let result =
473                ::std::panic::catch_unwind::<_, ()>(::std::panic::AssertUnwindSafe(|| __quack_rs_body($info, $input, $states)));
474            if let Err(panic) = result {
475                let c_msg = $crate::callback::panic_c_message(panic);
476                // SAFETY: `info` is the pointer DuckDB passed in.
477                unsafe {
478                    ::libduckdb_sys::duckdb_aggregate_function_set_error($info, c_msg.as_ptr());
479                }
480            }
481        }
482    };
483}
484
485/// Generates a panic-safe `unsafe extern "C"` aggregate **combine** callback.
486///
487/// Emits
488/// `unsafe extern "C" fn $name(info: duckdb_function_info, source: *mut duckdb_aggregate_state, target: *mut duckdb_aggregate_state, count: idx_t)`.
489///
490/// # Pitfall L1
491///
492/// `target` states were set up by the aggregate's `init` callback, not copied
493/// from anything, so the body must propagate **every** field of the state, not
494/// only the accumulated data. See
495/// [`CombineFn`][crate::aggregate::callbacks::CombineFn].
496///
497/// # Example
498///
499/// ```rust,no_run
500/// quack_rs::aggregate_combine_callback!(my_combine, |info, source, target, count| {
501///     let _ = (source, target, count);
502/// });
503/// ```
504#[macro_export]
505macro_rules! aggregate_combine_callback {
506    ($name:ident, |$info:ident, $source:ident, $target:ident, $count:ident| $body:block) => {
507        /// Aggregate combine callback (generated by `aggregate_combine_callback!`).
508        ///
509        /// # Safety
510        ///
511        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
512        #[allow(unused_unsafe)]
513        pub unsafe extern "C" fn $name(
514            $info: ::libduckdb_sys::duckdb_function_info,
515            $source: *mut ::libduckdb_sys::duckdb_aggregate_state,
516            $target: *mut ::libduckdb_sys::duckdb_aggregate_state,
517            $count: ::libduckdb_sys::idx_t,
518        ) {
519            // The body is an ordinary `fn`, so it is not an `unsafe` context:
520            // unsafe operations in it need their own `unsafe` block.
521            #[inline]
522            fn __quack_rs_body($info: ::libduckdb_sys::duckdb_function_info, $source: *mut ::libduckdb_sys::duckdb_aggregate_state, $target: *mut ::libduckdb_sys::duckdb_aggregate_state, $count: ::libduckdb_sys::idx_t) $body
523            let result =
524                ::std::panic::catch_unwind::<_, ()>(::std::panic::AssertUnwindSafe(|| __quack_rs_body($info, $source, $target, $count)));
525            if let Err(panic) = result {
526                let c_msg = $crate::callback::panic_c_message(panic);
527                // SAFETY: `info` is the pointer DuckDB passed in.
528                unsafe {
529                    ::libduckdb_sys::duckdb_aggregate_function_set_error($info, c_msg.as_ptr());
530                }
531            }
532        }
533    };
534}
535
536/// Generates a panic-safe `unsafe extern "C"` aggregate **finalize** callback.
537///
538/// Emits
539/// `unsafe extern "C" fn $name(info: duckdb_function_info, source: *mut duckdb_aggregate_state, result: duckdb_vector, count: idx_t, offset: idx_t)`.
540///
541/// Results are written starting at `offset` in the output vector, not at 0.
542///
543/// # Example
544///
545/// ```rust,no_run
546/// quack_rs::aggregate_finalize_callback!(my_finalize, |info, source, result, count, offset| {
547///     let _ = (source, result, count, offset);
548/// });
549/// ```
550#[macro_export]
551macro_rules! aggregate_finalize_callback {
552    ($name:ident, |$info:ident, $source:ident, $result:ident, $count:ident, $offset:ident| $body:block) => {
553        /// Aggregate finalize callback (generated by `aggregate_finalize_callback!`).
554        ///
555        /// # Safety
556        ///
557        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
558        #[allow(unused_unsafe)]
559        pub unsafe extern "C" fn $name(
560            $info: ::libduckdb_sys::duckdb_function_info,
561            $source: *mut ::libduckdb_sys::duckdb_aggregate_state,
562            $result: ::libduckdb_sys::duckdb_vector,
563            $count: ::libduckdb_sys::idx_t,
564            $offset: ::libduckdb_sys::idx_t,
565        ) {
566            // The body is an ordinary `fn`, so it is not an `unsafe` context:
567            // unsafe operations in it need their own `unsafe` block.
568            #[inline]
569            fn __quack_rs_body($info: ::libduckdb_sys::duckdb_function_info, $source: *mut ::libduckdb_sys::duckdb_aggregate_state, $result: ::libduckdb_sys::duckdb_vector, $count: ::libduckdb_sys::idx_t, $offset: ::libduckdb_sys::idx_t) $body
570            let outcome =
571                ::std::panic::catch_unwind::<_, ()>(::std::panic::AssertUnwindSafe(|| __quack_rs_body($info, $source, $result, $count, $offset)));
572            if let Err(panic) = outcome {
573                let c_msg = $crate::callback::panic_c_message(panic);
574                // SAFETY: `info` is the pointer DuckDB passed in.
575                unsafe {
576                    ::libduckdb_sys::duckdb_aggregate_function_set_error($info, c_msg.as_ptr());
577                }
578            }
579        }
580    };
581}
582
583/// Generates a panic-safe `unsafe extern "C"` aggregate **state destructor**.
584///
585/// Emits `unsafe extern "C" fn $name(states: *mut duckdb_aggregate_state, count: idx_t)`.
586///
587/// This callback receives no `info`, so `DuckDB` offers no way to report an
588/// error from it. A panic is therefore caught and **swallowed**: that leaks
589/// whatever the destructor had not yet freed, which is strictly better than
590/// aborting the database process during query teardown.
591///
592/// # Example
593///
594/// ```rust,no_run
595/// quack_rs::aggregate_destroy_callback!(my_destroy, |states, count| {
596///     let _ = (states, count);
597/// });
598/// ```
599#[macro_export]
600macro_rules! aggregate_destroy_callback {
601    ($name:ident, |$states:ident, $count:ident| $body:block) => {
602        /// Aggregate state destructor (generated by `aggregate_destroy_callback!`).
603        ///
604        /// # Safety
605        ///
606        /// Called by `DuckDB`. All parameters are provided by the `DuckDB` runtime.
607        #[allow(unused_unsafe)]
608        pub unsafe extern "C" fn $name(
609            $states: *mut ::libduckdb_sys::duckdb_aggregate_state,
610            $count: ::libduckdb_sys::idx_t,
611        ) {
612            // The body is an ordinary `fn`, so it is not an `unsafe` context:
613            // unsafe operations in it need their own `unsafe` block.
614            #[inline]
615            fn __quack_rs_body($states: *mut ::libduckdb_sys::duckdb_aggregate_state, $count: ::libduckdb_sys::idx_t) $body
616            // DuckDB provides no error channel for the destructor, so the panic
617            // is dropped rather than reported. Leaking beats aborting — and the
618            // payload's own `Drop` is user code too, so it is dropped under a
619            // second guard rather than here.
620            // `::<_, ()>`: a body that always panics has type `!`, and under
621            // the never-type fallback that would make this `if let`
622            // irrefutable (`irrefutable_let_patterns`, an error under
623            // `-D warnings` on nightly).
624            if let ::std::result::Result::Err(panic) =
625                ::std::panic::catch_unwind::<_, ()>(::std::panic::AssertUnwindSafe(|| __quack_rs_body($states, $count)))
626            {
627                $crate::callback::drop_panic_payload(panic);
628            }
629        }
630    };
631}
632
633/// The error a [`cast_callback!`][crate::cast_callback] function reports in a
634/// regular `CAST` when its body returns `false` without setting a message.
635pub const CAST_FAILED_WITHOUT_MESSAGE: &std::ffi::CStr =
636    c"cast function failed without reporting an error message";
637
638/// Generates a panic-safe `unsafe extern "C"` **cast** callback.
639///
640/// Emits
641/// `unsafe extern "C" fn $name(info: duckdb_function_info, count: idx_t, input: duckdb_vector, output: duckdb_vector) -> bool`.
642/// The body must evaluate to `bool` — `true` when every row converted.
643///
644/// A panic is reported through `duckdb_cast_function_set_error` and the
645/// generated function returns `false`. In a regular `CAST` that fails the
646/// query with the panic message, and in `DuckDB`'s internal value casts it
647/// makes `DuckDB` throw. In a `TRY_CAST`, `DuckDB` ignores the return
648/// value (see [`CastFn`][crate::cast::CastFn]), so the generated function also
649/// sets **every** row of the chunk to `NULL` through
650/// `duckdb_cast_function_set_row_error`: whatever the body wrote before it
651/// panicked cannot be trusted, and a row it never reached would otherwise keep
652/// a stale value.
653///
654/// A body that returns `false` without panicking is passed through untouched;
655/// in `TRY_CAST` mode it must null its own failed rows. In a regular `CAST`, a
656/// body that returns `false` without setting a message fails the query with
657/// [`CAST_FAILED_WITHOUT_MESSAGE`] rather than an empty `Conversion Error: `.
658///
659/// # Example
660///
661/// ```rust,no_run
662/// quack_rs::cast_callback!(my_cast, |info, count, input, output| {
663///     let _ = (count, input, output);
664///     true
665/// });
666/// ```
667#[macro_export]
668macro_rules! cast_callback {
669    ($name:ident, |$info:ident, $count:ident, $input:ident, $output:ident| $body:block) => {
670        /// Cast function callback (generated by `cast_callback!`).
671        ///
672        /// # Safety
673        ///
674        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
675        #[allow(unused_unsafe)]
676        pub unsafe extern "C" fn $name(
677            $info: ::libduckdb_sys::duckdb_function_info,
678            $count: ::libduckdb_sys::idx_t,
679            $input: ::libduckdb_sys::duckdb_vector,
680            $output: ::libduckdb_sys::duckdb_vector,
681        ) -> bool {
682            // The body is an ordinary `fn`, so it is not an `unsafe` context:
683            // unsafe operations in it need their own `unsafe` block.
684            #[inline]
685            fn __quack_rs_body($info: ::libduckdb_sys::duckdb_function_info, $count: ::libduckdb_sys::idx_t, $input: ::libduckdb_sys::duckdb_vector, $output: ::libduckdb_sys::duckdb_vector) -> bool $body
686            // SAFETY: `info` is the pointer DuckDB passed in.
687            let try_mode = unsafe {
688                ::libduckdb_sys::duckdb_cast_function_get_cast_mode($info)
689                    == ::libduckdb_sys::duckdb_cast_mode_DUCKDB_CAST_TRY
690            };
691            if !try_mode {
692                // A default for a body that returns `false` without a message:
693                // `set_error` only assigns the message (cast_function-c.cpp),
694                // so the body's own call replaces it, and DuckDB reads it only
695                // when the callback returns `false`.
696                // SAFETY: `info` is the pointer DuckDB passed in; the message
697                // is a static NUL-terminated string DuckDB copies.
698                unsafe {
699                    ::libduckdb_sys::duckdb_cast_function_set_error(
700                        $info,
701                        $crate::callback::CAST_FAILED_WITHOUT_MESSAGE.as_ptr(),
702                    );
703                }
704            }
705            let outcome: ::std::result::Result<bool, _> =
706                ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| __quack_rs_body($info, $count, $input, $output)));
707            match outcome {
708                ::std::result::Result::Ok(ok) => ok,
709                ::std::result::Result::Err(panic) => {
710                    let c_msg = $crate::callback::panic_c_message(panic);
711                    if try_mode {
712                        // DuckDB ignores the return value of a TRY cast
713                        // (execute_cast.cpp), so the rows must be nulled here.
714                        for row in 0..$count {
715                            // SAFETY: `info` and `output` are the handles
716                            // DuckDB passed in, and `row < count`.
717                            unsafe {
718                                ::libduckdb_sys::duckdb_cast_function_set_row_error(
719                                    $info,
720                                    c_msg.as_ptr(),
721                                    row,
722                                    $output,
723                                );
724                            }
725                        }
726                    } else {
727                        // SAFETY: `info` is the pointer DuckDB passed in.
728                        unsafe {
729                            ::libduckdb_sys::duckdb_cast_function_set_error($info, c_msg.as_ptr());
730                        }
731                    }
732                    false
733                }
734            }
735        }
736    };
737}
738
739/// Generates a panic-safe `unsafe extern "C"` **replacement scan** callback.
740///
741/// Emits
742/// `unsafe extern "C" fn $name(info: duckdb_replacement_scan_info, table_name: *const c_char, data: *mut c_void)`.
743/// A panic is reported through `duckdb_replacement_scan_set_error`.
744///
745/// # Example
746///
747/// ```rust,no_run
748/// quack_rs::replacement_scan_callback!(my_scan, |info, table_name, data| {
749///     let _ = (info, table_name, data);
750/// });
751/// ```
752#[macro_export]
753macro_rules! replacement_scan_callback {
754    ($name:ident, |$info:ident, $table_name:ident, $data:ident| $body:block) => {
755        /// Replacement scan callback (generated by `replacement_scan_callback!`).
756        ///
757        /// # Safety
758        ///
759        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
760        #[allow(unused_unsafe)]
761        pub unsafe extern "C" fn $name(
762            $info: ::libduckdb_sys::duckdb_replacement_scan_info,
763            $table_name: *const ::std::os::raw::c_char,
764            $data: *mut ::std::os::raw::c_void,
765        ) {
766            // The body is an ordinary `fn`, so it is not an `unsafe` context:
767            // unsafe operations in it need their own `unsafe` block.
768            #[inline]
769            fn __quack_rs_body($info: ::libduckdb_sys::duckdb_replacement_scan_info, $table_name: *const ::std::os::raw::c_char, $data: *mut ::std::os::raw::c_void) $body
770            let result =
771                ::std::panic::catch_unwind::<_, ()>(::std::panic::AssertUnwindSafe(|| __quack_rs_body($info, $table_name, $data)));
772            if let Err(panic) = result {
773                let c_msg = $crate::callback::panic_c_message(panic);
774                // SAFETY: `info` is the pointer DuckDB passed in.
775                unsafe {
776                    ::libduckdb_sys::duckdb_replacement_scan_set_error($info, c_msg.as_ptr());
777                }
778            }
779        }
780    };
781}
782
783/// Wraps a `COPY ... TO` **bind** callback so a panic becomes a `DuckDB` error.
784///
785/// Requires the `duckdb-1-5` feature: `duckdb_copy_function_bind_set_error`
786/// lives past the stable prefix of `duckdb_ext_api_v1`.
787///
788/// # Example
789///
790/// ```rust,no_run
791/// # #[cfg(feature = "duckdb-1-5")]
792/// quack_rs::copy_bind_callback!(my_bind, |info| {
793///     let _ = info;
794/// });
795/// ```
796#[cfg(feature = "duckdb-1-5")]
797#[macro_export]
798macro_rules! copy_bind_callback {
799    ($name:ident, |$info:ident| $body:block) => {
800        $crate::__copy_callback_impl!(
801            $name,
802            $info,
803            duckdb_copy_function_bind_info,
804            duckdb_copy_function_bind_set_error,
805            $body
806        );
807    };
808}
809
810/// Wraps a `COPY ... TO` **global init** callback so a panic becomes a
811/// `DuckDB` error.
812///
813/// Requires the `duckdb-1-5` feature.
814///
815/// # Example
816///
817/// ```rust,no_run
818/// # #[cfg(feature = "duckdb-1-5")]
819/// quack_rs::copy_global_init_callback!(my_init, |info| {
820///     let _ = info;
821/// });
822/// ```
823#[cfg(feature = "duckdb-1-5")]
824#[macro_export]
825macro_rules! copy_global_init_callback {
826    ($name:ident, |$info:ident| $body:block) => {
827        $crate::__copy_callback_impl!(
828            $name,
829            $info,
830            duckdb_copy_function_global_init_info,
831            duckdb_copy_function_global_init_set_error,
832            $body
833        );
834    };
835}
836
837/// Wraps a `COPY ... TO` **finalize** callback so a panic becomes a `DuckDB`
838/// error.
839///
840/// Requires the `duckdb-1-5` feature.
841///
842/// # Example
843///
844/// ```rust,no_run
845/// # #[cfg(feature = "duckdb-1-5")]
846/// quack_rs::copy_finalize_callback!(my_finalize, |info| {
847///     let _ = info;
848/// });
849/// ```
850#[cfg(feature = "duckdb-1-5")]
851#[macro_export]
852macro_rules! copy_finalize_callback {
853    ($name:ident, |$info:ident| $body:block) => {
854        $crate::__copy_callback_impl!(
855            $name,
856            $info,
857            duckdb_copy_function_finalize_info,
858            duckdb_copy_function_finalize_set_error,
859            $body
860        );
861    };
862}
863
864/// Shared body of the single-argument copy-function callback macros.
865///
866/// Not part of the public API: it exists because bind, global init and finalize
867/// differ only in their info type and their `set_error` function.
868#[cfg(feature = "duckdb-1-5")]
869#[doc(hidden)]
870#[macro_export]
871macro_rules! __copy_callback_impl {
872    ($name:ident, $info:ident, $info_ty:ident, $set_error:ident, $body:block) => {
873        /// Copy function callback (generated by a `copy_*_callback!` macro).
874        ///
875        /// # Safety
876        ///
877        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
878        #[allow(unused_unsafe)]
879        pub unsafe extern "C" fn $name($info: ::libduckdb_sys::$info_ty) {
880            // The body is an ordinary `fn`, so it is not an `unsafe` context:
881            // unsafe operations in it need their own `unsafe` block.
882            #[inline]
883            fn __quack_rs_body($info: ::libduckdb_sys::$info_ty) $body
884            let result =
885                ::std::panic::catch_unwind::<_, ()>(::std::panic::AssertUnwindSafe(|| __quack_rs_body($info)));
886            if let ::std::result::Result::Err(panic) = result {
887                let c_msg = $crate::callback::panic_c_message(panic);
888                // SAFETY: `info` is the pointer DuckDB passed in.
889                unsafe {
890                    ::libduckdb_sys::$set_error($info, c_msg.as_ptr());
891                }
892            }
893        }
894    };
895}
896
897/// Wraps a `COPY ... TO` **sink** callback so a panic becomes a `DuckDB` error.
898///
899/// The sink takes a data chunk as well as its info handle, so it has its own
900/// macro rather than sharing the single-argument implementation.
901///
902/// Requires the `duckdb-1-5` feature.
903///
904/// # Example
905///
906/// ```rust,no_run
907/// # #[cfg(feature = "duckdb-1-5")]
908/// quack_rs::copy_sink_callback!(my_sink, |info, chunk| {
909///     let _ = (info, chunk);
910/// });
911/// ```
912#[cfg(feature = "duckdb-1-5")]
913#[macro_export]
914macro_rules! copy_sink_callback {
915    ($name:ident, |$info:ident, $chunk:ident| $body:block) => {
916        /// Copy function sink callback (generated by `copy_sink_callback!`).
917        ///
918        /// # Safety
919        ///
920        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
921        #[allow(unused_unsafe)]
922        pub unsafe extern "C" fn $name(
923            $info: ::libduckdb_sys::duckdb_copy_function_sink_info,
924            $chunk: ::libduckdb_sys::duckdb_data_chunk,
925        ) {
926            // The body is an ordinary `fn`, so it is not an `unsafe` context:
927            // unsafe operations in it need their own `unsafe` block.
928            #[inline]
929            fn __quack_rs_body($info: ::libduckdb_sys::duckdb_copy_function_sink_info, $chunk: ::libduckdb_sys::duckdb_data_chunk) $body
930            let result =
931                ::std::panic::catch_unwind::<_, ()>(::std::panic::AssertUnwindSafe(|| __quack_rs_body($info, $chunk)));
932            if let ::std::result::Result::Err(panic) = result {
933                let c_msg = $crate::callback::panic_c_message(panic);
934                // SAFETY: `info` is the pointer DuckDB passed in.
935                unsafe {
936                    ::libduckdb_sys::duckdb_copy_function_sink_set_error($info, c_msg.as_ptr());
937                }
938            }
939        }
940    };
941}
942
943/// Extracts a human-readable message from a `catch_unwind` payload.
944///
945/// This only borrows the payload; when you are done with it, dispose of it with
946/// [`drop_panic_payload`] (or use [`take_panic_message`], which does both) — a
947/// payload's own `Drop` may panic, and at an FFI boundary that aborts.
948///
949/// # Example
950///
951/// ```rust
952/// let payload = std::panic::catch_unwind(|| panic!("boom")).unwrap_err();
953/// assert_eq!(quack_rs::callback::panic_message(&payload), "boom");
954/// ```
955#[must_use]
956pub fn panic_message(payload: &Box<dyn std::any::Any + Send>) -> String {
957    payload
958        .downcast_ref::<&str>()
959        .map(|s| (*s).to_string())
960        .or_else(|| payload.downcast_ref::<String>().cloned())
961        .or_else(|| payload.downcast_ref::<Box<str>>().map(ToString::to_string))
962        .unwrap_or_else(|| String::from("<non-string panic payload>"))
963}
964
965/// What the callback macros report for a panic whose message is empty
966/// (`panic!("")`).
967///
968/// `DuckDB` would otherwise show a bare error prefix such as
969/// `Invalid Input Error: ` — and a replacement scan ignores an empty error
970/// altogether and carries on with whatever the callback set up before it
971/// panicked (`replacement_scan-c.cpp` only raises a non-empty message).
972pub const EMPTY_PANIC_PLACEHOLDER: &str = "an extension callback panicked without a message";
973
974/// Turns a caught panic into the C string a callback macro reports.
975///
976/// That is the panic message, with any interior NUL replaced by `?`, or
977/// [`EMPTY_PANIC_PLACEHOLDER`] if the message is empty. The payload is
978/// disposed of as [`take_panic_message`] does.
979///
980/// # Example
981///
982/// ```rust
983/// let payload = std::panic::catch_unwind(|| panic!("")).unwrap_err();
984/// assert_eq!(
985///     quack_rs::callback::panic_c_message(payload).to_str().unwrap(),
986///     quack_rs::callback::EMPTY_PANIC_PLACEHOLDER,
987/// );
988/// ```
989#[must_use]
990pub fn panic_c_message(payload: Box<dyn std::any::Any + Send>) -> std::ffi::CString {
991    crate::table::cstr::error_cstring(&take_panic_message(payload), EMPTY_PANIC_PLACEHOLDER)
992}
993
994/// Converts a panic message into a `CString`, replacing any interior NUL.
995///
996/// `CString::new` rejects interior NULs, and a panic message is arbitrary user
997/// text — dropping the diagnostic because it happened to contain a NUL would be
998/// the wrong trade.
999///
1000/// # Example
1001///
1002/// ```rust
1003/// let c = quack_rs::callback::message_to_c_string("a\0b");
1004/// assert_eq!(c.to_str().unwrap(), "a?b");
1005/// ```
1006#[must_use]
1007pub fn message_to_c_string(message: &str) -> std::ffi::CString {
1008    std::ffi::CString::new(message.replace('\0', "?"))
1009        .unwrap_or_else(|_| std::ffi::CString::default())
1010}
1011
1012/// Runs `body` with unwinding contained, returning the panic message on unwind.
1013///
1014/// # Why this exists
1015///
1016/// Every function quack-rs hands to `DuckDB` is an `extern "C" fn`. Since Rust
1017/// 1.81 a panic that reaches such a boundary is a guaranteed **process abort**
1018/// (`panic_cannot_unwind`), not merely undefined behaviour — so an aggregate
1019/// state whose `Drop` calls `.unwrap()` takes the whole `DuckDB` session down.
1020/// The macros in this module contain that for the callbacks *you* write; this
1021/// function is the same containment for the ones quack-rs generates on your
1022/// behalf, and it is public so extensions writing their own `extern "C"`
1023/// destructors can use it too.
1024///
1025/// `AssertUnwindSafe` is applied internally: at an FFI boundary there is no
1026/// caller left to observe a broken invariant, and aborting instead is strictly
1027/// worse.
1028///
1029/// # Not a substitute for an error channel
1030///
1031/// Where the `DuckDB` callback has a `set_error` counterpart, report the message
1032/// through it — see the macro table in the [module docs][self]. Some callbacks
1033/// (notably the aggregate state destructor, which `DuckDB` invokes as
1034/// `info.destroy(states, count)` with no info handle and no return value) have
1035/// no channel at all; there, discarding the message is the only option left, and
1036/// it still beats aborting.
1037///
1038/// # `panic = "abort"`
1039///
1040/// Like every `catch_unwind` in this crate, this is inert under
1041/// `panic = "abort"`. Keep extension crates on `panic = "unwind"`.
1042///
1043/// # Example
1044///
1045/// ```rust
1046/// use quack_rs::callback::catch_ffi_panic;
1047///
1048/// assert_eq!(catch_ffi_panic(|| 1 + 1), Ok(2));
1049/// assert_eq!(catch_ffi_panic(|| panic!("boom")), Err("boom".to_string()));
1050/// ```
1051pub fn catch_ffi_panic<T, F>(body: F) -> Result<T, String>
1052where
1053    F: FnOnce() -> T,
1054{
1055    std::panic::catch_unwind(std::panic::AssertUnwindSafe(body)).map_err(take_panic_message)
1056}