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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
// 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!

//! Extension entry point helper.
//!
//! Provides [`init_extension`], the core helper called by the `entry_point!` macro.
//!
//! # Problem 1: Custom C entry point
//!
//! `DuckDB`'s Rust crate does not provide a safe way to obtain a raw
//! `duckdb_connection` handle for function registration. The prior approach
//! using `extract_raw_connection` relied on `Rc<RefCell<InnerConnection>>` layout,
//! causing SEGFAULTs. The correct approach is a hand-written C entry point that:
//!
//! 1. Calls `duckdb_rs_extension_api_init(info, access, "v1.2.0")`
//! 2. Calls `access.get_database(info)` to get a `duckdb_database`
//! 3. Calls `duckdb_connect(db, &mut raw_con)` to get a `duckdb_connection`
//! 4. Registers all functions
//! 5. Calls `duckdb_disconnect(&mut raw_con)`
//!
//! # Pitfall L3: No panic across FFI
//!
//! `init_extension` uses `Result` for all error propagation and never calls
//! `unwrap()` or `panic!()` inside an FFI callback.
//!
//! # Usage
//!
//! Extension authors typically use the `entry_point!` macro,
//! which generates the required `#[no_mangle] extern "C"` function automatically.
//!
//! If you need full control over the entry point, you can call `init_extension`
//! directly:
//!
//! ```rust,no_run
//! use quack_rs::entry_point::init_extension;
//!
//! #[no_mangle]
//! pub unsafe extern "C" fn my_extension_init_c_api(
//!     info: libduckdb_sys::duckdb_extension_info,
//!     access: *const libduckdb_sys::duckdb_extension_access,
//! ) -> bool {
//!     unsafe {
//!         init_extension(info, access, quack_rs::DUCKDB_API_VERSION, |con| {
//!             // register functions with `con: libduckdb_sys::duckdb_connection`
//!             Ok(())
//!         })
//!     }
//! }
//! ```

use libduckdb_sys::{
    duckdb_connect, duckdb_connection, duckdb_disconnect, duckdb_extension_access,
    duckdb_extension_info, duckdb_rs_extension_api_init, DuckDBSuccess,
};

use crate::abi::AbiPolicy;
use crate::connection::Connection;
use crate::error::ExtensionError;

/// Generates the `#[no_mangle] unsafe extern "C"` entry point for a `DuckDB` extension.
///
/// This macro eliminates the boilerplate of writing the entry point manually.
/// It emits a `#[no_mangle] pub unsafe extern "C"` function with the name you
/// supply, which `DuckDB` locates by symbol when loading the extension.
///
/// # Arguments
///
/// - `$fn_name`: The exact symbol name `DuckDB` will call (e.g.,
///   `my_extension_init_c_api`). `DuckDB` requires this to follow the
///   `{extension_name}_init_c_api` convention.
/// - `$register`: A closure or function of type
///   `fn(duckdb_connection) -> Result<(), ExtensionError>` that registers your
///   functions on the given connection.
///
/// # ABI policy
///
/// A three-argument form takes an [`AbiPolicy`][crate::abi::AbiPolicy] between
/// the name and the closure:
///
/// ```rust,no_run
/// use quack_rs::abi::AbiPolicy;
/// use quack_rs::error::ExtensionError;
///
/// quack_rs::entry_point!(my_ext_init_c_api, AbiPolicy::Trust, |_con| {
///     Ok::<(), ExtensionError>(())
/// });
/// ```
///
/// The default is [`AbiPolicy::Strict`][crate::abi::AbiPolicy::Strict], which
/// refuses to load when the running `DuckDB` does not provide the C API struct
/// layout this extension was compiled against. See [`crate::abi`].
///
/// # Example
///
/// ```rust,no_run
/// use quack_rs::entry_point;
/// use quack_rs::error::ExtensionError;
///
/// fn register_functions(
///     _con: libduckdb_sys::duckdb_connection,
/// ) -> Result<(), ExtensionError> {
///     Ok(())
/// }
///
/// entry_point!(my_extension_init_c_api, |con| register_functions(con));
/// ```
#[macro_export]
macro_rules! entry_point {
    ($fn_name:ident, $register:expr) => {
        $crate::entry_point!($fn_name, $crate::abi::AbiPolicy::Strict, $register);
    };
    ($fn_name:ident, $policy:expr, $register:expr) => {
        /// DuckDB extension entry point (generated by `entry_point!`).
        ///
        /// # Safety
        ///
        /// Called by DuckDB. `info` and `access` are provided by the DuckDB runtime.
        #[no_mangle]
        pub unsafe extern "C" fn $fn_name(
            info: ::libduckdb_sys::duckdb_extension_info,
            access: *const ::libduckdb_sys::duckdb_extension_access,
        ) -> bool {
            unsafe {
                $crate::entry_point::init_extension_with_policy(
                    info,
                    access,
                    $crate::DUCKDB_API_VERSION,
                    $policy,
                    $register,
                )
            }
        }
    };
}

