nitr-std 0.0.0-beta.7

The built-in `nitr.*` standard library for Nitr: dbg, fetch, template, json, http, log, crypto, and the SQLite driver.
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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
// SPDX-License-Identifier: MIT OR Apache-2.0
// This file is part of Nitr.
// See https://nitrweb.com/ for more information
// Copyright (C) 2024-present Jose Quintana <joseluisq.net>

//! The `conn` builtin: SQLite statements and transactions. Blocking
//! rusqlite calls run on the blocking thread pool; each Lua state owns its
//! own connection, and requests are serialized per state, so a transaction
//! never interleaves with other statements.

use std::future::Future;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};

use mlua::{AnyUserData, Function, Lua, Table, UserData, UserDataMethods, Value};
use rusqlite::Connection;
use tracing::Instrument as _;

use crate::db::types::{Conn, Db, SqlValue, params_from_table, row_to_lua, rows_to_lua};
use nitr_core::Result;

pub(crate) mod execute;
pub mod migrate;
pub mod pragmas;
pub(crate) mod query;
pub(crate) mod query_one;
pub(crate) mod query_row;
pub mod testing;
pub(crate) mod types;

use crate::config::SqlitePragmas;

/// Set while a transaction is open on the connection.
type TxFlag = Arc<AtomicBool>;

pub(crate) struct LuaDatabase {
    conn: Conn,
    in_transaction: TxFlag,
}

/// One (possibly nested) transaction scope handed to the Lua callback of
/// `db:transaction(fn)` / `tx:transaction(fn)`.
pub(crate) struct LuaTransaction {
    conn: Conn,
    /// Names nested savepoints uniquely within this scope.
    savepoints: AtomicUsize,
    /// Cleared when the scope's transaction ends — normally or because
    /// the handler's timeout dropped it mid-flight. A `tx` a script
    /// stashed and reused later must fail loudly rather than write into
    /// an abandoned transaction the next outer statement will roll back.
    alive: Arc<AtomicBool>,
}

/// The connection of a live scope; an ended one is refused.
fn tx_conn(tx: &LuaTransaction) -> mlua::Result<Conn> {
    if !tx.alive.load(Ordering::Acquire) {
        return Err(mlua::Error::RuntimeError(
            "this transaction has ended: a `tx` handle is only valid inside the \
             db:transaction(function(tx) ... end) body that received it"
                .into(),
        ));
    }
    Ok(tx.conn.clone())
}

/// Where a pending query came from, which decides the check it runs
/// before touching the connection: an outer handle must not run while a
/// transaction is open (it would rollback-or-join it), an inner one must
/// not outlive its scope.
#[derive(Clone)]
enum QueryOrigin {
    Outer(TxFlag),
    Inner(Arc<AtomicBool>),
}

impl QueryOrigin {
    fn check(&self) -> mlua::Result<()> {
        match self {
            QueryOrigin::Outer(flag) if flag.load(Ordering::Acquire) => {
                Err(mlua::Error::RuntimeError(
                    "a transaction is open on this connection: a `nitr.db:query_async` handle \
                     cannot run inside db:transaction(...); use `tx:query_async` instead"
                        .into(),
                ))
            }
            QueryOrigin::Inner(alive) if !alive.load(Ordering::Acquire) => {
                Err(mlua::Error::RuntimeError(
                    "this transaction has ended: the `tx:query_async` handle can no longer run"
                        .into(),
                ))
            }
            _ => Ok(()),
        }
    }

    fn is_outer(&self) -> bool {
        matches!(self, QueryOrigin::Outer(_))
    }
}

/// Runs a blocking database operation on the blocking thread pool so it
/// stalls a blocking-pool thread instead of an async worker. Only plain
/// `Send` data crosses the boundary — never a Lua handle.
///
/// `outer` says the statement comes from the `nitr.db` handle, i.e. from
/// outside any `db:transaction` scope. Such a statement must run in
/// autocommit mode; if the connection is still inside a transaction, that
/// transaction was abandoned — its `db:transaction` future was dropped
/// mid-flight by the handler's timeout — and it is rolled back first,
/// rather than silently joined. Statements from a `tx` handle pass
/// `false`: being inside a transaction is their whole point.
async fn run_blocking<T, F>(
    conn: Conn,
    kind: &'static str,
    sql: String,
    params: Vec<SqlValue>,
    outer: bool,
    f: F,
) -> mlua::Result<T>
where
    T: Send + 'static,
    F: FnOnce(&Connection, &str, &[SqlValue], usize) -> Result<T, rusqlite::Error> + Send + 'static,
{
    // The `db_query` span: which statement kind ran, for how long, and a
    // correlator for *which* statement. Deliberately no SQL text and no
    // bind values — statements can embed secrets, and logs outlive them.
    // DEBUG so the per-request decomposition is opt-in via the level
    // filter.
    // The tag is hashed and formatted only when something consumes it: the
    // span at DEBUG, or the error path. At INFO neither happens, and a
    // statement used to pay a hash of its whole text plus a `format!`
    // regardless.
    let span = tracing::debug_span!(
        "db_query",
        kind,
        stmt = tracing::field::Empty,
        elapsed_ms = tracing::field::Empty
    );
    let started = (!span.is_disabled()).then(|| {
        span.record("stmt", stmt_tag(&sql).as_str());
        std::time::Instant::now()
    });
    let result = tokio::task::spawn_blocking(move || {
        let db = conn.lock().map_err(|_| {
            mlua::Error::RuntimeError("failed to lock the database connection".into())
        })?;
        let conn = &db.conn;
        if outer && !conn.is_autocommit() {
            tracing::warn!(
                "rolling back a transaction a previous request left open on this connection \
                 (its handler was cut off mid-transaction)"
            );
            conn.execute_batch("ROLLBACK").map_err(|err| {
                mlua::Error::RuntimeError(format!(
                    "failed to roll back an abandoned transaction: {}",
                    redact(&err)
                ))
            })?;
        }
        // The same policy as the span above, and for the same reason: this
        // message becomes an ordinary Lua error, so it reaches the
        // operator's log through the handler's error path *and* reaches
        // application Lua through `nitr.errinfo`, which can forward it
        // anywhere. Interpolating the statement here put a token or an
        // email address in a literal into both. The tag keeps repeated
        // failures groupable without carrying what the statement said.
        f(conn, &sql, &params, db.max_rows).map_err(|err| {
            mlua::Error::RuntimeError(format!(
                "{kind} failed (stmt {}): {}",
                stmt_tag(&sql),
                redact(&err)
            ))
        })
    })
    .instrument(span.clone())
    .await
    .map_err(mlua::Error::external)?;
    if let Some(started) = started {
        span.record("elapsed_ms", started.elapsed().as_millis() as u64);
    }
    result
}

