tinystore 0.3.0

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
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
//! Rows as a statement gives them, and how they become the program's values.
//!
//! A statement's rows are read inside a snapshot or a savepoint, as SQLite's
//! own values, and decoded after it ends, so that decoding never holds either
//! open: a reader's snapshot is the oldest the write-ahead log keeps, and a
//! savepoint holds the writer.

use std::fmt;
use std::sync::Arc;

use rusqlite::{Statement, params_from_iter};
use serde::de::value::{SeqDeserializer, StrDeserializer};
use serde::de::{self, DeserializeOwned, DeserializeSeed, IntoDeserializer, Visitor};

use super::included::literal_rows;
use super::values::Value;
use crate::{Error, Memory, Reservation, Result};

/// Values a call reads at most, in bytes, before it is `limit`: past them a
/// program reads in pages, or a row at a time.
pub(crate) const MOST_READ: usize = 64 << 20;

/// What a `limit` of a call's rows names in its `limit` fact.
const ROW_BYTES: &str = "bytes of a call's rows";

/// The store's memory a call reserves first for its rows, and at least each
/// time it grows.
const FIRST_HELD: u64 = 64 << 10;

/// The rows a statement gave, each `columns.len()` values long, and the
/// store's memory they hold.
pub(crate) struct Rows {
    columns: Arc<[String]>,
    values: Vec<Value>,
    #[expect(dead_code, reason = "held while the rows are: its drop gives the store's memory back")]
    held: Held,
    /// The columns that hold an included query's rows.
    nested: Vec<Nested>,
}

/// A column whose value is the rows of an included query, as their literals,
/// and the names of those rows' columns.
#[derive(Clone, Debug)]
pub(crate) struct Nested {
    pub(crate) column: String,
    pub(crate) columns: Arc<[String]>,
}

/// The store's memory a call's rows hold, reserved as they are read: twice
/// what it holds while that is free, so that a large answer reserves a few
/// times rather than a row at a time. It never waits, since the call holds a
/// snapshot or the writer that the work holding the memory may wait for: what
/// is not free now is `limit`. A store without a budget counts nothing.
#[derive(Debug, Default)]
pub(crate) struct Held {
    reservation: Option<Reservation>,
    bytes: u64,
}

impl Held {
    pub(crate) fn of(memory: &Arc<Memory>) -> Held {
        Held { reservation: memory.bounded().then(|| memory.nothing()), bytes: 0 }
    }

    /// Covers `bytes` of rows, or fails `limit` naming the store's memory.
    fn reach(&mut self, bytes: u64) -> Result<()> {
        self.bytes = bytes;
        let Some(reservation) = &mut self.reservation else {
            return Ok(());
        };
        let Some(short) = bytes.checked_sub(reservation.bytes()).filter(|short| *short > 0) else {
            return Ok(());
        };
        let doubled = short.max(reservation.bytes()).max(FIRST_HELD);
        reservation.grow(doubled, "its rows").or_else(|_| reservation.grow(short, "its rows"))
    }

    /// Covers `bytes` of the rows several statements read for one call,
    /// within one call's bound, or fails `limit`.
    #[cfg(feature = "search")]
    pub(crate) fn cover(&mut self, bytes: usize) -> Result<()> {
        if bytes > MOST_READ {
            return Err(past_bound(bytes, MOST_READ));
        }
        self.reach(bytes as u64)
    }

    /// Gives back what the rows no longer hold: a part of them sent.
    #[cfg(feature = "wire")]
    pub(crate) fn give_back(&mut self, bytes: u64) {
        self.bytes = self.bytes.saturating_sub(bytes);
        self.settle();
    }

    /// Keeps no more than the rows hold.
    fn settle(&mut self) {
        if let Some(reservation) = &mut self.reservation {
            reservation.shrink(self.bytes);
        }
    }
}

