tinystore 0.11.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
//! The query builder: every query of testdata/sql/queries.json, written as
//! the Bun SDK writes it, and tables over a real database.

use std::sync::{Arc, Mutex};
use std::time::{Duration, UNIX_EPOCH};

use serde::de::{Deserializer, MapAccess, Visitor};
use serde::ser::{SerializeMap, Serializer};
use serde::{Deserialize, Serialize};
use serde_json::Value as Json;

use super::values::Value;
use super::{Direction, Sql, Table, Upsert};
use crate::{ErrorKind, Options, Store, TestClock, sql};

/// A row as the vectors give one: its columns in their order.
#[derive(Clone, Debug, Default, PartialEq)]
struct Ordered(Vec<(String, Json)>);

impl Serialize for Ordered {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut map = serializer.serialize_map(Some(self.0.len()))?;
        for (name, value) in &self.0 {
            map.serialize_entry(name, value)?;
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for Ordered {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct Pairs;
        impl<'de> Visitor<'de> for Pairs {
            type Value = Ordered;
            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("a row")
            }
            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Ordered, A::Error> {
                let mut pairs = Vec::new();
                while let Some(pair) = map.next_entry::<String, Json>()? {
                    pairs.push(pair);
                }
                Ok(Ordered(pairs))
            }
        }
        deserializer.deserialize_map(Pairs)
    }
}

fn ordered(pairs: &Json) -> Ordered {
    Ordered(
        pairs.as_array().unwrap().iter().map(|pair| (pair[0].as_str().unwrap().to_owned(), pair[1].clone())).collect(),
    )
}

fn condition(given: &Json) -> Sql {
    let (kind, argument) = given.as_object().unwrap().iter().next().unwrap();
    match kind.as_str() {
        "equal" => {
            let mut names: Vec<&String> = argument.as_object().unwrap().keys().collect();
            names.sort();
            let pieces: Vec<Sql> = names.iter().map(|name| equal(name, &argument[name.as_str()])).collect();
            if pieces.len() == 1 { pieces.into_iter().next().unwrap() } else { sql::and(pieces) }
        }
        "sql" => {
            let parts = argument.as_array().unwrap();
            parts[1..].iter().fold(Sql::new(parts[0].as_str().unwrap()), |piece, value| piece.bind(value))
        }
        "or" => sql::or(argument.as_array().unwrap().iter().map(condition)),
        "and" => sql::and(argument.as_array().unwrap().iter().map(condition)),
        "has" => sql::has(argument[0].as_str().unwrap(), &argument[1]),
        other => panic!("no condition {other}"),
    }
}

fn equal(name: &str, value: &Json) -> Sql {
    match value.as_array() {
        Some(list) => sql::is_in(name, list),
        None => sql::eq(name, value),
    }
}

/// Equal values at the top of a query stand apart, as an object's do in the Bun SDK.
fn conditions(given: &Json) -> Vec<Sql> {
    match given.get("equal").and_then(Json::as_object) {
        Some(object) => {
            let mut names: Vec<&String> = object.keys().collect();
            names.sort();
            names.iter().map(|name| equal(name, &object[name.as_str()])).collect()
        }
        None => vec![condition(given)],
    }
}

fn on(given: &Json) -> Sql {
    given.as_str().map_or_else(|| condition(given), Sql::new)
}

type Rows<'r> = super::Query<'r, Ordered>;

