powdb-query 0.18.1

PowQL lexer, parser, planner, and executor — compiled query engine for PowDB
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
use powdb_query::executor::Engine;
use powdb_query::result::QueryResult;
use powdb_storage::types::Value;

#[test]
fn sql_json_arrows_preserve_scalar_and_canonical_text_semantics() {
    let dir = tempfile::tempdir().unwrap();
    let mut engine = Engine::new(dir.path()).unwrap();
    engine
        .execute_powql("type Post { required id: int, data: json }")
        .unwrap();
    engine
        .execute_powql(
            r#"insert Post { id := 1, data := "{\"arr\":[1,2],\"flag\":true,\"name\":\"alice\",\"nil\":null,\"obj\":{\"b\":2,\"a\":1}}" }"#,
        )
        .unwrap();

    let result = engine
        .execute_sql(
            "SELECT data ->> 'name' AS name, data -> 'arr' ->> 0 AS first, data ->> 'flag' AS flag, data ->> 'arr' AS arr, data ->> 'obj' AS obj, data ->> 'nil' AS nil, data ->> 'missing' AS missing, data -> 'arr' -> 1 AS raw_second FROM Post WHERE data ->> 'name' = 'alice'",
        )
        .unwrap();
    let QueryResult::Rows { columns, rows } = result else {
        panic!("expected rows");
    };
    assert_eq!(
        columns,
        vec![
            "name",
            "first",
            "flag",
            "arr",
            "obj",
            "nil",
            "missing",
            "raw_second",
        ]
    );
    assert_eq!(
        rows,
        vec![vec![
            Value::Str("alice".into()),
            Value::Str("1".into()),
            Value::Str("true".into()),
            Value::Str("[1,2]".into()),
            Value::Str(r#"{"a":1,"b":2}"#.into()),
            Value::Empty,
            Value::Empty,
            Value::Int(2),
        ]]
    );
}

#[test]
fn sql_json_arrow_expression_orders_rows() {
    let dir = tempfile::tempdir().unwrap();
    let mut engine = Engine::new(dir.path()).unwrap();
    engine
        .execute_powql("type Post { required id: int, data: json }")
        .unwrap();
    engine
        .execute_powql(
            r#"insert Post { id := 1, data := "{\"kind\":\"x\",\"rank\":\"b\"}" }, { id := 2, data := "{\"kind\":\"x\",\"rank\":\"a\"}" }, { id := 3, data := "{\"kind\":\"y\",\"rank\":\"c\"}" }"#,
        )
        .unwrap();

    let result = engine
        .execute_sql("SELECT id FROM Post ORDER BY data ->> 'rank' ASC")
        .unwrap();
    let QueryResult::Rows { rows, .. } = result else {
        panic!("expected rows");
    };
    assert_eq!(
        rows,
        vec![
            vec![Value::Int(2)],
            vec![Value::Int(1)],
            vec![Value::Int(3)],
        ]
    );

    let grouped = engine
        .execute_sql(
            "SELECT data ->> 'kind' AS kind, COUNT(*) AS n FROM Post GROUP BY data ->> 'kind' ORDER BY data ->> 'kind' ASC",
        )
        .unwrap();
    let QueryResult::Rows { rows, .. } = grouped else {
        panic!("expected grouped rows");
    };
    assert_eq!(
        rows,
        vec![
            vec![Value::Str("x".into()), Value::Int(2)],
            vec![Value::Str("y".into()), Value::Int(1)],
        ]
    );
}

#[test]
fn sql_select_matches_powql_and_shares_plan_cache() {
    let dir = tempfile::tempdir().unwrap();
    let mut engine = Engine::new(dir.path()).unwrap();
    engine
        .execute_powql("type User { required id: int, required name: str, age: int }")
        .unwrap();
    engine
        .execute_powql(r#"insert User { id := 1, name := "Ada", age := 37 }, { id := 2, name := "Grace", age := 31 }"#)
        .unwrap();

    let sql = engine
        .execute_sql("SELECT name, age FROM User WHERE age > 30 ORDER BY age DESC LIMIT 10")
        .unwrap();
    let powql = engine
        .execute_powql("User filter .age > 30 order .age desc limit 10 { .name, .age }")
        .unwrap();
    assert_eq!(format!("{sql:?}"), format!("{powql:?}"));
    let (hits, misses, len) = engine.plan_cache_stats();
    assert!(misses >= 1, "first SQL execution should populate cache");
    assert!(
        hits >= 1,
        "equivalent PowQL should reuse SQL-populated cache"
    );
    assert!(len >= 1);
}

#[test]
fn sql_mutations_execute_through_existing_engine() {
    let dir = tempfile::tempdir().unwrap();
    let mut engine = Engine::new(dir.path()).unwrap();
    engine
        .execute_sql("CREATE TABLE User (id INTEGER NOT NULL UNIQUE, name TEXT, age INTEGER)")
        .unwrap();
    engine
        .execute_sql("INSERT INTO User (id, name, age) VALUES (1, 'Ada', 37), (2, 'Grace', 31)")
        .unwrap();
    engine
        .execute_sql("UPDATE User SET age = 38 WHERE id = 1")
        .unwrap();
    engine.execute_sql("DELETE FROM User WHERE id = 2").unwrap();

    match engine
        .execute_sql("SELECT id, name, age FROM User")
        .unwrap()
    {
        QueryResult::Rows { columns, rows } => {
            assert_eq!(columns, vec!["id", "name", "age"]);
            assert_eq!(rows.len(), 1);
            assert_eq!(rows[0][0], Value::Int(1));
            assert_eq!(rows[0][1], Value::Str("Ada".into()));
            assert_eq!(rows[0][2], Value::Int(38));
        }
        other => panic!("expected rows, got {other:?}"),
    }
}

#[test]
fn sql_readonly_rejects_writes() {
    let dir = tempfile::tempdir().unwrap();
    let engine = Engine::new(dir.path()).unwrap();
    let err = engine
        .execute_sql_readonly("CREATE TABLE T (id INTEGER)")
        .unwrap_err();
    assert_eq!(err.to_string(), "__POWDB_READONLY_NEEDS_WRITE__");
}

fn seeded_engine() -> (tempfile::TempDir, Engine) {
    let dir = tempfile::tempdir().unwrap();
    let mut engine = Engine::new(dir.path()).unwrap();
    engine
        .execute_powql("type T { required id: int, required x: int }")
        .unwrap();
    engine
        .execute_powql("insert T { id := 1, x := 1 }, { id := 2, x := 5 }")
        .unwrap();
    (dir, engine)
}

/// Regression: a deeply-nested SQL expression must return a parse error, not
/// overflow the stack and abort the process. Reachable over the wire via
/// MSG_QUERY_SQL, so an unbounded-recursion overflow + panic=abort is a remote
/// DoS. The PowQL guard (MAX_NESTING_DEPTH) runs in the second stage and never
/// fires because the SQL pre-parser overflows first.
#[test]
fn sql_deeply_nested_expression_errors_instead_of_aborting() {
    let n = 50_000usize;
    let mut q = String::from("SELECT a FROM T WHERE ");
    q.push_str(&"(".repeat(n));
    q.push('1');
    q.push_str(&")".repeat(n));
    let r = powdb_query::sql::parse_sql(&q);
    assert!(r.is_err(), "deep nesting should error, not abort");
}

/// Regression: `NOT x = 1` is standard SQL `NOT (x = 1)`, not `(NOT x) = 1`.
/// Row id=2 has x=5, so the predicate is true for it.
#[test]
fn sql_not_binds_looser_than_comparison() {
    let (_dir, mut engine) = seeded_engine();
    match engine
        .execute_sql("SELECT id FROM T WHERE NOT x = 1")
        .unwrap()
    {
        QueryResult::Rows { rows, .. } => {
            assert_eq!(rows.len(), 1, "NOT (x = 1) should match the x=5 row");
            assert_eq!(rows[0][0], Value::Int(2));
        }
        other => panic!("expected rows, got {other:?}"),
    }
}

/// Regression: arithmetic in a bare (un-aliased) projection must parse and
/// evaluate. Previously PowQL's projection grammar only accepted a single
/// field/agg token in a bare slot, so `SELECT x - 1` (→ PowQL `T { .x - 1 }`)
/// failed with "expected field, got '-'".
#[test]
fn sql_subtraction_in_bare_projection() {
    let (_dir, mut engine) = seeded_engine();
    match engine
        .execute_sql("SELECT x - 1 FROM T WHERE id = 2")
        .unwrap()
    {
        QueryResult::Rows { rows, .. } => {
            assert_eq!(rows.len(), 1);
            assert_eq!(rows[0][0], Value::Int(4), "5 - 1 = 4");
        }
        other => panic!("expected rows, got {other:?}"),
    }
}

/// The same computed-projection support must hold for native PowQL, not just
/// the SQL frontend — this is an engine-level grammar fix.
#[test]
fn powql_subtraction_in_bare_projection() {
    let (_dir, mut engine) = seeded_engine();
    match engine.execute_powql("T filter .id = 2 { .x - 1 }").unwrap() {
        QueryResult::Rows { rows, .. } => {
            assert_eq!(rows.len(), 1);
            assert_eq!(rows[0][0], Value::Int(4), "5 - 1 = 4");
        }
        other => panic!("expected rows, got {other:?}"),
    }
}

/// SQL `INSERT ... RETURNING *` returns the inserted row, so an ORM gets the
/// row back in one round-trip instead of a write followed by a reselect. PowQL
/// already supports `insert ... returning`; this wires the SQL surface to it.
#[test]
fn sql_insert_returning_star_yields_inserted_row() {
    let dir = tempfile::tempdir().unwrap();
    let mut engine = Engine::new(dir.path()).unwrap();
    engine
        .execute_sql("CREATE TABLE User (id INTEGER NOT NULL UNIQUE, name TEXT)")
        .unwrap();
    match engine
        .execute_sql("INSERT INTO User (id, name) VALUES (1, 'Ada') RETURNING *")
        .unwrap()
    {
        QueryResult::Rows { columns, rows } => {
            assert_eq!(columns, vec!["id", "name"]);
            assert_eq!(rows.len(), 1);
            assert_eq!(rows[0][0], Value::Int(1));
            assert_eq!(rows[0][1], Value::Str("Ada".into()));
        }
        other => panic!("expected rows, got {other:?}"),
    }
}

/// The createMany case: a multi-row `INSERT ... VALUES (..),(..) RETURNING *`
/// returns every inserted row in one statement (one round-trip, one fsync).
#[test]
fn sql_multi_row_insert_returning_star_yields_all_rows() {
    let dir = tempfile::tempdir().unwrap();
    let mut engine = Engine::new(dir.path()).unwrap();
    engine
        .execute_sql("CREATE TABLE User (id INTEGER NOT NULL UNIQUE, name TEXT)")
        .unwrap();
    match engine
        .execute_sql(
            "INSERT INTO User (id, name) VALUES (1, 'Ada'), (2, 'Grace'), (3, 'Mary') RETURNING *",
        )
        .unwrap()
    {
        QueryResult::Rows { rows, .. } => {
            assert_eq!(rows.len(), 3);
            assert_eq!(rows[0][0], Value::Int(1));
            assert_eq!(rows[1][1], Value::Str("Grace".into()));
            assert_eq!(rows[2][0], Value::Int(3));
        }
        other => panic!("expected rows, got {other:?}"),
    }
}

/// A plain `INSERT` (no RETURNING) still reports an affected-row count rather
/// than materializing rows — RETURNING stays opt-in.
#[test]
fn sql_insert_without_returning_reports_modified() {
    let dir = tempfile::tempdir().unwrap();
    let mut engine = Engine::new(dir.path()).unwrap();
    engine
        .execute_sql("CREATE TABLE User (id INTEGER NOT NULL UNIQUE, name TEXT)")
        .unwrap();
    match engine
        .execute_sql("INSERT INTO User (id, name) VALUES (1, 'Ada')")
        .unwrap()
    {
        QueryResult::Modified(n) => assert_eq!(n, 1),
        other => panic!("expected Modified, got {other:?}"),
    }
}

/// `UPDATE ... SET ... WHERE ... RETURNING *` returns the post-image of the
/// updated rows.
#[test]
fn sql_update_returning_star_yields_post_image() {
    let dir = tempfile::tempdir().unwrap();
    let mut engine = Engine::new(dir.path()).unwrap();
    engine
        .execute_sql("CREATE TABLE User (id INTEGER NOT NULL UNIQUE, age INTEGER)")
        .unwrap();
    engine
        .execute_sql("INSERT INTO User (id, age) VALUES (1, 37)")
        .unwrap();
    match engine
        .execute_sql("UPDATE User SET age = 38 WHERE id = 1 RETURNING *")
        .unwrap()
    {
        QueryResult::Rows { rows, .. } => {
            assert_eq!(rows.len(), 1);
            assert_eq!(rows[0][0], Value::Int(1));
            assert_eq!(rows[0][1], Value::Int(38), "post-image: the new age");
        }
        other => panic!("expected rows, got {other:?}"),
    }
}

/// `UPDATE` with no `WHERE` still parses a trailing `RETURNING *` (the clause
/// must not be swallowed into the SET assignments).
#[test]
fn sql_update_returning_without_where() {
    let dir = tempfile::tempdir().unwrap();
    let mut engine = Engine::new(dir.path()).unwrap();
    engine
        .execute_sql("CREATE TABLE User (id INTEGER NOT NULL UNIQUE, age INTEGER)")
        .unwrap();
    engine
        .execute_sql("INSERT INTO User (id, age) VALUES (1, 37), (2, 40)")
        .unwrap();
    match engine
        .execute_sql("UPDATE User SET age = 50 RETURNING *")
        .unwrap()
    {
        QueryResult::Rows { rows, .. } => {
            assert_eq!(rows.len(), 2);
            assert!(rows.iter().all(|r| r[1] == Value::Int(50)));
        }
        other => panic!("expected rows, got {other:?}"),
    }
}

/// `DELETE ... WHERE ... RETURNING *` returns the pre-image of the deleted rows.
#[test]
fn sql_delete_returning_star_yields_pre_image() {
    let dir = tempfile::tempdir().unwrap();
    let mut engine = Engine::new(dir.path()).unwrap();
    engine
        .execute_sql("CREATE TABLE User (id INTEGER NOT NULL UNIQUE, name TEXT)")
        .unwrap();
    engine
        .execute_sql("INSERT INTO User (id, name) VALUES (1, 'Ada'), (2, 'Grace')")
        .unwrap();
    match engine
        .execute_sql("DELETE FROM User WHERE id = 2 RETURNING *")
        .unwrap()
    {
        QueryResult::Rows { rows, .. } => {
            assert_eq!(rows.len(), 1);
            assert_eq!(rows[0][0], Value::Int(2));
            assert_eq!(rows[0][1], Value::Str("Grace".into()), "pre-image");
        }
        other => panic!("expected rows, got {other:?}"),
    }
    // The row is actually gone.
    match engine.execute_sql("SELECT id FROM User").unwrap() {
        QueryResult::Rows { rows, .. } => assert_eq!(rows.len(), 1),
        other => panic!("expected rows, got {other:?}"),
    }
}

/// PowQL's `returning` is all-columns, so a projected `RETURNING id, name` is
/// rejected with a clear error rather than silently returning every column.
#[test]
fn sql_returning_column_list_is_unsupported() {
    let err = powdb_query::sql::parse_sql(
        "INSERT INTO User (id, name) VALUES (1, 'Ada') RETURNING id, name",
    )
    .unwrap_err();
    assert!(
        err.to_string().contains("column projection"),
        "error should explain the column-projection limitation, got: {err}"
    );
}

// --- Ungrouped aggregates (regression: `SELECT count(*)` must aggregate) ------
//
// Before the fix the SQL frontend lowered `SELECT count(*) FROM T` as a *row
// projection* `T { count(*) }`, so it returned one null row per source row
// instead of a scalar count. `count(*)` is documented (docs/SQL.md) and is the
// README's headline SQL example, so this was a silent wrong-answer bug across
// both the server `QuerySql` path and the embedded addon.

/// `SELECT count(*) FROM T` must lower to PowQL's aggregate form `count(T)`.
#[test]
fn sql_count_star_lowers_to_powql_aggregate() {
    let parsed = powdb_query::sql::parse_sql_with_canonical("SELECT count(*) FROM T").unwrap();
    assert_eq!(parsed.canonical_powql, "count(T)");
}

#[test]
fn sql_count_star_aggregates_to_scalar() {
    let (_dir, mut engine) = seeded_engine();
    match engine.execute_sql("SELECT count(*) FROM T").unwrap() {
        QueryResult::Scalar(Value::Int(n)) => assert_eq!(n, 2),
        other => panic!("expected Scalar(2), got {other:?}"),
    }
}

#[test]
fn sql_count_star_with_where_filters_then_counts() {
    let (_dir, mut engine) = seeded_engine();
    match engine
        .execute_sql("SELECT count(*) FROM T WHERE x > 3")
        .unwrap()
    {
        QueryResult::Scalar(Value::Int(n)) => assert_eq!(n, 1),
        other => panic!("expected Scalar(1), got {other:?}"),
    }
}

#[test]
fn sql_count_star_alias_still_aggregates() {
    let (_dir, mut engine) = seeded_engine();
    match engine.execute_sql("SELECT count(*) AS n FROM T").unwrap() {
        QueryResult::Scalar(Value::Int(n)) => assert_eq!(n, 2),
        other => panic!("expected Scalar(2), got {other:?}"),
    }
}

#[test]
fn sql_sum_aggregates_to_scalar() {
    let (_dir, mut engine) = seeded_engine();
    match engine.execute_sql("SELECT sum(x) FROM T").unwrap() {
        QueryResult::Scalar(Value::Int(n)) => assert_eq!(n, 6),
        other => panic!("expected Scalar(6), got {other:?}"),
    }
}

#[test]
fn sql_max_aggregates_to_scalar() {
    let (_dir, mut engine) = seeded_engine();
    match engine.execute_sql("SELECT max(x) FROM T").unwrap() {
        QueryResult::Scalar(Value::Int(n)) => assert_eq!(n, 5),
        other => panic!("expected Scalar(5), got {other:?}"),
    }
}

/// PowQL has no single-statement form for several ungrouped aggregates at once,
/// so the SQL frontend must reject it with a clear error rather than silently
/// returning garbage rows.
#[test]
fn sql_multiple_ungrouped_aggregates_error_not_garbage() {
    let (_dir, mut engine) = seeded_engine();
    let r = engine.execute_sql("SELECT count(*), sum(x) FROM T");
    assert!(
        r.is_err(),
        "multiple ungrouped aggregates should error, got: {r:?}"
    );
}

/// Grouped `count(*)` was already correct (the planner extracts it per group);
/// the ungrouped-aggregate fix must not regress it. `x=5` appears twice.
#[test]
fn sql_grouped_count_star_counts_per_group() {
    let dir = tempfile::tempdir().unwrap();
    let mut engine = Engine::new(dir.path()).unwrap();
    engine
        .execute_powql("type T { required id: int, required x: int }")
        .unwrap();
    engine
        .execute_powql("insert T { id := 1, x := 1 }, { id := 2, x := 5 }, { id := 3, x := 5 }")
        .unwrap();
    match engine
        .execute_sql("SELECT x, count(*) FROM T GROUP BY x ORDER BY x")
        .unwrap()
    {
        QueryResult::Rows { rows, .. } => {
            assert_eq!(rows.len(), 2);
            assert_eq!(rows[0], vec![Value::Int(1), Value::Int(1)]);
            assert_eq!(rows[1], vec![Value::Int(5), Value::Int(2)]);
        }
        other => panic!("expected grouped rows, got {other:?}"),
    }
}

// ---------------------------------------------------------------------------
// Qualified column references in single-table statements (`t.col`).
//
// Regression suite for the v0.18.0 P0: in single-table SQL, `table.column`
// silently lowered to a join-style qualified ref that the executor resolved
// to Empty, so projections returned Empty, WHERE filters matched nothing
// (or everything, when negated ranges collapsed), UPDATE affected 0 rows,
// and DELETE removed every row (data loss). SQLite semantics: the qualifier
// resolves to the column when it names the (single) table or its alias, and
// is a hard error otherwise.
// ---------------------------------------------------------------------------

fn qualified_fixture() -> (tempfile::TempDir, Engine) {
    let dir = tempfile::tempdir().unwrap();
    let mut engine = Engine::new(dir.path()).unwrap();
    engine
        .execute_powql("type t { required id: int, required v: int }")
        .unwrap();
    engine
        .execute_powql("insert t { id := 1, v := 5 }, { id := 2, v := 50 }")
        .unwrap();
    (dir, engine)
}

#[test]
fn sql_qualified_projection_single_table_returns_values() {
    let (_dir, mut engine) = qualified_fixture();
    match engine
        .execute_sql("SELECT t.id FROM t ORDER BY t.id")
        .unwrap()
    {
        QueryResult::Rows { columns, rows } => {
            assert_eq!(columns, vec!["id"]);
            assert_eq!(rows, vec![vec![Value::Int(1)], vec![Value::Int(2)]]);
        }
        other => panic!("expected rows, got {other:?}"),
    }
}

#[test]
fn sql_qualified_where_eq_single_table_matches_row() {
    let (_dir, mut engine) = qualified_fixture();
    match engine
        .execute_sql("SELECT id FROM t WHERE t.id = 1")
        .unwrap()
    {
        QueryResult::Rows { rows, .. } => {
            assert_eq!(rows, vec![vec![Value::Int(1)]]);
        }
        other => panic!("expected rows, got {other:?}"),
    }
}

#[test]
fn sql_qualified_where_range_single_table_filters() {
    let (_dir, mut engine) = qualified_fixture();
    match engine
        .execute_sql("SELECT id FROM t WHERE t.v < 10")
        .unwrap()
    {
        QueryResult::Rows { rows, .. } => {
            assert_eq!(rows, vec![vec![Value::Int(1)]]);
        }
        other => panic!("expected rows, got {other:?}"),
    }
}

#[test]
fn sql_qualified_update_where_single_table_affects_matching_row() {
    let (_dir, mut engine) = qualified_fixture();
    match engine
        .execute_sql("UPDATE t SET v = 99 WHERE t.id = 1")
        .unwrap()
    {
        QueryResult::Modified(n) => assert_eq!(n, 1, "UPDATE must affect exactly the matching row"),
        other => panic!("expected Modified, got {other:?}"),
    }
    match engine.execute_sql("SELECT v FROM t WHERE id = 1").unwrap() {
        QueryResult::Rows { rows, .. } => assert_eq!(rows, vec![vec![Value::Int(99)]]),
        other => panic!("expected rows, got {other:?}"),
    }
}

#[test]
fn sql_qualified_update_set_rhs_single_table_reads_column() {
    let (_dir, mut engine) = qualified_fixture();
    match engine
        .execute_sql("UPDATE t SET v = t.v + 1 WHERE t.id = 2")
        .unwrap()
    {
        QueryResult::Modified(n) => assert_eq!(n, 1),
        other => panic!("expected Modified, got {other:?}"),
    }
    match engine.execute_sql("SELECT v FROM t WHERE id = 2").unwrap() {
        QueryResult::Rows { rows, .. } => assert_eq!(rows, vec![vec![Value::Int(51)]]),
        other => panic!("expected rows, got {other:?}"),
    }
}

/// The data-loss case: DELETE with a qualified WHERE must delete only the
/// matching row. The pre-fix behavior deleted BOTH rows.
#[test]
fn sql_qualified_delete_where_single_table_keeps_survivor() {
    let (_dir, mut engine) = qualified_fixture();
    match engine.execute_sql("DELETE FROM t WHERE t.v < 10").unwrap() {
        QueryResult::Modified(n) => assert_eq!(n, 1, "DELETE must remove only the matching row"),
        other => panic!("expected Modified, got {other:?}"),
    }
    match engine.execute_sql("SELECT id, v FROM t").unwrap() {
        QueryResult::Rows { rows, .. } => {
            assert_eq!(
                rows,
                vec![vec![Value::Int(2), Value::Int(50)]],
                "the non-matching row must survive"
            );
        }
        other => panic!("expected rows, got {other:?}"),
    }
}

#[test]
fn sql_qualified_order_by_single_table_sorts() {
    let (_dir, mut engine) = qualified_fixture();
    match engine
        .execute_sql("SELECT id FROM t ORDER BY t.v DESC")
        .unwrap()
    {
        QueryResult::Rows { rows, .. } => {
            assert_eq!(rows, vec![vec![Value::Int(2)], vec![Value::Int(1)]]);
        }
        other => panic!("expected rows, got {other:?}"),
    }
}

#[test]
fn sql_qualified_group_by_and_having_single_table() {
    let (_dir, mut engine) = qualified_fixture();
    engine
        .execute_powql("insert t { id := 3, v := 5 }")
        .unwrap();
    match engine
        .execute_sql("SELECT v, count(*) FROM t GROUP BY t.v HAVING t.v < 10 ORDER BY v")
        .unwrap()
    {
        QueryResult::Rows { rows, .. } => {
            assert_eq!(rows, vec![vec![Value::Int(5), Value::Int(2)]]);
        }
        other => panic!("expected grouped rows, got {other:?}"),
    }
}

#[test]
fn sql_qualified_expression_over_two_columns_single_table() {
    let (_dir, mut engine) = qualified_fixture();
    match engine
        .execute_sql("SELECT t.id + t.v AS s FROM t WHERE t.id + t.v > 10")
        .unwrap()
    {
        QueryResult::Rows { columns, rows } => {
            assert_eq!(columns, vec!["s"]);
            assert_eq!(rows, vec![vec![Value::Int(52)]]);
        }
        other => panic!("expected rows, got {other:?}"),
    }
}

/// A qualifier that names no table in the statement must be a hard error
/// (SQLite: "no such column: x.id"), never a silent Empty.
#[test]
fn sql_unknown_qualifier_in_projection_errors() {
    let (_dir, mut engine) = qualified_fixture();
    let r = engine.execute_sql("SELECT x.id FROM t");
    assert!(r.is_err(), "unknown qualifier must error, got: {r:?}");
}

#[test]
fn sql_unknown_qualifier_in_where_errors() {
    let (_dir, mut engine) = qualified_fixture();
    let r = engine.execute_sql("SELECT id FROM t WHERE x.id = 1");
    assert!(r.is_err(), "unknown qualifier must error, got: {r:?}");
    let r = engine.execute_sql("DELETE FROM t WHERE x.v < 10");
    assert!(
        r.is_err(),
        "unknown qualifier in DELETE must error, got: {r:?}"
    );
    match engine.execute_sql("SELECT id, v FROM t").unwrap() {
        QueryResult::Rows { rows, .. } => assert_eq!(rows.len(), 2, "no rows may be deleted"),
        other => panic!("expected rows, got {other:?}"),
    }
}

#[test]
fn sql_qualified_ref_matches_single_table_alias() {
    let (_dir, mut engine) = qualified_fixture();
    match engine
        .execute_sql("SELECT a.id FROM t AS a WHERE a.v < 10")
        .unwrap()
    {
        QueryResult::Rows { rows, .. } => assert_eq!(rows, vec![vec![Value::Int(1)]]),
        other => panic!("expected rows, got {other:?}"),
    }
}

/// Per SQL, an alias hides the table name: `SELECT t.id FROM t AS a` is an
/// error in SQLite ("no such column: t.id").
#[test]
fn sql_table_name_qualifier_hidden_by_alias_errors() {
    let (_dir, mut engine) = qualified_fixture();
    let r = engine.execute_sql("SELECT t.id FROM t AS a");
    assert!(r.is_err(), "alias must hide the table name, got: {r:?}");
}

/// Qualified refs make no sense in INSERT ... VALUES; they must error rather
/// than lower to a join-style ref.
#[test]
fn sql_qualified_ref_in_insert_values_errors() {
    let (_dir, mut engine) = qualified_fixture();
    let r = engine.execute_sql("INSERT INTO t (id, v) VALUES (t.id, 1)");
    assert!(r.is_err(), "qualified ref in VALUES must error, got: {r:?}");
}