quarb-sql 0.68.0

SQL importer for the Quarb query engine
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
//! Translation assertions, plus the differential rig: the SQL runs
//! through SQLite and the translated Quarb through the engine over
//! the same database — the outputs must agree.

use quarb_sql::translate;
use rusqlite::Connection;

fn t(sql: &str) -> String {
    translate(sql).unwrap().query
}

#[test]
fn translations() {
    assert_eq!(
        t("SELECT title, price FROM tracks WHERE price < 1 ORDER BY title"),
        "/tracks/*[::price < 1] @| sort_by(::title) | %(::title; ::price)"
    );
    assert_eq!(t("SELECT COUNT(*) FROM tracks"), "/tracks/* @| count");
    assert_eq!(
        t("SELECT customer, SUM(qty) AS total FROM invoices GROUP BY customer HAVING total > 1"),
        "/invoices/* | .customer(::customer) | ::qty @|{.customer} sum | .total | [$_ > 1] | %."
    );
    assert_eq!(
        t(
            "SELECT al.title, t.title FROM albums al JOIN tracks t ON t.album_id = al.id \
           WHERE t.secs > 400"
        ),
        "/albums/* <=> /tracks/*[::album_id = $$0::id && ::secs > 400] \
         | %(::title; \"t.title\" = $$1::title)"
    );
    assert_eq!(
        t("SELECT DISTINCT country FROM artists"),
        "/artists/* | ::country @| unique"
    );
    assert_eq!(
        t("SELECT title FROM tracks WHERE title LIKE '%o%' AND secs >= 200"),
        "/tracks/*[::title == (/(?i)o/) && ::secs >= 200] | %(::title)"
    );
    // `IS [NOT] NULL` → `= null` / `!= null`: exact under Quarb's
    // value_eq (truthiness would also drop 0 and '').
    assert_eq!(
        t("SELECT name FROM artists WHERE country IS NOT NULL"),
        "/artists/*[::country != null] | %(::name)"
    );
    assert_eq!(
        t("SELECT name FROM artists WHERE country IS NULL"),
        "/artists/*[::country = null] | %(::name)"
    );
    // DISTINCT dedups before LIMIT (SQL's order of operations).
    assert_eq!(
        t("SELECT DISTINCT country FROM artists ORDER BY country LIMIT 3"),
        "/artists/* @| sort_by(::country) | ::country @| unique @| [..3]"
    );
    // `AS` table aliases.
    assert_eq!(
        t("SELECT t.title FROM tracks AS t WHERE t.secs > -10"),
        "/tracks/*[::secs > -10] | %(::title)"
    );
    // HAVING may name the aggregate by call, alias, or function.
    assert_eq!(
        t(
            "SELECT customer, SUM(qty) AS total FROM invoices GROUP BY customer \
           HAVING SUM(qty) > 1"
        ),
        "/invoices/* | .customer(::customer) | ::qty @|{.customer} sum | .total | [$_ > 1] | %."
    );
    // An aliased group key names the key field.
    assert_eq!(
        t("SELECT country AS c, COUNT(*) FROM artists GROUP BY country"),
        "/artists/* | .c(::country) @|{.c} count | .count | %."
    );
    // SQL strings escape into Quarb string syntax.
    assert_eq!(
        t("SELECT a FROM t WHERE a = 'say \"hi\" for $5'"),
        "/t/*[::a = \"say \\\"hi\\\" for \\$5\"] | %(::a)"
    );
}