/// Renders a rusqlite error without the statement it came from.
///
/// Dropping the interpolated `{sql}` from our own `format!` is not enough:
/// `rusqlite::Error::SqlInputError`'s own `Display` is
/// `"{msg} in {sql} at offset {n}"`, so every prepare-time failure that
/// carries an offset — a syntax error, an unknown column — puts the whole
/// statement back into the message, quoted literals included. That is the
/// original leak, re-entering through the error type rather than through
/// the caller. Everything else formats normally: no other variant embeds
/// the statement.
///
/// The offset survives because it is a position, not content, and it is
/// what makes the message actionable next to the statement tag.
///
/// One residual, stated rather than papered over: SQLite's own `msg` names
/// the *identifier* it could not resolve (`no such column: foo`). If an
/// application interpolated an untrusted value into the statement as a
/// bare identifier, that value appears here. Nothing this function can do
/// helps — the message would have to be discarded entirely, leaving
/// "query failed (stmt a1b2c3d4)" and nothing to act on — and a value
/// reaching SQL unquoted is a SQL-injection bug in the handler, which is a
/// different and larger problem than the one this redaction addresses.
/// Bind parameters (`?1`) are the fix for that, and they never reach the
/// statement text at all.
fn redact(err: &rusqlite::Error) -> String {
    match err {
        rusqlite::Error::SqlInputError { msg, offset, .. } => {
            format!("{msg} at offset {offset}")
        }
        other => other.to_string(),
    }
}

/// A short correlator for a statement, so repeated failures of the *same*
/// query can be grouped in a log without the log carrying the query.
///
/// Stable **within one process only**: `DefaultHasher`'s output is not
/// guaranteed across Rust releases, and nothing here should encourage
/// treating the tag as an identifier that outlives the run. It is chosen
/// over a digest to avoid coupling the database to the optional `crypto`
/// feature for what is a log-grouping aid, not a security primitive.
fn stmt_tag(sql: &str) -> String {
    use std::hash::{Hash as _, Hasher as _};
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    sql.hash(&mut hasher);
    format!("{:08x}", hasher.finish() as u32)
}

/// Executes a control statement (`BEGIN`, `COMMIT`, `SAVEPOINT ...`).
async fn exec_batch(conn: Conn, sql: String, outer: bool) -> mlua::Result<()> {
    run_blocking(conn, "tx", sql, Vec::new(), outer, |conn, sql, _, _| {
        conn.execute_batch(sql)
    })
    .await
}

/// Registers `execute`/`query`/`query_row`/`query_one` on a userdata type
/// that exposes a connection — shared between `db` and transactions.
///
/// `conn_of` may refuse: the outer `nitr.db` handle does so while a
/// transaction is open on the same connection. `outer` is forwarded to
/// [`run_blocking`].
fn add_stmt_methods<T, M>(methods: &mut M, conn_of: fn(&T) -> mlua::Result<Conn>, outer: bool)
where
    T: UserData + 'static,
    M: UserDataMethods<T>,
{
    // The connection is cloned out before each async block so no
    // userdata borrow lives across an await point.
    methods.add_async_method("execute", move |_, this, args: (String, Option<Table>)| {
        let conn = conn_of(&this);
        async move {
            let (sql, params) = args;
            let params = params_from_table(params.as_ref())?;
            let affected =
                run_blocking(conn?, "execute", sql, params, outer, execute::call).await?;
            Ok(affected)
        }
    });

    methods.add_async_method(
        "query_row",
        move |lua, this, args: (String, Option<Table>)| {
            let conn = conn_of(&this);
            async move {
                let (sql, params) = args;
                let params = params_from_table(params.as_ref())?;
                let row =
                    run_blocking(conn?, "query_row", sql, params, outer, query_row::call).await?;
                match row {
                    Some(row) => row_to_lua(&lua, row).map(Value::Table),
                    None => Ok(Value::Nil),
                }
            }
        },
    );

    methods.add_async_method(
        "query_one",
        move |lua, this, args: (String, Option<Table>)| {
            let conn = conn_of(&this);
            async move {
                let (sql, params) = args;
                let params = params_from_table(params.as_ref())?;
                let row =
                    run_blocking(conn?, "query_one", sql, params, outer, query_one::call).await?;
                row_to_lua(&lua, row)
            }
        },
    );

    methods.add_async_method("query", move |lua, this, args: (String, Option<Table>)| {
        let conn = conn_of(&this);
        async move {
            let (sql, params) = args;
            let params = params_from_table(params.as_ref())?;
            let rows = run_blocking(conn?, "query", sql, params, outer, query::call).await?;
            rows_to_lua(&lua, rows)
        }
    });
}

