Skip to main content

quack_rs/
entry_point.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//! Extension entry point helper.
7//!
8//! Provides [`init_extension`], the core helper called by the `entry_point!` macro.
9//!
10//! # Problem 1: Custom C entry point
11//!
12//! `DuckDB`'s Rust crate does not provide a safe way to obtain a raw
13//! `duckdb_connection` handle for function registration. The prior approach
14//! using `extract_raw_connection` relied on `Rc<RefCell<InnerConnection>>` layout,
15//! causing SEGFAULTs. The correct approach is a hand-written C entry point that:
16//!
17//! 1. Calls `duckdb_rs_extension_api_init(info, access, "v1.2.0")`
18//! 2. Calls `access.get_database(info)` to get a `duckdb_database`
19//! 3. Calls `duckdb_connect(db, &mut raw_con)` to get a `duckdb_connection`
20//! 4. Registers all functions
21//! 5. Calls `duckdb_disconnect(&mut raw_con)`
22//!
23//! # Pitfall L3: No panic across FFI
24//!
25//! `init_extension` uses `Result` for all error propagation and never calls
26//! `unwrap()` or `panic!()` inside an FFI callback.
27//!
28//! # Registration is transactional
29//!
30//! The registration connection is an ordinary connection, so the entry point
31//! runs the closure inside `BEGIN TRANSACTION` on it, `COMMIT`s when the
32//! closure returns `Ok` and `ROLLBACK`s when it returns `Err` or panics
33//! ([`Registration::Transactional`], the default). Every registration the C API
34//! makes through a connection joins that transaction. So a `LOAD` that fails
35//! part-way leaves **no catalog entry** behind — no scalar, aggregate or table
36//! function, macro, type, copy function or table the closure created — and
37//! retrying it in the same database works. Before quack-rs 0.20 the functions
38//! registered before the failure stayed, and every retry failed at the first
39//! name it registered again.
40//!
41//! What is **not** rolled back, because `DuckDB` keeps it in the database
42//! configuration rather than the catalog: casts
43//! ([`register_cast`][crate::connection::Registrar::register_cast]),
44//! replacement scans and configuration options. A retry registers a cast
45//! again (the new one replaces the old) and appends a second replacement
46//! scan, and quack-rs refuses a configuration option whose name is taken, so
47//! register those **last**, after everything that can fail.
48//!
49//! What the transaction changes for the closure:
50//!
51//! - A statement or registration that fails can abort the transaction
52//!   (`DuckDB` 2.0 aborts it on every failed statement; 1.x on most failures
53//!   that are not binder, catalog or parser errors), after which every later
54//!   statement in the closure fails with "Current transaction is aborted".
55//!   Return the first error rather than carrying on past it.
56//! - The closure must not run `BEGIN`, `COMMIT` or `ROLLBACK` on the
57//!   registration connection.
58//! - What the closure creates is visible to other connections only once the
59//!   `LOAD` commits, including a connection the closure opened itself with
60//!   [`Connection::open_connection`].
61//!
62//! Choose [`Registration::Autocommit`] (through [`EntryPointOptions`]) to get
63//! the old behaviour back: every statement commits on its own.
64//!
65//! The transaction costs two statements, `BEGIN` and `COMMIT`, per `LOAD`.
66//! A `LOAD` issued inside the host's own transaction does not wait on it: the
67//! registration connection is a separate connection with a transaction of its
68//! own, which commits on its own (so the host rolling back does not undo the
69//! registrations), and `DuckDB`'s catalog reports a conflicting write as an
70//! error rather than waiting for the other transaction.
71//!
72//! # `panic = "abort"` is refused at compile time
73//!
74//! Every panic guard in quack-rs is `std::panic::catch_unwind`, which does
75//! nothing when the extension is built with `panic = "abort"`. So
76//! [`entry_point!`][crate::entry_point!] and [`entry_point_v2!`][crate::entry_point_v2!] fail to compile there, with an error
77//! that names the fix (`panic = "unwind"` under `[profile.release]`). The check
78//! runs in the extension's crate, where the profile applies; an entry point
79//! written by hand around [`init_extension_v2`] has no such check.
80//!
81//! Even under `panic = "unwind"` a few failures abort the `DuckDB` process
82//! whatever quack-rs does: a panic while another panic unwinds (a `Drop` that
83//! panics during the unwind), a panic hook that panics, and running out of
84//! memory. See [`crate::callback`].
85//!
86//! # Edition 2024
87//!
88//! The macros expand cleanly in an edition-2024 extension, and are written so
89//! that they keep doing so once quack-rs itself moves to that edition
90//! (`#[unsafe(no_mangle)]`):
91//!
92//! ```rust,no_run,edition2024
93//! use quack_rs::abi::AbiPolicy;
94//! use quack_rs::error::ExtensionError;
95//!
96//! fn register(_con: libduckdb_sys::duckdb_connection) -> Result<(), ExtensionError> {
97//!     Ok(())
98//! }
99//!
100//! quack_rs::entry_point!(a_init_c_api, |con| register(con));
101//! quack_rs::entry_point!(b_init_c_api, AbiPolicy::Trust, |con| register(con));
102//! quack_rs::entry_point_v2!(c_init_c_api, |_con| Ok(()));
103//! quack_rs::entry_point_v2!(d_init_c_api, AbiPolicy::Warn, |_con| Ok(()));
104//! quack_rs::entry_point_v2!(
105//!     e_init_c_api,
106//!     options = quack_rs::entry_point::EntryPointOptions::new(),
107//!     |_con| Ok(())
108//! );
109//! ```
110//!
111//! # Usage
112//!
113//! Extension authors typically use the `entry_point!` macro,
114//! which generates the required `#[unsafe(no_mangle)] extern "C"` function automatically.
115//!
116//! If you need full control over the entry point, you can call `init_extension`
117//! directly:
118//!
119//! ```rust,no_run
120//! use quack_rs::entry_point::init_extension;
121//!
122//! #[unsafe(no_mangle)]
123//! pub unsafe extern "C" fn my_extension_init_c_api(
124//!     info: libduckdb_sys::duckdb_extension_info,
125//!     access: *const libduckdb_sys::duckdb_extension_access,
126//! ) -> bool {
127//!     unsafe {
128//!         init_extension(info, access, quack_rs::DUCKDB_API_VERSION, |con| {
129//!             // register functions with `con: libduckdb_sys::duckdb_connection`
130//!             Ok(())
131//!         })
132//!     }
133//! }
134//! ```
135
136use std::io::Write as _;
137
138use libduckdb_sys::{
139    duckdb_connect, duckdb_connection, duckdb_disconnect, duckdb_extension_access,
140    duckdb_extension_info, duckdb_rs_extension_api_init, DuckDBSuccess,
141};
142
143use crate::abi::AbiPolicy;
144use crate::connection::Connection;
145use crate::error::ExtensionError;
146
147mod registration;
148
149#[cfg(feature = "duckdb-1-5")]
150pub(crate) use registration::{copy_format_scope, record_copy_format};
151pub use registration::{EntryPointOptions, Registration};
152
153/// Generates the `#[unsafe(no_mangle)] unsafe extern "C"` entry point for a `DuckDB` extension.
154///
155/// This macro eliminates the boilerplate of writing the entry point manually.
156/// It emits a `#[unsafe(no_mangle)] pub unsafe extern "C"` function with the name you
157/// supply, which `DuckDB` locates by symbol when loading the extension.
158///
159/// # Arguments
160///
161/// - `$fn_name`: The exact symbol name `DuckDB` will call (e.g.,
162///   `my_extension_init_c_api`). `DuckDB` requires this to follow the
163///   `{extension_name}_init_c_api` convention.
164/// - `$register`: A closure or function of type
165///   `fn(duckdb_connection) -> Result<(), ExtensionError>` that registers your
166///   functions on the given connection.
167///
168/// # ABI policy and options
169///
170/// A three-argument form takes an [`AbiPolicy`] between the name and the
171/// closure, and `options = ` an [`EntryPointOptions`] sets the policy and the
172/// [`Registration`] mode together:
173///
174/// ```rust,no_run
175/// use quack_rs::abi::AbiPolicy;
176/// use quack_rs::entry_point::{EntryPointOptions, Registration};
177/// use quack_rs::error::ExtensionError;
178///
179/// quack_rs::entry_point!(my_ext_init_c_api, AbiPolicy::Trust, |_con| {
180///     Ok::<(), ExtensionError>(())
181/// });
182/// quack_rs::entry_point!(
183///     my_other_ext_init_c_api,
184///     options = EntryPointOptions::new().registration(Registration::Autocommit),
185///     |_con| Ok::<(), ExtensionError>(())
186/// );
187/// ```
188///
189/// The default is [`AbiPolicy::Strict`], which
190/// refuses to load when the running `DuckDB` does not provide the C API struct
191/// layout this extension was compiled against. See [`crate::abi`].
192///
193/// # `panic = "abort"`
194///
195/// The macro fails to compile when the extension is built with
196/// `panic = "abort"`, under which none of quack-rs's panic guards work. See the
197/// [module documentation](mod@crate::entry_point#panic--abort-is-refused-at-compile-time).
198///
199/// The closure runs in one transaction, so a failed `LOAD` leaves no catalog
200/// entry behind; casts, replacement scans and configuration options are not
201/// rolled back. See the
202/// [module documentation](mod@crate::entry_point#registration-is-transactional).
203///
204/// # Example
205///
206/// ```rust,no_run
207/// use quack_rs::entry_point;
208/// use quack_rs::error::ExtensionError;
209///
210/// fn register_functions(
211///     _con: libduckdb_sys::duckdb_connection,
212/// ) -> Result<(), ExtensionError> {
213///     Ok(())
214/// }
215///
216/// entry_point!(my_extension_init_c_api, |con| register_functions(con));
217/// ```
218#[macro_export]
219macro_rules! entry_point {
220    ($fn_name:ident, $register:expr) => {
221        $crate::entry_point!($fn_name, $crate::abi::AbiPolicy::Strict, $register);
222    };
223    ($fn_name:ident, options = $options:expr, $register:expr) => {
224        $crate::__quack_rs_entry_point_fn!(
225            $fn_name,
226            __entry_point_with_options,
227            || -> $crate::entry_point::EntryPointOptions { $options },
228            $register
229        );
230    };
231    ($fn_name:ident, $policy:expr, $register:expr) => {
232        $crate::__quack_rs_entry_point_fn!($fn_name, __entry_point, || $policy, $register);
233    };
234}
235
236/// Generates the `#[unsafe(no_mangle)] unsafe extern "C"` entry point using the
237/// version-agnostic [`Connection`] facade.
238///
239/// This is the recommended alternative to [`entry_point!`][crate::entry_point!]. The registration
240/// callback receives a <code>&[Connection]</code> instead of a raw `duckdb_connection`,
241/// giving access to the [`Registrar`][crate::connection::Registrar] trait and to
242/// both the connection and database handles.
243///
244/// # Arguments
245///
246/// - `$fn_name`: The exact symbol name `DuckDB` will call.
247/// - `$register`: A closure of type `fn(&Connection) -> Result<(), ExtensionError>`.
248///
249/// Like [`entry_point!`][crate::entry_point!], it takes an optional [`AbiPolicy`], or
250/// `options = ` an [`EntryPointOptions`], between the two, and fails to
251/// compile under `panic = "abort"`.
252///
253/// The closure runs in one transaction, so a failed `LOAD` leaves no catalog
254/// entry behind; casts, replacement scans and configuration options are not
255/// rolled back. See the
256/// [module documentation](mod@crate::entry_point#registration-is-transactional).
257///
258/// # Example
259///
260/// ```rust,no_run
261/// use quack_rs::connection::Registrar;
262/// use quack_rs::error::ExtensionError;
263/// use quack_rs::connection::Connection;
264///
265/// quack_rs::entry_point_v2!(my_extension_init_c_api, |con| {
266///     // unsafe { con.register_scalar(builder)? };
267///     Ok(())
268/// });
269/// ```
270#[macro_export]
271macro_rules! entry_point_v2 {
272    ($fn_name:ident, $register:expr) => {
273        $crate::entry_point_v2!($fn_name, $crate::abi::AbiPolicy::Strict, $register);
274    };
275    ($fn_name:ident, options = $options:expr, $register:expr) => {
276        $crate::__quack_rs_entry_point_fn!(
277            $fn_name,
278            __entry_point_v2_with_options,
279            || -> $crate::entry_point::EntryPointOptions { $options },
280            $register
281        );
282    };
283    ($fn_name:ident, $policy:expr, $register:expr) => {
284        $crate::__quack_rs_entry_point_fn!($fn_name, __entry_point_v2, || $policy, $register);
285    };
286}
287
288/// The `extern "C"` function both entry-point macros generate: `$helper` is
289/// one of the `__entry_point*` functions, `$options` the closure that yields
290/// its policy or options. Not public API.
291#[doc(hidden)]
292#[macro_export]
293macro_rules! __quack_rs_entry_point_fn {
294    ($fn_name:ident, $helper:ident, $options:expr, $register:expr) => {
295        $crate::__quack_rs_refuse_panic_abort!();
296
297        /// DuckDB extension entry point (generated by quack-rs's `entry_point!`
298        /// or `entry_point_v2!`).
299        ///
300        /// # Safety
301        ///
302        /// Called by DuckDB. `info` and `access` are provided by the DuckDB runtime.
303        // `unsafe(...)`: accepted on every edition since Rust 1.82, and
304        // required once quack-rs itself moves to edition 2024, where a bare
305        // `#[no_mangle]` in this macro would fail every crate that expands it
306        // (`cargo fix --edition` does not rewrite macro bodies).
307        #[unsafe(no_mangle)]
308        // `$register` is expanded inside the `unsafe` block below, so the
309        // `unsafe { … }` a registration closure rightly writes around its own
310        // unsafe calls would otherwise warn as nested (`unused_unsafe`), and
311        // fail a `-D warnings` build of the extension.
312        #[allow(unused_unsafe)]
313        pub unsafe extern "C" fn $fn_name(
314            info: ::libduckdb_sys::duckdb_extension_info,
315            access: *const ::libduckdb_sys::duckdb_extension_access,
316        ) -> bool {
317            // The arguments are evaluated inside the entry point's panic guard.
318            // SAFETY: `info` and `access` are the pointers DuckDB passed to this
319            // entry point, valid for the call, which is the helper's contract.
320            unsafe {
321                $crate::entry_point::$helper(
322                    info,
323                    access,
324                    $crate::DUCKDB_API_VERSION,
325                    $options,
326                    || $register,
327                )
328            }
329        }
330    };
331}
332
333/// Fails the build of an extension compiled with `panic = "abort"`. Expanded
334/// by [`entry_point!`][crate::entry_point!] and [`entry_point_v2!`][crate::entry_point_v2!], so the `cfg` is the
335/// extension's own: a check in quack-rs's own code would also stop crates
336/// that use quack-rs only for its tooling. Not public API.
337///
338/// Every panic guard in quack-rs is `std::panic::catch_unwind`, which catches
339/// nothing under `panic = "abort"`: a panic anywhere in the extension would
340/// abort the `DuckDB` process instead of failing one statement.
341#[doc(hidden)]
342#[macro_export]
343macro_rules! __quack_rs_refuse_panic_abort {
344    () => {
345        #[cfg(panic = "abort")]
346        ::core::compile_error!(
347            "quack-rs: this DuckDB extension is being compiled with `panic = \"abort\"`. \
348             quack-rs turns a panic in extension code into a DuckDB error with \
349             `std::panic::catch_unwind`, which does nothing under `panic = \"abort\"`, so any \
350             panic would abort the whole DuckDB process. Build it with `panic = \"unwind\"`: \
351             set it under `[profile.release]` (and under any other profile you build the \
352             extension with) in Cargo.toml, and remove `-C panic=abort` from RUSTFLAGS."
353        );
354    };
355}
356
357/// Core entry point helper — sets up a connection and calls your registration closure.
358///
359/// This function encapsulates the correct initialization sequence for a `DuckDB`
360/// loadable extension written in Rust:
361///
362/// 1. Calls `duckdb_rs_extension_api_init` with the given `api_version`.
363/// 2. Extracts the `duckdb_database` via `access.get_database`.
364/// 3. Opens a `duckdb_connection` via `duckdb_connect`.
365/// 4. Calls `register(connection)`.
366/// 5. Disconnects with `duckdb_disconnect`.
367/// 6. On any error, reports via `access.set_error` and returns `false`.
368///
369/// The closure runs in one transaction, so a failed `LOAD` leaves no catalog
370/// entry behind; casts, replacement scans and configuration options are not
371/// rolled back. See the
372/// [module documentation](mod@crate::entry_point#registration-is-transactional).
373///
374/// # Return value
375///
376/// Returns `true` if initialization succeeded, `false` on any error.
377///
378/// # Safety
379///
380/// - `info` must be the `duckdb_extension_info` passed by `DuckDB` to your entry point.
381/// - `access` must be the `*const duckdb_extension_access` passed by `DuckDB`.
382/// - Both pointers must remain valid for the duration of this call.
383///
384/// # Pitfall L3: No panic across FFI
385///
386/// This function never panics. All errors are reported via `access.set_error`
387/// (when `access` itself is null, there is nowhere to report one, and the
388/// function returns `false`).
389///
390/// # Example
391///
392/// ```rust,no_run
393/// use quack_rs::entry_point::init_extension;
394///
395/// #[unsafe(no_mangle)]
396/// pub unsafe extern "C" fn my_ext_init_c_api(
397///     info: libduckdb_sys::duckdb_extension_info,
398///     access: *const libduckdb_sys::duckdb_extension_access,
399/// ) -> bool {
400///     unsafe {
401///         init_extension(info, access, quack_rs::DUCKDB_API_VERSION, |_con| {
402///             // Register your functions here
403///             Ok(())
404///         })
405///     }
406/// }
407/// ```
408pub unsafe fn init_extension<F>(
409    info: duckdb_extension_info,
410    access: *const duckdb_extension_access,
411    api_version: &str,
412    register: F,
413) -> bool
414where
415    F: FnOnce(duckdb_connection) -> Result<(), ExtensionError>,
416{
417    // SAFETY: forwarded from this function's own contract.
418    unsafe {
419        init_extension_with_options(
420            info,
421            access,
422            api_version,
423            EntryPointOptions::default(),
424            register,
425        )
426    }
427}
428
429/// [`init_extension`] with an explicit [`AbiPolicy`].
430///
431/// Use this to opt out of the C API layout check — for example when the
432/// extension's metadata already makes `DuckDB` refuse a mismatched release:
433/// `C_STRUCT` with C API v1.5.6 ([`DUCKDB_API_VERSION_1_5_6`][crate::DUCKDB_API_VERSION_1_5_6]),
434/// built against the v1.5.6 bindings, which `DuckDB` before v1.5.6 refuses, or
435/// `C_STRUCT_UNSTABLE` on `DuckDB` 1.x, which pins the binary to one release
436/// (`DuckDB` 2.0 cannot load a `C_STRUCT_UNSTABLE` binary built by quack-rs).
437///
438/// # Safety
439///
440/// Same invariants as [`init_extension`].
441pub unsafe fn init_extension_with_policy<F>(
442    info: duckdb_extension_info,
443    access: *const duckdb_extension_access,
444    api_version: &str,
445    policy: AbiPolicy,
446    register: F,
447) -> bool
448where
449    F: FnOnce(duckdb_connection) -> Result<(), ExtensionError>,
450{
451    // SAFETY: forwarded from this function's own contract.
452    unsafe { init_extension_with_options(info, access, api_version, policy.into(), register) }
453}
454
455/// [`init_extension`] with explicit [`EntryPointOptions`]: the [`AbiPolicy`]
456/// and the [`Registration`] mode.
457///
458/// # Safety
459///
460/// Same invariants as [`init_extension`].
461pub unsafe fn init_extension_with_options<F>(
462    info: duckdb_extension_info,
463    access: *const duckdb_extension_access,
464    api_version: &str,
465    options: EntryPointOptions,
466    register: F,
467) -> bool
468where
469    F: FnOnce(duckdb_connection) -> Result<(), ExtensionError>,
470{
471    // SAFETY: `init_extension_internal`'s `# Safety` is "same invariants as
472    // `init_extension`", which this function's own `# Safety` ("same invariants as
473    // `init_extension`") passes on unchanged: `info` and `access` are the pointers DuckDB
474    // passed to the entry point, valid for the duration of this call.
475    match unsafe { init_extension_internal(info, access, api_version, options, register) } {
476        Ok(result) => result,
477        Err(e) => {
478            // SAFETY: access is a valid pointer per the caller's contract.
479            unsafe { report_error(info, access, &e) };
480            false
481        }
482    }
483}
484
485/// Core entry point helper — sets up a [`Connection`] and calls your registration closure.
486///
487/// Identical to [`init_extension`] except that the callback receives a
488/// <code>&[Connection]</code> instead of a raw `duckdb_connection`. [`Connection`]
489/// implements [`Registrar`][crate::connection::Registrar] and also exposes the
490/// `duckdb_database` handle for replacement scan registration.
491///
492/// Prefer this over [`init_extension`] for new extensions. The raw
493/// `duckdb_connection` entry point is retained for backward compatibility.
494///
495/// The closure runs in one transaction, so a failed `LOAD` leaves no catalog
496/// entry behind; casts, replacement scans and configuration options are not
497/// rolled back. See the
498/// [module documentation](mod@crate::entry_point#registration-is-transactional).
499///
500/// # Return value
501///
502/// Returns `true` if initialization succeeded, `false` on any error.
503///
504/// # Safety
505///
506/// - `info` must be the `duckdb_extension_info` passed by `DuckDB` to your entry point.
507/// - `access` must be the `*const duckdb_extension_access` passed by `DuckDB`.
508/// - Both pointers must remain valid for the duration of this call.
509///
510/// # Example
511///
512/// ```rust,no_run
513/// use quack_rs::entry_point::init_extension_v2;
514/// use quack_rs::connection::Registrar;
515///
516/// #[unsafe(no_mangle)]
517/// pub unsafe extern "C" fn my_ext_init_c_api(
518///     info: libduckdb_sys::duckdb_extension_info,
519///     access: *const libduckdb_sys::duckdb_extension_access,
520/// ) -> bool {
521///     unsafe {
522///         init_extension_v2(info, access, quack_rs::DUCKDB_API_VERSION, |con| {
523///             // unsafe { con.register_scalar(builder)?; }
524///             Ok(())
525///         })
526///     }
527/// }
528/// ```
529pub unsafe fn init_extension_v2<F>(
530    info: duckdb_extension_info,
531    access: *const duckdb_extension_access,
532    api_version: &str,
533    register: F,
534) -> bool
535where
536    F: FnOnce(&Connection) -> Result<(), crate::error::ExtensionError>,
537{
538    // SAFETY: forwarded from this function's own contract.
539    unsafe {
540        init_extension_v2_with_options(
541            info,
542            access,
543            api_version,
544            EntryPointOptions::default(),
545            register,
546        )
547    }
548}
549
550/// [`init_extension_v2`] with an explicit [`AbiPolicy`].
551///
552/// See [`init_extension_with_policy`].
553///
554/// # Safety
555///
556/// Same invariants as [`init_extension_v2`].
557pub unsafe fn init_extension_v2_with_policy<F>(
558    info: duckdb_extension_info,
559    access: *const duckdb_extension_access,
560    api_version: &str,
561    policy: AbiPolicy,
562    register: F,
563) -> bool
564where
565    F: FnOnce(&Connection) -> Result<(), crate::error::ExtensionError>,
566{
567    // SAFETY: forwarded from this function's own contract.
568    unsafe { init_extension_v2_with_options(info, access, api_version, policy.into(), register) }
569}
570
571/// [`init_extension_v2`] with explicit [`EntryPointOptions`]: the
572/// [`AbiPolicy`] and the [`Registration`] mode.
573///
574/// # Safety
575///
576/// Same invariants as [`init_extension_v2`].
577pub unsafe fn init_extension_v2_with_options<F>(
578    info: duckdb_extension_info,
579    access: *const duckdb_extension_access,
580    api_version: &str,
581    options: EntryPointOptions,
582    register: F,
583) -> bool
584where
585    F: FnOnce(&Connection) -> Result<(), crate::error::ExtensionError>,
586{
587    // SAFETY: `init_extension_v2_internal`'s `# Safety` is "same invariants as
588    // `init_extension_v2`", which this function's own `# Safety` ("same invariants as
589    // `init_extension_v2`") passes on unchanged: `info` and `access` are the pointers
590    // DuckDB passed to the entry point, valid for the duration of this call.
591    match unsafe { init_extension_v2_internal(info, access, api_version, options, register) } {
592        Ok(result) => result,
593        Err(e) => {
594            // SAFETY: access is a valid pointer per the caller's contract.
595            unsafe { report_error(info, access, &e) };
596            false
597        }
598    }
599}
600
601/// Internal implementation of [`init_extension_v2`] using `?` for error propagation.
602///
603/// # Safety
604///
605/// Same invariants as [`init_extension_v2`].
606unsafe fn init_extension_v2_internal<F>(
607    info: duckdb_extension_info,
608    access: *const duckdb_extension_access,
609    api_version: &str,
610    options: EntryPointOptions,
611    register: F,
612) -> Result<bool, crate::error::ExtensionError>
613where
614    F: FnOnce(&Connection) -> Result<(), crate::error::ExtensionError>,
615{
616    // Step 1: Initialize the DuckDB C API.
617    //
618    // PITFALL P2: Use the C API version, not the DuckDB release version.
619    // Every DuckDB 1.4.x and 1.5.x release loads C API version v1.2.0 (1.5.6
620    // declares v1.5.6 and accepts every earlier version).
621    //
622    // `duckdb_rs_extension_api_init` builds a CString from `api_version` and
623    // unwraps; an interior NUL would panic across the C entry point.
624    if api_version.contains('\0') {
625        return Err(crate::error::ExtensionError::new(
626            "api_version must not contain an interior NUL byte",
627        ));
628    }
629
630    // SAFETY: `access` is the pointer DuckDB passed; the helper only reads it.
631    unsafe { check_access(access)? };
632
633    // SAFETY: info and access are valid pointers provided by DuckDB.
634    let have_api = unsafe {
635        duckdb_rs_extension_api_init(info, access, api_version)
636            .map_err(|e| crate::error::ExtensionError::new(e.to_string()))?
637    };
638
639    if !have_api {
640        return Ok(false);
641    }
642
643    // Step 1b: Verify the C API struct layout before touching anything past the
644    // stable prefix. See `crate::abi` for why this matters.
645    //
646    // SAFETY: the dispatch table was initialised by the call above.
647    unsafe { enforce_abi_policy(info, access, options.get_abi_policy())? };
648
649    // Step 2: Get the database handle. `None` means DuckDB failed and has
650    // already recorded why; reporting again would overwrite its message.
651    // SAFETY: info and access are the pointers DuckDB passed to the entry point.
652    let Some(db) = (unsafe { database_from_access(info, access)? }) else {
653        return Ok(false);
654    };
655
656    // Step 3: Open a connection for function registration.
657    let mut raw_con: duckdb_connection = core::ptr::null_mut();
658    // SAFETY: db is a valid duckdb_database returned by get_database.
659    let rc = unsafe { duckdb_connect(db, &raw mut raw_con) };
660    if rc != DuckDBSuccess {
661        return Err(crate::error::ExtensionError::new(
662            "duckdb_connect failed during extension initialization",
663        ));
664    }
665
666    // Step 4: Build the Connection facade and call the user's registration closure.
667    //
668    // SAFETY: raw_con and db are both valid for the duration of this scope.
669    let con = unsafe { Connection::from_raw(raw_con, db) };
670    // PITFALL L3: see `init_extension_internal` — user code must not unwind out
671    // of the C entry point. `registration::run` runs the closure under
672    // `catch_unwind`, in a transaction unless the options say otherwise.
673    // SAFETY: `raw_con` is open on `db` and used by nothing else meanwhile.
674    let result =
675        unsafe { registration::run(raw_con, db, options.get_registration(), || register(&con)) };
676
677    // Step 5: Always disconnect, even if registration failed.
678    // SAFETY: raw_con was successfully created by duckdb_connect above.
679    unsafe { duckdb_disconnect(&raw mut raw_con) };
680
681    result?;
682    Ok(true)
683}
684
685/// Internal implementation using `?` for ergonomic error propagation.
686///
687/// # Safety
688///
689/// Same invariants as [`init_extension`].
690unsafe fn init_extension_internal<F>(
691    info: duckdb_extension_info,
692    access: *const duckdb_extension_access,
693    api_version: &str,
694    options: EntryPointOptions,
695    register: F,
696) -> Result<bool, ExtensionError>
697where
698    F: FnOnce(duckdb_connection) -> Result<(), ExtensionError>,
699{
700    // Step 1: Initialize the DuckDB C API. This must be called before any other
701    // libduckdb_sys function in a loadable extension. The version string must be
702    // the C API version (e.g. "v1.2.0"), NOT the DuckDB release version.
703    //
704    // PITFALL P2: Use the C API version, not the DuckDB release version.
705    // Every DuckDB 1.4.x and 1.5.x release loads C API version v1.2.0 (1.5.6
706    // declares v1.5.6 and accepts every earlier version).
707    //
708    // `duckdb_rs_extension_api_init` builds a CString from `api_version` and
709    // unwraps; an interior NUL would panic across the C entry point.
710    if api_version.contains('\0') {
711        return Err(ExtensionError::new(
712            "api_version must not contain an interior NUL byte",
713        ));
714    }
715
716    // SAFETY: `access` is the pointer DuckDB passed; the helper only reads it.
717    unsafe { check_access(access)? };
718
719    // SAFETY: info and access are valid pointers provided by DuckDB.
720    let have_api = unsafe {
721        duckdb_rs_extension_api_init(info, access, api_version)
722            .map_err(|e| ExtensionError::new(e.to_string()))?
723    };
724
725    if !have_api {
726        // DuckDB indicated that the API version is not available. Return false
727        // without an error — this can happen when the extension is loaded by
728        // an older DuckDB version that predates the requested API version.
729        return Ok(false);
730    }
731
732    // Step 1b: Verify the C API struct layout before touching anything past the
733    // stable prefix. See `crate::abi` for why this matters.
734    //
735    // SAFETY: the dispatch table was initialised by the call above.
736    unsafe { enforce_abi_policy(info, access, options.get_abi_policy())? };
737
738    // Step 2: Get the database handle. `None` means DuckDB failed and has
739    // already recorded why; reporting again would overwrite its message.
740    // SAFETY: info and access are the pointers DuckDB passed to the entry point.
741    let Some(db) = (unsafe { database_from_access(info, access)? }) else {
742        return Ok(false);
743    };
744
745    // Step 3: Open a connection for function registration.
746    let mut raw_con: duckdb_connection = core::ptr::null_mut();
747    // SAFETY: db is a valid duckdb_database returned by get_database.
748    let rc = unsafe { duckdb_connect(db, &raw mut raw_con) };
749    if rc != DuckDBSuccess {
750        return Err(ExtensionError::new(
751            "duckdb_connect failed during extension initialization",
752        ));
753    }
754
755    // Step 4: Call the user's registration closure.
756    //
757    // PITFALL L3: a panic must never unwind across the C entry point. The
758    // closure is arbitrary user code, so it is run inside `catch_unwind` and any
759    // panic is converted into an `ExtensionError` that DuckDB reports as a LOAD
760    // failure. (`catch_unwind` is inert under `panic = "abort"`; see the module
761    // docs for why quack-rs recommends `panic = "unwind"` for extensions.)
762    // `registration::run` does that, in a transaction unless the options say
763    // otherwise.
764    // SAFETY: `raw_con` is open on `db` and used by nothing else meanwhile.
765    let result = unsafe {
766        registration::run(raw_con, db, options.get_registration(), || {
767            register(raw_con)
768        })
769    };
770
771    // Step 5: Always disconnect, even if registration failed.
772    // SAFETY: raw_con was successfully created by duckdb_connect above.
773    unsafe { duckdb_disconnect(&raw mut raw_con) };
774
775    result?;
776    Ok(true)
777}
778
779/// Fetches the `duckdb_database` through `access.get_database`.
780///
781/// Returns `Ok(None)` when `get_database` returns a null pointer. `DuckDB`'s
782/// implementation (`ExtensionAccess::GetDatabase` in
783/// `src/main/extension/extension_load.cpp`) returns null only after catching an
784/// exception, and it records that exception as the load error before returning —
785/// so the caller must return `false` **without** calling `set_error`, which would
786/// replace `DuckDB`'s own diagnostic with a vaguer one. The loader then throws
787/// the recorded error.
788///
789/// # Errors
790///
791/// Returns an error if `access.get_database` itself is null; that is a broken
792/// access struct, and nothing has been reported yet.
793///
794/// # Safety
795///
796/// `access` must be a valid, non-null `duckdb_extension_access` and `info` the
797/// matching `duckdb_extension_info`.
798unsafe fn database_from_access(
799    info: duckdb_extension_info,
800    access: *const duckdb_extension_access,
801) -> Result<Option<libduckdb_sys::duckdb_database>, ExtensionError> {
802    // SAFETY: `access` is valid per this function's contract.
803    let get_database = unsafe { (*access).get_database }
804        .ok_or_else(|| ExtensionError::new("get_database function pointer is null"))?;
805    // SAFETY: `info` is the handle DuckDB passed with `access`.
806    let db_ptr = unsafe { get_database(info) };
807    if db_ptr.is_null() {
808        return Ok(None);
809    }
810    // SAFETY: non-null, and DuckDB keeps the wrapper it points to alive for the
811    // whole load (`load_state.database_data`).
812    Ok(Some(unsafe { *db_ptr }))
813}
814
815/// Evaluates an entry-point macro's `$policy` and `$register` arguments, with
816/// a panic in either turned into an error rather than unwinding out of the
817/// generated `extern "C"` function.
818fn evaluate_arguments<P, R, F>(
819    options: P,
820    register: R,
821) -> Result<(EntryPointOptions, F), ExtensionError>
822where
823    P: FnOnce() -> EntryPointOptions,
824    R: FnOnce() -> F,
825{
826    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (options(), register()))).map_err(
827        |panic| {
828            ExtensionError::new(format!(
829                "evaluating the entry point's arguments panicked: {}",
830                crate::callback::take_panic_message(panic)
831            ))
832        },
833    )
834}
835
836/// What [`entry_point!`][crate::entry_point!] expands to with an [`AbiPolicy`] argument:
837/// [`init_extension_with_options`], with the macro's arguments evaluated
838/// under the panic guard. Not public API.
839///
840/// # Safety
841///
842/// Same invariants as [`init_extension`].
843#[doc(hidden)]
844pub unsafe fn __entry_point<P, R, F>(
845    info: duckdb_extension_info,
846    access: *const duckdb_extension_access,
847    api_version: &str,
848    policy: P,
849    register: R,
850) -> bool
851where
852    P: FnOnce() -> AbiPolicy,
853    R: FnOnce() -> F,
854    F: FnOnce(duckdb_connection) -> Result<(), ExtensionError>,
855{
856    // SAFETY: forwarded from this function's own contract.
857    unsafe { __entry_point_with_options(info, access, api_version, || policy().into(), register) }
858}
859
860/// What [`entry_point!`][crate::entry_point!] expands to with `options = `. Not public API.
861///
862/// # Safety
863///
864/// Same invariants as [`init_extension`].
865#[doc(hidden)]
866pub unsafe fn __entry_point_with_options<P, R, F>(
867    info: duckdb_extension_info,
868    access: *const duckdb_extension_access,
869    api_version: &str,
870    options: P,
871    register: R,
872) -> bool
873where
874    P: FnOnce() -> EntryPointOptions,
875    R: FnOnce() -> F,
876    F: FnOnce(duckdb_connection) -> Result<(), ExtensionError>,
877{
878    match evaluate_arguments(options, register) {
879        // SAFETY: forwarded from this function's own contract.
880        Ok((options, register)) => unsafe {
881            init_extension_with_options(info, access, api_version, options, register)
882        },
883        Err(e) => {
884            // SAFETY: `access` is null or valid per the caller's contract.
885            unsafe { report_error(info, access, &e) };
886            false
887        }
888    }
889}
890
891/// What [`entry_point_v2!`][crate::entry_point_v2!] expands to with an [`AbiPolicy`] argument:
892/// [`init_extension_v2_with_options`], with the macro's arguments evaluated
893/// under the panic guard. Not public API.
894///
895/// # Safety
896///
897/// Same invariants as [`init_extension_v2`].
898#[doc(hidden)]
899pub unsafe fn __entry_point_v2<P, R, F>(
900    info: duckdb_extension_info,
901    access: *const duckdb_extension_access,
902    api_version: &str,
903    policy: P,
904    register: R,
905) -> bool
906where
907    P: FnOnce() -> AbiPolicy,
908    R: FnOnce() -> F,
909    F: FnOnce(&Connection) -> Result<(), ExtensionError>,
910{
911    // SAFETY: forwarded from this function's own contract.
912    unsafe {
913        __entry_point_v2_with_options(info, access, api_version, || policy().into(), register)
914    }
915}
916
917/// What [`entry_point_v2!`][crate::entry_point_v2!] expands to with `options = `. Not public API.
918///
919/// # Safety
920///
921/// Same invariants as [`init_extension_v2`].
922#[doc(hidden)]
923pub unsafe fn __entry_point_v2_with_options<P, R, F>(
924    info: duckdb_extension_info,
925    access: *const duckdb_extension_access,
926    api_version: &str,
927    options: P,
928    register: R,
929) -> bool
930where
931    P: FnOnce() -> EntryPointOptions,
932    R: FnOnce() -> F,
933    F: FnOnce(&Connection) -> Result<(), ExtensionError>,
934{
935    match evaluate_arguments(options, register) {
936        // SAFETY: forwarded from this function's own contract.
937        Ok((options, register)) => unsafe {
938            init_extension_v2_with_options(info, access, api_version, options, register)
939        },
940        Err(e) => {
941            // SAFETY: `access` is null or valid per the caller's contract.
942            unsafe { report_error(info, access, &e) };
943            false
944        }
945    }
946}
947
948/// Runs the user's registration closure, converting any panic into an
949/// [`ExtensionError`] instead of letting it unwind across the C boundary.
950///
951/// # Pitfall L3: no panic across FFI
952///
953/// The registration closure is arbitrary user code. Without this, a panic
954/// unwinds to the `#[unsafe(no_mangle)] extern "C"` entry point, where Rust
955/// aborts the whole process — taking the user's `DuckDB` session with it.
956/// Catching it here turns a bug in registration into an ordinary `LOAD` error.
957///
958/// `catch_unwind` cannot catch anything when the extension is built with
959/// `panic = "abort"`, which is why the entry-point macros refuse to compile
960/// there.
961fn catch_registration_panic<F>(register: F) -> Result<(), ExtensionError>
962where
963    F: FnOnce() -> Result<(), ExtensionError>,
964{
965    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(register)) {
966        Ok(result) => result,
967        // The payload is user data whose `Drop` may itself panic; dropping it
968        // here, unguarded, would unwind out of the C entry point after all.
969        Err(panic) => Err(ExtensionError::new(format!(
970            "extension registration panicked: {}",
971            crate::callback::take_panic_message(panic)
972        ))),
973    }
974}
975
976/// Refuses an `access` that `duckdb_rs_extension_api_init` cannot use: it
977/// dereferences `access` and calls `get_api` through `Option::unwrap`, so a
978/// null pointer would crash and a missing `get_api` would panic across the C
979/// entry point. A released `DuckDB` always sets both for a loadable extension;
980/// unreleased `DuckDB` (`main`) passes a null `get_api` when it links a C API
981/// extension statically.
982///
983/// # Safety
984///
985/// `access` must be null or point at a live `duckdb_extension_access`.
986unsafe fn check_access(access: *const duckdb_extension_access) -> Result<(), ExtensionError> {
987    if access.is_null() {
988        return Err(ExtensionError::new(
989            "DuckDB passed a null extension access struct",
990        ));
991    }
992    // SAFETY: `access` is non-null and live per this function's contract.
993    if unsafe { (*access).get_api }.is_none() {
994        return Err(ExtensionError::new(
995            "DuckDB passed no get_api function, so the C API cannot be initialised",
996        ));
997    }
998    Ok(())
999}
1000
1001/// Applies an [`AbiPolicy`] to the result of [`crate::abi::check`].
1002///
1003/// Returns `Err` when [`policy_verdict`] refuses the load. Under
1004/// [`AbiPolicy::Warn`] the diagnostic goes to stderr and loading continues
1005/// (not through `set_error`, which would fail the load: see below); under
1006/// [`AbiPolicy::Trust`] no check runs.
1007///
1008/// # Safety
1009///
1010/// The `DuckDB` C API dispatch table must already be initialised, and `info` /
1011/// `access` must be the pointers `DuckDB` passed to the entry point.
1012unsafe fn enforce_abi_policy(
1013    info: duckdb_extension_info,
1014    access: *const duckdb_extension_access,
1015    policy: AbiPolicy,
1016) -> Result<(), ExtensionError> {
1017    if policy == AbiPolicy::Trust {
1018        return Ok(());
1019    }
1020    // SAFETY: forwarded from this function's own contract.
1021    let check = unsafe { crate::abi::check() };
1022    let message = match policy_verdict(policy, &check) {
1023        AbiVerdict::Load => return Ok(()),
1024        AbiVerdict::Refuse(message) => return Err(ExtensionError::new(message)),
1025        AbiVerdict::Warn(message) => message,
1026    };
1027    // AbiPolicy::Warn: surface the diagnostic without failing the load.
1028    //
1029    // This deliberately does NOT go through `access.set_error`. DuckDB's loader
1030    // throws whenever an extension called `set_error`, regardless of what the
1031    // init function returned:
1032    //
1033    //     if (load_state.has_error) {
1034    //         load_state.error_data.Throw("An error was thrown during ...");
1035    //     }
1036    //
1037    // — so reporting a *warning* that way would abort the load and make `Warn`
1038    // indistinguishable from `Strict`. The C extension API has no non-fatal
1039    // diagnostic channel, so stderr is the honest one.
1040    //
1041    // `eprintln!` panics when the write fails (a closed pipe, a full disk),
1042    // and this runs under the C entry point, outside the registration
1043    // closure's `catch_unwind`: a panic here would abort the host process.
1044    // A lost warning is the right trade.
1045    let _ = (info, access);
1046    let _ = writeln!(std::io::stderr(), "quack-rs warning: {message}");
1047    Ok(())
1048}
1049
1050/// What an [`AbiPolicy`] makes of one [`AbiCheck`][crate::abi::AbiCheck].
1051#[derive(Debug, PartialEq, Eq)]
1052enum AbiVerdict {
1053    Load,
1054    /// Load, and print the diagnostic.
1055    Warn(String),
1056    /// Fail the load with the diagnostic.
1057    Refuse(String),
1058}
1059
1060/// The decision [`enforce_abi_policy`] applies, kept pure so every policy can
1061/// be tested against every check result without a `DuckDB`.
1062///
1063/// A passing check loads under every policy. A failing one is refused, except
1064/// that [`AbiPolicy::Warn`] only warns, [`AbiPolicy::AllowUnknownEngine`]
1065/// loads on an engine release the table has no entry for (it still refuses a
1066/// layout it can identify as different), and [`AbiPolicy::Trust`] loads.
1067fn policy_verdict(policy: AbiPolicy, check: &crate::abi::AbiCheck) -> AbiVerdict {
1068    let Some(message) = check.error_message() else {
1069        return AbiVerdict::Load;
1070    };
1071    match policy {
1072        AbiPolicy::Trust => AbiVerdict::Load,
1073        AbiPolicy::Warn => AbiVerdict::Warn(message),
1074        AbiPolicy::AllowUnknownEngine
1075            if matches!(check, crate::abi::AbiCheck::UnknownEngineVersion { .. }) =>
1076        {
1077            AbiVerdict::Load
1078        }
1079        AbiPolicy::Strict | AbiPolicy::AllowUnknownEngine => AbiVerdict::Refuse(message),
1080    }
1081}
1082
1083/// What a load reports when the registration closure (or quack-rs's own
1084/// setup) returned an [`ExtensionError`] with an empty message.
1085pub const EMPTY_INIT_ERROR_PLACEHOLDER: &str =
1086    "the extension's initialization failed with an empty error message";
1087
1088/// Reports an `ExtensionError` back to `DuckDB` via `access.set_error`.
1089///
1090/// # Safety
1091///
1092/// `info` and `access` must be valid pointers provided by `DuckDB`.
1093unsafe fn report_error(
1094    info: duckdb_extension_info,
1095    access: *const duckdb_extension_access,
1096    error: &ExtensionError,
1097) {
1098    // Defensive: if access is null, we cannot report the error to DuckDB.
1099    if access.is_null() {
1100        return;
1101    }
1102    // SAFETY: access is non-null per the check above and valid per caller's contract.
1103    if let Some(set_error) = unsafe { (*access).set_error } {
1104        // Replace, not truncate at, an interior NUL: the same rule as every
1105        // other error path (`ExtensionError::to_c_string` included). An empty
1106        // message would leave DuckDB's "An error was thrown during
1107        // initialization of the extension '…': " with nothing after it.
1108        let text = if error.as_str().is_empty() {
1109            EMPTY_INIT_ERROR_PLACEHOLDER
1110        } else {
1111            error.as_str()
1112        };
1113        let c_msg = crate::callback::message_to_c_string(text);
1114        // SAFETY: c_msg is a valid CString; info is valid.
1115        unsafe { set_error(info, c_msg.as_ptr()) };
1116    }
1117}
1118
1119#[cfg(test)]
1120mod tests {
1121    // Integration tests for init_extension require a DuckDB instance and are in
1122    // tests/integration_test.rs. Unit tests here verify pure-Rust logic.
1123
1124    use super::{
1125        catch_registration_panic, database_from_access, evaluate_arguments,
1126        init_extension_internal, policy_verdict, AbiPolicy, AbiVerdict, EntryPointOptions,
1127        Registration,
1128    };
1129    use crate::error::ExtensionError;
1130
1131    /// Every policy against every kind of check result. `Trust` skips the
1132    /// check entirely in `enforce_abi_policy`; its row here pins that it
1133    /// would load anyway.
1134    #[test]
1135    fn every_policy_against_every_check_result() {
1136        use crate::abi::AbiCheck;
1137        let checks = [
1138            AbiCheck::Compatible {
1139                engine_version: "v1.5.5".into(),
1140                slots: 546,
1141            },
1142            AbiCheck::StableOnly,
1143            AbiCheck::LayoutMismatch {
1144                engine_version: "v1.5.0".into(),
1145                engine_slots: 545,
1146                compiled_slots: 546,
1147            },
1148            AbiCheck::UnknownEngineVersion {
1149                engine_version: "v9.9.9".into(),
1150                compiled_slots: 546,
1151            },
1152            AbiCheck::EngineVersionUnavailable {
1153                compiled_slots: 546,
1154            },
1155            AbiCheck::DeclaredVersionMismatch {
1156                declared_version: "v1.2.0".into(),
1157                declared_slots: 0,
1158                compiled_slots: 546,
1159            },
1160        ];
1161        // Expected verdict per check, in the order above: L = load,
1162        // W = warn and load, R = refuse.
1163        let table: [(AbiPolicy, [char; 6]); 4] = [
1164            (AbiPolicy::Strict, ['L', 'L', 'R', 'R', 'R', 'R']),
1165            (AbiPolicy::Warn, ['L', 'L', 'W', 'W', 'W', 'W']),
1166            (
1167                AbiPolicy::AllowUnknownEngine,
1168                ['L', 'L', 'R', 'L', 'R', 'R'],
1169            ),
1170            (AbiPolicy::Trust, ['L', 'L', 'L', 'L', 'L', 'L']),
1171        ];
1172        for (policy, row) in table {
1173            for (check, want) in checks.iter().zip(row) {
1174                let got = policy_verdict(policy, check);
1175                let message = check.error_message();
1176                let expected = match want {
1177                    'L' => AbiVerdict::Load,
1178                    'W' => AbiVerdict::Warn(message.expect("a failing check has a message")),
1179                    _ => AbiVerdict::Refuse(message.expect("a failing check has a message")),
1180                };
1181                assert_eq!(got, expected, "{policy:?} on {check:?}");
1182            }
1183        }
1184    }
1185
1186    #[test]
1187    fn extension_error_to_c_string() {
1188        let err = ExtensionError::new("test error message");
1189        let cstr = err.to_c_string();
1190        assert_eq!(cstr.to_str().unwrap(), "test error message");
1191    }
1192
1193    #[test]
1194    fn registration_success_passes_through() {
1195        assert!(catch_registration_panic(|| Ok(())).is_ok());
1196    }
1197
1198    #[test]
1199    fn registration_error_passes_through() {
1200        let err = catch_registration_panic(|| Err(ExtensionError::new("nope")))
1201            .expect_err("error must propagate");
1202        assert_eq!(err.as_str(), "nope");
1203    }
1204
1205    #[test]
1206    fn str_panic_is_converted_to_an_error() {
1207        let err =
1208            catch_registration_panic(|| panic!("boom")).expect_err("panic must become an error");
1209        assert!(err.as_str().contains("registration panicked"), "{err}");
1210        assert!(err.as_str().contains("boom"), "{err}");
1211    }
1212
1213    #[test]
1214    fn string_panic_is_converted_to_an_error() {
1215        let err = catch_registration_panic(|| panic!("boom {}", 42))
1216            .expect_err("panic must become an error");
1217        assert!(err.as_str().contains("boom 42"), "{err}");
1218    }
1219
1220    #[test]
1221    fn non_string_panic_payload_still_yields_an_error() {
1222        let err = catch_registration_panic(|| std::panic::panic_any(7u8))
1223            .expect_err("panic must become an error");
1224        assert!(err.as_str().contains("registration panicked"), "{err}");
1225    }
1226
1227    #[test]
1228    fn unwrap_inside_registration_does_not_escape() {
1229        // The single most common way real registration code panics.
1230        fn lookup(key: &str) -> Option<u8> {
1231            (key == "present").then_some(1)
1232        }
1233        let err = catch_registration_panic(|| {
1234            let _ = lookup("missing").unwrap();
1235            Ok(())
1236        })
1237        .expect_err("unwrap panic must become an error");
1238        assert!(err.as_str().contains("registration panicked"), "{err}");
1239    }
1240
1241    #[test]
1242    fn allow_unknown_engine_only_forgives_the_unknown_case() {
1243        use crate::abi::AbiCheck;
1244        // The policy must not become a blanket opt-out: a layout DuckDB can be
1245        // shown to lay out differently is still refused.
1246        let unknown = AbiCheck::UnknownEngineVersion {
1247            engine_version: "v1.6.0".into(),
1248            compiled_slots: 546,
1249        };
1250        let mismatch = AbiCheck::LayoutMismatch {
1251            engine_version: "v1.5.0".into(),
1252            engine_slots: 545,
1253            compiled_slots: 546,
1254        };
1255        assert!(matches!(unknown, AbiCheck::UnknownEngineVersion { .. }));
1256        assert!(!matches!(mismatch, AbiCheck::UnknownEngineVersion { .. }));
1257        assert!(mismatch.error_message().is_some());
1258    }
1259
1260    /// `DuckDB` v2.0.1 is not in the layout table yet (see `abi`'s module
1261    /// docs): the default policy refuses a `duckdb-1-5` build on it, and only
1262    /// the opt-out loads it.
1263    #[test]
1264    fn duckdb_2_0_1_is_refused_by_default_and_loaded_only_by_the_opt_out() {
1265        use crate::abi::AbiCheck;
1266        let check = AbiCheck::UnknownEngineVersion {
1267            engine_version: "v2.0.1".into(),
1268            compiled_slots: 548,
1269        };
1270        assert!(matches!(
1271            policy_verdict(AbiPolicy::default(), &check),
1272            AbiVerdict::Refuse(message) if message.contains("'v2.0.1'")
1273        ));
1274        assert_eq!(
1275            policy_verdict(AbiPolicy::AllowUnknownEngine, &check),
1276            AbiVerdict::Load
1277        );
1278    }
1279
1280    #[test]
1281    fn api_version_with_interior_nul_is_rejected_before_ffi() {
1282        // Must fail before touching DuckDB: libduckdb-sys would otherwise
1283        // `CString::new(..).unwrap()` and panic across the C entry point. Both
1284        // pointers stay null because nothing may dereference them on this path.
1285        let result = unsafe {
1286            init_extension_internal(
1287                core::ptr::null_mut(),
1288                core::ptr::null(),
1289                "v1.2\0.0",
1290                AbiPolicy::Trust.into(),
1291                |_| Ok(()),
1292            )
1293        };
1294        let err = result.expect_err("interior NUL must be rejected");
1295        assert!(err.as_str().contains("NUL"), "{err}");
1296    }
1297
1298    // ─── get_database returning null ────────────────────────────────────────
1299    //
1300    // A fake access struct stands in for DuckDB's here; nothing on this path
1301    // touches the C API dispatch table, so no database is needed.
1302
1303    use libduckdb_sys::{duckdb_database, duckdb_extension_access, duckdb_extension_info};
1304    use std::os::raw::c_char;
1305
1306    unsafe extern "C" fn no_error(_: duckdb_extension_info, _: *const c_char) {}
1307    unsafe extern "C" fn no_api(
1308        _: duckdb_extension_info,
1309        _: *const c_char,
1310    ) -> *const std::os::raw::c_void {
1311        core::ptr::null()
1312    }
1313    unsafe extern "C" fn null_database(_: duckdb_extension_info) -> *mut duckdb_database {
1314        core::ptr::null_mut()
1315    }
1316
1317    /// A sentinel handle: only ever compared, never dereferenced.
1318    static mut FAKE_DB: duckdb_database = 0x5eed as duckdb_database;
1319
1320    unsafe extern "C" fn fake_database(_: duckdb_extension_info) -> *mut duckdb_database {
1321        // Only the address is taken here; no reference to the `static mut` is
1322        // formed.
1323        &raw mut FAKE_DB
1324    }
1325
1326    fn access_with(
1327        get_database: Option<unsafe extern "C" fn(duckdb_extension_info) -> *mut duckdb_database>,
1328    ) -> duckdb_extension_access {
1329        duckdb_extension_access {
1330            set_error: Some(no_error),
1331            get_database,
1332            get_api: Some(no_api),
1333        }
1334    }
1335
1336    /// The message the capturing `set_error` below last received.
1337    static REPORTED: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
1338
1339    unsafe extern "C" fn capture_error(_: duckdb_extension_info, msg: *const c_char) {
1340        // SAFETY: `report_error` passes a live NUL-terminated string.
1341        let text = unsafe { std::ffi::CStr::from_ptr(msg) }
1342            .to_string_lossy()
1343            .into_owned();
1344        if let Ok(mut slot) = REPORTED.lock() {
1345            *slot = Some(text);
1346        }
1347    }
1348
1349    /// A NUL inside an error message is replaced, not truncated at: the same
1350    /// rule as every other `set_error` path in the crate
1351    /// (`callback::message_to_c_string`), so the text after it survives.
1352    #[test]
1353    fn an_init_error_with_an_interior_nul_keeps_its_tail() {
1354        let access = duckdb_extension_access {
1355            set_error: Some(capture_error),
1356            get_database: Some(null_database),
1357            get_api: Some(no_api),
1358        };
1359        // SAFETY: `access` is a valid struct; `info` is never dereferenced.
1360        unsafe {
1361            super::report_error(
1362                core::ptr::null_mut(),
1363                &raw const access,
1364                &crate::error::ExtensionError::new("bad config\0: key `x` missing"),
1365            );
1366        }
1367        let reported = REPORTED.lock().ok().and_then(|mut s| s.take());
1368        assert_eq!(reported.as_deref(), Some("bad config?: key `x` missing"));
1369    }
1370
1371    static REPORTED_EMPTY: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
1372
1373    unsafe extern "C" fn capture_empty(_: duckdb_extension_info, msg: *const c_char) {
1374        // SAFETY: `report_error` passes a live NUL-terminated string.
1375        let text = unsafe { std::ffi::CStr::from_ptr(msg) }
1376            .to_string_lossy()
1377            .into_owned();
1378        if let Ok(mut slot) = REPORTED_EMPTY.lock() {
1379            *slot = Some(text);
1380        }
1381    }
1382
1383    /// An empty error message is replaced, so the failed LOAD says something.
1384    #[test]
1385    fn an_init_error_with_an_empty_message_reports_a_placeholder() {
1386        let access = duckdb_extension_access {
1387            set_error: Some(capture_empty),
1388            get_database: Some(null_database),
1389            get_api: Some(no_api),
1390        };
1391        // SAFETY: `access` is a valid struct; `info` is never dereferenced.
1392        unsafe {
1393            super::report_error(
1394                core::ptr::null_mut(),
1395                &raw const access,
1396                &crate::error::ExtensionError::new(""),
1397            );
1398        }
1399        let reported = REPORTED_EMPTY.lock().ok().and_then(|mut s| s.take());
1400        assert_eq!(
1401            reported.as_deref(),
1402            Some(super::EMPTY_INIT_ERROR_PLACEHOLDER)
1403        );
1404    }
1405
1406    static REPORTED_NO_API: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
1407
1408    unsafe extern "C" fn capture_no_api(_: duckdb_extension_info, msg: *const c_char) {
1409        // SAFETY: `report_error` passes a live NUL-terminated string.
1410        let text = unsafe { std::ffi::CStr::from_ptr(msg) }
1411            .to_string_lossy()
1412            .into_owned();
1413        if let Ok(mut slot) = REPORTED_NO_API.lock() {
1414            *slot = Some(text);
1415        }
1416    }
1417
1418    /// `duckdb_rs_extension_api_init` unwraps `get_api`: a null one panicked
1419    /// across the C entry point (an abort in a real load), and a null
1420    /// `access` was dereferenced. Both now fail the load cleanly.
1421    #[test]
1422    fn a_missing_get_api_or_access_fails_the_load_without_panicking() {
1423        let access = duckdb_extension_access {
1424            set_error: Some(capture_no_api),
1425            get_database: Some(null_database),
1426            get_api: None,
1427        };
1428        // SAFETY: `access` is a valid struct; `info` is never dereferenced.
1429        let loaded = unsafe {
1430            super::init_extension(core::ptr::null_mut(), &raw const access, "v1.2.0", |_| {
1431                Ok(())
1432            })
1433        };
1434        assert!(!loaded);
1435        let reported = REPORTED_NO_API.lock().ok().and_then(|mut s| s.take());
1436        assert!(
1437            reported
1438                .as_deref()
1439                .is_some_and(|m| m.contains("no get_api")),
1440            "{reported:?}"
1441        );
1442        // SAFETY: a null `access` is what is being tested; nothing reads it.
1443        let loaded = unsafe {
1444            super::init_extension(core::ptr::null_mut(), core::ptr::null(), "v1.2.0", |_| {
1445                Ok(())
1446            })
1447        };
1448        assert!(!loaded);
1449    }
1450
1451    #[test]
1452    fn a_null_database_is_reported_as_already_handled() {
1453        // Before the fix this dereferenced the null pointer (SIGSEGV).
1454        let access = access_with(Some(null_database));
1455        // SAFETY: `access` is a valid struct; `info` is never dereferenced.
1456        let db = unsafe { database_from_access(core::ptr::null_mut(), &raw const access) }
1457            .expect("a null database is not a new error");
1458        assert!(db.is_none(), "DuckDB already recorded the error");
1459    }
1460
1461    #[test]
1462    fn a_non_null_database_is_read_through() {
1463        let access = access_with(Some(fake_database));
1464        // SAFETY: as above.
1465        let db = unsafe { database_from_access(core::ptr::null_mut(), &raw const access) }
1466            .expect("get_database succeeded");
1467        assert_eq!(db, Some(0x5eed as duckdb_database));
1468    }
1469
1470    #[test]
1471    fn a_missing_get_database_pointer_is_an_error() {
1472        let access = access_with(None);
1473        // SAFETY: as above.
1474        let err = unsafe { database_from_access(core::ptr::null_mut(), &raw const access) }
1475            .expect_err("no function pointer is our error to report");
1476        assert!(err.as_str().contains("get_database"), "{err}");
1477    }
1478
1479    #[test]
1480    fn a_payload_whose_drop_panics_does_not_escape_registration() {
1481        // Before the fix the payload was dropped outside any guard, so this
1482        // aborted the test binary instead of returning.
1483        struct PayloadBomb;
1484        impl Drop for PayloadBomb {
1485            fn drop(&mut self) {
1486                panic!("payload destructor deliberately exploded");
1487            }
1488        }
1489        let err = catch_registration_panic(|| std::panic::panic_any(PayloadBomb))
1490            .expect_err("panic must become an error");
1491        assert!(err.as_str().contains("registration panicked"), "{err}");
1492    }
1493
1494    #[test]
1495    fn a_panicking_entry_point_argument_is_an_error_naming_the_panic() {
1496        let autocommit = EntryPointOptions::new().registration(Registration::Autocommit);
1497        let (options, register) =
1498            evaluate_arguments(|| autocommit, || 7).expect("no panic, no error");
1499        assert_eq!((options, register), (autocommit, 7));
1500        let err = evaluate_arguments(EntryPointOptions::new, || -> u8 { panic!("bad register") })
1501            .expect_err("a panic is an error");
1502        assert_eq!(
1503            err.as_str(),
1504            "evaluating the entry point's arguments panicked: bad register"
1505        );
1506        let err = evaluate_arguments(|| -> EntryPointOptions { panic!("bad policy") }, || 0)
1507            .expect_err("a panic is an error");
1508        assert!(err.as_str().ends_with("bad policy"), "{err}");
1509    }
1510}