#[test]
fn refusals() {
    let err = |sql: &str| translate(sql).unwrap_err().to_string();
    assert!(err("DELETE FROM tracks").contains("only SELECT"));
    assert!(
        err("SELECT a FROM t1 JOIN t2 ON t2.x = t1.x JOIN t3 ON t3.y = t2.y")
            .contains("more than one JOIN")
    );
    assert!(err("SELECT title FROM tracks WHERE title LIKE 'a%b'").contains("LIKE pattern"));
    assert!(err("SELECT a, COUNT(*) FROM t").contains("mixing aggregates"));
    // Outer and cross joins have no existential-correlation
    // equivalent — refused, never silently inner.
    assert!(err("SELECT t.a FROM t LEFT JOIN u ON u.x = t.x").contains("outer JOIN"));
    assert!(err("SELECT t.a FROM t RIGHT JOIN u ON u.x = t.x").contains("outer JOIN"));
    assert!(err("SELECT t.a FROM t CROSS JOIN u ON u.x = t.x").contains("CROSS"));
    // HAVING binds to a group.
    assert!(err("SELECT name FROM t HAVING name > 5").contains("HAVING without GROUP BY"));
    assert!(err("SELECT SUM(x) FROM t HAVING x > 5").contains("HAVING without GROUP BY"));
    // Every plain select item must be the GROUP BY key.
    assert!(err("SELECT name, COUNT(*) FROM emp GROUP BY dept").contains("not the GROUP BY key"));
    // HAVING may only name the select list's aggregate or the key.
    assert!(
        err("SELECT k, SUM(x) FROM t GROUP BY k HAVING COUNT(*) > 1")
            .contains("not in the select list")
    );
    assert!(err("SELECT k, SUM(x) FROM t GROUP BY k HAVING z > 1").contains("HAVING column"));
    // Aggregates belong in HAVING, not WHERE.
    assert!(err("SELECT a FROM t WHERE SUM(x) > 5").contains("aggregate in WHERE"));
    assert!(err("SELECT DISTINCT COUNT(*) FROM t").contains("DISTINCT"));
    assert!(err("SELECT \"a FROM t").contains("unterminated"));
}

/// The differential rig: SQL through SQLite, the translation
/// through the engine, same database, same answers.
#[test]
fn differential_against_sqlite() {
    let conn = Connection::open_in_memory().unwrap();
    conn.execute_batch(
        r#"
        CREATE TABLE artists (id INTEGER PRIMARY KEY, name TEXT, country TEXT);
        CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, secs INTEGER,
                             price REAL, artist_id INTEGER REFERENCES artists(id));
        INSERT INTO artists VALUES
          (1,'Holst','GB'), (2,'Bartok','HU'), (3,'Satie',NULL), (4,'Anon','');
        INSERT INTO tracks VALUES
          (1,'Mars',430,1.29,1), (2,'Venus',480,0.99,1), (3,'Jupiter',470,1.29,1),
          (4,'Bourree',95,0.99,2), (5,'Gymnopedie',210,0.99,3), (6,'Sketch',60,0.5,NULL);
        "#,
    )
    .unwrap();
    let adapter = quarb_sqlite::SqliteAdapter::load(&conn).unwrap();

    // Scalar-column cases: compare flattened value lists. The ''
    // country row keeps the NULL translations exact — SQL's
    // IS [NOT] NULL distinguishes '' from NULL, and so must the
    // `= null` / `!= null` forms.
    let cases = [
        "SELECT title FROM tracks WHERE price < 1 ORDER BY title",
        "SELECT name FROM artists WHERE country IS NOT NULL ORDER BY name",
        "SELECT name FROM artists WHERE country IS NULL ORDER BY name",
        "SELECT name FROM artists WHERE country = '' ORDER BY name",
        "SELECT title FROM tracks WHERE title LIKE '%s%' ORDER BY title",
        "SELECT DISTINCT price FROM tracks ORDER BY price",
        "SELECT DISTINCT price FROM tracks ORDER BY price LIMIT 2",
        "SELECT title FROM tracks WHERE secs > 100 AND price >= 1 ORDER BY title",
        "SELECT title FROM tracks WHERE secs > -1 AND price < 1 ORDER BY title",
        "SELECT name FROM artists WHERE country IN ('GB','HU') ORDER BY name",
        "SELECT price, COUNT(*) AS n FROM tracks GROUP BY price ORDER BY price",
    ];
    for sql in cases {
        // SQL side.
        let mut stmt = conn.prepare(sql).unwrap();
        let ncols = stmt.column_count();
        let sql_rows: Vec<String> = stmt
            .query_map([], |r| {
                Ok((0..ncols)
                    .map(|i| {
                        r.get_ref(i)
                            .map(|v| match v {
                                rusqlite::types::ValueRef::Null => String::new(),
                                rusqlite::types::ValueRef::Integer(n) => n.to_string(),
                                rusqlite::types::ValueRef::Real(f) => f.to_string(),
                                rusqlite::types::ValueRef::Text(t) => {
                                    String::from_utf8_lossy(t).into_owned()
                                }
                                _ => "<blob>".into(),
                            })
                            .unwrap()
                    })
                    .collect::<Vec<_>>()
                    .join("|"))
            })
            .unwrap()
            .collect::<Result<_, _>>()
            .unwrap();

        // Quarb side: single-column rec streams as {"col": v} — use
        // the projected value form for comparison.
        let quarb = translate(sql).unwrap().query;
        let got = match quarb::run(&quarb, &adapter).unwrap() {
            quarb::QueryResult::Values(vs) => vs,
            quarb::QueryResult::Nodes(_) => panic!("expected values for {sql}"),
        };
        let quarb_rows: Vec<String> = got
            .iter()
            .map(|v| match v {
                quarb::Value::Record(fields) => fields
                    .iter()
                    .map(|(_, v)| v.to_string())
                    .collect::<Vec<_>>()
                    .join("|"),
                other => other.to_string(),
            })
            .collect();
        assert_eq!(quarb_rows, sql_rows, "differential mismatch for: {sql}");
    }
}

