qua 0.75.0

Structure-aware query CLI for the Quarb engine
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
//! A pushed plan answers as the scan does. Quarb compares by value
//! (numeric-looking text meets a number as a number); SQLite by the
//! column's type, so a comparison pushes only where the catalog
//! says the two agree, and the query scans otherwise.

use std::path::{Path, PathBuf};

fn fixture(tag: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("quarb-pushdown-{}-{tag}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let db = rusqlite::Connection::open(dir.join("lib.db")).unwrap();
    db.execute_batch(
        "CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT, code TEXT, born INTEGER);
         INSERT INTO authors VALUES
           (1, 'Homer', '150', -800), (2, 'Austen', '150.0', 1775),
           (3, 'Twain', ' 150', 1835), (4, 'Dante', '151', 1265),
           (5, 'Herodotus', 'abc', 0);
         CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT, pages);
         INSERT INTO books VALUES
           (1, 'Iliad', 300), (2, 'Emma', '300'), (3, 'Tom Sawyer', 300.0),
           (4, 'La divina commedia', 3000);",
    )
    .unwrap();
    dir
}

/// stdout, and what `--diagnostics=info` said on stderr.
fn qua(dir: &Path, query: &str) -> (String, String) {
    let out = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
        .env("QUARB_LOCALE", "C")
        .current_dir(dir)
        .args(["--diagnostics=info", query, "lib.db"])
        .stdin(std::process::Stdio::null())
        .output()
        .unwrap();
    let err = String::from_utf8_lossy(&out.stderr).to_string();
    assert!(out.status.success(), "{query}: {err}");
    (
        String::from_utf8(out.stdout).unwrap().trim().to_string(),
        err,
    )
}

#[test]
fn a_typed_column_pushes() {
    let dir = fixture("typed");
    let (out, err) = qua(&dir, "/authors/*[::born > 1700]::name");
    assert_eq!(out, "Austen\nTwain");
    assert!(
        err.contains("pushdown: SELECT name FROM authors WHERE born > 1700"),
        "{err}"
    );
    let (out, err) = qua(&dir, "/authors/*[::name = 'Homer']::born");
    assert_eq!(out, "-800");
    assert!(
        err.contains("pushdown: SELECT born FROM authors WHERE name = 'Homer'"),
        "{err}"
    );
}

#[test]
fn a_comparison_the_types_would_change_scans() {
    let dir = fixture("loose");
    // a number against a TEXT column: the scan reads every
    // numeric-looking cell as its number; SQLite's `code = 150`
    // would keep '150' alone
    let (out, err) = qua(&dir, "/authors/*[::code = 150]::name");
    assert_eq!(out, "Homer\nAusten\nTwain");
    assert!(
        err.contains("info TYPE_NOT_PUSHED (query): the comparison on code would"),
        "{err}"
    );
    assert!(
        err.contains("info TYPE_NOT_PUSHED (prefilter): the comparison on code"),
        "{err}"
    );
    // an untyped column holding 300, '300' and 300.0
    let (out, err) = qua(&dir, "/books/*[::pages = 300] @| count");
    assert_eq!(out, "3");
    assert!(err.contains("info TYPE_NOT_PUSHED (query): "), "{err}");
    // numeric-looking text against anything: two texts are two
    // texts to the scan (the user's ruling of 2026-11-29), so the
    // answer is the one cell so spelled; the plan is still refused,
    // for a column that holds numbers reads the literal as one
    let (out, err) = qua(&dir, "/authors/*[::code = '150']::name");
    assert_eq!(out, "Homer");
    assert!(
        err.contains(
            "info TYPE_NOT_PUSHED (query): a numeric-looking text literal compares \
             numerically in Quarb (value coercion); SQL compares it as text; scanning"
        ),
        "{err}"
    );
    // a literal of a kind a database compares its own way, named
    // with its article
    let (_, err) = qua(&dir, "/authors/*[::born = 2017-01-07T00:00:00Z] @| count");
    assert!(
        err.contains(
            "info TYPE_NOT_PUSHED (query): an instant literal against a column (a database \
             compares it its own way); scanning"
        ),
        "{err}"
    );
    let (_, err) = qua(&dir, "/authors/*[::born = true] @| count");
    assert!(
        err.contains("info TYPE_NOT_PUSHED (query): a bool literal against a column"),
        "{err}"
    );
    // text against a numeric column; the unmet column alone is named
    let (out, err) = qua(&dir, "/authors/*[::born > 1700 && ::code = 150]::name");
    assert_eq!(out, "Austen\nTwain");
    assert!(err.contains("the comparison on code would"), "{err}");
    let (out, err) = qua(&dir, "/authors/*[::born = 'abc'] @| count");
    assert_eq!(out, "0");
    assert!(err.contains("info TYPE_NOT_PUSHED (query): "), "{err}");
    // a numeric reducer over a text column: SQL would sum the
    // leading digits and order by collation; the scan reads values
    let (_, err) = qua(&dir, "/authors/* | ::name @| max");
    assert!(err.contains("the reducer on name would"), "{err}");
    let (out, err) = qua(&dir, "/authors/* | ::born @| sum");
    assert!(err.contains("pushdown: SELECT SUM(born)"), "{err}");
    assert!(!out.is_empty());
}