/// Which statement an unsent query will run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum QueryKind {
    Query,
    QueryRow,
    QueryOne,
    Execute,
}

impl QueryKind {
    fn parse(name: Option<&str>) -> mlua::Result<Self> {
        match name.unwrap_or("query") {
            "query" => Ok(QueryKind::Query),
            "query_row" => Ok(QueryKind::QueryRow),
            "query_one" => Ok(QueryKind::QueryOne),
            "execute" => Ok(QueryKind::Execute),
            other => Err(mlua::Error::RuntimeError(format!(
                "unknown query kind `{other}`: expected \"query\", \"query_row\", \
                 \"query_one\" or \"execute\""
            ))),
        }
    }
}

/// The work an unsent query represents, lifted out of the Lua handle so it
/// can be awaited without holding a userdata borrow.
pub struct PendingQuery {
    conn: Conn,
    kind: QueryKind,
    sql: String,
    params: Vec<SqlValue>,
    /// Which handle built it; checked when it runs, not only when it was
    /// built — a handle made before `db:transaction` and awaited inside
    /// it would otherwise roll the live transaction back.
    origin: QueryOrigin,
}

impl PendingQuery {
    /// Runs the statement and converts the result to a Lua value.
    pub async fn run(self, lua: &Lua) -> mlua::Result<Value> {
        let PendingQuery {
            conn,
            kind,
            sql,
            params,
            origin,
        } = self;
        origin.check()?;
        let outer = origin.is_outer();
        match kind {
            QueryKind::Execute => {
                let affected =
                    run_blocking(conn, "execute", sql, params, outer, execute::call).await?;
                Ok(Value::Integer(affected as i64))
            }
            QueryKind::QueryRow => {
                let row =
                    run_blocking(conn, "query_row", sql, params, outer, query_row::call).await?;
                match row {
                    Some(row) => row_to_lua(lua, row).map(Value::Table),
                    None => Ok(Value::Nil),
                }
            }
            QueryKind::QueryOne => {
                let row =
                    run_blocking(conn, "query_one", sql, params, outer, query_one::call).await?;
                row_to_lua(lua, row).map(Value::Table)
            }
            QueryKind::Query => {
                let rows = run_blocking(conn, "query", sql, params, outer, query::call).await?;
                rows_to_lua(lua, rows).map(Value::Table)
            }
        }
    }
}

/// An unsent query handle, the database counterpart of an unsent `fetch`.
///
/// Exists so `nitr.await_all` can run a query and an HTTP call at the same
/// time instead of one after the other. It carries no Lua state, which is
/// what keeps `await_all` a fixed set of Rust-side jobs rather than a
/// general concurrency primitive.
pub(crate) struct LuaPendingQuery(Mutex<Option<PendingQuery>>);

impl LuaPendingQuery {
    /// Takes the pending work; a handle can only be run once.
    pub(crate) fn take(&self) -> mlua::Result<PendingQuery> {
        self.0
            .lock()
            .map_err(|_| mlua::Error::RuntimeError("the query handle lock is poisoned".into()))?
            .take()
            .ok_or_else(|| {
                mlua::Error::RuntimeError(
                    "this query handle has already been awaited; build a new one".into(),
                )
            })
    }
}

impl UserData for LuaPendingQuery {
    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
        // Awaiting one handle on its own, for symmetry with fetch:send().
        methods.add_async_method("send", |lua, handle, ()| {
            let pending = handle.take();
            async move { pending?.run(&lua).await }
        });
    }
}

/// Registers `query_async` on a userdata type that exposes a connection.
fn add_async_query_method<T, M>(
    methods: &mut M,
    origin_of: fn(&T) -> mlua::Result<(Conn, QueryOrigin)>,
) where
    T: UserData + 'static,
    M: UserDataMethods<T>,
{
    // db:query_async(sql, params?, kind?) -> unsent handle for await_all.
    methods.add_method(
        "query_async",
        move |_, this, (sql, params, kind): (String, Option<Table>, Option<String>)| {
            let (conn, origin) = origin_of(this)?;
            Ok(LuaPendingQuery(Mutex::new(Some(PendingQuery {
                conn,
                kind: QueryKind::parse(kind.as_deref())?,
                sql,
                params: params_from_table(params.as_ref())?,
                origin,
            }))))
        },
    );
}