// ---------------------------------------------------------------
// The exporter: Quarb → SQL, and its own differential rig.
// ---------------------------------------------------------------

use quarb_sql::export;

fn x(quarb: &str) -> String {
    export(quarb).unwrap().query
}

#[test]
fn export_translations() {
    assert_eq!(
        x("/tracks/*[::price < 1] | %(::title; ::secs) @| sort_by(::title)"),
        "SELECT title, secs FROM tracks WHERE price < 1 ORDER BY title"
    );
    assert_eq!(x("/tracks/* @| count"), "SELECT COUNT(*) FROM tracks");
    // the fold's answer unrecorded: one value per group
    assert_eq!(
        x("/tracks/* | .price(::price) @|{.price} count"),
        "SELECT COUNT(*) FROM tracks GROUP BY price"
    );
    assert_eq!(
        x("/invoices/* | .customer(::customer) | ::qty @|{.customer} sum | .total | [$_ > 1] | %."),
        "SELECT customer, SUM(qty) AS total FROM invoices GROUP BY customer \
         HAVING SUM(qty) > 1"
    );
    assert_eq!(
        x(
            "/albums/* <=> /tracks/*[::album_id = $$0::id && ::secs > 400] \
           | %(album = ::title; $$1::title)"
        ),
        "SELECT albums.title AS album, tracks.title FROM albums \
         JOIN tracks ON tracks.album_id = albums.id WHERE tracks.secs > 400"
    );
    assert_eq!(
        x("/tracks/* | ::price @| unique"),
        "SELECT DISTINCT price FROM tracks"
    );
    assert_eq!(
        x("/tracks/* @| top(2, ::price) | %(::title; ::price)"),
        "SELECT title, price FROM tracks ORDER BY price DESC LIMIT 2"
    );
}

#[test]
fn export_refusals() {
    let err = |q: &str| export(q).unwrap_err().to_string();
    assert!(err("/tracks/* | %(::album_id-->::title)").contains("schema"));
    assert!(err("/tracks/* | ::price @| window(3) | mean").contains("aggregate"));
    assert!(err("/a/*[::x == (/y/)]").contains("regex"));
    assert!(err("//tracks/*::title").contains("/table/*"));
    // SUM(*) is not SQL: bare-row aggregates beyond count refuse.
    assert!(err("/t/* @| sum").contains("project a column"));
    // The fixed SELECT shape orders before LIMIT and dedups before
    // LIMIT; command orders it cannot render refuse rather than
    // silently reordering.
    assert!(err("/t/* @| [..5] @| sort_by(::c) | ::c").contains("before LIMIT"));
    assert!(err("/t/* @| [..5] | ::c @| unique").contains("DISTINCT before LIMIT"));
    assert!(err("/t/* @| sort_by(::a) @| sort_by(::b) | ::a").contains("second sort"));
    // the keyed sort's options are its own: the direction is said, a
    // named collation and a second key are not SQL's to say
    assert_eq!(
        x("/t/* @| sort_by(::c; --desc) | ::c"),
        "SELECT c FROM t ORDER BY c DESC"
    );
    assert!(
        err("/t/* @| sort_by(::c; --locale=de) | ::c").contains("names the engine's collation")
    );
    assert!(err("/t/* @| sort_by(::a; ::b) | ::a").contains("a sort by several keys"));
    // a case order is the engine's collation's as well (ruling
    // 2026-11-12), and `top` says the same of its options: they were
    // dropped, and the SQL ordered as the backend pleased
    for flag in [
        "-u",
        "--upper-first",
        "-l",
        "--lower-first",
        "-i",
        "--ignore-case",
    ] {
        let e = err(&format!("/t/* @| sort_by(::c; {flag}) | ::c"));
        assert!(
            e.contains("case order is the engine's collation's"),
            "{flag}: {e}"
        );
    }
    assert_eq!(
        x("/t/* @| top(3; ::c) | ::c"),
        "SELECT c FROM t ORDER BY c DESC LIMIT 3"
    );
    for option in ["--locale=de", "-i", "--upper-first"] {
        let e = err(&format!("/t/* @| top(3; ::c; {option}) | ::c"));
        assert!(e.contains("names the engine's collation"), "{option}: {e}");
    }
    // A '*=' pattern must be a text literal — a column operand
    // holds a value, not a pattern.
    assert!(err("/t/*[::a *= ::b] | ::a").contains("non-literal"));
    // `$*k` belongs on a joined expression; the driver cannot
    // reference the join (a parse-level placement error).
    assert!(err("/t/*[$$1::x = 5] | ::a").contains("drives"));
}

