async-sqlite 0.6.0

A library for working with sqlite asynchronously
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
use std::sync::atomic::{AtomicUsize, Ordering};

use async_sqlite::{ClientBuilder, Error, JournalMode, PoolBuilder};
use futures_util::FutureExt;

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

fn shared_memory_name(prefix: &str) -> String {
    let id = SHARED_MEMORY_ID.fetch_add(1, Ordering::Relaxed);
    format!("{prefix}-{}-{id}", std::process::id())
}

fn assert_config_message(err: Error, expected: &str) {
    match err {
        Error::Config { message } => assert_eq!(message, expected),
        other => panic!("expected Error::Config, got {other:?}"),
    }
}

fn journal_modes() -> [(JournalMode, &'static str); 6] {
    [
        (JournalMode::Delete, "delete"),
        (JournalMode::Truncate, "truncate"),
        (JournalMode::Persist, "persist"),
        (JournalMode::Memory, "memory"),
        (JournalMode::Wal, "wal"),
        (JournalMode::Off, "off"),
    ]
}

#[derive(Debug)]
enum CustomError {
    AsyncSqlite,
    Rusqlite,
    User(&'static str),
}

impl From<Error> for CustomError {
    fn from(_value: Error) -> Self {
        Self::AsyncSqlite
    }
}

impl From<rusqlite::Error> for CustomError {
    fn from(_value: rusqlite::Error) -> Self {
        Self::Rusqlite
    }
}

fn assert_user_error(result: Result<(), CustomError>, expected: &'static str) {
    match result {
        Err(CustomError::User(actual)) => assert_eq!(actual, expected),
        other => panic!("expected CustomError::User({expected:?}), got {other:?}"),
    }
}

#[test]
fn test_blocking_client() {
    let tmp_dir = tempfile::tempdir().unwrap();
    let client = ClientBuilder::new()
        .journal_mode(JournalMode::Wal)
        .path(tmp_dir.path().join("sqlite.db"))
        .open_blocking()
        .expect("client unable to be opened");

    client
        .conn_blocking(|conn| {
            conn.execute(
                "CREATE TABLE testing (id INTEGER PRIMARY KEY, val TEXT NOT NULL)",
                (),
            )?;
            conn.execute("INSERT INTO testing VALUES (1, ?)", ["value1"])
        })
        .expect("writing schema and seed data");

    client
        .conn_blocking(|conn| {
            let val: String =
                conn.query_row("SELECT val FROM testing WHERE id=?", [1], |row| row.get(0))?;
            assert_eq!(val, "value1");
            Ok(())
        })
        .expect("querying for result");

    client.close_blocking().expect("closing client conn");
}

#[test]
fn test_blocking_client_and_then_api() {
    let client = ClientBuilder::new()
        .open_blocking()
        .expect("client unable to be opened");

    client
        .conn_and_then_blocking(|conn| {
            conn.execute(
                "CREATE TABLE testing (id INTEGER PRIMARY KEY, val INTEGER NOT NULL)",
                (),
            )?;
            conn.execute("INSERT INTO testing VALUES (1, ?)", [42])?;
            Ok::<(), CustomError>(())
        })
        .expect("writing schema and seed data");

    let val: i64 = client
        .conn_mut_and_then_blocking(|conn| {
            conn.query_row("SELECT val FROM testing WHERE id=?", [1], |row| row.get(0))
                .map_err(CustomError::from)
        })
        .expect("querying for result");
    assert_eq!(val, 42);

    assert_user_error(
        client.conn_and_then_blocking(|_| Err(CustomError::User("client"))),
        "client",
    );

    client.close_blocking().expect("closing client conn");
}

#[test]
fn test_blocking_default_pool_in_memory_uses_one_connection() {
    let pool = PoolBuilder::new()
        .open_blocking()
        .expect("pool unable to be opened");

    pool.conn_blocking(|conn| {
        conn.execute(
            "CREATE TABLE testing (id INTEGER PRIMARY KEY, val TEXT NOT NULL)",
            (),
        )?;
        conn.execute("INSERT INTO testing VALUES (1, ?)", ["value1"])
    })
    .expect("writing schema and seed data");

    pool.conn_blocking(|conn| {
        let val: String =
            conn.query_row("SELECT val FROM testing WHERE id=?", [1], |row| row.get(0))?;
        assert_eq!(val, "value1");
        Ok(())
    })
    .expect("querying for result");

    let results = pool.conn_for_each_blocking(|_| Ok(()));
    assert_eq!(results.len(), 1);

    pool.close_blocking().expect("closing pool");

    let pool = PoolBuilder::new()
        .path(":memory:")
        .open_blocking()
        .expect("pool unable to be opened");
    let results = pool.conn_for_each_blocking(|_| Ok(()));
    assert_eq!(results.len(), 1);
    pool.close_blocking().expect("closing pool");
}

#[test]
fn test_blocking_pool() {
    let tmp_dir = tempfile::tempdir().unwrap();
    let pool = PoolBuilder::new()
        .journal_mode(JournalMode::Wal)
        .path(tmp_dir.path().join("sqlite.db"))
        .open_blocking()
        .expect("client unable to be opened");

    pool.conn_blocking(|conn| {
        conn.execute(
            "CREATE TABLE testing (id INTEGER PRIMARY KEY, val TEXT NOT NULL)",
            (),
        )?;
        conn.execute("INSERT INTO testing VALUES (1, ?)", ["value1"])
    })
    .expect("writing schema and seed data");

    pool.conn_blocking(|conn| {
        let val: String =
            conn.query_row("SELECT val FROM testing WHERE id=?", [1], |row| row.get(0))?;
        assert_eq!(val, "value1");
        Ok(())
    })
    .expect("querying for result");

    pool.close_blocking().expect("closing client conn");
}

#[test]
fn test_blocking_pool_and_then_api() {
    let pool = PoolBuilder::new()
        .open_blocking()
        .expect("pool unable to be opened");

    pool.conn_and_then_blocking(|conn| {
        conn.execute(
            "CREATE TABLE testing (id INTEGER PRIMARY KEY, val INTEGER NOT NULL)",
            (),
        )?;
        conn.execute("INSERT INTO testing VALUES (1, ?)", [42])?;
        Ok::<(), CustomError>(())
    })
    .expect("writing schema and seed data");

    let val: i64 = pool
        .conn_mut_and_then_blocking(|conn| {
            conn.query_row("SELECT val FROM testing WHERE id=?", [1], |row| row.get(0))
                .map_err(CustomError::from)
        })
        .expect("querying for result");
    assert_eq!(val, 42);

    assert_user_error(
        pool.conn_and_then_blocking(|_| Err(CustomError::User("pool"))),
        "pool",
    );

    pool.close_blocking().expect("closing pool");
}

#[test]
fn test_blocking_pool_rejects_multi_connection_anonymous_memory() {
    let err = match PoolBuilder::new().num_conns(2).open_blocking() {
        Ok(pool) => {
            pool.close_blocking().expect("closing unexpected pool");
            panic!("expected pool open to fail");
        }
        Err(err) => err,
    };

    assert_config_message(
        err,
        "anonymous in-memory pools cannot use multiple connections; call path(...) for file-backed pools or shared_memory(...) for named shared in-memory pools",
    );

    let err = match PoolBuilder::new()
        .path(":memory:")
        .num_conns(2)
        .open_blocking()
    {
        Ok(pool) => {
            pool.close_blocking().expect("closing unexpected pool");
            panic!("expected pool open to fail");
        }
        Err(err) => err,
    };

    assert_config_message(
        err,
        "anonymous in-memory pools cannot use multiple connections; call path(...) for file-backed pools or shared_memory(...) for named shared in-memory pools",
    );
}

#[test]
fn test_blocking_pool_journal_mode() {
    for (journal_mode, expected) in journal_modes() {
        let tmp_dir = tempfile::tempdir().unwrap();
        let pool = PoolBuilder::new()
            .journal_mode(journal_mode)
            .path(tmp_dir.path().join("sqlite.db"))
            .num_conns(4)
            .open_blocking()
            .expect("pool unable to be opened");

        let results = pool.conn_for_each_blocking(|conn| {
            conn.query_row("PRAGMA journal_mode", (), |row| row.get(0))
        });
        for (idx, result) in results.into_iter().enumerate() {
            let mode: String = result.unwrap();
            assert_eq!(
                mode, expected,
                "{journal_mode:?} journal mode mismatch on connection {idx}"
            );
        }

        pool.close_blocking().expect("closing pool");
    }
}

macro_rules! async_test {
    ($name:ident) => {
        paste::item! {
            #[::core::prelude::v1::test]
            fn [< $name _smol >] () {
                ::smol::block_on($name());
            }

            #[::core::prelude::v1::test]
            fn [< $name _tokio >] () {
                ::tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .unwrap()
                    .block_on($name());
            }
        }
    };
}

async_test!(test_journal_mode);
async_test!(test_concurrency);
async_test!(test_default_pool_in_memory_uses_one_connection);
async_test!(test_pool);
async_test!(test_pool_and_then_api);
async_test!(test_pool_rejects_multi_connection_anonymous_memory);
async_test!(test_shared_memory_pool);
async_test!(test_shared_memory_rejects_empty_name);
async_test!(test_pool_journal_mode);
async_test!(test_pool_conn_for_each);
async_test!(test_pool_close_concurrent);
async_test!(test_canceled_async_command_is_skipped);
async_test!(test_client_queue_capacity_reports_full);
async_test!(test_pool_num_conns_zero_clamps);
async_test!(test_closure_panic_surfaces_error);
async_test!(test_panic_after_begin_immediate_rolls_back);

async fn test_journal_mode() {
    for (journal_mode, expected) in journal_modes() {
        let tmp_dir = tempfile::tempdir().unwrap();
        let client = ClientBuilder::new()
            .journal_mode(journal_mode)
            .path(tmp_dir.path().join("sqlite.db"))
            .open()
            .await
            .expect("client unable to be opened");
        let mode: String = client
            .conn(|conn| conn.query_row("PRAGMA journal_mode", (), |row| row.get(0)))
            .await
            .expect("client unable to fetch journal_mode");
        assert_eq!(mode, expected, "{journal_mode:?} journal mode mismatch");
        client.close().await.expect("closing client");
    }
}

async fn test_concurrency() {
    let tmp_dir = tempfile::tempdir().unwrap();
    let client = ClientBuilder::new()
        .path(tmp_dir.path().join("sqlite.db"))
        .open()
        .await
        .expect("client unable to be opened");

    client
        .conn(|conn| {
            conn.execute(
                "CREATE TABLE testing (id INTEGER PRIMARY KEY, val TEXT NOT NULL)",
                (),
            )?;
            conn.execute("INSERT INTO testing VALUES (1, ?)", ["value1"])
        })
        .await
        .expect("writing schema and seed data");

    let fs = (0..10).map(|_| {
        client.conn(|conn| {
            let val: String =
                conn.query_row("SELECT val FROM testing WHERE id=?", [1], |row| row.get(0))?;
            assert_eq!(val, "value1");
            Ok(())
        })
    });
    futures_util::future::join_all(fs)
        .await
        .into_iter()
        .collect::<Result<(), Error>>()
        .expect("collecting query results");
}

async fn test_default_pool_in_memory_uses_one_connection() {
    let pool = PoolBuilder::new()
        .open()
        .await
        .expect("pool unable to be opened");

    pool.conn(|conn| {
        conn.execute(
            "CREATE TABLE testing (id INTEGER PRIMARY KEY, val TEXT NOT NULL)",
            (),
        )?;
        conn.execute("INSERT INTO testing VALUES (1, ?)", ["value1"])
    })
    .await
    .expect("writing schema and seed data");

    pool.conn(|conn| {
        let val: String =
            conn.query_row("SELECT val FROM testing WHERE id=?", [1], |row| row.get(0))?;
        assert_eq!(val, "value1");
        Ok(())
    })
    .await
    .expect("querying for result");

    let results = pool.conn_for_each(|_| Ok(())).await;
    assert_eq!(results.len(), 1);

    pool.close().await.expect("closing pool");

    let pool = PoolBuilder::new()
        .path(":memory:")
        .open()
        .await
        .expect("pool unable to be opened");
    let results = pool.conn_for_each(|_| Ok(())).await;
    assert_eq!(results.len(), 1);
    pool.close().await.expect("closing pool");
}

async fn test_pool() {
    let tmp_dir = tempfile::tempdir().unwrap();
    let pool = PoolBuilder::new()
        .path(tmp_dir.path().join("sqlite.db"))
        .num_conns(2)
        .open()
        .await
        .expect("client unable to be opened");

    pool.conn(|conn| {
        conn.execute(
            "CREATE TABLE testing (id INTEGER PRIMARY KEY, val TEXT NOT NULL)",
            (),
        )?;
        conn.execute("INSERT INTO testing VALUES (1, ?)", ["value1"])
    })
    .await
    .expect("writing schema and seed data");

    let fs = (0..10).map(|_| {
        pool.conn(|conn| {
            let val: String =
                conn.query_row("SELECT val FROM testing WHERE id=?", [1], |row| row.get(0))?;
            assert_eq!(val, "value1");
            Ok(())
        })
    });
    futures_util::future::join_all(fs)
        .await
        .into_iter()
        .collect::<Result<(), Error>>()
        .expect("collecting query results");
}

async fn test_pool_and_then_api() {
    let pool = PoolBuilder::new()
        .open()
        .await
        .expect("pool unable to be opened");

    pool.conn_and_then(|conn| {
        conn.execute(
            "CREATE TABLE testing (id INTEGER PRIMARY KEY, val INTEGER NOT NULL)",
            (),
        )?;
        conn.execute("INSERT INTO testing VALUES (1, ?)", [42])?;
        Ok::<(), CustomError>(())
    })
    .await
    .expect("writing schema and seed data");

    let val: i64 = pool
        .conn_mut_and_then(|conn| {
            conn.query_row("SELECT val FROM testing WHERE id=?", [1], |row| row.get(0))
                .map_err(CustomError::from)
        })
        .await
        .expect("querying for result");
    assert_eq!(val, 42);

    assert_user_error(
        pool.conn_and_then(|_| Err(CustomError::User("pool async")))
            .await,
        "pool async",
    );

    pool.close().await.expect("closing pool");
}

async fn test_pool_rejects_multi_connection_anonymous_memory() {
    let err = match PoolBuilder::new().num_conns(2).open().await {
        Ok(pool) => {
            pool.close().await.expect("closing unexpected pool");
            panic!("expected pool open to fail");
        }
        Err(err) => err,
    };

    assert_config_message(
        err,
        "anonymous in-memory pools cannot use multiple connections; call path(...) for file-backed pools or shared_memory(...) for named shared in-memory pools",
    );

    let err = match PoolBuilder::new()
        .path(":memory:")
        .num_conns(2)
        .open()
        .await
    {
        Ok(pool) => {
            pool.close().await.expect("closing unexpected pool");
            panic!("expected pool open to fail");
        }
        Err(err) => err,
    };

    assert_config_message(
        err,
        "anonymous in-memory pools cannot use multiple connections; call path(...) for file-backed pools or shared_memory(...) for named shared in-memory pools",
    );
}

async fn test_shared_memory_pool() {
    let name = shared_memory_name("shared-pool");
    let pool = PoolBuilder::new()
        .shared_memory(&name)
        .num_conns(2)
        .open()
        .await
        .expect("pool unable to be opened");

    let results = pool.conn_for_each(|_| Ok(())).await;
    assert_eq!(results.len(), 2);

    pool.conn(|conn| {
        conn.execute(
            "CREATE TABLE testing (id INTEGER PRIMARY KEY, val TEXT NOT NULL)",
            (),
        )?;
        conn.execute("INSERT INTO testing VALUES (1, ?)", ["value1"])
    })
    .await
    .expect("writing schema and seed data");

    let results = pool
        .conn_for_each(|conn| {
            conn.query_row("SELECT val FROM testing WHERE id=?", [1], |row| {
                row.get::<_, String>(0)
            })
        })
        .await;

    for result in results {
        assert_eq!(result.unwrap(), "value1");
    }

    pool.close().await.expect("closing pool");
}

async fn test_shared_memory_rejects_empty_name() {
    let err = match PoolBuilder::new().shared_memory("").open().await {
        Ok(pool) => {
            pool.close().await.expect("closing unexpected pool");
            panic!("expected pool open to fail");
        }
        Err(err) => err,
    };

    assert_config_message(err, "shared memory database name must not be empty");
}

async fn test_pool_journal_mode() {
    for (journal_mode, expected) in journal_modes() {
        let tmp_dir = tempfile::tempdir().unwrap();
        let pool = PoolBuilder::new()
            .journal_mode(journal_mode)
            .path(tmp_dir.path().join("sqlite.db"))
            .num_conns(4)
            .open()
            .await
            .expect("pool unable to be opened");

        let results = pool
            .conn_for_each(|conn| conn.query_row("PRAGMA journal_mode", (), |row| row.get(0)))
            .await;
        for (idx, result) in results.into_iter().enumerate() {
            let mode: String = result.unwrap();
            assert_eq!(
                mode, expected,
                "{journal_mode:?} journal mode mismatch on connection {idx}"
            );
        }

        pool.close().await.expect("closing pool");
    }
}

async fn test_pool_conn_for_each() {
    // make dummy db
    let tmp_dir = tempfile::tempdir().unwrap();
    {
        let client = ClientBuilder::new()
            .journal_mode(JournalMode::Wal)
            .path(tmp_dir.path().join("sqlite.db"))
            .open_blocking()
            .expect("client unable to be opened");

        client
            .conn_blocking(|conn| {
                conn.execute(
                    "CREATE TABLE testing (id INTEGER PRIMARY KEY, val TEXT NOT NULL)",
                    (),
                )?;
                conn.execute("INSERT INTO testing VALUES (1, ?)", ["value1"])
            })
            .expect("writing schema and seed data");
    }

    let pool = PoolBuilder::new()
        .path(tmp_dir.path().join("another-sqlite.db"))
        .num_conns(2)
        .open()
        .await
        .expect("pool unable to be opened");

    let dummy_db_path = tmp_dir.path().join("sqlite.db");
    let attach_fn = move |conn: &rusqlite::Connection| {
        conn.execute(
            "ATTACH DATABASE ? AS dummy",
            [dummy_db_path.to_str().unwrap()],
        )
    };
    // attach to the dummy db via conn_for_each
    let results = pool.conn_for_each(attach_fn).await;
    for result in results {
        result.unwrap();
    }

    // check that the dummy db is attached
    fn check_fn(conn: &rusqlite::Connection) -> Result<Vec<String>, rusqlite::Error> {
        let mut stmt = conn
            .prepare_cached("SELECT name FROM dummy.sqlite_master WHERE type='table'")
            .unwrap();
        let names = stmt
            .query_map([], |row| row.get(0))
            .unwrap()
            .map(|r| r.unwrap())
            .collect::<Vec<String>>();

        Ok(names)
    }
    let res = pool.conn_for_each(check_fn).await;
    for r in res {
        assert_eq!(r.unwrap(), vec!["testing"]);
    }

    // cleanup
    pool.close().await.expect("closing client conn");
}

async fn test_pool_close_concurrent() {
    let tmp_dir = tempfile::tempdir().unwrap();
    let pool = PoolBuilder::new()
        .path(tmp_dir.path().join("sqlite.db"))
        .num_conns(2)
        .open()
        .await
        .expect("pool unable to be opened");

    let c1 = pool.close();
    let c2 = pool.close();
    futures_util::future::join_all([c1, c2])
        .await
        .into_iter()
        .collect::<Result<Vec<_>, Error>>()
        .expect("closing concurrently");

    let res = pool.conn(|c| c.execute("SELECT 1", ())).await;
    assert!(matches!(res, Err(Error::Closed)));
}

async fn test_canceled_async_command_is_skipped() {
    let client = ClientBuilder::new()
        .open()
        .await
        .expect("client unable to be opened");

    client
        .conn(|conn| {
            conn.execute("CREATE TABLE testing (id INTEGER PRIMARY KEY)", ())?;
            Ok(())
        })
        .await
        .expect("creating table");

    let (started_tx, started_rx) = std::sync::mpsc::channel();
    let (release_tx, release_rx) = std::sync::mpsc::channel();
    let mut blocker = Box::pin(client.conn(move |_| {
        started_tx.send(()).expect("notifying blocker started");
        release_rx.recv().expect("waiting for blocker release");
        Ok(())
    }));

    assert!(blocker.as_mut().now_or_never().is_none());
    started_rx.recv().expect("waiting for blocker to start");

    let mut canceled = Box::pin(client.conn(|conn| {
        conn.execute("INSERT INTO testing VALUES (1)", ())?;
        Ok(())
    }));
    assert!(canceled.as_mut().now_or_never().is_none());
    drop(canceled);

    release_tx.send(()).expect("releasing blocker");
    blocker.await.expect("blocker finished");

    let row_count: i64 = client
        .conn(|conn| conn.query_row("SELECT COUNT(*) FROM testing", (), |row| row.get(0)))
        .await
        .expect("counting rows");
    assert_eq!(row_count, 0);

    client.close().await.expect("closing client");
}

async fn test_client_queue_capacity_reports_full() {
    let client = ClientBuilder::new()
        .queue_capacity(1)
        .open()
        .await
        .expect("client unable to be opened");

    let (started_tx, started_rx) = std::sync::mpsc::channel();
    let (release_tx, release_rx) = std::sync::mpsc::channel();
    let mut blocker = Box::pin(client.conn(move |_| {
        started_tx.send(()).expect("notifying blocker started");
        release_rx.recv().expect("waiting for blocker release");
        Ok(())
    }));

    assert!(blocker.as_mut().now_or_never().is_none());
    started_rx.recv().expect("waiting for blocker to start");

    let mut queued = Box::pin(client.conn(|_| Ok(())));
    assert!(queued.as_mut().now_or_never().is_none());

    let res: Result<(), Error> = client.conn(|_| Ok(())).await;
    assert!(matches!(res, Err(Error::QueueFull)));

    release_tx.send(()).expect("releasing blocker");
    blocker.await.expect("blocker finished");
    queued.await.expect("queued command finished");

    client.close().await.expect("closing client");
}

async fn test_closure_panic_surfaces_error() {
    let tmp_dir = tempfile::tempdir().unwrap();
    let client = ClientBuilder::new()
        .path(tmp_dir.path().join("sqlite.db"))
        .open()
        .await
        .expect("client unable to be opened");

    let res: Result<(), Error> = client.conn(|_| panic!("boom: &str")).await;
    match res {
        Err(Error::Panic { message }) => assert!(message.contains("boom"), "got {message}"),
        other => panic!("expected Error::Panic, got {other:?}"),
    }

    let res: Result<(), Error> = client
        .conn(|_| panic!("{}", String::from("boom: String")))
        .await;
    match res {
        Err(Error::Panic { message }) => assert!(message.contains("boom"), "got {message}"),
        other => panic!("expected Error::Panic, got {other:?}"),
    }

    // Connection must remain usable after a panic.
    client
        .conn(|conn| conn.query_row("SELECT 1", (), |row| row.get::<_, i64>(0)))
        .await
        .expect("connection still usable after panic");

    client.close().await.expect("closing client");
}

async fn test_panic_after_begin_immediate_rolls_back() {
    let tmp_dir = tempfile::tempdir().unwrap();
    let db_path = tmp_dir.path().join("sqlite.db");
    let client = ClientBuilder::new()
        .path(&db_path)
        .open()
        .await
        .expect("client unable to be opened");

    client
        .conn(|conn| {
            conn.execute(
                "CREATE TABLE testing (id INTEGER PRIMARY KEY, val TEXT NOT NULL)",
                (),
            )?;
            Ok(())
        })
        .await
        .expect("creating table");

    let res: Result<(), Error> = client
        .conn(|conn| {
            conn.execute_batch("BEGIN IMMEDIATE")?;
            conn.execute("INSERT INTO testing VALUES (1, ?)", ["panic"])?;
            panic!("boom after BEGIN IMMEDIATE");
        })
        .await;
    match res {
        Err(Error::Panic { message }) => assert!(message.contains("boom"), "got {message}"),
        other => panic!("expected Error::Panic, got {other:?}"),
    }

    let row_count: i64 = client
        .conn(|conn| conn.query_row("SELECT COUNT(*) FROM testing", (), |row| row.get(0)))
        .await
        .expect("counting rows after rollback");
    assert_eq!(row_count, 0);

    let other = rusqlite::Connection::open(&db_path).expect("opening second connection");
    other
        .busy_timeout(std::time::Duration::from_millis(0))
        .expect("setting busy timeout");
    other
        .execute("INSERT INTO testing VALUES (2, ?)", ["other"])
        .expect("second connection can write after panic rollback");

    client.close().await.expect("closing client");
}

async fn test_pool_num_conns_zero_clamps() {
    let tmp_dir = tempfile::tempdir().unwrap();
    let pool = PoolBuilder::new()
        .path(tmp_dir.path().join("clamp.db"))
        .num_conns(0)
        .open()
        .await
        .expect("pool unable to be opened");
    let results = pool.conn_for_each(|_| Ok(())).await;
    assert_eq!(results.len(), 1);
}