quack-rs 0.16.0

Production-grade Rust SDK for building DuckDB loadable extensions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
// SPDX-License-Identifier: MIT
// Copyright 2026 Tom F. <https://github.com/tomtom215/>
// My way of giving something small back to the open source community
// and encouraging more Rust development!

//! Panic-safe callback wrapper macros for `DuckDB` extension callbacks.
//!
//! Every `DuckDB` callback is an `unsafe extern "C" fn`, and a Rust panic that
//! reaches that boundary aborts the process — taking the user's `DuckDB` session,
//! and any application embedding it, with it. These macros wrap the body in
//! [`std::panic::catch_unwind`] and route the panic message to whichever
//! `set_error` `DuckDB` provides for that callback kind, so a bug in extension
//! code becomes an ordinary SQL error.
//!
//! # Macros
//!
//! | Macro | Wraps | Reports through |
//! |-------|-------|-----------------|
//! | `scalar_callback!` | scalar function execution | `duckdb_scalar_function_set_error` |
//! | `table_bind_callback!` | table function bind | `duckdb_bind_set_error` |
//! | `table_init_callback!` | table function init / local init | `duckdb_init_set_error` |
//! | `table_scan_callback!` | table function scan | `duckdb_function_set_error`, then chunk size 0 |
//! | `aggregate_update_callback!` | aggregate update | `duckdb_aggregate_function_set_error` |
//! | `aggregate_combine_callback!` | aggregate combine | `duckdb_aggregate_function_set_error` |
//! | `aggregate_finalize_callback!` | aggregate finalize | `duckdb_aggregate_function_set_error` |
//! | `aggregate_destroy_callback!` | aggregate state destructor | *(no error channel — panic is swallowed)* |
//! | `cast_callback!` | cast function | `duckdb_cast_function_set_error`, returns `false` |
//! | `replacement_scan_callback!` | replacement scan | `duckdb_replacement_scan_set_error` |
//!
//! # `panic = "abort"`
//!
//! `catch_unwind` cannot catch anything when the crate is built with
//! `panic = "abort"`, which silently disables everything in this module. Keep
//! extension crates on `panic = "unwind"` — the quack-rs scaffold generates that.
//!
//! # Example: Scalar callback
//!
//! ```rust,no_run
//! use quack_rs::data_chunk::DataChunk;
//! use quack_rs::vector::VectorWriter;
//!
//! quack_rs::scalar_callback!(my_func, |info, input, output| {
//!     let chunk = unsafe { DataChunk::from_raw(input) };
//!     let mut writer = unsafe { VectorWriter::from_vector(output) };
//!     for row in 0..chunk.size() {
//!         let val = unsafe { chunk.reader(0).read_i64(row) };
//!         unsafe { writer.write_i64(row, val * 2) };
//!     }
//! });
//! ```
//!
//! # Example: Table scan callback
//!
//! ```rust,no_run
//! use quack_rs::data_chunk::DataChunk;
//!
//! quack_rs::table_scan_callback!(my_scan, |info, output| {
//!     let chunk = unsafe { DataChunk::from_raw(output) };
//!     let mut writer = unsafe { chunk.writer(0) };
//!     unsafe { writer.write_i64(0, 42) };
//!     unsafe { chunk.set_size(1) };
//! });
//! ```