#[test]
fn export_details() {
    // A terminal projection on the joined branch selects from the
    // result context's table (it used to be silently dropped).
    assert_eq!(
        x("/albums/* <=> /tracks/*[::album_id = $$0::id] | %($$1::title)"),
        "SELECT tracks.title FROM albums JOIN tracks ON tracks.album_id = albums.id"
    );
    // `<=>?` keeps the unmatched driver rows: a LEFT JOIN, and the
    // joined expression's own predicates choose the witness, so they
    // stand in the ON (in a WHERE they would discard the unmatched
    // rows again).
    assert_eq!(
        x("/tracks/* <=>? /albums/*[::id = $$0::album_id] | %(::title; a = $$1::title)"),
        "SELECT tracks.title, albums.title AS a FROM tracks LEFT JOIN albums \
         ON albums.id = tracks.album_id"
    );
    assert_eq!(
        x(
            "/tracks/* <=>? /albums/*[::id = $$0::album_id && ::year > 1900] \
             | %(::title; a = $$1::title)"
        ),
        "SELECT tracks.title, albums.title AS a FROM tracks LEFT JOIN albums \
         ON albums.id = tracks.album_id AND albums.year > 1900"
    );
    // Grouped '| count' counts every member like Quarb does —
    // COUNT(*), never the NULL-skipping COUNT(col).
    assert_eq!(
        x("/t/* | ::c | .k(::k) @|{.k} count | .n | %."),
        "SELECT k, COUNT(*) AS n FROM t GROUP BY k"
    );
    // ORDER BY then LIMIT renders (that order matches Quarb's).
    assert_eq!(
        x("/t/* @| sort_by(::c) @| [..5] | ::c"),
        "SELECT c FROM t ORDER BY c LIMIT 5"
    );
    // LIKE metacharacters escape, with an explicit ESCAPE (SQLite,
    // MSSQL, and Oracle have no default escape character).
    assert_eq!(
        x("/t/*[::a *= \"50%\"] | ::a"),
        "SELECT a FROM t WHERE a LIKE '%50\\%%' ESCAPE '\\'"
    );
}

#[test]
fn identifiers_are_gated() {
    let pushdown = |q: &str| quarb_sql::pushdown(q, None);
    // Strict mode refuses any table or column name that is not a
    // plain SQL identifier: rendered bare it would rewrite the
    // SQL's meaning ("a OR b", "t; DROP TABLE u"), and quoting
    // dialects disagree.
    assert!(pushdown("/t/*[::\"a OR b\" = 5] | ::x").is_none());
    assert!(pushdown("/\"t; DROP TABLE u\"/*[::a = 5] | ::x").is_none());
    assert!(
        pushdown("/albums/* <=> /tracks/*[::aid = $$0::\"album-id\"] | %(t = $$1::title)")
            .is_none()
    );
    // The display translation double-quotes (ANSI) with a note.
    let t = export("/t/*[::\"a OR b\" = 5] | ::x").unwrap();
    assert_eq!(t.query, "SELECT x FROM t WHERE \"a OR b\" = 5");
    assert!(t.notes.iter().any(|n| n.contains("double-quoted")));
}

#[test]
fn refuses_the_internal_agg_marker() {
    // "__AGG__" is the exporter's placeholder for the HAVING
    // aggregate — same spoofing hazard as "__LEFT__".
    let q = "/t/* | ::q | .k(::k) @|{.k} sum | .s | [$_ = \"__AGG__\"] | %.";
    assert!(export(q).unwrap_err().to_string().contains("__AGG__"));
    assert!(quarb_sql::pushdown(q, None).is_none());
}