fn apply<'r>(query: Rows<'r>, step: &Json) -> Rows<'r> {
    let (verb, argument) = step.as_object().unwrap().iter().next().unwrap();
    match verb.as_str() {
        "where" => conditions(argument).into_iter().fold(query, |query, piece| query.filter(piece)),
        "having" => conditions(argument).into_iter().fold(query, |query, piece| query.having(piece)),
        "select" => query.select(argument.as_str().unwrap()),
        "join" => query.join(argument[0].as_str().unwrap(), on(&argument[1])),
        "leftJoin" => query.left_join(argument[0].as_str().unwrap(), on(&argument[1])),
        "groupBy" => query.group_by(argument.as_array().unwrap().iter().map(|name| name.as_str().unwrap())),
        "orderBy" => {
            let direction = if argument[1] == "desc" { Direction::Desc } else { Direction::Asc };
            match argument[0].as_str() {
                Some(column) => query.order_by(column, direction),
                None => query.order_by_sql(condition(&argument[0]), direction),
            }
        }
        "limit" => query.limit(argument.as_u64().unwrap()),
        "offset" => query.offset(argument.as_u64().unwrap()),
        "include" => {
            let table = Table::<Ordered>::recorded(argument[1]["table"].as_str().unwrap(), Arc::default());
            let included = argument[1]["steps"].as_array().unwrap().iter().fold((*table).clone(), apply);
            query.include(argument[0].as_str().unwrap(), &included)
        }
        other => panic!("no step {other}"),
    }
}

fn kept(value: &Value) -> Json {
    match value {
        Value::Null => Json::Null,
        Value::Integer(n) => Json::from(*n),
        Value::Real(x) => Json::from(*x),
        Value::Text(text) => Json::from(text.as_str()),
        Value::Blob(bytes) => Json::from(bytes.clone()),
    }
}

/// An upsert as a vector's options give it: an absent `update` names none.
fn upsert_of(options: &Json) -> Upsert {
    let update = options.get("update").and_then(Json::as_array).cloned().unwrap_or_default();
    let mut asked = Upsert::on([options["conflict"].as_str().unwrap()])
        .update(update.iter().map(|name| name.as_str().unwrap().to_owned()));
    if let Some(only_if) = options.get("where") {
        asked = asked.only_if(condition(only_if));
    }
    asked
}

/// Runs the call a vector ends in, which leaves its statement with `last`.
fn ran(
    vector: &Json,
    table: &Table<'_, Ordered>,
    query: &Rows<'_>,
    last: &Arc<Mutex<Option<Sql>>>,
) -> crate::Result<()> {
    if let Some(sets) = vector.get("update") {
        let sets = sets.as_array().unwrap().iter().map(|pair| {
            let value = &pair[1];
            let piece = if value.get("sql").is_some() { condition(value) } else { sql::value(value) };
            (pair[0].as_str().unwrap().to_owned(), piece)
        });
        query.update(sets.collect::<Vec<_>>()).map(drop)
    } else if vector.get("delete").is_some() {
        query.delete().map(drop)
    } else if let Some(rows) = vector.get("insert") {
        let rows: Vec<Ordered> = rows.as_array().unwrap().iter().map(ordered).collect();
        table.insert_all(&rows).map(drop)
    } else if let Some(upsert) = vector.get("upsert") {
        table.upsert(&ordered(&upsert[0]), upsert_of(&upsert[1])).map(drop)
    } else if let Some(upserts) = vector.get("upserts") {
        let rows: Vec<Ordered> = upserts[0].as_array().unwrap().iter().map(ordered).collect();
        table.upsert_all(&rows, upsert_of(&upserts[1])).map(drop)
    } else if vector.get("count").is_some() {
        query.count().map(drop)
    } else if let Some(page) = vector.get("list") {
        query.list(page["limit"].as_u64().unwrap(), None).map(drop)
    } else {
        query.to_sql().map(|statement| *last.lock().unwrap() = Some(statement))
    }
}