/// Generates a panic-safe `unsafe extern "C"` scalar function callback.
///
/// The macro emits a function with signature:
/// ```text
/// unsafe extern "C" fn $name(
///     info: duckdb_function_info,
///     input: duckdb_data_chunk,
///     output: duckdb_vector,
/// )
/// ```
///
/// The body is wrapped in `std::panic::catch_unwind`. If the closure panics,
/// the error is reported via `duckdb_scalar_function_set_error` and the
/// function returns without unwinding across the FFI boundary.
///
/// # Parameters
///
/// - `$name` — the name of the generated function
/// - `$body` — a closure with signature `|info: duckdb_function_info, input: duckdb_data_chunk, output: duckdb_vector|`
///
/// # Example
///
/// ```rust,no_run
/// quack_rs::scalar_callback!(double_it, |info, input, output| {
///     let chunk = unsafe { quack_rs::data_chunk::DataChunk::from_raw(input) };
///     let mut writer = unsafe { quack_rs::vector::VectorWriter::from_vector(output) };
///     for row in 0..chunk.size() {
///         let val = unsafe { chunk.reader(0).read_i64(row) };
///         unsafe { writer.write_i64(row, val * 2) };
///     }
/// });
/// ```
#[macro_export]
macro_rules! scalar_callback {
    ($name:ident, |$info:ident, $input:ident, $output:ident| $body:block) => {
        /// Scalar function callback (generated by `scalar_callback!`).
        ///
        /// # Safety
        ///
        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
        /// Panics are caught and reported via `duckdb_scalar_function_set_error`.
        #[allow(unused_unsafe)]
        pub unsafe extern "C" fn $name(
            $info: ::libduckdb_sys::duckdb_function_info,
            $input: ::libduckdb_sys::duckdb_data_chunk,
            $output: ::libduckdb_sys::duckdb_vector,
        ) {
            let result = ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| $body));
            if let Err(panic) = result {
                let c_msg =
                    $crate::callback::message_to_c_string(&$crate::callback::panic_message(&panic));
                // SAFETY: `info` is the pointer DuckDB passed in; `c_msg` outlives the call.
                unsafe {
                    ::libduckdb_sys::duckdb_scalar_function_set_error($info, c_msg.as_ptr());
                }
            }
        }
    };
}

/// Generates a panic-safe `unsafe extern "C"` table function scan callback.
///
/// The macro emits a function with signature:
/// ```text
/// unsafe extern "C" fn $name(
///     info: duckdb_function_info,
///     output: duckdb_data_chunk,
/// )
/// ```
///
/// The body is wrapped in `std::panic::catch_unwind`. If the closure panics,
/// the output chunk size is set to 0 (signaling end of stream) to prevent
/// undefined behaviour from unwinding across the FFI boundary.
///
/// # Parameters
///
/// - `$name` — the name of the generated function
/// - `$body` — a closure with signature `|info: duckdb_function_info, output: duckdb_data_chunk|`
///
/// # Example
///
/// ```rust,no_run
/// quack_rs::table_scan_callback!(my_scan, |info, output| {
///     let chunk = unsafe { quack_rs::data_chunk::DataChunk::from_raw(output) };
///     let mut writer = unsafe { chunk.writer(0) };
///     unsafe { writer.write_i64(0, 42) };
///     unsafe { chunk.set_size(1) };
/// });
/// ```
#[macro_export]
macro_rules! table_scan_callback {
    ($name:ident, |$info:ident, $output:ident| $body:block) => {
        /// Table function scan callback (generated by `table_scan_callback!`).
        ///
        /// # Safety
        ///
        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
        /// Panics are caught; on panic the output chunk size is set to 0.
        #[allow(unused_unsafe)]
        pub unsafe extern "C" fn $name(
            $info: ::libduckdb_sys::duckdb_function_info,
            $output: ::libduckdb_sys::duckdb_data_chunk,
        ) {
            let result = ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| $body));
            if let Err(panic) = result {
                let c_msg =
                    $crate::callback::message_to_c_string(&$crate::callback::panic_message(&panic));
                // SAFETY: `info` and `output` are the pointers DuckDB passed in.
                unsafe {
                    ::libduckdb_sys::duckdb_function_set_error($info, c_msg.as_ptr());
                    // Signal end-of-stream so the scan terminates.
                    ::libduckdb_sys::duckdb_data_chunk_set_size($output, 0);
                }
            }
        }
    };
}

/// Generates a panic-safe `unsafe extern "C"` table function **bind** callback.
///
/// Emits `unsafe extern "C" fn $name(info: duckdb_bind_info)`. A panic is
/// reported through `duckdb_bind_set_error`, which fails the query during
/// planning rather than aborting the process.
///
/// # Example
///
/// ```rust,no_run
/// quack_rs::table_bind_callback!(my_bind, |info| {
///     let bind = unsafe { quack_rs::table::BindInfo::new(info) };
///     bind.add_result_column("n", quack_rs::types::TypeId::BigInt);
/// });
/// ```
#[macro_export]
macro_rules! table_bind_callback {
    ($name:ident, |$info:ident| $body:block) => {
        /// Table function bind callback (generated by `table_bind_callback!`).
        ///
        /// # Safety
        ///
        /// Called by DuckDB. `info` is provided by the DuckDB runtime.
        #[allow(unused_unsafe)]
        pub unsafe extern "C" fn $name($info: ::libduckdb_sys::duckdb_bind_info) {
            let result = ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| $body));
            if let Err(panic) = result {
                let c_msg =
                    $crate::callback::message_to_c_string(&$crate::callback::panic_message(&panic));
                // SAFETY: `info` is the pointer DuckDB passed in.
                unsafe {
                    ::libduckdb_sys::duckdb_bind_set_error($info, c_msg.as_ptr());
                }
            }
        }
    };
}