/// Round-trip differential: the Quarb query through the engine, its
/// exported SQL through SQLite, same database, same answers.
#[test]
fn export_differential_against_sqlite() {
    let conn = Connection::open_in_memory().unwrap();
    conn.execute_batch(
        r#"
        CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, secs INTEGER, price REAL);
        INSERT INTO tracks VALUES
          (1,'Mars',430,1.29), (2,'Venus',480,0.99), (3,'Jupiter',470,1.29),
          (4,'Bourree',95,0.99), (5,'Gymnopedie',210,0.5);
        "#,
    )
    .unwrap();
    let adapter = quarb_sqlite::SqliteAdapter::load(&conn).unwrap();

    let cases = [
        "/tracks/*[::price < 1] | ::title @| sort_by(::title)",
        "/tracks/* @| count",
        "/tracks/*[::secs > 100 && ::price >= 1] | ::title @| sort_by(::title)",
        "/tracks/* | ::price @| sum",
        "/tracks/* @| top(2, ::secs) | %(::title)",
    ];
    for quarb in cases {
        let sql = export(quarb).unwrap().query;
        let mut stmt = conn.prepare(&sql).unwrap();
        let ncols = stmt.column_count();
        let sql_rows: Vec<String> = stmt
            .query_map([], |r| {
                Ok((0..ncols)
                    .map(|i| {
                        r.get_ref(i)
                            .map(|v| match v {
                                rusqlite::types::ValueRef::Null => String::new(),
                                rusqlite::types::ValueRef::Integer(n) => n.to_string(),
                                rusqlite::types::ValueRef::Real(f) => f.to_string(),
                                rusqlite::types::ValueRef::Text(t) => {
                                    String::from_utf8_lossy(t).into_owned()
                                }
                                _ => "<blob>".into(),
                            })
                            .unwrap()
                    })
                    .collect::<Vec<_>>()
                    .join("|"))
            })
            .unwrap()
            .collect::<Result<_, _>>()
            .unwrap();
        let got = match quarb::run(quarb, &adapter).unwrap() {
            quarb::QueryResult::Values(vs) => vs,
            quarb::QueryResult::Nodes(_) => panic!("expected values for {quarb}"),
        };
        let quarb_rows: Vec<String> = got
            .iter()
            .map(|v| match v {
                quarb::Value::Record(fields) => fields
                    .iter()
                    .map(|(_, v)| v.to_string())
                    .collect::<Vec<_>>()
                    .join("|"),
                other => other.to_string(),
            })
            .collect();
        assert_eq!(
            quarb_rows, sql_rows,
            "export differential mismatch for: {quarb}"
        );
    }
}

#[test]
fn pushdown_gate() {
    let pushdown = |q: &str| quarb_sql::pushdown(q, None);
    // In: aggregates, filtered selections, witness joins.
    assert!(pushdown("/tracks/* @| count").is_some());
    assert!(pushdown("/tracks/*[::price < 1] | %(::title)").is_some());
    assert!(
        pushdown("/albums/* <=> /tracks/*[::album_id = $$0::id] | %(::title; track = $$1::title)")
            .is_some()
    );
    // Aggregates carry no order table; row selections order by the
    // result context's table.
    assert!(
        pushdown("/tracks/* @| count")
            .unwrap()
            .order_table
            .is_none()
    );
    assert_eq!(
        pushdown("/tracks/*[::price < 1] | %(::title)")
            .unwrap()
            .order_table
            .as_deref(),
        Some("tracks")
    );
    // Out: every construct whose SQL semantics are not provably
    // identical.
    assert!(pushdown("/tracks/*[::title *= \"o\"] | ::title").is_none()); // LIKE folding
    assert!(pushdown("/tracks/*[::album_id] | ::title").is_none()); // truthiness
    assert!(pushdown("/t/* | ::p | .k(::k) @|{.k} sum | .s | %.").is_none()); // group order
    assert!(pushdown("/t/* | ::p @| unique").is_none()); // distinct order
    assert!(pushdown("/t/* @| sort_by(::a) | ::a").is_none()); // collation
    assert!(pushdown("/t/* @| [..3]").is_none()); // unordered LIMIT
    assert!(pushdown("/t/* | ::p @| window(3) | mean").is_none()); // quarb-side
}