// contract: SQL-10
#[test]
fn every_query_of_the_vectors_is_the_statement_every_sdk_writes() {
    let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../testdata/sql/queries.json");
    let vectors: Json = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
    for vector in vectors["queries"].as_array().unwrap() {
        let name = vector["name"].as_str().unwrap();
        let last = Arc::new(Mutex::new(None));
        let table = Table::<Ordered>::recorded(vector["table"].as_str().unwrap(), Arc::clone(&last));
        let steps = vector.get("steps").and_then(Json::as_array).cloned().unwrap_or_default();
        let query = steps.iter().fold((*table).clone(), apply);
        let statement = ran(vector, &table, &query, &last).map(|()| last.lock().unwrap().take().unwrap());
        if let Some(why) = vector.get("refused").and_then(Json::as_str) {
            let error = statement.unwrap_err();
            assert_eq!(error.kind(), ErrorKind::Invalid, "{name}: {error}");
            assert!(error.to_string().contains(why), "{name}: {error}");
            continue;
        }
        let statement = statement.unwrap();
        assert_eq!(statement.text(), vector["text"].as_str().unwrap(), "{name}");
        let values: Vec<Json> = statement.values().iter().map(kept).collect();
        assert_eq!(Json::from(values), vector["values"], "{name}");
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct Note {
    id: String,
    author_id: i64,
    title: String,
    done: bool,
    tags: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    views: Option<i64>,
}

fn note(id: &str, author_id: i64, title: &str) -> Note {
    Note { id: id.to_owned(), author_id, title: title.to_owned(), done: false, tags: Vec::new(), views: None }
}

struct Fixture {
    store: Store,
    // Last: fields drop in order, and Windows removes no file the store still holds.
    _dir: tempfile::TempDir,
}

fn fixture() -> Fixture {
    let dir = tempfile::tempdir().unwrap();
    let clock = Arc::new(TestClock::new(UNIX_EPOCH + Duration::from_secs(1_791_547_200)));
    let options = Options { clock: Some(clock), background: false, ..Options::default() };
    let store = Store::open(dir.path(), options).unwrap();
    Fixture { _dir: dir, store }
}

const NOTES: &str = "create table notes (
    id        text primary key,
    author_id integer not null,
    title     text not null,
    done      integer not null default 0 check (done in (0, 1)),
    tags      text not null default '[]' check (json_valid(tags)),
    views     integer not null default 0
) strict";

#[test]
fn a_table_inserts_rows_and_reads_them_back_as_its_type() {
    let f = fixture();
    let db = f.store.database("app").migrations([("0001_notes.sql", NOTES)]).open().unwrap();
    let notes = db.table::<Note>("notes");
    let first = Note { tags: vec!["home".to_owned()], ..note("n1", 5, "Buy milk") };
    assert_eq!(notes.insert(&first).unwrap(), Note { views: Some(0), ..first.clone() }, "the default filled");
    let more = notes.insert_all(&[note("n2", 5, "Call mom"), note("n3", 6, "Read")]).unwrap();
    assert_eq!(more.len(), 2);
    assert_eq!(notes.insert(&first).unwrap_err().kind(), ErrorKind::Conflict);

    assert_eq!(notes.filter(sql::eq("author_id", &5)).count().unwrap(), 2);
    let tagged = notes.filter(sql::has("tags", "home")).all().unwrap();
    assert_eq!(tagged.iter().map(|row| row.id.as_str()).collect::<Vec<_>>(), ["n1"]);
    let mine = notes.filter(sql::is_in("id", &["n1", "n3"])).order_by("id", Direction::Desc).all().unwrap();
    assert_eq!(mine.iter().map(|row| row.id.as_str()).collect::<Vec<_>>(), ["n3", "n1"]);
    let titles: Vec<String> = notes.select("title").order_by("title", Direction::Asc).limit(2).all().unwrap();
    assert_eq!(titles, ["Buy milk", "Call mom"]);
}

// contract: SQL-09
#[test]
fn an_update_or_a_delete_changes_what_its_condition_says_and_refuses_every_row() {
    let f = fixture();
    let db = f.store.database("app").migrations([("0001_notes.sql", NOTES)]).open().unwrap();
    let notes = db.table::<Note>("notes");
    notes.insert_all(&[note("n1", 5, "a"), note("n2", 5, "b")]).unwrap();

    let one = notes.filter(sql::eq("id", "n1"));
    let changed = one.update([("done", sql::value(&true)), ("views", sql!("views + 1"))]).unwrap();
    assert_eq!(changed.changes, 1);
    let read = one.one().unwrap().unwrap();
    assert_eq!((read.done, read.views), (true, Some(1)));

    for refused in [notes.delete(), notes.filter(sql::and(Vec::<Sql>::new())).delete()] {
        assert_eq!(refused.unwrap_err().kind(), ErrorKind::Invalid);
    }
    let limited = notes.filter(sql::eq("author_id", &5)).limit(1).delete().unwrap_err();
    assert_eq!(limited.kind(), ErrorKind::Invalid, "a limit SQLite would not keep: {limited}");
    assert_eq!(notes.count().unwrap(), 2);
    assert_eq!(notes.filter(sql::eq("done", &true)).delete().unwrap().changes, 1);
    assert_eq!(notes.count().unwrap(), 1);
    let short = notes.filter(sql!("id = ? and author_id = ?", "n2")).all().unwrap_err();
    assert!(short.to_string().contains("2 placeholders and 1 values"), "{short}");
}

// contract: SQL-10
#[test]
fn a_comment_at_the_end_of_a_piece_hides_nothing_the_builder_writes_after_it() {
    let f = fixture();
    let db = f.store.database("app").migrations([("0001_notes.sql", NOTES)]).open().unwrap();
    let notes = db.table::<Note>("notes");
    notes.insert_all(&[note("n1", 5, "a"), Note { done: true, ..note("n2", 5, "b") }, note("n3", 6, "c")]).unwrap();

    let ids = |rows: Vec<Note>| rows.into_iter().map(|row| row.id).collect::<Vec<_>>();
    let newest = notes.filter("author_id = 5 -- the first author").order_by("id", Direction::Desc).all();
    assert_eq!(ids(newest.unwrap()), ["n2", "n1"], "the order after the comment holds");
    let one = notes.filter("id = 'n1' -- the first note").update([("views", sql!("views + 1 -- one more"))]);
    assert_eq!(one.unwrap().changes, 1, "an update sets the rows its condition says, not every row");
    let done = notes.filter("author_id = 5 -- the first author").filter("done = 1").delete();
    assert_eq!(done.unwrap().changes, 1, "a delete keeps the condition after the comment");
    assert_eq!(ids(notes.order_by("id", Direction::Asc).all().unwrap()), ["n1", "n3"]);

    let open = notes.filter("done = 1 /* the done ones").all().unwrap_err();
    assert_eq!(open.kind(), ErrorKind::Invalid, "{open}");
    assert!(open.to_string().contains("ends inside a /* comment"), "{open}");
}

#[test]
fn an_upsert_sets_only_what_it_names_on_the_row_its_owner_holds() {
    let f = fixture();
    let db = f.store.database("app").migrations([("0001_notes.sql", NOTES)]).open().unwrap();
    let notes = db.table::<Note>("notes");
    let owners = |author: i64| Upsert::on(["id"]).update(["title"]).only_if(sql::eq("author_id", &author));
    assert_eq!(notes.upsert(&note("u1", 1, "mine"), owners(1)).unwrap().unwrap().title, "mine");
    let changed = notes.upsert(&Note { done: true, ..note("u1", 1, "still mine") }, owners(1)).unwrap().unwrap();
    assert_eq!((changed.title.as_str(), changed.done), ("still mine", false), "only the title it named");
    assert!(notes.upsert(&note("u1", 2, "stolen"), owners(2)).unwrap().is_none(), "another's row stays as it is");
    assert_eq!(notes.filter(sql::eq("id", "u1")).one().unwrap().unwrap().title, "still mine");
}

// contract: SQL-15
#[test]
fn an_upsert_of_rows_writes_every_row_or_none_in_one_statement() {
    let f = fixture();
    let db = f.store.database("app").migrations([("0001_notes.sql", NOTES)]).open().unwrap();
    let notes = db.table::<Note>("notes");
    let owners = |author: i64| Upsert::on(["id"]).update(["title"]).only_if(sql::eq("author_id", &author));
    notes.insert(&note("u1", 1, "mine")).unwrap();
    notes.insert(&note("u2", 2, "theirs")).unwrap();

    let rows = [note("u1", 1, "still mine"), note("u2", 1, "stolen"), note("u3", 1, "new")];
    let written = notes.upsert_all(&rows, owners(1)).unwrap();
    let titles: Vec<&str> = written.iter().map(|row| row.title.as_str()).collect();
    assert_eq!(titles, ["still mine", "new"], "every row it wrote, not the one whose owner kept it");
    assert_eq!(notes.filter(sql::eq("id", "u2")).one().unwrap().unwrap().title, "theirs");

    let broken = [note("u4", 1, "a"), Note { done: true, ..note("u5", 1, "b") }];
    let refuse_u5 =
        "create trigger no_u5 before insert on notes when new.id = 'u5' begin select raise(abort, 'no'); end";
    db.exec(refuse_u5).unwrap();
    assert_eq!(notes.upsert_all(&broken, owners(1)).unwrap_err().kind(), ErrorKind::Invalid);
    assert!(notes.filter(sql::eq("id", "u4")).one().unwrap().is_none(), "one statement: none of its rows");

    // a key twice: the rows go in order, so the second sets what the first wrote, held or not
    let twice = [note("u6", 1, "a"), note("u6", 1, "b")];
    assert_eq!(notes.upsert_all(&twice, owners(1)).unwrap().len(), 2);
    let again = [note("u6", 1, "c"), note("u6", 1, "d")];
    assert_eq!(notes.upsert_all(&again, owners(1)).unwrap().len(), 2);
    assert_eq!(notes.filter(sql::eq("id", "u6")).one().unwrap().unwrap().title, "d", "the last row's title stays");
    assert!(notes.upsert_all(&[], owners(1)).unwrap().is_empty(), "no row writes nothing");
    let unnamed = notes.upsert_all(&[], Upsert::on(["id"])).unwrap_err();
    assert!(unnamed.to_string().contains("the columns its update sets"), "{unnamed}");
}

#[test]
fn a_page_reads_after_the_last_row_of_the_one_before_and_only_its_own_query() {
    let f = fixture();
    let db = f.store.database("app").migrations([("0001_notes.sql", NOTES)]).open().unwrap();
    let notes = db.table::<Note>("notes");
    for n in 0..5 {
        notes.insert(&Note { views: Some(n / 2), ..note(&format!("p{n}"), 8, "x") }).unwrap();
    }
    let query =
        notes.filter(sql::eq("author_id", &8)).order_by("views", Direction::Desc).order_by("id", Direction::Desc);
    let first = query.list(2, None).unwrap();
    let second = query.list(2, first.next.as_deref()).unwrap();
    let third = query.list(2, second.next.as_deref()).unwrap();
    let ids: Vec<String> =
        [first.rows, second.rows, third.rows.clone()].concat().into_iter().map(|row| row.id).collect();
    assert_eq!(ids, ["p4", "p3", "p2", "p1", "p0"]);
    assert!(third.next.is_none());
    let other =
        notes.filter(sql::eq("author_id", &9)).order_by("views", Direction::Desc).order_by("id", Direction::Desc);
    assert_eq!(other.list(2, second.next.as_deref()).unwrap_err().kind(), ErrorKind::Invalid);
    // a cursor of this query with one order value of two is anyone's forgery
    let next = first.next.unwrap();
    let bytes: Vec<u8> =
        (0..next.len()).step_by(2).map(|at| u8::from_str_radix(&next[at..at + 2], 16).unwrap()).collect();
    let mut read: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    read["v"].as_array_mut().unwrap().truncate(1);
    let forged: String = serde_json::to_vec(&read).unwrap().iter().map(|byte| format!("{byte:02x}")).collect();
    assert_eq!(query.list(2, Some(&forged)).unwrap_err().kind(), ErrorKind::Invalid);
}

// contract: SQL-09
#[test]
fn a_page_refuses_a_limit_or_an_offset_its_list_would_drop() {
    let f = fixture();
    let db = f.store.database("app").migrations([("0001_notes.sql", NOTES)]).open().unwrap();
    let notes = db.table::<Note>("notes");
    for n in 0..3 {
        notes.insert(&note(&format!("p{n}"), 8, "x")).unwrap();
    }
    let by_id = notes.order_by("id", Direction::Asc);
    for query in [by_id.limit(1), by_id.offset(1), by_id.limit(1).offset(1)] {
        let error = query.list(2, None).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::Invalid, "{error}");
        assert!(error.to_string().contains("takes its own limit"), "{error}");
    }
    assert_eq!(by_id.list(2, None).unwrap().rows.len(), 2, "without them a page reads its own limit");
}