/// Generates a panic-safe `unsafe extern "C"` table function **init** callback.
///
/// Emits `unsafe extern "C" fn $name(info: duckdb_init_info)`. Use it for both
/// the global `init` and the per-thread `local_init` callback — they share a
/// signature. A panic is reported through `duckdb_init_set_error`.
///
/// # Example
///
/// ```rust,no_run
/// quack_rs::table_init_callback!(my_init, |info| {
///     let init = unsafe { quack_rs::table::InitInfo::new(info) };
///     init.set_max_threads(1);
/// });
/// ```
#[macro_export]
macro_rules! table_init_callback {
    ($name:ident, |$info:ident| $body:block) => {
        /// Table function init callback (generated by `table_init_callback!`).
        ///
        /// # Safety
        ///
        /// Called by DuckDB. `info` is provided by the DuckDB runtime.
        #[allow(unused_unsafe)]
        pub unsafe extern "C" fn $name($info: ::libduckdb_sys::duckdb_init_info) {
            let result = ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| $body));
            if let Err(panic) = result {
                let c_msg =
                    $crate::callback::message_to_c_string(&$crate::callback::panic_message(&panic));
                // SAFETY: `info` is the pointer DuckDB passed in.
                unsafe {
                    ::libduckdb_sys::duckdb_init_set_error($info, c_msg.as_ptr());
                }
            }
        }
    };
}

/// Generates a panic-safe `unsafe extern "C"` aggregate **update** callback.
///
/// Emits
/// `unsafe extern "C" fn $name(info: duckdb_function_info, input: duckdb_data_chunk, states: *mut duckdb_aggregate_state)`.
/// A panic is reported through `duckdb_aggregate_function_set_error`.
///
/// Aggregate callbacks run on `DuckDB`'s worker threads, so an unguarded panic
/// here aborts the process from a thread the user never sees.
///
/// # Example
///
/// ```rust,no_run
/// quack_rs::aggregate_update_callback!(my_update, |info, input, states| {
///     let _ = (input, states);
/// });
/// ```
#[macro_export]
macro_rules! aggregate_update_callback {
    ($name:ident, |$info:ident, $input:ident, $states:ident| $body:block) => {
        /// Aggregate update callback (generated by `aggregate_update_callback!`).
        ///
        /// # Safety
        ///
        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
        #[allow(unused_unsafe)]
        pub unsafe extern "C" fn $name(
            $info: ::libduckdb_sys::duckdb_function_info,
            $input: ::libduckdb_sys::duckdb_data_chunk,
            $states: *mut ::libduckdb_sys::duckdb_aggregate_state,
        ) {
            let result = ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| $body));
            if let Err(panic) = result {
                let c_msg =
                    $crate::callback::message_to_c_string(&$crate::callback::panic_message(&panic));
                // SAFETY: `info` is the pointer DuckDB passed in.
                unsafe {
                    ::libduckdb_sys::duckdb_aggregate_function_set_error($info, c_msg.as_ptr());
                }
            }
        }
    };
}

/// Generates a panic-safe `unsafe extern "C"` aggregate **combine** callback.
///
/// Emits
/// `unsafe extern "C" fn $name(info: duckdb_function_info, source: *mut duckdb_aggregate_state, target: *mut duckdb_aggregate_state, count: idx_t)`.
///
/// # Pitfall L1
///
/// `target` states are freshly zero-initialised, so the body must propagate
/// **every** field of the state, not only the accumulated data. See
/// [`CombineFn`][crate::aggregate::callbacks::CombineFn].
///
/// # Example
///
/// ```rust,no_run
/// quack_rs::aggregate_combine_callback!(my_combine, |info, source, target, count| {
///     let _ = (source, target, count);
/// });
/// ```
#[macro_export]
macro_rules! aggregate_combine_callback {
    ($name:ident, |$info:ident, $source:ident, $target:ident, $count:ident| $body:block) => {
        /// Aggregate combine callback (generated by `aggregate_combine_callback!`).
        ///
        /// # Safety
        ///
        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
        #[allow(unused_unsafe)]
        pub unsafe extern "C" fn $name(
            $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,
        ) {
            let result = ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| $body));
            if let Err(panic) = result {
                let c_msg =
                    $crate::callback::message_to_c_string(&$crate::callback::panic_message(&panic));
                // SAFETY: `info` is the pointer DuckDB passed in.
                unsafe {
                    ::libduckdb_sys::duckdb_aggregate_function_set_error($info, c_msg.as_ptr());
                }
            }
        }
    };
}

