diesel 2.4.0

A safe, extensible ORM and Query Builder for PostgreSQL, SQLite, and MySQL
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
#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
extern crate libsqlite3_sys as ffi;
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
use sqlite_wasm_rs as ffi;

use crate::result::Error::DatabaseError;
use crate::result::*;
use crate::sqlite::SqliteConnection;
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use core::ffi::{c_char, c_int};
#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
type RawApiPointer = *const core::ffi::c_void;
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
type RawApiPointer = *const ffi::sqlite3_api_routines;

/// SQLite's auto-extension callback type.
type RawAutoExtension = unsafe extern "C" fn(
    db: *mut ffi::sqlite3,
    pz_err_msg: *mut *mut c_char,
    p_api: RawApiPointer,
) -> c_int;

// TODO: diesel 3.0 use `libsqlite3-sys` declarations after raising the minimum to 0.29.
#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
mod auto_extension_ffi {
    use super::{RawAutoExtension, c_int};

    // SAFETY: These declarations match SQLite's C ABI and bypass incompatible callback types in older bindings.
    #[allow(unsafe_code)]
    unsafe extern "C" {
        pub(super) fn sqlite3_auto_extension(entry_point: Option<RawAutoExtension>) -> c_int;
        pub(super) fn sqlite3_cancel_auto_extension(entry_point: Option<RawAutoExtension>)
        -> c_int;
    }
}

#[cfg(all(target_family = "wasm", target_os = "unknown"))]
use ffi as auto_extension_ffi;

use super::BorrowedSqliteConnection;