/// Rolls back only when a transaction is actually open: after
/// `SQLITE_FULL`/`SQLITE_IOERR` SQLite may already have aborted it, and
/// a `ROLLBACK` then fails with "no transaction is active" — noise, not
/// news.
async fn rollback_if_open(conn: Conn, sql: String) -> mlua::Result<()> {
    run_blocking(conn, "tx", sql, Vec::new(), false, |conn, sql, _, _| {
        if conn.is_autocommit() {
            Ok(())
        } else {
            conn.execute_batch(sql)
        }
    })
    .await
}

/// Ends a scope when dropped — after the body, or when the future is
/// dropped mid-flight — so its `tx` handles and pending queries refuse
/// to run from then on. Plain Rust, no Lua API: it may run while the
/// coroutine is being collected.
struct ScopeEnd(Arc<AtomicBool>);

impl Drop for ScopeEnd {
    fn drop(&mut self) {
        self.0.store(false, Ordering::Release);
    }
}

/// Runs the transaction body between `begin` and `commit`/`rollback`,
/// passing a fresh [`LuaTransaction`] scope and re-raising body errors
/// after rolling back.
///
/// The scope is invalidated once the body returns, so a `tx` a script
/// stashed somewhere cannot run statements after its transaction ended
/// — which would silently bypass the outer handle's transaction guard.
///
/// A `COMMIT` that fails (`SQLITE_BUSY` past the busy timeout, a full
/// disk) leaves SQLite's transaction open; it is rolled back here so the
/// connection is in autocommit mode again when the error reaches Lua,
/// instead of every later statement quietly joining a doomed transaction.
/// The Lua half of `transaction`, built once per state around the Rust
/// `run` (which begins, calls the body and commits or rolls back) and an
/// `unpack`. The body runs under Lua's `pcall`, so its error value never
/// crosses into Rust, where mlua would flatten a table to a string; the
/// wrapper re-raises it at level 0, so a handler's `pcall` receives exactly
/// what the body threw, and every value the body returned comes back.
const TRANSACTION_WRAPPER: &str = r#"
local run, unpack = ...
return function(self, f)
    local packed = run(self, f)
    if packed[1] then
        return unpack(packed, 2, packed.n)
    end
    error(packed[2], 0)
end
"#;

/// Calls the body under `pcall` and packs `(ok, ...)` into a table with
/// `n`, so a trailing `nil` survives the trip.
const TRANSACTION_BODY: &str = r#"
local pack = ...
return function(f, scope) return pack(pcall(f, scope)) end
"#;

const TRANSACTION_BODY_KEY: &str = "nitr::db::transaction_body";
const TRANSACTION_OUTER_KEY: &str = "nitr::db::transaction";
const TRANSACTION_SAVEPOINT_KEY: &str = "nitr::db::savepoint";

/// The `transaction` method of a handle: the wrapper cached under `key`,
/// built on first use around `run`.
fn transaction_method<R>(
    lua: &Lua,
    key: &str,
    run: fn(Lua, (AnyUserData, Function)) -> R,
) -> mlua::Result<Function>
where
    R: Future<Output = mlua::Result<Table>> + mlua::MaybeSend + 'static,
{
    if let Ok(wrapper) = lua.named_registry_value::<Function>(key) {
        return Ok(wrapper);
    }
    let run = lua.create_async_function(run)?;
    let unpack = lua.create_function(|_, (packed, from, to): (Table, usize, usize)| {
        let mut values = mlua::MultiValue::with_capacity(to.saturating_sub(from) + 1);
        for index in from..=to {
            values.push_back(packed.raw_get::<Value>(index)?);
        }
        Ok(values)
    })?;
    let wrapper = lua
        .load(TRANSACTION_WRAPPER)
        .set_name("=nitr.db")
        .call::<Function>((run, unpack))?;
    lua.set_named_registry_value(key, wrapper.clone())?;
    Ok(wrapper)
}

/// The `pcall` runner of [`TRANSACTION_BODY`], built once per state.
fn transaction_body(lua: &Lua) -> mlua::Result<Function> {
    if let Ok(body) = lua.named_registry_value::<Function>(TRANSACTION_BODY_KEY) {
        return Ok(body);
    }
    let pack = lua.create_function(|lua, args: mlua::MultiValue| {
        let packed = lua.create_table_with_capacity(args.len(), 1)?;
        packed.raw_set("n", args.len())?;
        for (index, value) in args.into_iter().enumerate() {
            packed.raw_set(index + 1, value)?;
        }
        Ok(packed)
    })?;
    let body = lua
        .load(TRANSACTION_BODY)
        .set_name("=nitr.db")
        .call::<Function>(pack)?;
    lua.set_named_registry_value(TRANSACTION_BODY_KEY, body.clone())?;
    Ok(body)
}