#[test]
fn partial_pushdown_gate() {
    use quarb_sql::partial_pushdown;
    // In: a strict leading predicate with an unpushable pipeline.
    let p = partial_pushdown(
        "/events/*[::kind = \"rare\"] | ::amount | .b(::amount idiv 100) @|{.b} count | .n | %.",
        None,
    )
    .unwrap();
    assert_eq!(p.table, "events");
    assert_eq!(p.where_sql, "kind = 'rare'");
    // Only the LEADING expression run pushes; positional first = out.
    assert!(
        partial_pushdown(
            "/t/*[2][::a = 1] | ::a | .g(::a) @|{.g} count | .n | %.",
            None
        )
        .is_none()
    );
    // Reaching the table twice (a ^-anchored subcontext) = out.
    assert!(partial_pushdown("/t/*[::a = 1] | .n(^/t/* @| count) | $.n", None).is_none());
    // Crosslink/resolution axes = out.
    assert!(partial_pushdown("/t/*[::a = 1]::b-->::c", None).is_none());
    // Metadata = out (a filtered :::n-rows would lie).
    assert!(partial_pushdown("/t/*[::a = 1] | :::table", None).is_none());
    // Non-strict predicates (LIKE folding) = out.
    assert!(
        partial_pushdown(
            "/t/*[::a *= \"x\"] | ::a | .g(::a) @|{.g} count | .n | %.",
            None
        )
        .is_none()
    );
}

#[test]
fn pushdown_join_soundness_metadata() {
    let pushdown = |q: &str| quarb_sql::pushdown(q, None);
    // A witness join carries the joined table's ON-bound columns
    // so the driver can verify uniqueness (SQL JOIN multiplies
    // rows when several joined rows match one FROM row; Quarb's
    // existential binding never does).
    let p = pushdown("/albums/* <=> /tracks/*[::album_id = $$0::id] | %(a = ::title)")
        .expect("canonical witness join pushes down");
    let (table, cols) = p.join_left.expect("join carries its obligation");
    assert_eq!(table, "tracks");
    assert_eq!(cols, vec!["album_id".to_string()]);
    // No join → no obligation.
    assert!(
        pushdown("/tracks/* @| count")
            .expect("plain aggregate pushes down")
            .join_left
            .is_none()
    );
}

/// An every-witness join (`<=>*`, ruling 2026-11-11) is the JOIN
/// as SQL means it: no uniqueness to verify, and the joined table's
/// order owed after the driver's.
#[test]
fn pushdown_of_the_every_witness_join() {
    let pushdown = |q: &str| quarb_sql::pushdown(q, None);
    let p =
        pushdown("/albums/* <=>* /tracks/*[::album_id = $$0::id] | %(a = ::title; t = $$1::title)")
            .expect("the every-witness join pushes down");
    assert_eq!(
        p.sql,
        "SELECT albums.title AS a, tracks.title AS t FROM albums JOIN tracks \
         ON tracks.album_id = albums.id"
    );
    assert!(p.join_left.is_none(), "no uniqueness obligation");
    assert_eq!(p.order_table.as_deref(), Some("albums"));
    assert_eq!(p.order_then.as_deref(), Some("tracks"));
    // the outer form is the LEFT JOIN
    let p = pushdown(
        "/albums/* <=>*? /tracks/*[::album_id = $$0::id] | %(a = ::title; t = $$1::title)",
    )
    .expect("the outer every-witness join pushes down");
    assert!(p.sql.contains(" LEFT JOIN tracks ON "), "{}", p.sql);
    assert_eq!(p.order_then.as_deref(), Some("tracks"));
    // an aggregate over it has no rows to order
    let p = pushdown("/albums/* <=>* /tracks/*[::album_id = $$0::id] @| count")
        .expect("the count pushes down");
    assert!(p.order_then.is_none() && p.join_left.is_none());
    // the plain witness join keeps its obligation and owes no second order
    let p = pushdown("/albums/* <=> /tracks/*[::album_id = $$0::id] | %(a = ::title)").unwrap();
    assert!(p.join_left.is_some() && p.order_then.is_none());
}

#[test]
fn pushdown_refuses_keyword_aliases() {
    let pushdown_explained = |q: &str| quarb_sql::pushdown_explained(q, None);
    // `AS order` is an SQL syntax error; quoting portably differs
    // by dialect, so strict pushdown refuses outright.
    let Err(err) =
        pushdown_explained("/albums/* <=> /tracks/*[::album_id = $$0::id] | %(order = $$1::title)")
    else {
        panic!("keyword alias must refuse")
    };
    assert!(format!("{err}").contains("needs SQL quoting"), "{err}");
}