/// What a statement's rows are read into: the rows, or their columns.
pub(crate) trait Answer: Sized {
    /// Reads `statement`'s rows as [`step`] gives them, within `bounds`: so
    /// many rows, and so many bytes of values.
    fn read(statement: &mut Statement<'_>, values: &[Value], bounds: (usize, usize), held: Held) -> Result<Self>;

    fn len(&self) -> usize;

    fn width(&self) -> usize;
}

/// What a column holds: said by its values, or by its declaration when it
/// holds none.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Holds {
    Integers,
    Reals,
    /// Text, blobs, values of several types, or nothing known.
    Any,
}

impl Holds {
    /// What a column declared as `declaration` holds, by the affinity SQLite
    /// reads from it (<https://sqlite.org/datatype3.html>, 3.1): `INT`
    /// anywhere in it is integers, a text or a blob anything, and what is
    /// left, `real` and `numeric` among it, reals. A strict table's `any`
    /// holds anything, and so does an expression, which declares nothing.
    pub(crate) fn declared(declaration: Option<&str>) -> Holds {
        let Some(declaration) = declaration else {
            return Holds::Any;
        };
        let says = |word: &str| {
            declaration.as_bytes().windows(word.len()).any(|part| part.eq_ignore_ascii_case(word.as_bytes()))
        };
        if says("int") {
            return Holds::Integers;
        }
        let anything = declaration.is_empty() || declaration.eq_ignore_ascii_case("any");
        if anything || ["char", "clob", "text", "blob"].into_iter().any(says) { Holds::Any } else { Holds::Reals }
    }
}

/// What a statement gave as it was stepped: its columns' names, what each is
/// declared to hold, and its rows.
pub(crate) struct Stepped {
    pub(crate) columns: Vec<String>,
    #[cfg_attr(not(feature = "wire"), expect(dead_code, reason = "the wire's answers read them"))]
    pub(crate) declared: Vec<Holds>,
    #[cfg_attr(not(feature = "wire"), expect(dead_code, reason = "the wire's answers read them"))]
    pub(crate) rows: usize,
}

/// Steps `statement` to its end, or until it gave `most` rows, giving `keep`
/// each value with its column and the row's width, a row after another,
/// within the store's memory; past `bytes` of values it is `limit`.
pub(crate) fn step(
    statement: &mut Statement<'_>,
    values: &[Value],
    (most, bytes): (usize, usize),
    held: &mut Held,
    mut keep: impl FnMut(usize, usize, Value),
) -> Result<Stepped> {
    let mut rows = statement.query(params_from_iter(values)).map_err(|error| failure("its rows", error))?;
    let mut named = None;
    let (mut count, mut size) = (0, 0usize);
    while count < most {
        let Some(row) = rows.next().map_err(|error| failure("its rows", error))? else {
            break;
        };
        // A kept statement compiled before its table changed is compiled
        // again at its first step, so its columns are named after it.
        let (columns, _) = named.get_or_insert_with(|| named_columns(row.as_ref()));
        let width = columns.len();
        for index in 0..width {
            let value = Value::of(row.get_ref(index).map_err(|error| failure("its rows", error))?);
            size += value.size();
            keep(index, width, value);
        }
        if size > bytes {
            return Err(past_bound(size, bytes));
        }
        held.reach(size as u64)?;
        count += 1;
    }
    held.settle();
    drop(rows);
    let (columns, declared) = named.unwrap_or_else(|| named_columns(statement));
    Ok(Stepped { columns, declared, rows: count })
}

/// A stepped statement's columns, and what each one's declared type holds.
fn named_columns(statement: &Statement<'_>) -> (Vec<String>, Vec<Holds>) {
    let named = statement.columns();
    let columns = named.iter().map(|column| column.name().to_owned()).collect();
    (columns, named.iter().map(|column| Holds::declared(column.decl_type())).collect())
}