/// Generates the `#[no_mangle] unsafe extern "C"` entry point using the
/// version-agnostic [`Connection`] facade.
///
/// This is the recommended alternative to [`entry_point!`]. The registration
/// callback receives a <code>&[Connection]</code> instead of a raw `duckdb_connection`,
/// giving access to the [`Registrar`][crate::connection::Registrar] trait and to
/// both the connection and database handles.
///
/// # Arguments
///
/// - `$fn_name`: The exact symbol name `DuckDB` will call.
/// - `$register`: A closure of type `fn(&Connection) -> Result<(), ExtensionError>`.
///
/// # Example
///
/// ```rust,no_run
/// use quack_rs::connection::Registrar;
/// use quack_rs::error::ExtensionError;
/// use quack_rs::connection::Connection;
///
/// quack_rs::entry_point_v2!(my_extension_init_c_api, |con| {
///     // unsafe { con.register_scalar(builder)? };
///     Ok(())
/// });
/// ```
#[macro_export]
macro_rules! entry_point_v2 {
    ($fn_name:ident, $register:expr) => {
        $crate::entry_point_v2!($fn_name, $crate::abi::AbiPolicy::Strict, $register);
    };
    ($fn_name:ident, $policy:expr, $register:expr) => {
        /// DuckDB extension entry point (generated by `entry_point_v2!`).
        ///
        /// # Safety
        ///
        /// Called by DuckDB. `info` and `access` are provided by the DuckDB runtime.
        #[no_mangle]
        pub unsafe extern "C" fn $fn_name(
            info: ::libduckdb_sys::duckdb_extension_info,
            access: *const ::libduckdb_sys::duckdb_extension_access,
        ) -> bool {
            unsafe {
                $crate::entry_point::init_extension_v2_with_policy(
                    info,
                    access,
                    $crate::DUCKDB_API_VERSION,
                    $policy,
                    $register,
                )
            }
        }
    };
}

/// Core entry point helper — sets up a connection and calls your registration closure.
///
/// This function encapsulates the correct initialization sequence for a `DuckDB`
/// loadable extension written in Rust:
///
/// 1. Calls `duckdb_rs_extension_api_init` with the given `api_version`.
/// 2. Extracts the `duckdb_database` via `access.get_database`.
/// 3. Opens a `duckdb_connection` via `duckdb_connect`.
/// 4. Calls `register(connection)`.
/// 5. Disconnects with `duckdb_disconnect`.
/// 6. On any error, reports via `access.set_error` and returns `false`.
///
/// # Return value
///
/// Returns `true` if initialization succeeded, `false` on any error.
///
/// # Safety
///
/// - `info` must be the `duckdb_extension_info` passed by `DuckDB` to your entry point.
/// - `access` must be the `*const duckdb_extension_access` passed by `DuckDB`.
/// - Both pointers must remain valid for the duration of this call.
///
/// # Pitfall L3: No panic across FFI
///
/// This function never panics. All errors are reported via `access.set_error`.
///
/// # Example
///
/// ```rust,no_run
/// use quack_rs::entry_point::init_extension;
///
/// #[no_mangle]
/// pub unsafe extern "C" fn my_ext_init_c_api(
///     info: libduckdb_sys::duckdb_extension_info,
///     access: *const libduckdb_sys::duckdb_extension_access,
/// ) -> bool {
///     unsafe {
///         init_extension(info, access, quack_rs::DUCKDB_API_VERSION, |_con| {
///             // Register your functions here
///             Ok(())
///         })
///     }
/// }
/// ```
pub unsafe fn init_extension<F>(
    info: duckdb_extension_info,
    access: *const duckdb_extension_access,
    api_version: &str,
    register: F,
) -> bool
where
    F: FnOnce(duckdb_connection) -> Result<(), ExtensionError>,
{
    // SAFETY: forwarded from this function's own contract.
    unsafe { init_extension_with_policy(info, access, api_version, AbiPolicy::default(), register) }
}