/// `db:transaction(fn)`: refused while one is open on the connection.
async fn run_outer_transaction(lua: Lua, (db, f): (AnyUserData, Function)) -> mlua::Result<Table> {
    let (conn, flag) = {
        let db = db.borrow::<LuaDatabase>()?;
        (db.conn.clone(), db.in_transaction.clone())
    };
    if flag.swap(true, Ordering::AcqRel) {
        return Err(mlua::Error::RuntimeError(
            "a transaction is already open on this connection; nest with \
             tx:transaction(...) instead"
                .into(),
        ));
    }
    let _guard = TxGuard(flag);
    run_transaction(
        &lua,
        conn,
        f,
        "BEGIN".into(),
        "COMMIT".into(),
        "ROLLBACK".into(),
        true,
    )
    .await
}

/// `tx:transaction(fn)`: a savepoint, so rolling back the inner scope
/// keeps the outer transaction alive.
async fn run_savepoint(lua: Lua, (tx, f): (AnyUserData, Function)) -> mlua::Result<Table> {
    let (conn, n) = {
        let tx = tx.borrow::<LuaTransaction>()?;
        (tx_conn(&tx)?, tx.savepoints.fetch_add(1, Ordering::Relaxed))
    };
    let name = format!("nitr_sp_{n}");
    run_transaction(
        &lua,
        conn,
        f,
        format!("SAVEPOINT {name}"),
        format!("RELEASE {name}"),
        format!("ROLLBACK TO {name}; RELEASE {name}"),
        false,
    )
    .await
}

/// Begins, runs the body under `pcall`, then commits on `ok` and rolls
/// back otherwise. The packed `(ok, ...)` goes back to the wrapper, which
/// returns the values or re-raises the error.
async fn run_transaction(
    lua: &Lua,
    conn: Conn,
    f: Function,
    begin: String,
    commit: String,
    rollback: String,
    outer: bool,
) -> mlua::Result<Table> {
    let body = transaction_body(lua)?;
    exec_batch(conn.clone(), begin, outer).await?;
    let alive = Arc::new(AtomicBool::new(true));
    let _scope_end = ScopeEnd(alive.clone());
    let scope = lua.create_userdata(LuaTransaction {
        conn: conn.clone(),
        savepoints: AtomicUsize::new(0),
        alive,
    })?;
    let result = body.call_async::<Table>((f, &scope)).await;
    // A savepoint's rollback must run even when the outer transaction is
    // open (it always is), so only the top-level one is conditional.
    let roll_back = |conn: Conn| async move {
        if outer {
            rollback_if_open(conn, rollback).await
        } else {
            exec_batch(conn, rollback, false).await
        }
    };
    let ok = match &result {
        Ok(packed) => packed.raw_get::<bool>(1)?,
        // Only what `pcall` does not catch: the guarded `pcall` re-raises
        // a spent budget.
        Err(_) => false,
    };
    if ok {
        if let Err(commit_err) = exec_batch(conn.clone(), commit, false).await {
            if let Err(rollback_err) = roll_back(conn).await {
                tracing::error!("rollback after a failed commit failed: {rollback_err}");
            }
            return Err(commit_err);
        }
    } else if let Err(rollback_err) = roll_back(conn).await {
        tracing::error!("transaction rollback failed: {rollback_err}");
    }
    result
}

/// Holds `in_transaction` for the lifetime of one `db:transaction` call.
///
/// The flag used to be cleared by a plain store after the body — which
/// never ran when the handler's timeout dropped the future mid-await. The
/// state then went back to the pool with the flag stuck, and every later
/// `nitr.db` call on it was refused for good, while SQLite's write lock
/// stayed held against every other state. A guard clears the flag on
/// every exit, the dropped-future one included; the transaction itself
/// is rolled back by the next outer statement (see [`run_blocking`]).
struct TxGuard(TxFlag);

impl Drop for TxGuard {
    fn drop(&mut self) {
        self.0.store(false, Ordering::Release);
    }
}

impl UserData for LuaDatabase {
    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
        // Statements on the outer handle are refused while a transaction is
        // open. They would run on the same connection and therefore *inside*
        // the transaction, silently — so a write meant to be independent
        // would roll back with it, and a read would see uncommitted rows.
        // Phase 6 documented this as a footgun; documenting a trap is not
        // the same as removing it.
        add_stmt_methods(
            methods,
            |db: &LuaDatabase| {
                if db.in_transaction.load(Ordering::Acquire) {
                    return Err(mlua::Error::RuntimeError(
                        "a transaction is open on this connection: use the `tx` handle passed \
                         to db:transaction(function(tx) ... end), not `nitr.db`. Statements \
                         on the outer handle would join the transaction without saying so."
                            .into(),
                    ));
                }
                Ok(db.conn.clone())
            },
            true,
        );
        add_async_query_method(methods, |db: &LuaDatabase| {
            if db.in_transaction.load(Ordering::Acquire) {
                return Err(mlua::Error::RuntimeError(
                    "a transaction is open on this connection: use the `tx` handle".into(),
                ));
            }
            Ok((
                db.conn.clone(),
                QueryOrigin::Outer(db.in_transaction.clone()),
            ))
        });
    }

    fn add_fields<F: mlua::UserDataFields<Self>>(fields: &mut F) {
        // db:transaction(function(tx) ... end): commits when the function
        // returns, rolls back (and re-raises) when it errors.
        fields.add_field_method_get("transaction", |lua, _| {
            transaction_method(lua, TRANSACTION_OUTER_KEY, run_outer_transaction)
        });
    }
}