/// Generates a panic-safe `unsafe extern "C"` aggregate **finalize** callback.
///
/// Emits
/// `unsafe extern "C" fn $name(info: duckdb_function_info, source: *mut duckdb_aggregate_state, result: duckdb_vector, count: idx_t, offset: idx_t)`.
///
/// Results are written starting at `offset` in the output vector, not at 0.
///
/// # Example
///
/// ```rust,no_run
/// quack_rs::aggregate_finalize_callback!(my_finalize, |info, source, result, count, offset| {
///     let _ = (source, result, count, offset);
/// });
/// ```
#[macro_export]
macro_rules! aggregate_finalize_callback {
    ($name:ident, |$info:ident, $source:ident, $result:ident, $count:ident, $offset:ident| $body:block) => {
        /// Aggregate finalize callback (generated by `aggregate_finalize_callback!`).
        ///
        /// # Safety
        ///
        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
        #[allow(unused_unsafe)]
        pub unsafe extern "C" fn $name(
            $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,
        ) {
            let outcome = ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| $body));
            if let Err(panic) = outcome {
                let c_msg =
                    $crate::callback::message_to_c_string(&$crate::callback::panic_message(&panic));
                // SAFETY: `info` is the pointer DuckDB passed in.
                unsafe {
                    ::libduckdb_sys::duckdb_aggregate_function_set_error($info, c_msg.as_ptr());
                }
            }
        }
    };
}

/// Generates a panic-safe `unsafe extern "C"` aggregate **state destructor**.
///
/// Emits `unsafe extern "C" fn $name(states: *mut duckdb_aggregate_state, count: idx_t)`.
///
/// This callback receives no `info`, so `DuckDB` offers no way to report an
/// error from it. A panic is therefore caught and **swallowed**: that leaks
/// whatever the destructor had not yet freed, which is strictly better than
/// aborting the database process during query teardown.
///
/// # Example
///
/// ```rust,no_run
/// quack_rs::aggregate_destroy_callback!(my_destroy, |states, count| {
///     let _ = (states, count);
/// });
/// ```
#[macro_export]
macro_rules! aggregate_destroy_callback {
    ($name:ident, |$states:ident, $count:ident| $body:block) => {
        /// Aggregate state destructor (generated by `aggregate_destroy_callback!`).
        ///
        /// # Safety
        ///
        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
        #[allow(unused_unsafe)]
        pub unsafe extern "C" fn $name(
            $states: *mut ::libduckdb_sys::duckdb_aggregate_state,
            $count: ::libduckdb_sys::idx_t,
        ) {
            // DuckDB provides no error channel for the destructor, so the panic
            // is dropped rather than reported. Leaking beats aborting.
            let _ = ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| $body));
        }
    };
}

/// Generates a panic-safe `unsafe extern "C"` **cast** callback.
///
/// Emits
/// `unsafe extern "C" fn $name(info: duckdb_function_info, count: idx_t, input: duckdb_vector, output: duckdb_vector) -> bool`.
/// The body must evaluate to `bool` — `true` when every row converted.
///
/// A panic is reported through `duckdb_cast_function_set_error` and the
/// generated function returns `false`, which `DuckDB` treats as a failed cast
/// (and `TRY_CAST` turns into NULL).
///
/// # Example
///
/// ```rust,no_run
/// quack_rs::cast_callback!(my_cast, |info, count, input, output| {
///     let _ = (count, input, output);
///     true
/// });
/// ```
#[macro_export]
macro_rules! cast_callback {
    ($name:ident, |$info:ident, $count:ident, $input:ident, $output:ident| $body:block) => {
        /// Cast function callback (generated by `cast_callback!`).
        ///
        /// # Safety
        ///
        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
        #[allow(unused_unsafe)]
        pub unsafe extern "C" fn $name(
            $info: ::libduckdb_sys::duckdb_function_info,
            $count: ::libduckdb_sys::idx_t,
            $input: ::libduckdb_sys::duckdb_vector,
            $output: ::libduckdb_sys::duckdb_vector,
        ) -> bool {
            let outcome: ::std::result::Result<bool, _> =
                ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| $body));
            match outcome {
                ::std::result::Result::Ok(ok) => ok,
                ::std::result::Result::Err(panic) => {
                    let c_msg = $crate::callback::message_to_c_string(
                        &$crate::callback::panic_message(&panic),
                    );
                    // SAFETY: `info` is the pointer DuckDB passed in.
                    unsafe {
                        ::libduckdb_sys::duckdb_cast_function_set_error($info, c_msg.as_ptr());
                    }
                    false
                }
            }
        }
    };
}