/// [`init_extension`] with an explicit [`AbiPolicy`].
///
/// Use this to opt out of the C API layout check — for example when the
/// extension binary is stamped `C_STRUCT_UNSTABLE`, so `DuckDB` already refuses
/// to load it into any release other than the one it was built for.
///
/// # Safety
///
/// Same invariants as [`init_extension`].
pub unsafe fn init_extension_with_policy<F>(
    info: duckdb_extension_info,
    access: *const duckdb_extension_access,
    api_version: &str,
    policy: AbiPolicy,
    register: F,
) -> bool
where
    F: FnOnce(duckdb_connection) -> Result<(), ExtensionError>,
{
    match unsafe { init_extension_internal(info, access, api_version, policy, register) } {
        Ok(result) => result,
        Err(e) => {
            // SAFETY: access is a valid pointer per the caller's contract.
            unsafe { report_error(info, access, &e) };
            false
        }
    }
}

/// Core entry point helper — sets up a [`Connection`] and calls your registration closure.
///
/// Identical to [`init_extension`] except that the callback receives a
/// <code>&[Connection]</code> instead of a raw `duckdb_connection`. [`Connection`]
/// implements [`Registrar`][crate::connection::Registrar] and also exposes the
/// `duckdb_database` handle for replacement scan registration.
///
/// Prefer this over [`init_extension`] for new extensions. The raw
/// `duckdb_connection` entry point is retained for backward compatibility.
///
/// # Return value
///
/// Returns `true` if initialization succeeded, `false` on any error.
///
/// # Safety
///
/// - `info` must be the `duckdb_extension_info` passed by `DuckDB` to your entry point.
/// - `access` must be the `*const duckdb_extension_access` passed by `DuckDB`.
/// - Both pointers must remain valid for the duration of this call.
///
/// # Example
///
/// ```rust,no_run
/// use quack_rs::entry_point::init_extension_v2;
/// use quack_rs::connection::Registrar;
///
/// #[no_mangle]
/// pub unsafe extern "C" fn my_ext_init_c_api(
///     info: libduckdb_sys::duckdb_extension_info,
///     access: *const libduckdb_sys::duckdb_extension_access,
/// ) -> bool {
///     unsafe {
///         init_extension_v2(info, access, quack_rs::DUCKDB_API_VERSION, |con| {
///             // unsafe { con.register_scalar(builder)?; }
///             Ok(())
///         })
///     }
/// }
/// ```
pub unsafe fn init_extension_v2<F>(
    info: duckdb_extension_info,
    access: *const duckdb_extension_access,
    api_version: &str,
    register: F,
) -> bool
where
    F: FnOnce(&Connection) -> Result<(), crate::error::ExtensionError>,
{
    // SAFETY: forwarded from this function's own contract.
    unsafe {
        init_extension_v2_with_policy(info, access, api_version, AbiPolicy::default(), register)
    }
}

/// [`init_extension_v2`] with an explicit [`AbiPolicy`].
///
/// See [`init_extension_with_policy`].
///
/// # Safety
///
/// Same invariants as [`init_extension_v2`].
pub unsafe fn init_extension_v2_with_policy<F>(
    info: duckdb_extension_info,
    access: *const duckdb_extension_access,
    api_version: &str,
    policy: AbiPolicy,
    register: F,
) -> bool
where
    F: FnOnce(&Connection) -> Result<(), crate::error::ExtensionError>,
{
    match unsafe { init_extension_v2_internal(info, access, api_version, policy, register) } {
        Ok(result) => result,
        Err(e) => {
            // SAFETY: access is a valid pointer per the caller's contract.
            unsafe { report_error(info, access, &e) };
            false
        }
    }
}