/// A JSON path under a column pushes down only as the scan grafts:
/// a TEXT column holding JSON text is a leaf on both roads (no
/// rows), a column declared JSON grafts on both, and `<json>` on
/// the step declares the graft on both whatever the column's type.
#[test]
fn a_json_path_pushes_only_as_declared() {
    let dir = fixture("json-declared");
    let db = rusqlite::Connection::open(dir.join("lib.db")).unwrap();
    db.execute_batch(
        "CREATE TABLE jrows (id INTEGER PRIMARY KEY, j TEXT);
         INSERT INTO jrows VALUES
           (1, '{\"tag\":\"gold\"}'), (2, '{\"tag\":\"lead\"}'), (3, '{\"tag\":\"gold\"}');
         CREATE TABLE t (id INTEGER PRIMARY KEY, doc JSON);
         INSERT INTO t VALUES (1, '{\"tag\":\"gold\"}'), (2, '{\"tag\":\"lead\"}');",
    )
    .unwrap();
    let scan = |q: &str| {
        let out = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
            .env("QUARB_LOCALE", "C")
            .current_dir(&dir)
            .args(["--no-pushdown", q, "lib.db"])
            .stdin(std::process::Stdio::null())
            .output()
            .unwrap();
        String::from_utf8(out.stdout).unwrap().trim().to_string()
    };
    // TEXT, undeclared: the leaf is a leaf on both roads.
    let q = "/jrows/*[/j/tag:: = \"gold\"]::id";
    let (out, err) = qua(&dir, q);
    assert_eq!(out, "");
    assert_eq!(scan(q), "");
    assert!(
        !err.contains("json_extract") || err.contains("scann"),
        "{err}"
    );
    // Declared JSON: both roads graft and agree.
    let q = "/t/*[/doc/tag:: = \"gold\"]::id";
    let (out, err) = qua(&dir, q);
    assert_eq!(out, "1");
    assert_eq!(scan(q), "1");
    assert!(err.contains("json_extract"), "{err}");
    // `<json>` on the step declares the graft on both roads.
    let q = "/jrows/*[/j<json>/tag:: = \"gold\"]::id";
    let (out, _) = qua(&dir, q);
    assert_eq!(out, "1\n3");
    assert_eq!(scan(q), "1\n3");
}