impl UserData for LuaTransaction {
    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
        add_stmt_methods(methods, tx_conn, false);
        add_async_query_method(methods, |tx: &LuaTransaction| {
            Ok((tx_conn(tx)?, QueryOrigin::Inner(tx.alive.clone())))
        });
    }

    fn add_fields<F: mlua::UserDataFields<Self>>(fields: &mut F) {
        fields.add_field_method_get("transaction", |lua, _| {
            transaction_method(lua, TRANSACTION_SAVEPOINT_KEY, run_savepoint)
        });
    }
}

/// Opens this state's SQLite connection and builds the `nitr.db` handle.
pub(crate) fn create_database_fn(
    lua: &Lua,
    path: &std::path::Path,
    pragmas: &SqlitePragmas,
) -> Result<AnyUserData> {
    let conn = Arc::new(Mutex::new(Db {
        conn: pragmas::open(path, pragmas)?,
        max_rows: pragmas.max_rows,
    }));
    let value = lua.create_userdata(LuaDatabase {
        conn,
        in_transaction: Arc::new(AtomicBool::new(false)),
    })?;
    Ok(value)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A Lua state with `nitr.db` over a fresh temporary database and a
    /// `stall()` builtin that never returns, standing in for the slow
    /// upstream a handler awaits inside a transaction.
    async fn db_state(label: &str) -> (Lua, std::path::PathBuf) {
        db_state_with(label, SqlitePragmas::default()).await
    }

    async fn db_state_with(label: &str, pragmas: SqlitePragmas) -> (Lua, std::path::PathBuf) {
        static NEXT: AtomicUsize = AtomicUsize::new(0);
        let id = NEXT.fetch_add(1, Ordering::Relaxed);
        let dir =
            std::env::temp_dir().join(format!("nitr-db-test-{label}-{}-{id}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("temp dir");
        let path = dir.join("app.db");
        let lua = Lua::new();
        let db = create_database_fn(&lua, &path, &pragmas).expect("db");
        let nitr = lua.create_table().expect("table");
        nitr.set("db", db).expect("set");
        lua.globals().set("nitr", nitr).expect("set");
        let stall = lua
            .create_async_function(|_, ()| async {
                tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                Ok(())
            })
            .expect("stall");
        lua.globals().set("stall", stall).expect("set");
        lua.load("nitr.db:execute('CREATE TABLE t (x INTEGER)')")
            .exec_async()
            .await
            .expect("setup statement");
        (lua, dir)
    }

    async fn count(lua: &Lua) -> i64 {
        lua.load("return nitr.db:query_row('SELECT COUNT(*) AS n FROM t').n")
            .eval_async()
            .await
            .expect("count")
    }

    /// The body's own error reaches the caller unchanged, table and all,
    /// and every value it returns comes back: a handler branches on
    /// `err.code`, and a body returning `id, created` is ordinary Lua.
    #[tokio::test(flavor = "multi_thread")]
    async fn a_transaction_returns_every_value_and_reraises_the_original_error() {
        let (lua, dir) = db_state("txvalues").await;
        let (a, b, c): (i64, Option<i64>, i64) = lua
            .load("return nitr.db:transaction(function(tx) return 1, nil, 3 end)")
            .eval_async()
            .await
            .expect("values");
        assert_eq!((a, b, c), (1, None, 3));
        let (is_table, code, rolled_back): (bool, String, bool) = lua
            .load(
                r#"
                local ok, err = pcall(nitr.db.transaction, nitr.db, function(tx)
                    tx:execute("INSERT INTO t VALUES (1)")
                    tx:transaction(function(sp)
                        sp:execute("INSERT INTO t VALUES (2)")
                    end)
                    error({ code = "OUT_OF_STOCK", item = 7 })
                end)
                local n = nitr.db:query_row("SELECT COUNT(*) AS n FROM t").n
                return type(err) == "table", err.code, n == 0
                "#,
            )
            .eval_async()
            .await
            .expect("pcall");
        assert!(is_table, "the error value must stay a table");
        assert_eq!(code, "OUT_OF_STOCK");
        assert!(rolled_back);
        // A savepoint's error is the inner body's value too, and only the
        // savepoint is rolled back.
        let (code, n): (String, i64) = lua
            .load(
                r#"
                return nitr.db:transaction(function(tx)
                    tx:execute("INSERT INTO t VALUES (1)")
                    local ok, err = pcall(tx.transaction, tx, function(sp)
                        sp:execute("INSERT INTO t VALUES (2)")
                        error({ code = "INNER" })
                    end)
                    return err.code, tx:query_row("SELECT COUNT(*) AS n FROM t").n
                end)
                "#,
            )
            .eval_async()
            .await
            .expect("savepoint");
        assert_eq!((code.as_str(), n), ("INNER", 1));
        let _ = std::fs::remove_dir_all(dir);
    }

    /// A result set is a list, so an empty one encodes as `[]`, not `{}`.
    #[tokio::test(flavor = "multi_thread")]
    async fn an_empty_result_set_is_a_list() {
        let (lua, dir) = db_state("emptyrows").await;
        let rows: Value = lua
            .load("return nitr.db:query('SELECT x FROM t WHERE x = 42')")
            .eval_async()
            .await
            .expect("query");
        assert_eq!(crate::bounded::to_json_string(&rows).expect("json"), "[]");
        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn query_row_returns_nil_for_an_empty_result() {
        let (lua, dir) = db_state("qrow").await;
        let row: Value = lua
            .load("return nitr.db:query_row('SELECT x FROM t WHERE x = 42')")
            .eval_async()
            .await
            .expect("query_row");
        assert!(row.is_nil(), "no rows must be nil, got {row:?}");
        let _ = std::fs::remove_dir_all(dir);
    }

    /// A trailing nil is padded because a Lua list cannot hold it; a
    /// statement called with no parameters at all keeps failing, or a
    /// forgotten list would run `WHERE id = NULL` and match nothing.
    #[tokio::test(flavor = "multi_thread")]
    async fn a_nil_parameter_inserts_null_but_a_missing_list_does_not() {
        let (lua, dir) = db_state("null").await;
        let (trailing, packed): (bool, bool) = lua
            .load(
                "nitr.db:execute('CREATE TABLE p (a INTEGER, b TEXT)')
                 nitr.db:execute('INSERT INTO p (a, b) VALUES (?, ?)', { 1, nil })
                 nitr.db:execute('INSERT INTO p (a, b) VALUES (?, ?)', table.pack(nil, 'x'))
                 return nitr.db:query_one('SELECT b IS NULL AS missing FROM p WHERE a = 1').missing == 1,
                        nitr.db:query_one('SELECT a IS NULL AS missing FROM p WHERE b = ?', { 'x' }).missing == 1",
            )
            .eval_async()
            .await
            .expect("insert");
        assert!(trailing && packed);
        for params in ["", ", {}"] {
            let err = lua
                .load(format!(
                    "return nitr.db:query('SELECT * FROM p WHERE a = ?'{params})"
                ))
                .eval_async::<Value>()
                .await
                .expect_err("no parameters")
                .to_string();
            assert!(err.contains("parameters"), "`{params}`: {err}");
        }
        let _ = std::fs::remove_dir_all(dir);
    }

    /// A row is keyed by column name: two columns sharing one would keep
    /// only the last, so a join reading `id` gets the wrong table's.
    #[tokio::test(flavor = "multi_thread")]
    async fn duplicate_column_names_are_refused() {
        let (lua, dir) = db_state("dupcol").await;
        for call in ["query", "query_row", "query_one"] {
            let err = lua
                .load(format!("return nitr.db:{call}('SELECT 1 AS id, 2 AS id')"))
                .eval_async::<Value>()
                .await
                .expect_err(call)
                .to_string();
            assert!(err.contains("columns 1 and 2"), "{call}: {err}");
        }
        let _ = std::fs::remove_dir_all(dir);
    }

    /// A transaction whose future is dropped mid-await (the handler's
    /// timeout) must not brick the connection: the flag clears, the next
    /// outer statement rolls the abandoned work back, and a new
    /// transaction can begin.
    #[tokio::test(flavor = "multi_thread")]
    async fn an_abandoned_transaction_is_rolled_back_and_the_connection_recovers() {
        let (lua, dir) = db_state("abandon").await;
        let body = lua
            .load(
                "nitr.db:transaction(function(tx)
                     tx:execute('INSERT INTO t VALUES (1)')
                     stall()
                 end)",
            )
            .exec_async();
        let timed = tokio::time::timeout(std::time::Duration::from_millis(200), body).await;
        assert!(timed.is_err(), "the stall must outlive the timeout");
        // The future is gone; the state is what the pool would hand out.

        lua.load("nitr.db:execute('INSERT INTO t VALUES (2)')")
            .exec_async()
            .await
            .expect("an outer statement runs after the abandoned transaction");
        assert_eq!(count(&lua).await, 1, "the abandoned insert was rolled back");

        lua.load("nitr.db:transaction(function(tx) tx:execute('INSERT INTO t VALUES (3)') end)")
            .exec_async()
            .await
            .expect("a new transaction opens");
        assert_eq!(count(&lua).await, 2);
        let _ = std::fs::remove_dir_all(dir);
    }

    /// A `nitr.db:query_async` handle built before a transaction and
    /// awaited inside it is refused, not silently run in autocommit
    /// (which would roll the live transaction back underneath it).
    #[tokio::test(flavor = "multi_thread")]
    async fn an_outer_pending_query_is_refused_inside_a_transaction() {
        let (lua, dir) = db_state("pending").await;
        let (ok, err): (bool, String) = lua
            .load(
                "local h = nitr.db:query_async('SELECT 1')
                 local ok, err = pcall(function()
                     nitr.db:transaction(function(tx)
                         tx:execute('INSERT INTO t VALUES (1)')
                         h:send()
                     end)
                 end)
                 return ok, tostring(err)",
            )
            .eval_async()
            .await
            .expect("script");
        assert!(!ok, "the handle must be refused");
        assert!(err.contains("transaction is open"), "got: {err}");
        assert_eq!(
            count(&lua).await,
            0,
            "the body's insert rolled back with the error"
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    /// A `tx` stashed past its transaction is dead, and says so.
    #[tokio::test(flavor = "multi_thread")]
    async fn a_stashed_tx_handle_is_dead_after_its_transaction_ends() {
        let (lua, dir) = db_state("stash").await;
        let (ok, err): (bool, String) = lua
            .load(
                "local saved
                 nitr.db:transaction(function(tx) saved = tx end)
                 local ok, err = pcall(function() saved:execute('INSERT INTO t VALUES (1)') end)
                 return ok, tostring(err)",
            )
            .eval_async()
            .await
            .expect("script");
        assert!(!ok);
        assert!(err.contains("has ended"), "got: {err}");
        assert_eq!(count(&lua).await, 0);
        let _ = std::fs::remove_dir_all(dir);
    }

    /// A result past `max_rows` is an error naming the setting, never a
    /// silent truncation; results at the cap still come back whole.
    #[tokio::test(flavor = "multi_thread")]
    async fn queries_past_max_rows_are_refused_not_truncated() {
        let pragmas = SqlitePragmas {
            max_rows: 2,
            ..SqlitePragmas::default()
        };
        let (lua, dir) = db_state_with("maxrows", pragmas).await;
        lua.load("nitr.db:execute('INSERT INTO t VALUES (1), (2), (3)')")
            .exec_async()
            .await
            .expect("seed");
        let (ok, err): (bool, String) = lua
            .load(
                "local ok, err = pcall(function() return nitr.db:query('SELECT x FROM t') end)
                 return ok, tostring(err)",
            )
            .eval_async()
            .await
            .expect("script");
        assert!(!ok, "three rows over a cap of two must fail");
        assert!(err.contains("max_rows"), "got: {err}");
        let n: i64 = lua
            .load("return #nitr.db:query('SELECT x FROM t LIMIT 2')")
            .eval_async()
            .await
            .expect("at the cap");
        assert_eq!(n, 2);
        let _ = std::fs::remove_dir_all(dir);
    }

    /// A `COMMIT` that fails leaves SQLite's transaction open; it must be
    /// rolled back so the connection is in autocommit mode again for the
    /// next statement. Induced the way it happens in production: in
    /// rollback-journal mode a reader holding a shared lock (an open
    /// cursor on another connection) blocks the exclusive lock `COMMIT`
    /// needs, and `busy_timeout` turns that into `SQLITE_BUSY`.
    #[tokio::test(flavor = "multi_thread")]
    async fn a_failed_commit_rolls_back_and_the_connection_recovers() {
        let pragmas = SqlitePragmas {
            journal_mode: "delete".into(),
            busy_timeout: 50,
            ..SqlitePragmas::default()
        };
        let (lua, dir) = db_state_with("commitfail", pragmas).await;
        lua.load("nitr.db:execute('INSERT INTO t VALUES (1)')")
            .exec_async()
            .await
            .expect("seed");

        // The reader: a stepped, unfinished cursor keeps the shared lock.
        let reader = Connection::open(dir.join("app.db")).expect("reader");
        let mut stmt = reader.prepare("SELECT x FROM t").expect("prepare");
        let mut rows = stmt.query([]).expect("query");
        assert!(
            rows.next().expect("step").is_some(),
            "the cursor must be live"
        );

        let (ok, err): (bool, String) = lua
            .load(
                "local ok, err = pcall(function()
                     nitr.db:transaction(function(tx) tx:execute('INSERT INTO t VALUES (2)') end)
                 end)
                 return ok, tostring(err)",
            )
            .eval_async()
            .await
            .expect("script");
        assert!(!ok, "COMMIT must fail while the reader holds its lock");
        assert!(
            err.contains("locked") || err.contains("busy"),
            "the failure must be the lock, got: {err}"
        );
        drop(rows);
        drop(stmt);
        drop(reader);

        // Autocommit again: an outer statement runs without an abandoned
        // transaction in the way, and the failed insert is gone.
        lua.load("nitr.db:execute('INSERT INTO t VALUES (3)')")
            .exec_async()
            .await
            .expect("the connection is usable after the failed commit");
        let xs: Vec<i64> = lua
            .load(
                "local out = {}
                 for _, r in ipairs(nitr.db:query('SELECT x FROM t ORDER BY x')) do
                     out[#out + 1] = r.x
                 end
                 return out",
            )
            .eval_async()
            .await
            .expect("rows");
        assert_eq!(
            xs,
            vec![1, 3],
            "row 2 was rolled back with the failed commit"
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn query_kinds_parse_strictly_with_a_query_default() {
        assert_eq!(QueryKind::parse(None).expect("default"), QueryKind::Query);
        for (name, kind) in [
            ("query", QueryKind::Query),
            ("query_row", QueryKind::QueryRow),
            ("query_one", QueryKind::QueryOne),
            ("execute", QueryKind::Execute),
        ] {
            assert_eq!(QueryKind::parse(Some(name)).expect(name), kind);
        }
        let err = QueryKind::parse(Some("insert")).expect_err("unknown kind");
        assert!(err.to_string().contains("insert"), "{err}");
    }
}