/// Internal implementation of [`init_extension_v2`] using `?` for error propagation.
///
/// # Safety
///
/// Same invariants as [`init_extension_v2`].
unsafe fn init_extension_v2_internal<F>(
    info: duckdb_extension_info,
    access: *const duckdb_extension_access,
    api_version: &str,
    policy: AbiPolicy,
    register: F,
) -> Result<bool, crate::error::ExtensionError>
where
    F: FnOnce(&Connection) -> Result<(), crate::error::ExtensionError>,
{
    // Step 1: Initialize the DuckDB C API.
    //
    // PITFALL P2: Use the C API version, not the DuckDB release version.
    // DuckDB v1.4.x and v1.5.x use C API version v1.2.0.
    //
    // `duckdb_rs_extension_api_init` builds a CString from `api_version` and
    // unwraps; an interior NUL would panic across the C entry point.
    if api_version.contains('\0') {
        return Err(crate::error::ExtensionError::new(
            "api_version must not contain an interior NUL byte",
        ));
    }

    // SAFETY: info and access are valid pointers provided by DuckDB.
    let have_api = unsafe {
        duckdb_rs_extension_api_init(info, access, api_version)
            .map_err(|e| crate::error::ExtensionError::new(e.to_string()))?
    };

    if !have_api {
        return Ok(false);
    }

    // Step 1b: Verify the C API struct layout before touching anything past the
    // stable prefix. See `crate::abi` for why this matters.
    //
    // SAFETY: the dispatch table was initialised by the call above.
    unsafe { enforce_abi_policy(info, access, policy)? };

    // Step 2: Get the database handle.
    // SAFETY: access is valid and have_api is true, so get_database is non-null.
    let get_database = unsafe { (*access).get_database }.ok_or_else(|| {
        crate::error::ExtensionError::new("get_database function pointer is null")
    })?;

    // SAFETY: info is valid. The returned pointer is DuckDB-managed.
    let db = unsafe { *get_database(info) };

    // Step 3: Open a connection for function registration.
    let mut raw_con: duckdb_connection = core::ptr::null_mut();
    // SAFETY: db is a valid duckdb_database returned by get_database.
    let rc = unsafe { duckdb_connect(db, &raw mut raw_con) };
    if rc != DuckDBSuccess {
        return Err(crate::error::ExtensionError::new(
            "duckdb_connect failed during extension initialization",
        ));
    }

    // Step 4: Build the Connection facade and call the user's registration closure.
    //
    // SAFETY: raw_con and db are both valid for the duration of this scope.
    let con = unsafe { Connection::from_raw(raw_con, db) };
    // PITFALL L3: see `init_extension_internal` — user code must not unwind out
    // of the C entry point.
    let result = catch_registration_panic(|| register(&con));

    // Step 5: Always disconnect, even if registration failed.
    // SAFETY: raw_con was successfully created by duckdb_connect above.
    unsafe { duckdb_disconnect(&raw mut raw_con) };

    result?;
    Ok(true)
}

/// Internal implementation using `?` for ergonomic error propagation.
///
/// # Safety
///
/// Same invariants as [`init_extension`].
unsafe fn init_extension_internal<F>(
    info: duckdb_extension_info,
    access: *const duckdb_extension_access,
    api_version: &str,
    policy: AbiPolicy,
    register: F,
) -> Result<bool, ExtensionError>
where
    F: FnOnce(duckdb_connection) -> Result<(), ExtensionError>,
{
    // Step 1: Initialize the DuckDB C API. This must be called before any other
    // libduckdb_sys function in a loadable extension. The version string must be
    // the C API version (e.g. "v1.2.0"), NOT the DuckDB release version.
    //
    // PITFALL P2: Use the C API version, not the DuckDB release version.
    // DuckDB v1.4.x and v1.5.x use C API version v1.2.0.
    //
    // `duckdb_rs_extension_api_init` builds a CString from `api_version` and
    // unwraps; an interior NUL would panic across the C entry point.
    if api_version.contains('\0') {
        return Err(ExtensionError::new(
            "api_version must not contain an interior NUL byte",
        ));
    }

    // SAFETY: info and access are valid pointers provided by DuckDB.
    let have_api = unsafe {
        duckdb_rs_extension_api_init(info, access, api_version)
            .map_err(|e| ExtensionError::new(e.to_string()))?
    };

    if !have_api {
        // DuckDB indicated that the API version is not available. Return false
        // without an error — this can happen when the extension is loaded by
        // an older DuckDB version that predates the requested API version.
        return Ok(false);
    }

    // Step 1b: Verify the C API struct layout before touching anything past the
    // stable prefix. See `crate::abi` for why this matters.
    //
    // SAFETY: the dispatch table was initialised by the call above.
    unsafe { enforce_abi_policy(info, access, policy)? };

    // Step 2: Get the database handle.
    // SAFETY: access is valid and have_api is true, so get_database is non-null.
    let get_database = unsafe { (*access).get_database }
        .ok_or_else(|| ExtensionError::new("get_database function pointer is null"))?;

    // SAFETY: info is valid. The returned pointer is DuckDB-managed.
    let db = unsafe { *get_database(info) };

    // Step 3: Open a connection for function registration.
    let mut raw_con: duckdb_connection = core::ptr::null_mut();
    // SAFETY: db is a valid duckdb_database returned by get_database.
    let rc = unsafe { duckdb_connect(db, &raw mut raw_con) };
    if rc != DuckDBSuccess {
        return Err(ExtensionError::new(
            "duckdb_connect failed during extension initialization",
        ));
    }

    // Step 4: Call the user's registration closure.
    //
    // PITFALL L3: a panic must never unwind across the C entry point. The
    // closure is arbitrary user code, so it is run inside `catch_unwind` and any
    // panic is converted into an `ExtensionError` that DuckDB reports as a LOAD
    // failure. (`catch_unwind` is inert under `panic = "abort"`; see the module
    // docs for why quack-rs recommends `panic = "unwind"` for extensions.)
    let result = catch_registration_panic(|| register(raw_con));

    // Step 5: Always disconnect, even if registration failed.
    // SAFETY: raw_con was successfully created by duckdb_connect above.
    unsafe { duckdb_disconnect(&raw mut raw_con) };

    result?;
    Ok(true)
}