/// Where a statement's values go as its rows are read, for a caller that
/// keeps them in a form of its own: the wire, as the bytes of its message.
#[cfg(feature = "wire")]
pub(crate) trait Keep: Default {
    /// Takes the value of the row's column `column`, of `width` columns.
    fn value(&mut self, column: usize, width: usize, value: Value);
}

/// A statement's rows as a `K` kept them, and the store's memory they hold.
#[cfg(feature = "wire")]
pub(crate) struct Kept<K> {
    pub(crate) columns: Vec<String>,
    pub(crate) rows: usize,
    pub(crate) kept: K,
    held: Held,
}

#[cfg(feature = "wire")]
impl<K> Kept<K> {
    /// The store's memory the rows hold, for whoever keeps them after the
    /// call: a download until its last part is sent.
    pub(crate) fn held(&mut self) -> Held {
        std::mem::take(&mut self.held)
    }
}

#[cfg(feature = "wire")]
impl<K: Keep> Answer for Kept<K> {
    fn read(statement: &mut Statement<'_>, values: &[Value], bounds: (usize, usize), mut held: Held) -> Result<Self> {
        let mut kept = K::default();
        let stepped =
            step(statement, values, bounds, &mut held, |column, width, value| kept.value(column, width, value))?;
        Ok(Kept { columns: stepped.columns, rows: stepped.rows, kept, held })
    }

    fn len(&self) -> usize {
        self.rows
    }

    fn width(&self) -> usize {
        self.columns.len()
    }
}

impl Answer for Rows {
    fn read(statement: &mut Statement<'_>, values: &[Value], bounds: (usize, usize), mut held: Held) -> Result<Rows> {
        let mut kept = Vec::new();
        let stepped = step(statement, values, bounds, &mut held, |_, _, value| kept.push(value))?;
        Ok(Rows { columns: stepped.columns.into(), values: kept, held, nested: Vec::new() })
    }

    fn len(&self) -> usize {
        Rows::len(self)
    }

    fn width(&self) -> usize {
        Rows::width(self)
    }
}

impl Rows {
    /// The same rows, `nested` of their columns read as the rows of the
    /// queries they include.
    pub(crate) fn nesting(mut self, nested: Vec<Nested>) -> Rows {
        self.nested = nested;
        self
    }

    pub(crate) fn columns(&self) -> &[String] {
        &self.columns
    }

    /// The bytes of their values, as their bound counts them.
    #[cfg(feature = "search")]
    pub(crate) fn bytes(&self) -> usize {
        self.values.iter().map(Value::size).sum()
    }

    /// The values, a row after another, each `width()` long.
    #[cfg(feature = "wire")]
    pub(crate) fn into_values(self) -> Vec<Value> {
        self.values
    }

    /// What a test's runner answers: no row, or a scalar's zero.
    #[cfg(test)]
    pub(crate) fn answered(wanted: super::run::Wanted) -> Rows {
        match wanted {
            super::run::Wanted::Scalar => Rows {
                columns: Arc::from([String::new()]),
                values: vec![Value::Integer(0)],
                held: Held::default(),
                nested: Vec::new(),
            },
            _ => Rows { columns: Arc::from([]), values: Vec::new(), held: Held::default(), nested: Vec::new() },
        }
    }

    pub(crate) fn value_at(&self, at: usize) -> &Value {
        &self.values[at]
    }

    pub(crate) fn len(&self) -> usize {
        self.values.len().checked_div(self.columns.len()).unwrap_or(0)
    }

    pub(crate) fn width(&self) -> usize {
        self.columns.len()
    }

    /// Each row as a `T`: a struct by its columns' names, a tuple by their
    /// order, or a single value when the row has one column.
    pub(crate) fn decode<T: DeserializeOwned>(self) -> Result<Vec<T>> {
        let width = self.columns.len();
        if width == 0 {
            return Ok(Vec::new());
        }
        let mut decoded = Vec::with_capacity(self.len());
        let mut values = self.values.into_iter();
        loop {
            let row: Vec<Value> = values.by_ref().take(width).collect();
            if row.is_empty() {
                return Ok(decoded);
            }
            let row = RowDecoder { columns: &self.columns, values: row, nested: &self.nested };
            decoded.push(T::deserialize(row).map_err(|failure| Error::invalid(failure.0))?);
        }
    }