#[test]
fn pages_read_on_past_a_null_and_an_infinity_in_their_order() {
    let f = fixture();
    let orders = "create table orders (id integer primary key, shipped_at integer, total real)";
    let db = f.store.database("shop").migrations([("0001_orders.sql", orders)]).open().unwrap();
    db.batch([
        sql!("insert into orders values (1, null, 1.0), (2, null, ?), (3, null, ?)", f64::INFINITY, f64::NEG_INFINITY),
        sql!("insert into orders values (4, 10, 2.0), (5, 20, ?)", f64::INFINITY),
    ])
    .unwrap();
    #[derive(Debug, Deserialize)]
    struct Order {
        id: i64,
    }
    let orders = db.table::<Order>("orders");
    let paged = |query: super::Query<'_, Order>| {
        let mut ids = Vec::new();
        let mut after = None;
        loop {
            let page = query.list(2, after.as_deref()).unwrap();
            ids.extend(page.rows.iter().map(|order| order.id));
            match page.next {
                Some(next) => after = Some(next),
                None => return ids,
            }
        }
    };
    let ascending = orders.order_by("shipped_at", Direction::Asc).order_by("id", Direction::Asc);
    assert_eq!(paged(ascending), [1, 2, 3, 4, 5], "a page that ends among the nulls, first in ascending order");
    let descending = orders.order_by("shipped_at", Direction::Desc).order_by("id", Direction::Desc);
    assert_eq!(paged(descending), [5, 4, 3, 2, 1], "the nulls last in descending order");
    let by_total = orders.order_by("total", Direction::Asc).order_by("id", Direction::Asc);
    assert_eq!(paged(by_total), [3, 1, 4, 2, 5], "a page that ends on an infinity");
}