#[test]
fn refuses_the_internal_left_marker() {
    use quarb_sql::export;
    let pushdown = |q: &str| quarb_sql::pushdown(q, None);
    let pushdown_explained = |q: &str| quarb_sql::pushdown_explained(q, None);
    // "__LEFT__" is the exporter's internal placeholder for the
    // join's left table: query text containing it would be
    // rewritten inside its own literals and could spoof the join
    // obligation, so it stays on the scan path.
    let q =
        "/albums/* <=> /tracks/*[::note = '__LEFT__.id' && ::album_id = $$0::id] | %($$1::title)";
    assert!(pushdown(q).is_none());
    let Err(err) = pushdown_explained(q) else {
        panic!("marker in a literal must refuse")
    };
    assert!(format!("{err}").contains("__LEFT__"), "{err}");
    assert!(export(q).is_err(), "export substitutes too; must refuse");
}

#[test]
fn join_projections_qualify_by_operand_index() {
    let pushdown = |q: &str| quarb_sql::pushdown(q, None);
    let pushdown_explained = |q: &str| quarb_sql::pushdown_explained(q, None);
    // Bare columns project the driver/FROM table, `$$1` the
    // joined one — found by the seams article: every context used
    // to render as one table, compiling invalid SQL that only the
    // driver's runtime refusal caught.
    let p = pushdown(
        "/albums/* <=> /tracks/*[::album_id = $$0::id] \
         | %(a = ::title; t = $$1::title)",
    )
    .expect("two-sided projection pushes down");
    assert!(p.sql.contains("albums.title AS a"), "{}", p.sql);
    assert!(p.sql.contains("tracks.title AS t"), "{}", p.sql);
    // Beyond the joined operand there is no verified mapping.
    assert!(
        pushdown_explained("/albums/* <=> /tracks/*[::album_id = $$0::id] | %(x = $$2::title)")
            .is_err()
    );
}

/// Quarb compares by value, SQL by the column's type: a plan
/// records what it assumes of the columns it compares, and a
/// numeric-looking text literal does not push at all.
#[test]
fn a_plan_records_the_column_types_it_assumes() {
    let plan = quarb_sql::pushdown(
        "/books/*[::pages > 300 && ::genre = 'epic'] | ::title",
        None,
    )
    .unwrap();
    assert_eq!(plan.column_types.numeric, ["pages"]);
    assert_eq!(plan.column_types.text, ["genre"]);
    assert_eq!(plan.tables, ["books"]);
    let catalog = |pages: bool, genre: bool| {
        vec![
            ("title".to_string(), false, false),
            ("Pages".to_string(), pages, false),
            ("genre".to_string(), genre, false),
        ]
    };
    assert!(plan.column_types.unmet(&catalog(true, false)).is_empty());
    assert_eq!(plan.column_types.unmet(&catalog(false, false)), ["pages"]);
    assert_eq!(plan.column_types.unmet(&catalog(true, true)), ["genre"]);
    // a column the catalog does not list is unmet
    assert_eq!(plan.column_types.unmet(&[]), ["pages", "genre"]);
    // the literal on the left, and the prefilter, record the same
    let plan = quarb_sql::pushdown("/books/*[300 < ::pages] | ::title", None).unwrap();
    assert_eq!(plan.column_types.numeric, ["pages"]);
    // a numeric reducer over a column assumes the column numeric:
    // the scan lifts unit text to quantities, SQL sums its digits
    let plan = quarb_sql::pushdown("/books/* | ::pages @| sum", None).unwrap();
    assert_eq!(plan.sql, "SELECT SUM(pages) FROM books");
    assert_eq!(plan.column_types.numeric, ["pages"]);
    let plan = quarb_sql::pushdown("/books/* | ::title @| max", None).unwrap();
    assert_eq!(plan.column_types.numeric, ["title"]);
    // count assumes nothing of a column
    let plan = quarb_sql::pushdown("/books/* @| count", None).unwrap();
    assert!(plan.column_types.is_empty());
    // the glued projection plans as the piped one (the planner's
    // first exact edge, 2026-11-17): the same statement, the same
    // assumption; it was refused as a reducer "over row nodes"
    for (glued, piped) in [
        ("/books/*::pages @| sum", "/books/* | ::pages @| sum"),
        ("/books/*::pages @| mean", "/books/* | ::pages @| mean"),
        ("/books/*::pages @| min", "/books/* | ::pages @| min"),
        ("/books/*::pages @| max", "/books/* | ::pages @| max"),
        ("/books/*::pages @| count", "/books/* | ::pages @| count"),
        (
            "/books/*[::genre = 'epic']::pages @| max",
            "/books/*[::genre = 'epic'] | ::pages @| max",
        ),
    ] {
        let g = quarb_sql::pushdown(glued, None).unwrap_or_else(|| panic!("{glued}"));
        let p = quarb_sql::pushdown(piped, None).unwrap_or_else(|| panic!("{piped}"));
        assert_eq!(g.sql, p.sql, "{glued}");
        assert_eq!(g.column_types, p.column_types, "{glued}");
    }
    let plan = quarb_sql::pushdown("/books/*::pages @| max", None).unwrap();
    assert_eq!(plan.sql, "SELECT MAX(pages) FROM books");
    assert_eq!(plan.column_types.numeric, ["pages"]);
    let partial = quarb_sql::partial_pushdown(
        "/books/*[::pages > 300] | ::title | .title(::title) @|{.title} count",
        None,
    )
    .unwrap();
    assert_eq!(partial.column_types.numeric, ["pages"]);
    // '150' meets 150 and '150.0' in Quarb, and only '150' in SQL
    assert!(quarb_sql::pushdown("/books/*[::code = '150'] | ::title", None).is_none());
    assert!(
        quarb_sql::partial_pushdown(
            "/books/*[::code = '150'] | ::title | .title(::title) @|{.title} count",
            None
        )
        .is_none()
    );
    // a column against a column assumes nothing
    let plan = quarb_sql::pushdown("/books/*[::pages = ::leaves] | ::title", None).unwrap();
    assert!(plan.column_types.is_empty());
}