    /// The one value of a row of one column.
    pub(crate) fn scalar<T: DeserializeOwned>(mut self) -> Result<T> {
        let value = self.values.pop().unwrap_or(Value::Null);
        let column = self.columns.first().cloned().unwrap_or_default();
        T::deserialize(ValueDecoder(value)).map_err(|failure| Error::invalid(format!("column {column}: {}", failure.0)))
    }
}

/// The `limit` of a call's rows past their bound, with its facts.
fn past_bound(size: usize, bytes: usize) -> Error {
    Error::limit(format!("its rows pass {} MiB: read them a page at a time, or one at a time", bytes >> 20))
        .naming("limit", ROW_BYTES)
        .naming("wanted", size.to_string())
        .naming("bound", bytes.to_string())
}

/// A statement's failure as the error a caller acts on: a unique or primary
/// key already held is `conflict`, any other constraint and a statement
/// SQLite cannot run, as written, `invalid`.
pub(crate) fn failure(what: &str, error: rusqlite::Error) -> Error {
    crate::sqlite::given_sql_error(what, error)
}

/// Why a value does not read as the program's: said of its column.
#[derive(Debug)]
pub(crate) struct Mismatch(String);

impl fmt::Display for Mismatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for Mismatch {}

impl de::Error for Mismatch {
    fn custom<T: fmt::Display>(message: T) -> Self {
        Mismatch(message.to_string())
    }
}

/// A row: a map of its columns for a struct, a sequence for a tuple, its one
/// value for anything else.
struct RowDecoder<'a> {
    columns: &'a [String],
    values: Vec<Value>,
    nested: &'a [Nested],
}

impl<'de> de::Deserializer<'de> for RowDecoder<'_> {
    type Error = Mismatch;

    fn deserialize_any<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Mismatch> {
        if self.values.len() == 1 && self.nested.is_empty() {
            let column = &self.columns[0];
            let value = self.values.pop().unwrap_or(Value::Null);
            return ValueDecoder(value)
                .deserialize_any(visitor)
                .map_err(|failure| Mismatch(format!("column {column}: {failure}")));
        }
        self.deserialize_map(visitor)
    }

    fn deserialize_map<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        visitor.visit_map(self.columns())
    }

    fn deserialize_struct<V: Visitor<'de>>(
        self,
        _: &'static str,
        _: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Mismatch> {
        self.deserialize_map(visitor)
    }

    fn deserialize_seq<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        visitor.visit_seq(self.columns())
    }

    fn deserialize_tuple<V: Visitor<'de>>(self, _: usize, visitor: V) -> Result<V::Value, Mismatch> {
        self.deserialize_seq(visitor)
    }

    fn deserialize_tuple_struct<V: Visitor<'de>>(
        self,
        _: &'static str,
        _: usize,
        visitor: V,
    ) -> Result<V::Value, Mismatch> {
        self.deserialize_seq(visitor)
    }

    fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        self.one_column()?.deserialize_option(visitor)
    }

    fn deserialize_newtype_struct<V: Visitor<'de>>(self, _: &'static str, visitor: V) -> Result<V::Value, Mismatch> {
        visitor.visit_newtype_struct(self)
    }

    fn deserialize_enum<V: Visitor<'de>>(
        self,
        name: &'static str,
        variants: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Mismatch> {
        self.one_column()?.deserialize_enum(name, variants, visitor)
    }

    serde::forward_to_deserialize_any! {
        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf unit unit_struct
        identifier ignored_any
    }
}