#[test]
fn a_join_reads_its_first_table_and_a_table_inside_a_transaction_rolls_back_with_it() {
    let f = fixture();
    let books = "create table authors (id integer primary key, name text not null, active integer not null) strict;
        create table books (id integer primary key, author_id integer not null, title text not null) strict;";
    let db = f.store.database("library").migrations([("0001_books.sql", books)]).open().unwrap();
    db.batch([
        "insert into authors (id, name, active) values (1, 'Le Guin', 1), (2, 'Lem', 0)",
        "insert into books (id, author_id, title) values (1, 1, 'The Dispossessed'), (2, 2, 'Solaris')",
    ])
    .unwrap();
    #[derive(Debug, PartialEq, Deserialize)]
    struct Book {
        id: i64,
        title: String,
    }
    let read =
        db.table::<Book>("books as b").join("authors as a", "a.id = b.author_id").filter(sql::eq("a.active", &1)).all();
    assert_eq!(read.unwrap(), [Book { id: 1, title: "The Dispossessed".to_owned() }]);
    assert!(!db.table::<Book>("books").filter(sql::eq("author_id", &1)).explain().unwrap().is_empty());

    let refused = db.tx(|tx| -> crate::Result<()> {
        tx.exec("insert into books (id, author_id, title) values (3, 1, 'Lathe')")?;
        assert_eq!(tx.table::<Book>("books").count()?, 3, "the transaction's table sees its write");
        Err(crate::Error::invalid("changed my mind"))
    });
    assert!(refused.is_err());
    assert_eq!(db.table::<Book>("books").count().unwrap(), 2, "rolled back");
}