/// The property form of a JSON path, `[/col/a::b OP v]`, answers
/// pushed as it answers scanned, over every shape a value takes. It
/// is not the child form's question: an array of scalars is a list
/// (any item matches), and `!=` keeps a row whose key is absent.
/// And the child form's whole push no longer takes an array or an
/// object for the text literal that spells it.
#[test]
fn a_json_property_pushes_as_the_scan_answers() {
    let dir = fixture("json-property");
    let db = rusqlite::Connection::open(dir.join("lib.db")).unwrap();
    db.execute_batch(
        r#"CREATE TABLE orders (id INTEGER PRIMARY KEY, data JSON);
           INSERT INTO orders VALUES
             (1, '{"a":[1,2]}'), (2, '{"a":"[1,2]"}'), (3, '{"a":"x"}'),
             (4, '{"a":{"k":1}}'), (5, '{"a":"{\"k\":1}"}'), (6, '{"a":["x","y"]}'),
             (7, '{"a":["x",{"k":1}]}'), (8, '{}'), (9, '{"a":null}'), (10, '{"a":[]}'),
             (11, '{"a":7}'), (12, '{"a":"7"}'), (13, '{"a":true}'), (14, '{"a":["7"]}'),
             (15, '{"b":{"a":"x"}}'), (16, '{"a":[null,"x"]}'), (17, 'not json'),
             (18, '["x"]');
           CREATE TABLE named (id INTEGER PRIMARY KEY, value JSON);
           INSERT INTO named VALUES (1, '{"a":"x"}'), (2, '{"a":["x"]}'), (3, '{"a":"y"}');
           CREATE TABLE plain (id INTEGER PRIMARY KEY, j TEXT);
           INSERT INTO plain VALUES (1, '{"a":"x"}'), (2, '{"a":["x"]}'), (3, '{"a":"y"}');"#,
    )
    .unwrap();
    let scan = |q: &str| {
        let out = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
            .env("QUARB_LOCALE", "C")
            .current_dir(&dir)
            .args(["--no-pushdown", q, "lib.db"])
            .stdin(std::process::Stdio::null())
            .output()
            .unwrap();
        String::from_utf8(out.stdout)
            .unwrap()
            .trim()
            .replace('\n', " ")
    };
    let pushed = |q: &str| {
        let (out, err) = qua(&dir, q);
        (out.replace('\n', " "), err)
    };
    // what each answers, and that the two roads agree
    for (q, answer) in [
        ("/orders/*[/data::a = 'x']::id", "3 6 16"),
        ("/orders/*['x' = /data::a]::id", "3 6 16"),
        ("/orders/*[/data::a = '[1,2]']::id", "2"),
        // row 16's array is `[null, "x"]`: its null item compares
        // false, as every comparison of a null item does (spec, A
        // list operand), and its other item is 'x'. The predicate
        // took the null by the scalar rule, unequal to everything,
        // and kept the row (the review of 2026-11-23).
        (
            "/orders/*[/data::a != 'x']::id",
            "1 2 4 5 6 7 8 9 11 12 13 14 15 17 18",
        ),
        ("/orders/*[/data::a > 6]::id", "11 12 14"),
        ("/orders/*[/data::a = 7]::id", "11 12 14"),
        ("/orders/*[/data::a = '7']::id", "11 12 14"),
        ("/orders/*[/data::a < 'y']::id", "2 3 6 12 14 16"),
        ("/orders/*[/data::a]::id", "1 2 3 5 6 11 12 13 14 16"),
        ("/orders/*[/data/b::a = 'x']::id", "15"),
        ("/orders/*[/data/b::a != 'q']::id", "15"),
        ("/orders/*[/data::a = 'x'] @| count", "3"),
        // the child form, beside it: an array has no value
        ("/orders/*[/data/a:: = 'x']::id", "3"),
        ("/orders/*[/data/a:: = '[1,2]']::id", "2"),
        ("/orders/*[/data/a:: = '{\"k\":1}']::id", "5"),
        // a column of one of json_each's own names
        ("/named/*[/value::a = 'x']::id", "1 2"),
        // a TEXT column is a leaf on both roads, and a graft where
        // the step declares it
        ("/plain/*[/j::a = 'x']::id", ""),
        ("/plain/*[/j<json>::a = 'x']::id", "1 2"),
    ] {
        let (out, _) = pushed(q);
        assert_eq!(out, answer, "{q}");
        assert_eq!(scan(q), answer, "{q} (scanned)");
    }
    // the string equality is pushed whole, its array branch with it
    let (_, err) = pushed("/orders/*[/data::a = 'x']::id");
    assert!(
        err.contains("PUSHED (query)") && err.contains("json_each(data, '$.a')"),
        "{err}"
    );
    // a comparison narrows, the arrays let through
    let (_, err) = pushed("/orders/*[/data::a > 6]::id");
    assert!(
        err.contains("PUSHED (prefilter)") && err.contains("IN ('text', 'array')"),
        "{err}"
    );
    // the container-looking literal narrows too; it was pushed whole
    let (_, err) = pushed("/orders/*[/data/a:: = '[1,2]']::id");
    assert!(err.contains("PUSHED (prefilter)"), "{err}");
}