impl<'a> RowDecoder<'a> {
    fn columns(self) -> Columns<'a> {
        Columns { columns: self.columns, values: self.values.into_iter(), at: 0, nested: self.nested }
    }

    fn one_column(mut self) -> Result<ValueDecoder, Mismatch> {
        if self.values.len() != 1 {
            return Err(Mismatch(format!("a row of {} columns does not read as one value", self.values.len())));
        }
        Ok(ValueDecoder(self.values.pop().unwrap_or(Value::Null)))
    }
}

/// A row's columns as a map or in order, each value said of its column when
/// it fails.
struct Columns<'a> {
    columns: &'a [String],
    values: std::vec::IntoIter<Value>,
    at: usize,
    nested: &'a [Nested],
}

impl<'de> de::SeqAccess<'de> for Columns<'_> {
    type Error = Mismatch;

    fn next_element_seed<T: DeserializeSeed<'de>>(&mut self, seed: T) -> Result<Option<T::Value>, Mismatch> {
        if self.at == self.columns.len() {
            return Ok(None);
        }
        de::MapAccess::next_value_seed(self, seed).map(Some)
    }

    fn size_hint(&self) -> Option<usize> {
        Some(self.columns.len() - self.at)
    }
}

impl<'de> de::MapAccess<'de> for Columns<'_> {
    type Error = Mismatch;

    fn next_key_seed<K: DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<K::Value>, Mismatch> {
        let Some(column) = self.columns.get(self.at) else {
            return Ok(None);
        };
        let key: StrDeserializer<'_, Mismatch> = column.as_str().into_deserializer();
        seed.deserialize(key).map(Some)
    }

    fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value, Mismatch> {
        let column = &self.columns[self.at];
        self.at += 1;
        let value = self.values.next().unwrap_or(Value::Null);
        let named = |failure: Mismatch| Mismatch(format!("column {column}: {failure}"));
        match self.nested.iter().find(|nested| nested.column == *column) {
            Some(nested) => seed.deserialize(NestedRows::of(nested, value).map_err(named)?).map_err(named),
            None => seed.deserialize(ValueDecoder(value)).map_err(named),
        }
    }
}

/// The rows of an included query, each read as a row is: a list of them.
struct NestedRows<'a> {
    columns: &'a [String],
    rows: std::vec::IntoIter<Vec<Value>>,
}

impl<'a> NestedRows<'a> {
    /// The rows a column's literals hold; a row that included none holds
    /// `NULL`, and has none.
    fn of(nested: &'a Nested, value: Value) -> Result<NestedRows<'a>, Mismatch> {
        let rows = match value {
            Value::Null => Vec::new(),
            Value::Text(text) => literal_rows(&text).map_err(Mismatch)?,
            other => return ValueDecoder(other).refuse("the rows of an included query"),
        };
        Ok(NestedRows { columns: &nested.columns, rows: rows.into_iter() })
    }
}

impl<'de> de::Deserializer<'de> for NestedRows<'_> {
    type Error = Mismatch;

    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        visitor.visit_seq(self)
    }

    serde::forward_to_deserialize_any! {
        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit unit_struct
        newtype_struct seq tuple tuple_struct map struct enum identifier ignored_any
    }
}

impl<'de> de::SeqAccess<'de> for NestedRows<'_> {
    type Error = Mismatch;

    fn next_element_seed<T: DeserializeSeed<'de>>(&mut self, seed: T) -> Result<Option<T::Value>, Mismatch> {
        let Some(values) = self.rows.next() else {
            return Ok(None);
        };
        seed.deserialize(RowDecoder { columns: self.columns, values, nested: &[] }).map(Some)
    }

    fn size_hint(&self) -> Option<usize> {
        Some(self.rows.len())
    }
}

/// One value as SQLite keeps it, read as the program's type asks.
pub(crate) struct ValueDecoder(pub(crate) Value);