/// Generates a panic-safe `unsafe extern "C"` **replacement scan** callback.
///
/// Emits
/// `unsafe extern "C" fn $name(info: duckdb_replacement_scan_info, table_name: *const c_char, data: *mut c_void)`.
/// A panic is reported through `duckdb_replacement_scan_set_error`.
///
/// # Example
///
/// ```rust,no_run
/// quack_rs::replacement_scan_callback!(my_scan, |info, table_name, data| {
///     let _ = (info, table_name, data);
/// });
/// ```
#[macro_export]
macro_rules! replacement_scan_callback {
    ($name:ident, |$info:ident, $table_name:ident, $data:ident| $body:block) => {
        /// Replacement scan callback (generated by `replacement_scan_callback!`).
        ///
        /// # Safety
        ///
        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
        #[allow(unused_unsafe)]
        pub unsafe extern "C" fn $name(
            $info: ::libduckdb_sys::duckdb_replacement_scan_info,
            $table_name: *const ::std::os::raw::c_char,
            $data: *mut ::std::os::raw::c_void,
        ) {
            let result = ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| $body));
            if let Err(panic) = result {
                let c_msg =
                    $crate::callback::message_to_c_string(&$crate::callback::panic_message(&panic));
                // SAFETY: `info` is the pointer DuckDB passed in.
                unsafe {
                    ::libduckdb_sys::duckdb_replacement_scan_set_error($info, c_msg.as_ptr());
                }
            }
        }
    };
}

/// Wraps a `COPY ... TO` **bind** callback so a panic becomes a `DuckDB` error.
///
/// Requires the `duckdb-1-5` feature: `duckdb_copy_function_bind_set_error`
/// lives past the stable prefix of `duckdb_ext_api_v1`.
///
/// # Example
///
/// ```rust,no_run
/// # #[cfg(feature = "duckdb-1-5")]
/// quack_rs::copy_bind_callback!(my_bind, |info| {
///     let _ = info;
/// });
/// ```
#[cfg(feature = "duckdb-1-5")]
#[macro_export]
macro_rules! copy_bind_callback {
    ($name:ident, |$info:ident| $body:block) => {
        $crate::__copy_callback_impl!(
            $name,
            $info,
            duckdb_copy_function_bind_info,
            duckdb_copy_function_bind_set_error,
            $body
        );
    };
}

/// Wraps a `COPY ... TO` **global init** callback so a panic becomes a
/// `DuckDB` error.
///
/// Requires the `duckdb-1-5` feature.
///
/// # Example
///
/// ```rust,no_run
/// # #[cfg(feature = "duckdb-1-5")]
/// quack_rs::copy_global_init_callback!(my_init, |info| {
///     let _ = info;
/// });
/// ```
#[cfg(feature = "duckdb-1-5")]
#[macro_export]
macro_rules! copy_global_init_callback {
    ($name:ident, |$info:ident| $body:block) => {
        $crate::__copy_callback_impl!(
            $name,
            $info,
            duckdb_copy_function_global_init_info,
            duckdb_copy_function_global_init_set_error,
            $body
        );
    };
}

/// Wraps a `COPY ... TO` **finalize** callback so a panic becomes a `DuckDB`
/// error.
///
/// Requires the `duckdb-1-5` feature.
///
/// # Example
///
/// ```rust,no_run
/// # #[cfg(feature = "duckdb-1-5")]
/// quack_rs::copy_finalize_callback!(my_finalize, |info| {
///     let _ = info;
/// });
/// ```
#[cfg(feature = "duckdb-1-5")]
#[macro_export]
macro_rules! copy_finalize_callback {
    ($name:ident, |$info:ident| $body:block) => {
        $crate::__copy_callback_impl!(
            $name,
            $info,
            duckdb_copy_function_finalize_info,
            duckdb_copy_function_finalize_set_error,
            $body
        );
    };
}