/// A joined expression's mark (ruling 2026-11-14) and the driver's
/// are rows of the two tables: `$$.al::col` is the joined table's
/// column, `$$.t::col` the FROM table's, in the ON and after it.
#[test]
fn pushdown_reads_the_marks_of_a_join() {
    let pushdown = |q: &str| quarb_sql::pushdown(q, None);
    let named = pushdown(
        "/tracks/* .t <=> /albums/*[::id = $$.t::album_id] .al \
         | %(t = $$.t::title; al = $$.al::title)",
    )
    .expect("the named join pushes down");
    assert_eq!(
        named.sql,
        "SELECT tracks.title AS t, albums.title AS al FROM tracks JOIN albums \
         ON albums.id = tracks.album_id"
    );
    // the same plan as the numbered spelling, obligation included
    let numbered =
        pushdown("/tracks/* <=> /albums/*[::id = $$0::album_id] | %(t = ::title; al = $$1::title)")
            .unwrap();
    assert_eq!(named.sql, numbered.sql);
    assert_eq!(named.join_left, numbered.join_left);
    assert_eq!(
        named.join_left,
        Some(("albums".to_string(), vec!["id".to_string()]))
    );
    // the outer join and the every-witness join take the names too
    let p = pushdown(
        "/tracks/* .t <=>? /albums/*[::id = $$.t::album_id] .al \
         | %(t = $$.t::title; al = $$.al::title)",
    )
    .unwrap();
    assert!(
        p.sql
            .contains(" LEFT JOIN albums ON albums.id = tracks.album_id"),
        "{}",
        p.sql
    );
    let p = pushdown(
        "/albums/* .al <=>* /tracks/*[::album_id = $$.al::id] .t \
         | %(al = $$.al::title; t = $$.t::title)",
    )
    .unwrap();
    assert_eq!(
        p.sql,
        "SELECT albums.title AS al, tracks.title AS t FROM albums JOIN tracks \
         ON tracks.album_id = albums.id"
    );
    // a mark read the translation has no row for stays on the scan:
    // by position, of a mark on the table, of a mark with no name
    for q in [
        "/tracks/* .t <=> /albums/*[::id = $$.t::album_id] .al | %(n = $$.2::title)",
        "/tracks/* .t <=> /albums/*[::id = $$.t::album_id] . | %(n = $$.::title)",
        "/tracks .x /* | %(x = $$.x:name; t = ::title)",
        "/tracks/* .t <=> /albums .x /*[::id = $$.t::album_id] | %(t = ::title)",
    ] {
        assert!(pushdown(q).is_none(), "{q}");
    }
    // a driver's mark alone still pushes
    assert_eq!(
        pushdown("/tracks/* .t | %(x = $$.t::title; y = ::secs)")
            .unwrap()
            .sql,
        "SELECT title AS x, secs AS y FROM tracks"
    );
}