impl ValueDecoder {
    fn refuse<T>(self, wanted: &str) -> Result<T, Mismatch> {
        let shown = match &self.0 {
            Value::Text(text) if text.chars().count() > 40 => {
                format!("TEXT \"{}…\"", text.chars().take(40).collect::<String>())
            }
            Value::Text(text) => format!("TEXT {text:?}"),
            Value::Integer(n) => format!("INTEGER {n}"),
            Value::Real(x) => format!("REAL {x}"),
            Value::Blob(bytes) => format!("a BLOB of {} bytes", bytes.len()),
            Value::Null => "NULL".to_owned(),
        };
        Err(Mismatch(format!("{shown} does not read as {wanted}")))
    }

    fn integer(self, wanted: &str) -> Result<i64, Mismatch> {
        match self.0 {
            Value::Integer(n) => Ok(n),
            _ => self.refuse(wanted),
        }
    }

    /// A value of JSON's own shapes, read from the text that holds it.
    fn json(self, wanted: &str) -> Result<serde_json::Value, Mismatch> {
        match &self.0 {
            Value::Text(text) => serde_json::from_str(text)
                .map_err(|error| Mismatch(format!("its text is not JSON for {wanted}: {error}"))),
            _ => self.refuse(wanted),
        }
    }
}

macro_rules! integers {
    ($($method:ident $visit:ident $ty:ty)*) => {$(
        fn $method<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
            let n = self.integer(stringify!($ty))?;
            let n = <$ty>::try_from(n).map_err(|_| Mismatch(format!("INTEGER {n} is past {}", stringify!($ty))))?;
            visitor.$visit(n)
        }
    )*};
}