/// Shared body of the single-argument copy-function callback macros.
///
/// Not part of the public API: it exists because bind, global init and finalize
/// differ only in their info type and their `set_error` function.
#[cfg(feature = "duckdb-1-5")]
#[doc(hidden)]
#[macro_export]
macro_rules! __copy_callback_impl {
    ($name:ident, $info:ident, $info_ty:ident, $set_error:ident, $body:block) => {
        /// Copy function callback (generated by a `copy_*_callback!` macro).
        ///
        /// # Safety
        ///
        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
        #[allow(unused_unsafe)]
        pub unsafe extern "C" fn $name($info: ::libduckdb_sys::$info_ty) {
            let result = ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| $body));
            if let ::std::result::Result::Err(panic) = result {
                let c_msg =
                    $crate::callback::message_to_c_string(&$crate::callback::panic_message(&panic));
                // SAFETY: `info` is the pointer DuckDB passed in.
                unsafe {
                    ::libduckdb_sys::$set_error($info, c_msg.as_ptr());
                }
            }
        }
    };
}

/// Wraps a `COPY ... TO` **sink** callback so a panic becomes a `DuckDB` error.
///
/// The sink takes a data chunk as well as its info handle, so it has its own
/// macro rather than sharing the single-argument implementation.
///
/// Requires the `duckdb-1-5` feature.
///
/// # Example
///
/// ```rust,no_run
/// # #[cfg(feature = "duckdb-1-5")]
/// quack_rs::copy_sink_callback!(my_sink, |info, chunk| {
///     let _ = (info, chunk);
/// });
/// ```
#[cfg(feature = "duckdb-1-5")]
#[macro_export]
macro_rules! copy_sink_callback {
    ($name:ident, |$info:ident, $chunk:ident| $body:block) => {
        /// Copy function sink callback (generated by `copy_sink_callback!`).
        ///
        /// # Safety
        ///
        /// Called by DuckDB. All parameters are provided by the DuckDB runtime.
        #[allow(unused_unsafe)]
        pub unsafe extern "C" fn $name(
            $info: ::libduckdb_sys::duckdb_copy_function_sink_info,
            $chunk: ::libduckdb_sys::duckdb_data_chunk,
        ) {
            let result = ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| $body));
            if let ::std::result::Result::Err(panic) = result {
                let c_msg =
                    $crate::callback::message_to_c_string(&$crate::callback::panic_message(&panic));
                // SAFETY: `info` is the pointer DuckDB passed in.
                unsafe {
                    ::libduckdb_sys::duckdb_copy_function_sink_set_error($info, c_msg.as_ptr());
                }
            }
        }
    };
}

/// Extracts a human-readable message from a `catch_unwind` payload.
///
/// Used by every macro in this module. Public because the generated callbacks
/// expand at the call site and need to reach it.
///
/// # Example
///
/// ```rust
/// let payload = std::panic::catch_unwind(|| panic!("boom")).unwrap_err();
/// assert_eq!(quack_rs::callback::panic_message(&payload), "boom");
/// ```
#[must_use]
pub fn panic_message(payload: &Box<dyn std::any::Any + Send>) -> String {
    payload.downcast_ref::<&str>().map_or_else(
        || {
            payload
                .downcast_ref::<String>()
                .map_or_else(|| String::from("<non-string panic payload>"), Clone::clone)
        },
        |s| (*s).to_string(),
    )
}

/// Converts a panic message into a `CString`, replacing any interior NUL.
///
/// `CString::new` rejects interior NULs, and a panic message is arbitrary user
/// text — dropping the diagnostic because it happened to contain a NUL would be
/// the wrong trade.
///
/// # Example
///
/// ```rust
/// let c = quack_rs::callback::message_to_c_string("a\0b");
/// assert_eq!(c.to_str().unwrap(), "a?b");
/// ```
#[must_use]
pub fn message_to_c_string(message: &str) -> std::ffi::CString {
    std::ffi::CString::new(message.replace('\0', "?"))
        .unwrap_or_else(|_| std::ffi::CString::default())
}