const AUTHORS: &str = "create table authors (id integer primary key, name text not null) strict;
create table posts (
    id        integer primary key,
    author_id integer not null references authors (id),
    title     text not null,
    score     real not null,
    raw       blob,
    done      integer not null default 0 check (done in (0, 1))
) strict";

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct Post {
    id: i64,
    title: String,
    score: f64,
    raw: Option<Vec<u8>>,
    done: bool,
}

#[derive(Debug, PartialEq, Deserialize)]
struct Author {
    id: i64,
    name: String,
    posts: Vec<Post>,
}

/// An integer a float cannot hold.
const WIDE: i64 = (1 << 60) + 1;

fn authors_and_posts(db: &super::Database) -> Vec<Post> {
    db.exec(sql!("insert into authors (id, name) values (1, 'Ann'), (2, 'Bob'), (3, 'Cy')")).unwrap();
    let posts = vec![
        Post { id: 1, title: "first".to_owned(), score: 1.0, raw: None, done: false },
        Post {
            id: 2,
            title: "it's, (odd)\0 text".to_owned(),
            score: 0.1 + 0.2,
            raw: Some(vec![0, 255, 39]),
            done: true,
        },
        Post { id: WIDE, title: String::new(), score: 1e308, raw: None, done: false },
        Post { id: 4, title: "Bob's".to_owned(), score: -2.5, raw: None, done: false },
    ];
    for (post, author) in posts.iter().zip([1, 1, 1, 2]) {
        let insert = "insert into posts (id, author_id, title, score, raw, done) values (?, ?, ?, ?, ?, ?)";
        db.exec(sql!(insert, post.id, author, &post.title, post.score, &post.raw, post.done)).unwrap();
    }
    posts
}