/// Under `?graft=json2` (ruling 2026-11-17) a JSON scalar is a
/// property of its container and no child node: the child form
/// `/col/key::` answers nothing on the scan, so its whole plan is
/// not used (pushed, it would answer by the default reading's
/// spelling); the property form `/col::key` answers the same on
/// both roads and stays pushed.
#[test]
fn the_property_reading_keeps_a_child_form_plan_off() {
    let dir = fixture("json2-graft");
    let db = rusqlite::Connection::open(dir.join("lib.db")).unwrap();
    db.execute_batch(
        "CREATE TABLE t (id INTEGER PRIMARY KEY, doc JSON);
         INSERT INTO t VALUES (1, '{\"tag\":\"gold\"}'), (2, '{\"tag\":\"lead\"}');",
    )
    .unwrap();
    let run = |flags: &[&str], q: &str, target: &str| {
        let out = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
            .env("QUARB_LOCALE", "C")
            .current_dir(&dir)
            .args(flags)
            .args([q, target])
            .stdin(std::process::Stdio::null())
            .output()
            .unwrap();
        let err = String::from_utf8_lossy(&out.stderr).to_string();
        assert!(out.status.success(), "{q} on {target}: {err}");
        (
            String::from_utf8(out.stdout).unwrap().trim().to_string(),
            err,
        )
    };
    let info = ["--diagnostics=info"];
    let scan = ["--no-pushdown"];
    let child = "/t/*[/doc/tag:: = \"gold\"]::id";
    let property = "/t/*[/doc::tag = \"gold\"]::id";

    // the default reading: both spellings answer, both pushed
    assert_eq!(run(&info, child, "lib.db").0, "1");
    assert_eq!(run(&info, property, "lib.db").0, "1");

    // json2: the child form is empty on both roads, its plan unused
    let (out, err) = run(&info, child, "lib.db?graft=json2");
    assert_eq!(out, "");
    assert_eq!(run(&scan, child, "lib.db?graft=json2").0, "");
    assert!(
        err.contains("under ?graft=json2 a scalar is a property"),
        "{err}"
    );
    // json2: the property form answers, pushed and scanned alike
    let (out, err) = run(&info, property, "lib.db?graft=json2");
    assert_eq!(out, "1");
    assert_eq!(run(&scan, property, "lib.db?graft=json2").0, "1");
    assert!(err.contains("PUSHED (query)"), "{err}");
    // the cell itself, read through the mount's choice
    assert_eq!(run(&scan, "/t/1/doc::tag", "lib.db?graft=json2").0, "gold");
    assert_eq!(
        run(&scan, "/t/1/doc/* @| count", "lib.db?graft=json2").0,
        "0"
    );
    assert_eq!(run(&scan, "/t/1/doc/* @| count", "lib.db").0, "1");

    // a word that names no property reading is refused at the open
    let out = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
        .current_dir(&dir)
        .args(["/t/1/doc::tag", "lib.db?graft=json3"])
        .stdin(std::process::Stdio::null())
        .output()
        .unwrap();
    assert!(!out.status.success());
    let err = String::from_utf8_lossy(&out.stderr).to_string();
    assert!(
        err.contains("\"json3\" names no reading a graft takes (one of json2, yaml2, toml2)"),
        "{err}"
    );
}

/// A reducer after a glued projection (`/loans/*::days @| max`) is
/// pushed as the piped spelling is (`/loans/* | ::days @| max`), and
/// both answer as the scan does, over a column that holds a NULL.
/// The glued spelling was refused as a reducer "over row nodes".
#[test]
fn a_reducer_after_a_glued_projection_is_pushed() {
    let dir = fixture("glued-reducer");
    let db = rusqlite::Connection::open(dir.join("lib.db")).unwrap();
    db.execute_batch(
        "CREATE TABLE loans (id INTEGER PRIMARY KEY, book_id INTEGER, days INTEGER);
         INSERT INTO loans VALUES (1, 3, 14), (2, 7, 21), (3, 3, NULL), (4, 1, 7), (5, 7, 21);",
    )
    .unwrap();
    let scan = |q: &str| {
        let out = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
            .env("QUARB_LOCALE", "C")
            .current_dir(&dir)
            .args(["--no-pushdown", q, "lib.db"])
            .stdin(std::process::Stdio::null())
            .output()
            .unwrap();
        String::from_utf8(out.stdout).unwrap().trim().to_string()
    };
    for (reducer, sql) in [
        ("sum", "SELECT SUM(days) FROM loans"),
        ("mean", "SELECT AVG(days) FROM loans"),
        ("min", "SELECT MIN(days) FROM loans"),
        ("max", "SELECT MAX(days) FROM loans"),
        ("count", "SELECT COUNT(*) FROM loans"),
    ] {
        let glued = format!("/loans/*::days @| {reducer}");
        let piped = format!("/loans/* | ::days @| {reducer}");
        let (out, err) = qua(&dir, &glued);
        assert!(err.contains(&format!("pushdown: {sql}")), "{glued}: {err}");
        assert_eq!(out, scan(&glued), "{glued}");
        assert_eq!(out, qua(&dir, &piped).0, "{glued}");
        assert_eq!(out, scan(&piped), "{piped}");
    }
    // a condition before the projection goes with it
    let q = "/loans/*[::book_id = 7]::days @| max";
    let (out, err) = qua(&dir, q);
    assert!(
        err.contains("pushdown: SELECT MAX(days) FROM loans WHERE"),
        "{err}"
    );
    assert_eq!(out, "21");
    assert_eq!(out, scan(q));
}