/// Runs the user's registration closure, converting any panic into an
/// [`ExtensionError`] instead of letting it unwind across the C boundary.
///
/// # Pitfall L3: no panic across FFI
///
/// The registration closure is arbitrary user code. Without this, a panic
/// unwinds to the `#[no_mangle] extern "C"` entry point, where Rust aborts the
/// whole process — taking the user's `DuckDB` session with it. Catching it here
/// turns a bug in registration into an ordinary `LOAD` error.
///
/// Note that `catch_unwind` cannot catch anything when the extension is built
/// with `panic = "abort"`. quack-rs's scaffold therefore generates
/// `panic = "unwind"` for extension crates.
fn catch_registration_panic<F>(register: F) -> Result<(), ExtensionError>
where
    F: FnOnce() -> Result<(), ExtensionError>,
{
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(register)) {
        Ok(result) => result,
        Err(panic) => Err(ExtensionError::new(format!(
            "extension registration panicked: {}",
            panic_message(&panic)
        ))),
    }
}

/// Extracts a human-readable message from a `catch_unwind` payload.
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(),
    )
}

/// Applies an [`AbiPolicy`] to the result of [`crate::abi::check`].
///
/// Returns `Err` when the policy is [`AbiPolicy::Strict`] and the running
/// `DuckDB` does not provide the C API struct layout this extension was compiled
/// against. Under [`AbiPolicy::Warn`] the diagnostic is pushed to `DuckDB` via
/// `set_error` but loading continues; under [`AbiPolicy::Trust`] no check runs.
///
/// # Safety
///
/// The `DuckDB` C API dispatch table must already be initialised, and `info` /
/// `access` must be the pointers `DuckDB` passed to the entry point.
unsafe fn enforce_abi_policy(
    info: duckdb_extension_info,
    access: *const duckdb_extension_access,
    policy: AbiPolicy,
) -> Result<(), ExtensionError> {
    if policy == AbiPolicy::Trust {
        return Ok(());
    }
    // SAFETY: forwarded from this function's own contract.
    let check = unsafe { crate::abi::check() };

    // `AllowUnknownEngine` suspends judgement on a release quack-rs has no entry
    // for, but still refuses a layout it can positively identify as different.
    if policy == AbiPolicy::AllowUnknownEngine
        && matches!(check, crate::abi::AbiCheck::UnknownEngineVersion { .. })
    {
        return Ok(());
    }

    let Some(message) = check.error_message() else {
        return Ok(());
    };
    if policy == AbiPolicy::Strict || policy == AbiPolicy::AllowUnknownEngine {
        return Err(ExtensionError::new(message));
    }
    // AbiPolicy::Warn: surface the diagnostic without failing the load.
    //
    // This deliberately does NOT go through `access.set_error`. DuckDB's loader
    // throws whenever an extension called `set_error`, regardless of what the
    // init function returned:
    //
    //     if (load_state.has_error) {
    //         load_state.error_data.Throw("An error was thrown during ...");
    //     }
    //
    // — so reporting a *warning* that way would abort the load and make `Warn`
    // indistinguishable from `Strict`. The C extension API has no non-fatal
    // diagnostic channel, so stderr is the honest one.
    let _ = (info, access);
    eprintln!("quack-rs warning: {message}");
    Ok(())
}