#[test]
fn an_included_query_gives_each_row_its_rows_every_value_as_it_is_kept() {
    let f = fixture();
    let db = f.store.database("app").migrations([("0001_authors.sql", AUTHORS)]).open().unwrap();
    let posts = authors_and_posts(&db);
    let latest = db
        .table::<Post>("posts as p")
        .select::<Post>("p.id, p.title, p.score, p.raw, p.done")
        .filter("p.author_id = a.id")
        .order_by("p.id", Direction::Desc)
        .limit(2);
    let authors = db.table::<Author>("authors as a").include("posts", &latest).order_by("a.id", Direction::Asc);

    let read = authors.all().unwrap();
    assert_eq!(read.iter().map(|author| author.name.as_str()).collect::<Vec<_>>(), ["Ann", "Bob", "Cy"]);
    assert_eq!(read[0].posts, [posts[2].clone(), posts[1].clone()], "the two latest, each value as it is kept");
    assert_eq!(read[1].posts, [posts[3].clone()]);
    assert!(read[2].posts.is_empty(), "a row with none has an empty list");

    let bob = authors.filter(sql::eq("a.id", &2)).one().unwrap().unwrap();
    assert_eq!((bob.id, bob.posts.len()), (2, 1));
    assert_eq!(authors.count().unwrap(), 3, "a count reads no included rows");
    let inside = db.tx(|tx| tx.table::<Author>("authors as a").include("posts", &latest).all()).unwrap();
    assert_eq!(inside.len(), 3);
}

#[test]
fn an_included_query_names_its_columns_and_its_limit_and_includes_nothing() {
    let f = fixture();
    let db = f.store.database("app").migrations([("0001_authors.sql", AUTHORS)]).open().unwrap();
    let posts = db.table::<Post>("posts as p").filter("p.author_id = a.id");
    let named = posts.select::<Post>("p.id, p.title");
    let authors = db.table::<Author>("authors as a");
    let refused = [
        (authors.include("posts", &posts.limit(2)), "names its columns"),
        (authors.include("posts", &named), "needs a limit"),
        (authors.include("posts", &named.limit(2).include("more", &named.limit(1))), "includes nothing itself"),
        (authors.include("posts", &named.limit(2)).include("posts", &named.limit(2)), "a name of its own"),
        (authors.include("posts", &posts.select::<Post>("p.id, upper(p.title)").limit(2)), "upper(p.title)"),
    ];
    for (query, why) in refused {
        let error = query.all().unwrap_err();
        assert_eq!(error.kind(), ErrorKind::Invalid, "{error}");
        assert!(error.to_string().contains(why), "{error}");
    }
}