/// A bare projection read on a thread whose topic is null reads
/// nothing (spec: Projectors, "a read on a null topic later in a
/// pipeline is null"), and the statement says so row by row. It read
/// the column on every row: `/items/*::grp | ::name` answered the name
/// of a row whose grp is NULL, and a pushed sum counted the rows the
/// scan leaves out. Found by the re-run of the review's reproductions
/// (2026-11-24). A reducer over such a read is the scan's.
#[test]
fn a_read_after_a_null_value_is_null_in_the_statement_too() {
    let dir = fixture("null-topic");
    let db = rusqlite::Connection::open(dir.join("lib.db")).unwrap();
    db.execute_batch(
        "CREATE TABLE items (id INTEGER PRIMARY KEY, grp TEXT, qty INTEGER, name TEXT);
         INSERT INTO items VALUES
           (1, 'a', 10, 'Iliad'), (2, 'b', NULL, 'Odyssey'), (3, NULL, 5, 'Emma'),
           (4, 'a', 7, 'Hamlet');",
    )
    .unwrap();
    drop(db);
    let scan = |query: &str| {
        let out = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
            .env("QUARB_LOCALE", "C")
            .current_dir(&dir)
            .args(["--no-pushdown", query, "lib.db"])
            .stdin(std::process::Stdio::null())
            .output()
            .unwrap();
        String::from_utf8(out.stdout).unwrap().trim().to_string()
    };
    // the glued projection and the piped one, a chain of three
    for (query, sql, answer) in [
        (
            "/items/*::grp | ::name",
            "SELECT CASE WHEN grp IS NULL THEN NULL ELSE name END FROM items",
            "Iliad\nOdyssey\nnull\nHamlet",
        ),
        (
            "/items/* | ::qty | ::name",
            "SELECT CASE WHEN qty IS NULL THEN NULL ELSE name END FROM items",
            "Iliad\nnull\nEmma\nHamlet",
        ),
        (
            "/items/*::grp | ::qty | ::name",
            "SELECT CASE WHEN CASE WHEN grp IS NULL THEN NULL ELSE qty END IS NULL THEN NULL \
             ELSE name END FROM items",
            "Iliad\nnull\nnull\nHamlet",
        ),
    ] {
        let (out, err) = qua(&dir, query);
        assert_eq!(out, answer, "{query}");
        assert_eq!(out, scan(query), "{query}");
        assert!(err.contains(&format!("pushdown: {sql}")), "{query}: {err}");
    }
    // an expression around the projection reads the node, a record is
    // never null, and after a push the read is the node's: as before
    for (query, sql) in [
        ("/items/*::grp | ::qty + 1", "SELECT (qty + 1) FROM items"),
        (
            "/items/*::grp | %(n = ::name) | ::qty",
            "SELECT qty FROM items",
        ),
        (
            "/items/*::grp | .g(::qty) | ::name",
            "SELECT name FROM items",
        ),
    ] {
        let (out, err) = qua(&dir, query);
        assert_eq!(out, scan(query), "{query}");
        assert!(err.contains(&format!("pushdown: {sql}")), "{query}: {err}");
    }
    // a reducer over such a read is the scan's: 17, where the
    // statement summed 22
    let (out, err) = qua(&dir, "/items/*::grp | ::qty @| sum");
    assert_eq!(out, "17");
    assert!(
        err.contains(
            "info REDUCER_NOT_PUSHED (query): 'sum' over a read that is null where the value \
             before it is ('| ::a | ::b': reduce the read alone, '| ::b @| sum'); scanning"
        ),
        "{err}"
    );
    // the count of the threads takes no value, and pushes
    let (out, err) = qua(&dir, "/items/*::grp | ::name @| count");
    assert_eq!(out, "4");
    assert!(
        err.contains("pushdown: SELECT COUNT(*) FROM items"),
        "{err}"
    );
}