/// Reports an `ExtensionError` back to `DuckDB` via `access.set_error`.
///
/// # Safety
///
/// `info` and `access` must be valid pointers provided by `DuckDB`.
unsafe fn report_error(
    info: duckdb_extension_info,
    access: *const duckdb_extension_access,
    error: &ExtensionError,
) {
    // Defensive: if access is null, we cannot report the error to DuckDB.
    if access.is_null() {
        return;
    }
    // SAFETY: access is non-null per the check above and valid per caller's contract.
    if let Some(set_error) = unsafe { (*access).set_error } {
        let c_msg = error.to_c_string();
        // SAFETY: c_msg is a valid CString; info is valid.
        unsafe { set_error(info, c_msg.as_ptr()) };
    }
}

#[cfg(test)]
mod tests {
    // Integration tests for init_extension require a DuckDB instance and are in
    // tests/integration_test.rs. Unit tests here verify pure-Rust logic.

    use super::{catch_registration_panic, init_extension_internal, AbiPolicy};
    use crate::error::ExtensionError;

    #[test]
    fn extension_error_to_c_string() {
        let err = ExtensionError::new("test error message");
        let cstr = err.to_c_string();
        assert_eq!(cstr.to_str().unwrap(), "test error message");
    }

    #[test]
    fn registration_success_passes_through() {
        assert!(catch_registration_panic(|| Ok(())).is_ok());
    }

    #[test]
    fn registration_error_passes_through() {
        let err = catch_registration_panic(|| Err(ExtensionError::new("nope")))
            .expect_err("error must propagate");
        assert_eq!(err.as_str(), "nope");
    }

    #[test]
    fn str_panic_is_converted_to_an_error() {
        let err =
            catch_registration_panic(|| panic!("boom")).expect_err("panic must become an error");
        assert!(err.as_str().contains("registration panicked"), "{err}");
        assert!(err.as_str().contains("boom"), "{err}");
    }

    #[test]
    fn string_panic_is_converted_to_an_error() {
        let err = catch_registration_panic(|| panic!("boom {}", 42))
            .expect_err("panic must become an error");
        assert!(err.as_str().contains("boom 42"), "{err}");
    }

    #[test]
    fn non_string_panic_payload_still_yields_an_error() {
        let err = catch_registration_panic(|| std::panic::panic_any(7u8))
            .expect_err("panic must become an error");
        assert!(err.as_str().contains("registration panicked"), "{err}");
    }

    #[test]
    fn unwrap_inside_registration_does_not_escape() {
        // The single most common way real registration code panics.
        fn lookup(key: &str) -> Option<u8> {
            (key == "present").then_some(1)
        }
        let err = catch_registration_panic(|| {
            let _ = lookup("missing").unwrap();
            Ok(())
        })
        .expect_err("unwrap panic must become an error");
        assert!(err.as_str().contains("registration panicked"), "{err}");
    }

    #[test]
    fn allow_unknown_engine_only_forgives_the_unknown_case() {
        use crate::abi::AbiCheck;
        // The policy must not become a blanket opt-out: a layout DuckDB can be
        // shown to lay out differently is still refused.
        let unknown = AbiCheck::UnknownEngineVersion {
            engine_version: "v1.6.0".into(),
            compiled_slots: 546,
        };
        let mismatch = AbiCheck::LayoutMismatch {
            engine_version: "v1.5.0".into(),
            engine_slots: 545,
            compiled_slots: 546,
        };
        assert!(matches!(unknown, AbiCheck::UnknownEngineVersion { .. }));
        assert!(!matches!(mismatch, AbiCheck::UnknownEngineVersion { .. }));
        assert!(mismatch.error_message().is_some());
    }

    #[test]
    fn api_version_with_interior_nul_is_rejected_before_ffi() {
        // Must fail before touching DuckDB: libduckdb-sys would otherwise
        // `CString::new(..).unwrap()` and panic across the C entry point. Both
        // pointers stay null because nothing may dereference them on this path.
        let result = unsafe {
            init_extension_internal(
                core::ptr::null_mut(),
                core::ptr::null(),
                "v1.2\0.0",
                AbiPolicy::Trust,
                |_| Ok(()),
            )
        };
        let err = result.expect_err("interior NUL must be rejected");
        assert!(err.as_str().contains("NUL"), "{err}");
    }
}