impl<'de> de::Deserializer<'de> for ValueDecoder {
    type Error = Mismatch;

    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        match self.0 {
            Value::Null => visitor.visit_unit(),
            Value::Integer(n) => visitor.visit_i64(n),
            Value::Real(x) => visitor.visit_f64(x),
            Value::Text(text) => visitor.visit_string(text),
            Value::Blob(bytes) => visitor.visit_byte_buf(bytes),
        }
    }

    fn deserialize_bool<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        match self.0 {
            Value::Integer(0) => visitor.visit_bool(false),
            Value::Integer(1) => visitor.visit_bool(true),
            _ => self.refuse("a bool, which SQLite keeps as 0 or 1"),
        }
    }

    integers! {
        deserialize_i8 visit_i8 i8
        deserialize_i16 visit_i16 i16
        deserialize_i32 visit_i32 i32
        deserialize_i64 visit_i64 i64
        deserialize_u8 visit_u8 u8
        deserialize_u16 visit_u16 u16
        deserialize_u32 visit_u32 u32
        deserialize_u64 visit_u64 u64
    }

    fn deserialize_i128<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        visitor.visit_i128(i128::from(self.integer("i128")?))
    }

    fn deserialize_u128<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        let n = self.integer("u128")?;
        let n = u128::try_from(n).map_err(|_| Mismatch(format!("INTEGER {n} is past u128")))?;
        visitor.visit_u128(n)
    }

    #[expect(clippy::cast_precision_loss, reason = "an INTEGER read as a float is a float, as SQLite reads one")]
    fn deserialize_f64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        match self.0 {
            Value::Real(x) => visitor.visit_f64(x),
            Value::Integer(n) => visitor.visit_f64(n as f64),
            _ => self.refuse("a float"),
        }
    }

    fn deserialize_f32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        self.deserialize_f64(visitor)
    }

    fn deserialize_str<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        match self.0 {
            Value::Text(text) => visitor.visit_string(text),
            _ => self.refuse("text"),
        }
    }

    fn deserialize_string<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        self.deserialize_str(visitor)
    }

    fn deserialize_char<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        self.deserialize_str(visitor)
    }

    fn deserialize_identifier<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        self.deserialize_str(visitor)
    }

    fn deserialize_bytes<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        match self.0 {
            Value::Blob(bytes) => visitor.visit_byte_buf(bytes),
            Value::Text(text) => visitor.visit_byte_buf(text.into_bytes()),
            _ => self.refuse("bytes"),
        }
    }

    fn deserialize_byte_buf<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        self.deserialize_bytes(visitor)
    }

    fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        match self.0 {
            Value::Null => visitor.visit_none(),
            _ => visitor.visit_some(self),
        }
    }

    fn deserialize_unit<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        match self.0 {
            Value::Null => visitor.visit_unit(),
            _ => self.refuse("nothing"),
        }
    }

    fn deserialize_unit_struct<V: Visitor<'de>>(self, _: &'static str, visitor: V) -> Result<V::Value, Mismatch> {
        self.deserialize_unit(visitor)
    }

    fn deserialize_newtype_struct<V: Visitor<'de>>(self, _: &'static str, visitor: V) -> Result<V::Value, Mismatch> {
        visitor.visit_newtype_struct(self)
    }

    /// A list: a BLOB's bytes for a `Vec<u8>`, JSON's for anything else.
    fn deserialize_seq<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        if let Value::Blob(bytes) = self.0 {
            return visitor.visit_seq(SeqDeserializer::new(bytes.into_iter()));
        }
        de::Deserializer::deserialize_seq(self.json("a list")?, visitor).map_err(json_mismatch)
    }

    fn deserialize_tuple<V: Visitor<'de>>(self, len: usize, visitor: V) -> Result<V::Value, Mismatch> {
        de::Deserializer::deserialize_tuple(self.json("a tuple")?, len, visitor).map_err(json_mismatch)
    }

    fn deserialize_tuple_struct<V: Visitor<'de>>(
        self,
        name: &'static str,
        len: usize,
        visitor: V,
    ) -> Result<V::Value, Mismatch> {
        de::Deserializer::deserialize_tuple_struct(self.json(name)?, name, len, visitor).map_err(json_mismatch)
    }

    fn deserialize_map<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        de::Deserializer::deserialize_map(self.json("a map")?, visitor).map_err(json_mismatch)
    }

    /// A struct is JSON, but `SystemTime`, which is unix milliseconds: serde
    /// reads it as its seconds and nanoseconds since the epoch.
    fn deserialize_struct<V: Visitor<'de>>(
        self,
        name: &'static str,
        fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Mismatch> {
        if name == "SystemTime" {
            let millis = self.integer("a time, which SQLite keeps as unix milliseconds")?;
            let millis =
                u64::try_from(millis).map_err(|_| Mismatch(format!("INTEGER {millis} is a time before 1970")))?;
            let parts = [millis / 1000, (millis % 1000) * 1_000_000];
            return visitor.visit_seq(SeqDeserializer::new(parts.into_iter()));
        }
        de::Deserializer::deserialize_struct(self.json(name)?, name, fields, visitor).map_err(json_mismatch)
    }

    /// An enum kept as the name of its variant, or as JSON when it holds more.
    fn deserialize_enum<V: Visitor<'de>>(
        self,
        name: &'static str,
        variants: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Mismatch> {
        match self.0 {
            Value::Text(ref text) if !text.starts_with('{') => {
                let variant: StrDeserializer<'_, Mismatch> = text.as_str().into_deserializer();
                variant.deserialize_enum(name, variants, visitor)
            }
            _ => de::Deserializer::deserialize_enum(self.json(name)?, name, variants, visitor).map_err(json_mismatch),
        }
    }

    fn deserialize_ignored_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        visitor.visit_unit()
    }

    fn is_human_readable(&self) -> bool {
        true
    }
}

fn json_mismatch(error: serde_json::Error) -> Mismatch {
    Mismatch(format!("its JSON: {error}"))
}

impl<'de> IntoDeserializer<'de, Mismatch> for ValueDecoder {
    type Deserializer = ValueDecoder;

    fn into_deserializer(self) -> ValueDecoder {
        self
    }
}