/// SQLite has no nan: its SUM of +inf and -inf is NULL, where the
/// engine's sum is nan. A sum or a mean that comes back NULL is
/// asked of the scan, and the note says so; NULL is SQLite's answer
/// for no number at all too, which the scan answers null. Found by
/// the re-run of the review's reproductions (2026-11-24): the pushed
/// sum printed null for nan.
#[test]
fn a_sum_sqlite_answers_null_is_the_scans() {
    let dir = fixture("inf");
    let db = rusqlite::Connection::open(dir.join("lib.db")).unwrap();
    db.execute_batch(
        "CREATE TABLE heights (id INTEGER PRIMARY KEY, m REAL);
         INSERT INTO heights VALUES (1, 9e999), (2, -9e999), (3, 0.5);
         CREATE TABLE depths (id INTEGER PRIMARY KEY, m REAL);
         INSERT INTO depths VALUES (1, 1.5), (2, 2.5);",
    )
    .unwrap();
    drop(db);
    let note = "info STATEMENT_NOT_PUSHED (query): the plan's answer was not taken (a sum came \
                back NULL, which is SQLite's answer for no number and for the sum of +inf and \
                -inf alike); scanning";
    for (query, answer) in [
        ("/heights/*::m @| sum", "nan"),
        ("/heights/*::m @| mean", "nan"),
        ("/depths/*[::id > 9]::m @| sum", "null"),
    ] {
        let (out, err) = qua(&dir, query);
        assert_eq!(out, answer, "{query}");
        assert!(err.contains(note), "{query}: {err}");
    }
    // a sum of numbers is the statement's, as before
    let (out, err) = qua(&dir, "/depths/*::m @| sum");
    assert_eq!(out, "4.0");
    assert!(err.contains("pushdown: SELECT SUM(m) FROM depths"), "{err}");
}

/// A text literal that writes a quantity is a text, to the engine as
/// to the database, and is pushed as written (the user's ruling of
/// 2026-11-29: two texts compare as texts). For a day it was refused
/// to the plan (lang's finding of 2026-11-28), when two texts that
/// both wrote a span compared as the spans and the scan kept `60min`
/// beside `1h`.
#[test]
fn a_text_literal_that_writes_a_quantity_is_pushed_as_a_text() {
    let dir = fixture("quantity");
    let db = rusqlite::Connection::open(dir.join("days.db")).unwrap();
    db.execute_batch(
        "CREATE TABLE d (id INTEGER PRIMARY KEY, day TEXT, span TEXT);
         INSERT INTO d VALUES (1, '2026-01-01', '1h'),
           (2, '2026-01-01T00:00:00Z', '60min'), (3, '2026-01-02', '90min');",
    )
    .unwrap();
    drop(db);
    let run = |query: &str| -> (String, String) {
        let out = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
            .env("QUARB_LOCALE", "C")
            .current_dir(&dir)
            .args(["--diagnostics=info", query, "days.db"])
            .stdin(std::process::Stdio::null())
            .output()
            .unwrap();
        let err = String::from_utf8_lossy(&out.stderr).to_string();
        assert!(out.status.success(), "{query}: {err}");
        (
            String::from_utf8(out.stdout).unwrap().trim().to_string(),
            err,
        )
    };
    let (out, err) = run("/d/*[::span = \"1h\"]::id");
    assert_eq!(out, "1");
    assert!(
        err.contains("pushdown: SELECT id FROM d WHERE span = '1h'"),
        "{err}"
    );
    // beside a span the query writes the column is read, by the scan
    let (out, _) = run("/d/*[::span = 1_h]::id");
    assert_eq!(out, "1\n2");
    // a text that writes a date is a text to both, and is pushed
    let (out, err) = run("/d/*[::day = \"2026-01-01\"]::id");
    assert_eq!(out, "1");
    assert!(
        err.contains("pushdown: SELECT id FROM d WHERE day = '2026-01-01'"),
        "{err}"
    );
}