/// Registers an auto-extension that runs for every SQLite connection opened in
/// this process, including non-Diesel ones.
///
/// This is a safe wrapper around [`sqlite3_auto_extension`][docs]. The callback
/// receives the [`SqliteConnection`] being opened and returns `Ok(())` to
/// continue or an error to fail the open. Use it to register SQL functions,
/// collations, or aggregates through the usual connection API, or to initialize
/// a statically linked C extension such as Spatialite or sqlite-vec via
/// [`SqliteConnection::with_raw_connection`].
///
/// Call this before opening any connection. Extensions run in registration
/// order, and the first error aborts the open. The callback must be a `fn` item
/// or a closure that captures only zero-sized values (enforced at compile
/// time), and registering the same `fn` twice is a no-op. It may run on several
/// threads at once and must not open another connection (which would re-enter
/// the auto-extensions and recurse) or call [`register_auto_extension`],
/// [`cancel_auto_extension`], or [`reset_auto_extension`]. Panics are caught and
/// turned into a failed open.
///
/// [docs]: https://www.sqlite.org/c3ref/auto_extension.html
///
/// # Example
///
/// ```rust
/// # // This test registers Rust callbacks that sqlite invokes through the
/// # // FFI boundary, which is not supported by miri `-Zmiri-native-lib`.
/// # #[cfg(not(miri))]
/// # fn main() {
/// use diesel::dsl::sql;
/// use diesel::prelude::*;
/// use diesel::sql_types::Integer;
/// use diesel::sqlite::{register_auto_extension, reset_auto_extension, SqliteConnection, BorrowedSqliteConnection};
/// use std::pin::Pin;
///
/// // Registers a case-insensitive collation on every new connection.
/// fn my_ext(conn: &mut BorrowedSqliteConnection) -> QueryResult<()> {
///     unsafe {
///         // SAFETY: This is safe as long as we don't move or replace out the
///         // inner SqliteConnection. None of the functions defined on SqliteConnection
///         // do that
///         conn.inner_mut().register_collation("RUSTNOCASE", |a, b| a.to_lowercase().cmp(&b.to_lowercase()))
///     }
/// }
///
/// register_auto_extension(my_ext).unwrap();
///
/// // Every future connection now has the collation.
/// let mut conn = SqliteConnection::establish(":memory:").unwrap();
/// let equal: i32 = sql::<Integer>("SELECT 'a' = 'A' COLLATE RUSTNOCASE")
///     .get_result(&mut conn)
///     .unwrap();
/// assert_eq!(equal, 1);
/// # reset_auto_extension();
/// # }
/// # #[cfg(miri)]
/// # fn main() {}
/// ```
#[allow(unsafe_code)]
pub fn register_auto_extension<F>(extension: F) -> QueryResult<()>
where
    F: Fn(&'_ mut BorrowedSqliteConnection) -> QueryResult<()> + Sync + 'static,
{
    // SAFETY: `entry_point` returns a stable function pointer with SQLite's callback ABI.
    let result =
        unsafe { auto_extension_ffi::sqlite3_auto_extension(Some(entry_point(extension))) };
    if result == ffi::SQLITE_OK {
        Ok(())
    } else {
        Err(DatabaseError(
            DatabaseErrorKind::Unknown,
            Box::new(ffi::code_to_str(result).to_string()),
        ))
    }
}

/// Removes a previously registered auto-extension, returning `true` if it was
/// found ([docs][cancel_docs]).
///
/// Pass the same `fn` item given to [`register_auto_extension`]. A closure
/// cannot be cancelled this way, because its type cannot be named again. Use
/// [`reset_auto_extension`] to clear everything instead.
///
/// [cancel_docs]: https://www.sqlite.org/c3ref/cancel_auto_extension.html
#[allow(unsafe_code)]
pub fn cancel_auto_extension<F>(extension: F) -> bool
where
    F: Fn(&'_ mut BorrowedSqliteConnection) -> QueryResult<()> + Sync + 'static,
{
    // SAFETY: `entry_point` returns the same stable pointer used for registration.
    unsafe { auto_extension_ffi::sqlite3_cancel_auto_extension(Some(entry_point(extension))) != 0 }
}

/// Clears **all** registered auto-extensions ([docs][reset_docs]).
///
/// After this call, no auto-extensions will run for newly opened connections.
///
/// [reset_docs]: https://www.sqlite.org/c3ref/reset_auto_extension.html
#[allow(unsafe_code)]
pub fn reset_auto_extension() {
    unsafe { ffi::sqlite3_reset_auto_extension() }
}

/// Returns the trampoline for `F`. `extension` is taken by value to infer `F`,
/// then `forget`-ten so the zero-sized callback stays conceptually alive for the
/// process and its destructor never runs.
fn entry_point<F>(extension: F) -> RawAutoExtension
where
    F: Fn(&'_ mut BorrowedSqliteConnection) -> QueryResult<()> + Sync + 'static,
{
    core::mem::forget(extension);
    trampoline::<F>
}

/// The C entry point handed to SQLite, monomorphized per callback type `F` so
/// each distinct callback maps to a distinct, stable address. SQLite's
/// pointer-based deduplication and [`cancel_auto_extension`] rely on that.
#[allow(unsafe_code)]
unsafe extern "C" fn trampoline<F>(
    db: *mut ffi::sqlite3,
    pz_err_msg: *mut *mut c_char,
    _p_api: RawApiPointer,
) -> c_int
where
    F: Fn(&'_ mut BorrowedSqliteConnection) -> QueryResult<()> + Sync + 'static,
{
    const {
        assert!(
            core::mem::size_of::<F>() == 0,
            "an auto-extension callback must not capture non-zero-sized state. \
             Use a `fn` item or a closure that captures only zero-sized values"
        );
    }

    // `_p_api` matters only for runtime-loaded shared libraries. Statically
    // linked extensions link the SQLite symbols directly, so we ignore it.
    let result: Result<(), String> =
        crate::util::std_compat::catch_unwind(core::panic::AssertUnwindSafe(|| {
            let Some(db) = core::ptr::NonNull::new(db) else {
                return Err(String::from(
                    "auto-extension received a null database handle",
                ));
            };
            // Reconstruct a *reference* to the zero-sized callback, never an
            // owned value, so its destructor never runs. `&F: Fn` because `F: Fn`.
            // SAFETY: `F` is zero-sized (asserted above), so a dangling, aligned,
            // non-null pointer is a valid `&F`, which `NonNull::dangling` provides.
            let extension: &F = unsafe { core::ptr::NonNull::<F>::dangling().as_ref() };
            // SAFETY: `db` is a valid handle for the duration of this call, and
            // the borrowed connection does not take ownership of it.
            unsafe { SqliteConnection::with_borrowed_connection(db, extension) }
                .map_err(|e| e.to_string())
        }))
        .unwrap_or_else(|panic| {
            Err(match panic_detail(panic) {
                Some(message) => alloc::format!("auto-extension panicked: {message}"),
                None => String::from("auto-extension panicked"),
            })
        });

    match result {
        Ok(()) => ffi::SQLITE_OK,
        Err(message) => {
            set_error_message(pz_err_msg, &message);
            ffi::SQLITE_ERROR
        }
    }
}

/// Best-effort message from a caught panic payload. The no_std `catch_unwind`
/// carries no payload, so only the `std` variant can recover the text.
#[cfg(feature = "std")]
fn panic_detail(panic: alloc::boxed::Box<dyn core::any::Any + Send>) -> Option<String> {
    panic
        .downcast_ref::<&str>()
        .map(|s| (*s).to_owned())
        .or_else(|| panic.downcast_ref::<String>().cloned())
}

#[cfg(not(feature = "std"))]
fn panic_detail(_panic: ()) -> Option<String> {
    None
}

/// Writes `message` into `*pz_err_msg` with `sqlite3_malloc`, which is the
/// allocator SQLite later frees it with. The message is truncated at the first
/// NUL byte to form a valid C string, and allocation failure is ignored.
#[allow(unsafe_code)]
fn set_error_message(pz_err_msg: *mut *mut c_char, message: &str) {
    if pz_err_msg.is_null() {
        return;
    }

    let bytes = message.as_bytes();
    let len = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());

    // SQLite sizes allocations with a C `int`. A message that does not fit is
    // dropped rather than truncated to a bogus length.
    let Ok(size) = c_int::try_from(len + 1) else {
        return;
    };
    let buffer = unsafe { ffi::sqlite3_malloc(size) } as *mut u8;
    if buffer.is_null() {
        return;
    }

    unsafe {
        core::ptr::copy_nonoverlapping(bytes.as_ptr(), buffer, len);
        *buffer.add(len) = 0;
        *pz_err_msg = buffer as *mut c_char;
    }
}

// These tests either rely on sqlite calling a registered auto extension, or
// read an error message allocated by the native library, neither of which is
// supported when running under miri with a native libsqlite3
// (`-Zmiri-native-lib`), so the whole module is compiled out in that case.
#[cfg(all(test, not(miri)))]
mod tests {
    use super::*;
    use crate::dsl::sql;
    use crate::prelude::*;
    use crate::sql_types::Integer;
    use crate::sqlite::BorrowedSqliteConnection;
    use std::sync::Mutex;

    // `sqlite3_auto_extension` is process-global, so these tests serialize on
    // this lock and register only benign (never-failing) extensions, leaving
    // connections opened by other tests unaffected. The failing path is covered
    // by `trampoline_maps_result_to_return_code`, which calls the trampoline
    // directly without touching the global registry.
    static AUTO_EXT_TEST_LOCK: Mutex<()> = Mutex::new(());

    // A benign auto-extension: registers a `TESTCOLL` collation through the
    // normal connection API.
    #[allow(unsafe_code, reason = "Test call to inner unsafe function")]
    fn test_ext_init(conn: &mut BorrowedSqliteConnection) -> QueryResult<()> {
        unsafe {
            conn.inner_mut()
                .register_collation("TESTCOLL", |a, b| a.cmp(b))
        }
    }

    fn open_memory_connection() -> SqliteConnection {
        SqliteConnection::establish(":memory:").expect("Failed to open :memory: connection")
    }

    // Errors out if `TESTCOLL` is not registered on a freshly opened connection.
    fn probe_collation() -> QueryResult<i32> {
        let mut conn = open_memory_connection();
        sql::<Integer>("SELECT 'a' = 'a' COLLATE TESTCOLL").get_result(&mut conn)
    }

    /// RAII guard that calls `reset_auto_extension()` on drop, ensuring global
    /// state is cleaned up even if a test panics.
    struct TestResetGuard;

    impl Drop for TestResetGuard {
        fn drop(&mut self) {
            reset_auto_extension();
        }
    }

    #[test]
    fn auto_extension_lifecycle() {
        let _lock = AUTO_EXT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _guard = TestResetGuard;
        reset_auto_extension();

        // -- 1. register + new connection has the collation --
        register_auto_extension(test_ext_init).unwrap();
        assert_eq!(probe_collation().unwrap(), 1);

        // -- 2. cancel + new connection does NOT have the collation --
        let removed = cancel_auto_extension(test_ext_init);
        assert!(
            removed,
            "cancel should return true for registered extension"
        );
        assert!(
            probe_collation().is_err(),
            "collation should not be available after cancel"
        );

        // -- 3. cancel returns false for unregistered --
        let removed = cancel_auto_extension(test_ext_init);
        assert!(
            !removed,
            "cancel should return false for unregistered extension"
        );

        // -- 4. reset clears all --
        register_auto_extension(test_ext_init).unwrap();
        reset_auto_extension();
        assert!(
            probe_collation().is_err(),
            "collation should not be available after reset"
        );

        // -- 5. duplicate registration is idempotent --
        register_auto_extension(test_ext_init).unwrap();
        register_auto_extension(test_ext_init).unwrap();
        assert_eq!(probe_collation().unwrap(), 1);
        // _guard drops here, ensuring reset even on panic.
    }

    // Drives the trampoline directly (via `entry_point`), without registering
    // it in SQLite's global list, so the Ok/Err/null paths can be checked
    // deterministically without affecting connections opened by other tests.
    #[test]
    #[allow(unsafe_code)]
    fn trampoline_maps_result_to_return_code() {
        fn ok_ext(_conn: &mut BorrowedSqliteConnection) -> QueryResult<()> {
            Ok(())
        }
        fn err_ext(_conn: &mut BorrowedSqliteConnection) -> QueryResult<()> {
            Err(Error::QueryBuilderError("boom".into()))
        }

        let ok_tramp = entry_point(ok_ext);
        let err_tramp = entry_point(err_ext);

        let mut conn = open_memory_connection();
        // SAFETY: the pointer is only used for the duration of the closure,
        // while `conn` is alive.
        unsafe {
            conn.with_raw_connection(|db| {
                let mut err: *mut c_char = core::ptr::null_mut();

                // Ok -> SQLITE_OK, no error message allocated.
                let rc = ok_tramp(db, &mut err, core::ptr::null());
                assert_eq!(rc, ffi::SQLITE_OK);
                assert!(err.is_null());

                // Err -> SQLITE_ERROR, message written via sqlite3_malloc.
                let rc = err_tramp(db, &mut err, core::ptr::null());
                assert_eq!(rc, ffi::SQLITE_ERROR);
                assert!(!err.is_null());
                let message = core::ffi::CStr::from_ptr(err)
                    .to_string_lossy()
                    .into_owned();
                assert_eq!(message, "boom");
                ffi::sqlite3_free(err as *mut core::ffi::c_void);

                // Null db handle -> SQLITE_ERROR, never dereferenced.
                let mut err: *mut c_char = core::ptr::null_mut();
                let rc = ok_tramp(core::ptr::null_mut(), &mut err, core::ptr::null());
                assert_eq!(rc, ffi::SQLITE_ERROR);
                if !err.is_null() {
                    ffi::sqlite3_free(err as *mut core::ffi::c_void);
                }
            })
        }
    }

    // Regression test for the closure-reconstruction soundness fix. The callback
    // captures a zero-sized guard with a load-bearing `Drop` that must never run,
    // because the trampoline only reproduces the callback behind a reference and
    // `forget`s the registered value (the old `mem::zeroed()` ran it repeatedly).
    #[test]
    fn callback_zero_sized_capture_is_never_dropped() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        static DROPS: AtomicUsize = AtomicUsize::new(0);

        // Zero-sized, `Sync`, with a load-bearing `Drop`.
        struct Guard;
        impl Drop for Guard {
            fn drop(&mut self) {
                DROPS.fetch_add(1, Ordering::SeqCst);
            }
        }

        let _lock = AUTO_EXT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _reset = TestResetGuard;
        reset_auto_extension();

        let guard = Guard;
        // `move` captures the zero-sized `guard` by value, so the closure is a
        // zero-sized type with a non-trivial destructor.
        #[allow(unsafe_code, reason = "Test call to inner unsafe function")]
        register_auto_extension(move |conn: &mut BorrowedSqliteConnection| {
            let _ = &guard;
            unsafe {
                conn.inner_mut()
                    .register_collation("TESTCOLL", |a, b| a.cmp(b))
            }
        })
        .unwrap();

        for _ in 0..5 {
            assert_eq!(probe_collation().unwrap(), 1);
        }
        reset_auto_extension();

        assert_eq!(
            DROPS.load(Ordering::SeqCst),
            0,
            "the captured guard's destructor must never run"
        );
    }

    #[test]
    fn leaked_failed_cursor_in_auto_extension_fails_open_cleanly() {
        use std::cell::Cell;

        // Connections other tests open concurrently skip the extension.
        thread_local!(static ARMED: Cell<bool> = const { Cell::new(false) });

        #[allow(unsafe_code, reason = "Test code")]
        fn extension(conn: &mut BorrowedSqliteConnection) -> QueryResult<()> {
            if ARMED.get() {
                unsafe {
                    crate::sqlite::connection::leak_failed_cursor(conn.inner_mut());
                }
            }
            Ok(())
        }

        let _lock = AUTO_EXT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _reset = TestResetGuard;
        register_auto_extension(extension).unwrap();
        ARMED.set(true);

        // `sqlite3_open_v2` reports the error the finalized statement left on the handle.
        let conn = SqliteConnection::establish(":memory:");
        assert!(matches!(conn, Err(ConnectionError::BadConnection(_))));
    }

    #[test]
    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))] // there is no catch unwind for wasm
    fn panic_in_borrowed_connection_teardown_keeps_handle_open() {
        use crate::connection::{Instrumentation, InstrumentationEvent};
        use std::cell::Cell;

        // Connections other tests open concurrently skip the extension.
        thread_local!(static ARMED: Cell<bool> = const { Cell::new(false) });

        struct PanicOnDrop;

        impl Instrumentation for PanicOnDrop {
            fn on_connection_event(&mut self, _event: InstrumentationEvent<'_>) {}
        }

        impl Drop for PanicOnDrop {
            fn drop(&mut self) {
                if ARMED.get() {
                    panic!("instrumentation dropped");
                }
            }
        }

        fn extension(conn: &mut BorrowedSqliteConnection) -> QueryResult<()> {
            if ARMED.get() {
                conn.set_instrumentation(PanicOnDrop);
            }
            Ok(())
        }

        let _lock = AUTO_EXT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _reset = TestResetGuard;
        register_auto_extension(extension).unwrap();
        ARMED.set(true);
        let conn = SqliteConnection::establish(":memory:");
        ARMED.set(false);

        // The caught panic fails the open, and the handle is closed exactly once.
        assert!(matches!(conn, Err(ConnectionError::BadConnection(_))));
    }

    // Counts calls and destructor runs of the hook closures registered by
    // `register_all_hooks`. Tests using them hold `AUTO_EXT_TEST_LOCK`.
    mod hook_tokens {
        use std::sync::atomic::{AtomicUsize, Ordering};
        pub(super) static FIRED: AtomicUsize = AtomicUsize::new(0);
        pub(super) static DROPPED: AtomicUsize = AtomicUsize::new(0);
        /// Dropped together with its hook closure; panics on drop if the flag is set.
        pub(super) struct Token(pub(super) bool);
        impl Token {
            pub(super) fn fire(&self) {
                FIRED.fetch_add(1, Ordering::SeqCst);
            }
        }
        impl Drop for Token {
            fn drop(&mut self) {
                DROPPED.fetch_add(1, Ordering::SeqCst);
                if self.0 {
                    panic!("hook closure dropped");
                }
            }
        }
    }

    // Registers all nine hooks through the borrowed connection. The closure of hook
    // number `panicking` (in `RawConnection` field order) panics when dropped.
    #[allow(unsafe_code)]
    fn register_all_hooks(conn: &mut BorrowedSqliteConnection, panicking: usize) {
        use crate::sqlite::{
            AuthorizerDecision, BusyDecision, CommitDecision, ProgressDecision, SqliteChangeOps,
            SqliteTraceFlags, SqliteUpdateRouter,
        };
        use core::num::NonZeroU32;
        use hook_tokens::Token;
        let conn = unsafe { conn.inner_mut() };
        let t = Token(panicking == 0);
        conn.on_update(SqliteUpdateRouter::new().on_any(SqliteChangeOps::ALL, move |_| t.fire()));
        let t = Token(panicking == 1);
        conn.on_commit(move || {
            t.fire();
            CommitDecision::Proceed
        });
        let t = Token(panicking == 2);
        conn.on_rollback(move || t.fire());
        let t = Token(panicking == 3);
        conn.on_progress(NonZeroU32::new(1).unwrap(), move || {
            t.fire();
            ProgressDecision::Continue
        });
        let t = Token(panicking == 4);
        conn.on_wal(move |_, _, _| t.fire());
        let t = Token(panicking == 5);
        conn.on_busy(move |_| {
            t.fire();
            BusyDecision::GiveUp
        });
        let t = Token(panicking == 6);
        conn.on_authorize(move |_| {
            t.fire();
            AuthorizerDecision::Allow
        });
        let t = Token(panicking == 7);
        conn.on_trace(SqliteTraceFlags::all(), move |_| t.fire());
        let t = Token(panicking == 8);
        conn.on_collation_needed(move |_| {
            t.fire();
            None
        });
    }

    // Runs statements that would trigger the hooks `register_all_hooks` registers,
    // except the busy handler and the WAL hook (those need lock contention or WAL mode).
    fn trigger_hooks(conn: &mut SqliteConnection) {
        use crate::connection::SimpleConnection;
        conn.batch_execute(
            "CREATE TABLE IF NOT EXISTS t (x); INSERT INTO t VALUES (1);
             BEGIN; INSERT INTO t VALUES (2); ROLLBACK;",
        )
        .unwrap();
        let _ = conn.batch_execute("SELECT 'a' = 'b' COLLATE nosuch");
    }

    // All nine hooks an auto-extension registers are unregistered and freed.
    #[test]
    fn hooks_registered_in_auto_extension_are_unregistered_and_freed() {
        use std::cell::Cell;
        use std::sync::atomic::Ordering;
        thread_local!(static ARMED: Cell<bool> = const { Cell::new(false) });
        fn extension(conn: &mut BorrowedSqliteConnection) -> QueryResult<()> {
            if ARMED.get() {
                register_all_hooks(conn, usize::MAX);
            }
            Ok(())
        }
        let _lock = AUTO_EXT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _reset = TestResetGuard;
        hook_tokens::FIRED.store(0, Ordering::SeqCst);
        hook_tokens::DROPPED.store(0, Ordering::SeqCst);
        register_auto_extension(extension).unwrap();
        ARMED.set(true);
        let conn = SqliteConnection::establish(":memory:");
        ARMED.set(false);
        let mut conn = conn.unwrap();
        assert_eq!(hook_tokens::DROPPED.load(Ordering::SeqCst), 9);
        trigger_hooks(&mut conn);
        assert_eq!(hook_tokens::FIRED.load(Ordering::SeqCst), 0);
    }

    // A panic while freeing hook number `n` must not close the handle, and must
    // not leak the closures of the other hooks. Gated off WASM, where
    // `catch_unwind` aborts because `panic = "abort"`.
    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
    fn assert_panicking_hook_drop_frees_all_hooks(n: usize) {
        use std::cell::Cell;
        use std::sync::atomic::Ordering;
        thread_local!(static PANIC_AT: Cell<usize> = const { Cell::new(usize::MAX) });
        thread_local!(static ARMED: Cell<bool> = const { Cell::new(false) });
        fn extension(conn: &mut BorrowedSqliteConnection) -> QueryResult<()> {
            if ARMED.get() {
                register_all_hooks(conn, PANIC_AT.get());
            }
            Ok(())
        }
        let _lock = AUTO_EXT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _reset = TestResetGuard;
        hook_tokens::DROPPED.store(0, Ordering::SeqCst);
        register_auto_extension(extension).unwrap();
        PANIC_AT.set(n);
        ARMED.set(true);
        let conn = SqliteConnection::establish(":memory:");
        ARMED.set(false);
        assert!(matches!(conn, Err(ConnectionError::BadConnection(_))));
        assert_eq!(hook_tokens::DROPPED.load(Ordering::SeqCst), 9);
    }

    #[test]
    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
    fn panicking_first_hook_drop_frees_all_hooks() {
        assert_panicking_hook_drop_frees_all_hooks(0);
    }

    #[test]
    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
    fn panicking_last_hook_drop_frees_all_hooks() {
        assert_panicking_hook_drop_frees_all_hooks(8);
    }

    // A panicking callback becomes `SQLITE_ERROR` with the payload recovered
    // into the message (`&str` and `String` payloads, generic fallback
    // otherwise), and drives the panic-unwind path through the drop guard. Gated
    // off WASM, where `catch_unwind` aborts because `panic = "abort"`.
    #[test]
    #[allow(unsafe_code)]
    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
    fn trampoline_reports_panic_message() {
        fn panic_str(_conn: &mut BorrowedSqliteConnection) -> QueryResult<()> {
            panic!("boom-str");
        }
        fn panic_string(_conn: &mut BorrowedSqliteConnection) -> QueryResult<()> {
            panic!("boom-{}", 7);
        }
        fn panic_other(_conn: &mut BorrowedSqliteConnection) -> QueryResult<()> {
            std::panic::panic_any(7_u8);
        }

        let cases: [(RawAutoExtension, &str); 3] = [
            (entry_point(panic_str), "auto-extension panicked: boom-str"),
            (entry_point(panic_string), "auto-extension panicked: boom-7"),
            (entry_point(panic_other), "auto-extension panicked"),
        ];

        let mut conn = open_memory_connection();
        // SAFETY: the pointer is only used while `conn` is alive.
        unsafe {
            conn.with_raw_connection(|db| {
                for (tramp, expected) in cases {
                    let mut err: *mut c_char = core::ptr::null_mut();
                    let rc = tramp(db, &mut err, core::ptr::null());
                    assert_eq!(rc, ffi::SQLITE_ERROR);
                    assert!(!err.is_null());
                    let message = core::ffi::CStr::from_ptr(err)
                        .to_string_lossy()
                        .into_owned();
                    assert_eq!(message, expected);
                    ffi::sqlite3_free(err as *mut core::ffi::c_void);
                }
            })
        }
    }

    #[test]
    #[allow(unsafe_code)]
    fn error_message_truncates_at_interior_nul() {
        let mut err: *mut c_char = core::ptr::null_mut();
        set_error_message(&mut err, "before\0after");
        assert!(!err.is_null());
        // SAFETY: `err` is a sqlite-allocated C string we own until we free it.
        unsafe {
            let truncated = core::ffi::CStr::from_ptr(err).to_str().unwrap();
            assert_eq!(truncated, "before");
            ffi::sqlite3_free(err as *mut core::ffi::c_void);
        }

        // A null out-pointer is a no-op (must not write through it or crash).
        set_error_message(core::ptr::null_mut(), "ignored");
    }
}