reddb-io-server 1.43.21

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
use reddb_server::{RedDBError, RedDBOptions, RedDBRuntime};
use reddb_types::Value;

fn runtime_with_rows() -> RedDBRuntime {
    let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
    for sql in [
        "CREATE TABLE compat_l (row_no INT, join_code INT)",
        "INSERT INTO compat_l (row_no, join_code) VALUES (2,8),(1,7),(3,NULL),(4,7)",
        "CREATE TABLE compat_r (r_no INT, join_code INT)",
        "INSERT INTO compat_r (r_no, join_code) VALUES (10,7),(20,7),(30,9),(40,NULL)",
    ] {
        runtime.execute_query(sql).expect(sql);
    }
    runtime
}

#[test]
fn is_distinct_from_returns_a_boolean_for_nulls_and_values() {
    let runtime = runtime_with_rows();
    let result = runtime
        .execute_query(
            "SELECT NULL IS DISTINCT FROM NULL AS both_null,
                    2 IS DISTINCT FROM NULL AS right_null,
                    NULL IS DISTINCT FROM 2 AS left_null,
                    2 IS DISTINCT FROM 2.0 AS equal,
                    9007199254740992::bigint IS DISTINCT FROM 9007199254740993::bigint AS unequal,
                    2 = 2 IS DISTINCT FROM TRUE AS left_comparison,
                    FALSE IS DISTINCT FROM 2 = 2 AS right_comparison",
        )
        .expect("scalar distinctness comparisons");
    let [record] = result.result.records.as_slice() else {
        panic!("expected one scalar row");
    };
    for name in ["right_null", "left_null", "unequal", "right_comparison"] {
        assert_eq!(record.get(name), Some(&Value::Boolean(true)), "{name}");
    }
    for name in ["both_null", "equal", "left_comparison"] {
        assert_eq!(record.get(name), Some(&Value::Boolean(false)), "{name}");
    }
}

#[test]
fn is_distinct_from_filters_nulls_in_prepared_and_grouped_queries() {
    let runtime = runtime_with_rows();
    let prepared = runtime
        .execute_query_with_params(
            "SELECT row_no FROM compat_l WHERE (join_code IS DISTINCT FROM $1) ORDER BY row_no",
            &[Value::Null],
        )
        .expect("parameterized distinctness comparison");
    let row_numbers: Vec<_> = prepared
        .result
        .records
        .iter()
        .map(|row| row.get("row_no").cloned())
        .collect();
    assert_eq!(
        row_numbers,
        [1, 2, 4].map(|row_no| Some(Value::Integer(row_no)))
    );

    let aggregated = runtime
        .execute_query(
            "SELECT join_code AS code,
                    COUNT(*) FILTER (WHERE join_code IS DISTINCT FROM NULL) AS present
             FROM compat_l GROUP BY join_code
             HAVING (COUNT(*) IS DISTINCT FROM 2)
             ORDER BY code",
        )
        .expect("distinctness in aggregate predicates");
    let [with_code, no_code] = aggregated.result.records.as_slice() else {
        panic!("expected two groups with one row each");
    };
    assert_eq!(with_code.get("code"), Some(&Value::Integer(8)));
    assert_eq!(with_code.get("present"), Some(&Value::Integer(1)));
    assert_eq!(no_code.get("code"), Some(&Value::Null));
    assert_eq!(no_code.get("present"), Some(&Value::Integer(0)));
}

#[test]
fn is_not_distinct_from_returns_a_boolean_for_nulls_and_values() {
    let runtime = runtime_with_rows();
    let result = runtime
        .execute_query(
            "SELECT NULL IS NOT DISTINCT FROM NULL AS both_null,
                    2 IS NOT DISTINCT FROM NULL AS right_null,
                    NULL IS NOT DISTINCT FROM 2 AS left_null,
                    2 IS NOT DISTINCT FROM 2.0 AS equal,
                    9007199254740992::bigint IS NOT DISTINCT FROM 9007199254740993::bigint AS unequal,
                    2 = 2 IS NOT DISTINCT FROM TRUE AS left_comparison,
                    FALSE IS NOT DISTINCT FROM 2 = 3 AS right_comparison",
        )
        .expect("scalar null-safe comparisons");
    let [record] = result.result.records.as_slice() else {
        panic!("expected one scalar row");
    };
    for name in ["both_null", "equal", "left_comparison", "right_comparison"] {
        assert_eq!(record.get(name), Some(&Value::Boolean(true)), "{name}");
    }
    for name in ["right_null", "left_null", "unequal"] {
        assert_eq!(record.get(name), Some(&Value::Boolean(false)), "{name}");
    }
}

#[test]
fn is_not_distinct_from_filters_before_limit_and_binds_parameters() {
    let runtime = runtime_with_rows();
    for result in [
        runtime.execute_query(
            "SELECT row_no FROM compat_l
             WHERE join_code IS NOT DISTINCT FROM NULL LIMIT 1",
        ),
        runtime.execute_query_with_params(
            "SELECT row_no FROM compat_l WHERE join_code IS NOT DISTINCT FROM $1",
            &[Value::Null],
        ),
        runtime.execute_query(
            "SELECT row_no FROM compat_l
             WHERE row_no = 3 IS NOT DISTINCT FROM TRUE",
        ),
    ] {
        let result = result.expect("null-safe WHERE comparison");
        let [row] = result.result.records.as_slice() else {
            panic!("expected only the NULL join key");
        };
        assert_eq!(row.get("row_no"), Some(&Value::Integer(3)));
    }
}

#[test]
fn is_not_distinct_from_works_with_filtered_and_correlated_aggregates() {
    let runtime = runtime_with_rows();
    let result = runtime
        .execute_query(
            "SELECT l.join_code AS code,
                    COUNT(*) FILTER (WHERE l.join_code IS NOT DISTINCT FROM NULL) AS missing
             FROM compat_l l GROUP BY l.join_code
             HAVING EXISTS (SELECT 1 FROM compat_r r
                 WHERE r.join_code IS NOT DISTINCT FROM l.join_code)
             ORDER BY code",
        )
        .expect("null-safe correlated predicate");
    let [with_code, no_code] = result.result.records.as_slice() else {
        panic!("expected the non-null and NULL matches");
    };
    assert_eq!(with_code.get("code"), Some(&Value::Integer(7)));
    assert_eq!(with_code.get("missing"), Some(&Value::Integer(0)));
    assert_eq!(no_code.get("code"), Some(&Value::Null));
    assert_eq!(no_code.get("missing"), Some(&Value::Integer(1)));

    let result = runtime
        .execute_query(
            "SELECT COUNT(*) AS total FROM compat_l l CROSS JOIN compat_r r
             WHERE l.join_code IS NOT DISTINCT FROM r.join_code",
        )
        .expect("null-safe comparison on joined rows");
    assert_eq!(
        result.result.records[0].get("total"),
        Some(&Value::Integer(5))
    );
}

#[test]
fn having_exists_binds_outer_aggregates_and_group_keys() {
    let runtime = runtime_with_rows();
    for sql in [
        "CREATE TABLE exists_targets (total INT, match_code INT)",
        "INSERT INTO exists_targets (total, match_code) VALUES (5,7),(5,7),(2,8),(3,99),(NULL,NULL)",
    ] {
        runtime.execute_query(sql).expect(sql);
    }

    let sql = "SELECT l.join_code AS code, SUM(DISTINCT row_no) FILTER (WHERE row_no > 10) AS total
               FROM compat_l l GROUP BY code
               HAVING EXISTS (SELECT 1 / 0 FROM exists_targets r
                   WHERE r.total = SUM(DISTINCT l.row_no) AND r.match_code = l.join_code)
               ORDER BY code";
    let result = runtime.execute_query(sql).expect("correlated aggregate");
    let [first, second] = result.result.records.as_slice() else {
        panic!("expected only the two matching groups");
    };
    assert_eq!(first.get("code"), Some(&Value::Integer(7)));
    assert_eq!(second.get("code"), Some(&Value::Integer(8)));
    assert_eq!(first.get("total"), Some(&Value::Null));
    assert_eq!(second.get("total"), Some(&Value::Null));

    let result = runtime
        .execute_query_with_params(
            "SELECT join_code AS code FROM compat_l l GROUP BY join_code
             HAVING EXISTS (SELECT 1 FROM exists_targets r
                 WHERE r.match_code = l.join_code AND r.total = $1)",
            &[Value::Integer(2)],
        )
        .expect("prepared inner predicate");
    assert_eq!(result.result.records.len(), 1);
    assert_eq!(
        result.result.records[0].get("code"),
        Some(&Value::Integer(8))
    );

    let result = runtime
        .execute_query(
            "SELECT COUNT(*) AS total FROM compat_l
             HAVING EXISTS (SELECT 1 FROM exists_targets r
                 WHERE r.total = SUM(DISTINCT compat_l.join_code) - 10)",
        )
        .expect("single implicit group without GROUP BY");
    assert_eq!(
        result.result.records[0].get("total"),
        Some(&Value::Integer(4))
    );

    let result = runtime
        .execute_query(
            "SELECT l.join_code AS code FROM compat_l l GROUP BY l.join_code
             HAVING EXISTS (SELECT 1 FROM exists_targets r WHERE r.match_code = l.join_code OFFSET 1)
                AND NOT EXISTS (SELECT 1 FROM exists_targets r WHERE r.match_code = l.join_code LIMIT 0)",
        )
        .expect("pagination and qualified group key");
    assert_eq!(result.result.records.len(), 1);
    assert_eq!(
        result.result.records[0].get("code"),
        Some(&Value::Integer(7))
    );
}

#[test]
fn having_exists_rejects_inner_aggregates_and_ungrouped_columns() {
    let runtime = runtime_with_rows();
    assert!(runtime
        .execute_query("SELECT row_no FROM compat_l WHERE EXISTS (SELECT 1 FROM compat_r)")
        .is_err());
    for (predicate, message) in [
        (
            "SUM(DISTINCT l.row_no + r.r_no) = r.r_no",
            "aggregate functions are not allowed in WHERE",
        ),
        (
            "SUM(r.r_no) > 0",
            "aggregate functions are not allowed in WHERE",
        ),
        ("l.row_no = r.r_no", "subquery uses ungrouped column row_no"),
    ] {
        let sql = format!(
            "SELECT COUNT(*) FROM compat_l l GROUP BY join_code
             HAVING EXISTS (SELECT 1 FROM compat_r r WHERE {predicate})"
        );
        let error = runtime.execute_query(&sql).expect_err(&sql).to_string();
        assert!(error.contains(message), "{error}");
    }
}

#[test]
fn having_exists_checks_inner_row_policies_and_cache_dependencies() {
    let runtime = runtime_with_rows();
    runtime
        .execute_query("SET CONFIG runtime.result_cache.enabled = true")
        .unwrap();
    runtime
        .execute_query("CREATE POLICY visible ON compat_r FOR SELECT USING (r_no = 30)")
        .unwrap();
    runtime
        .execute_query("ALTER TABLE compat_r ENABLE ROW LEVEL SECURITY")
        .unwrap();
    let sql = "SELECT l.join_code AS code FROM compat_l l GROUP BY l.join_code
               HAVING EXISTS (SELECT 1 FROM compat_r r WHERE r.join_code = l.join_code)";
    assert!(runtime
        .execute_query(sql)
        .unwrap()
        .result
        .records
        .is_empty());
    runtime
        .execute_query("INSERT INTO compat_r (r_no, join_code) VALUES (30,8)")
        .unwrap();
    let result = runtime.execute_query(sql).unwrap();
    assert_eq!(result.result.records.len(), 1);
    assert_eq!(
        result.result.records[0].get("code"),
        Some(&Value::Integer(8))
    );
}

#[test]
fn text_cast_regex_filters_distinct_aggregate_inputs() {
    let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
    for sql in [
        "CREATE TABLE regex_values (bucket INT, n INT, pattern TEXT)",
        "INSERT INTO regex_values (bucket, n, pattern) VALUES (1,123,'^123$'),(1,123,'never'),(1,9123,'123'),(1,8,'8'),(2,NULL,'.'),(2,42,'^9'),(3,-123,'^-')",
    ] {
        runtime.execute_query(sql).expect(sql);
    }
    let result = runtime
        .execute_query("SELECT bucket, SUM(DISTINCT n) FILTER (WHERE n::text ~ '123') AS total, COUNT(*) FILTER (WHERE n::text ~ pattern) AS matched FROM regex_values GROUP BY bucket ORDER BY bucket")
        .expect("regex in independent aggregate filters");
    let [first, second, third] = result.result.records.as_slice() else {
        panic!("expected three groups");
    };
    assert_eq!(first.get("total"), Some(&Value::Integer(9246)));
    assert_eq!(first.get("matched"), Some(&Value::Integer(3)));
    assert_eq!(second.get("total"), Some(&Value::Null));
    assert_eq!(second.get("matched"), Some(&Value::Integer(0)));
    assert_eq!(third.get("total"), Some(&Value::Integer(-123)));
    assert_eq!(third.get("matched"), Some(&Value::Integer(1)));

    let result = runtime
        .execute_query(
            "SELECT COUNT(*) AS matched FROM regex_values WHERE n::text ~ '^12' AND bucket = 1",
        )
        .expect("regex in a WHERE predicate");
    assert_eq!(
        result.result.records[0].get("matched"),
        Some(&Value::Integer(2))
    );

    let result = runtime
        .execute_query("SELECT 'Alpha' ~ '(?i)^a' AS matched")
        .expect("quoted regex flags remain in SQL mode");
    assert_eq!(
        result.result.records[0].get("matched"),
        Some(&Value::Boolean(true))
    );

    let error = runtime
        .execute_query("SELECT COUNT(*) FILTER (WHERE n::text ~ '[') FROM regex_values")
        .expect_err("malformed regex must fail");
    assert!(
        error.to_string().contains("invalid regular expression"),
        "{error}"
    );
}

#[test]
fn text_cast_regex_in_a_join_filter_uses_qualified_columns() {
    let runtime = runtime_with_rows();
    let result = runtime
        .execute_query("SELECT SUM(DISTINCT r.r_no) FILTER (WHERE r.r_no::text ~ '^1') AS total FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code")
        .expect("regex filter on a joined aggregate");
    assert_eq!(
        result.result.records[0].get("total"),
        Some(&Value::Integer(10))
    );
}

#[test]
fn sum_distinct_filters_before_deduplication_and_sums_exactly() {
    let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
    for sql in [
        "CREATE TABLE distinct_values (bucket INT, n BIGINT, divisor INT, keep BOOLEAN)",
        "INSERT INTO distinct_values (bucket, n, divisor, keep) VALUES (1,9007199254740993,2,TRUE),(1,9007199254740993,2,TRUE),(1,9007199254740994,1,TRUE),(1,NULL,NULL,TRUE),(1,100,0,FALSE),(2,1,0,NULL)",
    ] {
        runtime.execute_query(sql).expect(sql);
    }
    let result = runtime
        .execute_query("SELECT bucket, SUM(DISTINCT n) FILTER (WHERE keep) AS exact, SUM(DISTINCT n) FILTER (WHERE NOT keep) AS rejected, SUM(DISTINCT 6 / divisor + 1) FILTER (WHERE keep) AS quotients FROM distinct_values GROUP BY bucket ORDER BY bucket")
        .expect("sum separate sets of admitted values");
    let [first, second] = result.result.records.as_slice() else {
        panic!("expected two groups");
    };
    assert_eq!(
        first.get("exact"),
        Some(&Value::Integer(18_014_398_509_481_987))
    );
    assert_eq!(first.get("rejected"), Some(&Value::Integer(100)));
    assert_eq!(first.get("quotients"), Some(&Value::Integer(11)));
    assert_eq!(second.get("exact"), Some(&Value::Null));
    assert_eq!(second.get("quotients"), Some(&Value::Null));

    let result = runtime
        .execute_query("SELECT bucket, SUM(DISTINCT divisor) FILTER (WHERE keep) AS total FROM distinct_values GROUP BY bucket HAVING SUM(DISTINCT divisor) FILTER (WHERE keep) > 0 ORDER BY SUM(DISTINCT n) FILTER (WHERE keep)")
        .expect("use filtered sums in HAVING and ORDER BY");
    assert_eq!(result.result.records.len(), 1);
    assert_eq!(
        result.result.records[0].get("total"),
        Some(&Value::Integer(3))
    );
}

#[test]
fn sum_distinct_over_a_join_counts_repeated_values_once() {
    let runtime = runtime_with_rows();
    let result = runtime
        .execute_query("SELECT SUM(DISTINCT r.r_no) FILTER (WHERE l.row_no > 0) AS unique_right, SUM(r.r_no) AS all_right, SUM(DISTINCT l.row_no) AS unique_left FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code")
        .expect("aggregate distinct join values");
    let record = &result.result.records[0];
    assert_eq!(record.get("unique_right"), Some(&Value::Integer(30)));
    assert_eq!(record.get("all_right"), Some(&Value::Integer(60)));
    assert_eq!(record.get("unique_left"), Some(&Value::Integer(5)));
}

#[test]
fn aggregate_filters_skip_rows_before_argument_evaluation() {
    let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
    for sql in [
        "CREATE TABLE filtered_rows (bucket INT, divisor INT, keep BOOLEAN)",
        "INSERT INTO filtered_rows (bucket, divisor, keep) VALUES (1,2,TRUE),(1,0,FALSE),(1,NULL,TRUE),(2,0,NULL)",
    ] {
        runtime.execute_query(sql).expect(sql);
    }
    let result = runtime
        .execute_query("SELECT bucket, COUNT(*) AS total, COUNT(*) FILTER (WHERE keep) AS kept, COUNT(divisor) FILTER (WHERE keep) AS non_null, SUM(6 / divisor) FILTER (WHERE keep) AS quotient, SUM(divisor) FILTER (WHERE NOT keep) AS rejected_sum, ARRAY_AGG(divisor) FILTER (WHERE keep AND divisor IS NULL) AS null_items FROM filtered_rows GROUP BY bucket ORDER BY bucket")
        .expect("apply independent aggregate filters");
    let [first, second] = result.result.records.as_slice() else {
        panic!("expected both groups");
    };
    assert_eq!(first.get("total"), Some(&Value::Integer(3)));
    assert_eq!(first.get("kept"), Some(&Value::Integer(2)));
    assert_eq!(first.get("non_null"), Some(&Value::Integer(1)));
    assert_eq!(first.get("quotient"), Some(&Value::Integer(3)));
    assert_eq!(first.get("rejected_sum"), Some(&Value::Integer(0)));
    assert_eq!(
        first.get("null_items"),
        Some(&Value::Array(vec![Value::Null]))
    );
    assert_eq!(second.get("total"), Some(&Value::Integer(1)));
    assert_eq!(second.get("kept"), Some(&Value::Integer(0)));
    assert_eq!(second.get("quotient"), Some(&Value::Null));
    assert_eq!(second.get("null_items"), Some(&Value::Null));

    let result = runtime
        .execute_query("SELECT bucket, COUNT(*) AS total FROM filtered_rows GROUP BY bucket HAVING COUNT(*) FILTER (WHERE keep) > 0 ORDER BY SUM(divisor) FILTER (WHERE keep)")
        .expect("use filtered aggregates in HAVING and ORDER BY");
    assert_eq!(result.result.records.len(), 1);
    assert_eq!(
        result.result.records[0].get("bucket"),
        Some(&Value::Integer(1))
    );

    let result = runtime
        .execute_query("SELECT COUNT(DISTINCT divisor) FILTER (WHERE keep) AS total FROM filtered_rows WHERE FALSE")
        .expect("return count zero for empty input");
    assert_eq!(
        result.result.records[0].get("total"),
        Some(&Value::Integer(0))
    );
}

#[test]
fn join_aggregate_filters_use_both_sides_and_preserve_null_extended_rows() {
    let runtime = runtime_with_rows();
    let result = runtime
        .execute_query("SELECT COUNT(*) AS total, COUNT(*) FILTER (WHERE r.r_no IS NULL) AS unmatched, COUNT(r.r_no) FILTER (WHERE l.row_no > 1) AS non_null, SUM(l.row_no + r.r_no) FILTER (WHERE r.r_no = 10) AS total_low, AVG(r.r_no) FILTER (WHERE l.row_no = 1) AS average FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code")
        .expect("aggregate filtered outer join");
    let record = &result.result.records[0];
    assert_eq!(record.get("total"), Some(&Value::Integer(6)));
    assert_eq!(record.get("unmatched"), Some(&Value::Integer(2)));
    assert_eq!(record.get("non_null"), Some(&Value::Integer(2)));
    assert_eq!(record.get("total_low"), Some(&Value::Integer(25)));
    assert_eq!(
        record.get("average"),
        Some(&Value::DecimalText("15.0000000000000000".into()))
    );

    let result = runtime
        .execute_query("SELECT l.row_no AS id, COUNT(*) AS total FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code GROUP BY l.row_no HAVING SUM(r.r_no) FILTER (WHERE r.r_no > 15) > 0 ORDER BY id")
        .expect("use a hidden filtered aggregate on an outer join");
    let [first, second] = result.result.records.as_slice() else {
        panic!("expected two groups");
    };
    assert_eq!(first.get("id"), Some(&Value::Integer(1)));
    assert_eq!(second.get("id"), Some(&Value::Integer(4)));
}

#[test]
fn count_star_aggregates_filtered_join_rows_before_pagination() {
    let runtime = runtime_with_rows();
    for (suffix, expected) in [
        ("", Some(4)),
        (" WHERE l.row_no < 0", Some(0)),
        (" LIMIT 1", Some(4)),
        (" LIMIT 0", None),
        (" OFFSET 1", None),
    ] {
        let result = runtime
            .execute_query(&format!(
                "SELECT COUNT(*) AS total FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code{suffix}"
            ))
            .expect("count join");
        assert_eq!(
            result.result.records.len(),
            usize::from(expected.is_some()),
            "{suffix}"
        );
        if let Some(expected) = expected {
            assert_eq!(
                result.result.records[0].get("total"),
                Some(&Value::Integer(expected))
            );
        }
    }
}

#[test]
fn sum_and_avg_aggregate_join_matches_before_pagination() {
    let runtime = runtime_with_rows();
    let result = runtime
        .execute_query("SELECT SUM(l.row_no) AS total, AVG(r.r_no) AS average, COUNT(*) AS pairs FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code WHERE l.row_no > 1 LIMIT 1")
        .expect("aggregate joined rows");
    assert_eq!(result.result.records.len(), 1);
    let record = &result.result.records[0];
    assert_eq!(record.get("total"), Some(&Value::Integer(8)));
    assert_eq!(
        record.get("average"),
        Some(&Value::DecimalText("15.0000000000000000".into()))
    );
    assert_eq!(record.get("pairs"), Some(&Value::Integer(2)));
    for predicate in ["l.row_no < 0", "l.row_no = 2"] {
        let result = runtime
            .execute_query(&format!(
                "SELECT SUM(r.r_no) AS total, AVG(r.r_no) AS average FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code WHERE {predicate}"
            ))
            .expect("aggregate join with no non-null inputs");
        assert_eq!(result.result.records.len(), 1);
        assert_eq!(result.result.records[0].get("total"), Some(&Value::Null));
        assert_eq!(result.result.records[0].get("average"), Some(&Value::Null));
    }
}

#[test]
fn outer_join_aggregates_keep_same_named_columns_on_their_own_side() {
    let runtime = runtime_with_rows();
    for sql in [
        "CREATE TABLE compat_amt_l (id INT, amount INT)",
        "INSERT INTO compat_amt_l (id, amount) VALUES (1,8),(2,17),(3,4)",
        "CREATE TABLE compat_amt_r (id INT, amount INT)",
        "INSERT INTO compat_amt_r (id, amount) VALUES (1,3),(1,6),(2,NULL),(4,31)",
    ] {
        runtime.execute_query(sql).expect(sql);
    }
    let result = runtime
        .execute_query("SELECT SUM(l.amount) AS lhs, SUM(r.amount) AS rhs, AVG(r.amount) AS average FROM compat_amt_l l FULL OUTER JOIN compat_amt_r r ON l.id = r.id")
        .expect("aggregate each side of the full outer join");
    assert_eq!(result.result.records.len(), 1);
    let record = &result.result.records[0];
    assert_eq!(record.get("lhs"), Some(&Value::Integer(37)));
    assert_eq!(record.get("rhs"), Some(&Value::Integer(40)));
    assert_eq!(
        record.get("average"),
        Some(&Value::DecimalText("13.3333333333333333".into()))
    );
    let result = runtime
        .execute_query("SELECT SUM(l.amount) AS lhs FROM compat_amt_l l LEFT JOIN compat_amt_r r ON l.id = r.id WHERE r.amount IS NULL")
        .expect("filter null-extended and explicitly null inputs");
    assert_eq!(
        result.result.records[0].get("lhs"),
        Some(&Value::Integer(21))
    );
    let result = runtime
        .execute_query("SELECT SUM(l.amount + r.amount) AS total FROM compat_amt_l l LEFT JOIN compat_amt_r r ON l.id = r.id")
        .expect("arithmetic uses the input scope and preserves NULL");
    assert_eq!(
        result.result.records[0].get("total"),
        Some(&Value::Integer(25))
    );
}

#[test]
fn aggregate_join_arguments_evaluate_arithmetic_before_accumulating() {
    let runtime = runtime_with_rows();
    let result = runtime
        .execute_query("SELECT SUM(l.row_no + r.r_no) AS total, AVG(r.r_no - l.row_no) AS average, SUM(5 / 2) AS integer_division, SUM(5.0 / 2) AS float_division FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code")
        .expect("numeric expressions over both inputs");
    let record = &result.result.records[0];
    assert_eq!(record.get("total"), Some(&Value::Integer(70)));
    assert_eq!(
        record.get("average"),
        Some(&Value::DecimalText("12.5000000000000000".into()))
    );
    assert_eq!(record.get("integer_division"), Some(&Value::Integer(8)));
    assert_eq!(record.get("float_division"), Some(&Value::Integer(10)));
}

#[test]
fn integer_division_preserves_precision_in_aggregates_and_updates() {
    let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
    for sql in [
        "CREATE TABLE quotients (n BIGINT, d INTEGER)",
        "INSERT INTO quotients (n, d) VALUES (9007199254740995,2),(5,2),(NULL,2)",
    ] {
        runtime.execute_query(sql).expect(sql);
    }
    let result = runtime
        .execute_query("SELECT SUM(n / d) AS total FROM quotients")
        .expect("aggregate the quotients");
    assert_eq!(
        result.result.records[0].get("total"),
        Some(&Value::Integer(4_503_599_627_370_499))
    );
    runtime
        .execute_query("UPDATE quotients SET n = n / d WHERE n / d = 4503599627370497")
        .expect("update the matching row");
    let result = runtime
        .execute_query("SELECT n FROM quotients WHERE n > 100")
        .expect("read the updated quotient");
    assert_eq!(result.result.records.len(), 1);
    assert_eq!(
        result.result.records[0].get("n"),
        Some(&Value::BigInt(4_503_599_627_370_497))
    );
}

#[test]
fn sum_join_integers_preserves_values_beyond_float_and_signed_integer_ranges() {
    let runtime = runtime_with_rows();
    let result = runtime
        .execute_query("SELECT AVG(9007199254740993) AS large_avg, SUM(9007199254740993) AS total, SUM(9223372036854775807) AS wide, SUM(9007199254740993 + 0) AS integer_total, SUM(9007199254740993 + 0.0) AS float_total FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code")
        .expect("integer SUM remains exact even when sharing an AVG input");
    let record = &result.result.records[0];
    assert_eq!(
        record.get("large_avg"),
        Some(&Value::DecimalText("9007199254740993.0000".into()))
    );
    assert_eq!(
        record.get("total"),
        Some(&Value::Integer(36_028_797_018_963_972))
    );
    assert_eq!(
        record.get("wide"),
        Some(&Value::DecimalText("36893488147419103228".into()))
    );
    assert_eq!(
        record.get("integer_total"),
        Some(&Value::Integer(36_028_797_018_963_972))
    );
    assert_eq!(
        record.get("float_total"),
        Some(&Value::Integer(36_028_797_018_963_968))
    );
}

#[test]
fn group_by_join_aggregates_orders_and_paginates_groups() {
    let runtime = runtime_with_rows();
    let result = runtime
        .execute_query("SELECT r.r_no AS bucket, SUM(l.row_no + r.r_no) AS total, AVG(l.row_no) AS average, COUNT(*) AS pairs FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code WHERE l.row_no > 0 GROUP BY r_no ORDER BY total DESC, 1 DESC LIMIT 1 OFFSET 1")
        .expect("grouping, then ordering and pagination");
    assert_eq!(result.result.records.len(), 1);
    let record = &result.result.records[0];
    assert_eq!(record.get("bucket"), Some(&Value::Integer(10)));
    assert_eq!(record.get("total"), Some(&Value::Integer(25)));
    assert_eq!(
        record.get("average"),
        Some(&Value::DecimalText("2.5000000000000000".into()))
    );
    assert_eq!(record.get("pairs"), Some(&Value::Integer(2)));
    assert!(runtime
        .execute_query("SELECT l.row_no, COUNT(*) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no")
        .expect_err("invalid ungrouped projection")
        .to_string()
        .contains("must appear in GROUP BY"));
}

#[test]
fn having_on_join_filters_with_hidden_aggregates_before_pagination() {
    let runtime = runtime_with_rows();
    let result = runtime
        .execute_query("SELECT r.r_no AS bucket FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no HAVING SUM(l.row_no + r.r_no) > 25 AND COUNT(*) = 2 ORDER BY bucket LIMIT 1")
        .expect("HAVING uses aggregates outside SELECT");
    assert_eq!(result.result.columns, vec!["bucket"]);
    assert_eq!(result.result.records.len(), 1);
    assert_eq!(
        result.result.records[0].get("bucket"),
        Some(&Value::Integer(20))
    );
    assert_eq!(result.result.records[0].column_names().len(), 1);

    let result = runtime
        .execute_query("SELECT r.r_no AS bucket FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no HAVING SUM(r.r_no) >= 20 ORDER BY bucket NULLS FIRST LIMIT 1 OFFSET 1")
        .expect("exclude unknown HAVING before OFFSET");
    assert_eq!(result.result.records.len(), 1);
    assert_eq!(
        result.result.records[0].get("bucket"),
        Some(&Value::Integer(20))
    );
}

#[test]
fn avg_join_integers_keeps_fractional_precision_after_cancellation() {
    let runtime = runtime_with_rows();
    runtime
        .execute_query("CREATE TABLE compat_avg (row_no INT, amount BIGINT)")
        .expect("table");
    runtime.execute_query("INSERT INTO compat_avg (row_no, amount) VALUES (1,9007199254740993),(1,-9007199254740992),(1,0),(1,NULL)").expect("amounts");
    let result = runtime
        .execute_query("SELECT AVG(a.amount) AS average, AVG(-a.amount) AS negative, AVG(l.row_no + 0.5) AS float_avg FROM compat_avg a JOIN compat_l l ON l.row_no = a.row_no")
        .expect("average exact inputs before rounding");
    let record = &result.result.records[0];
    assert_eq!(
        record.get("average"),
        Some(&Value::DecimalText("0.33333333333333333333".into()))
    );
    assert_eq!(
        record.get("negative"),
        Some(&Value::DecimalText("-0.33333333333333333333".into()))
    );
    assert_eq!(record.get("float_avg"), Some(&Value::Float(1.5)));
}

#[test]
fn avg_join_integers_remains_numeric_in_having_and_order_by() {
    let runtime = runtime_with_rows();
    let result = runtime
        .execute_query("SELECT r.r_no AS bucket, AVG(l.row_no + r.r_no) AS average FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no HAVING AVG(l.row_no + r.r_no) BETWEEN 12.49 AND 22.51 AND AVG(9007199254740993) > 9007199254740992 ORDER BY average DESC")
        .expect("decimal averages compare numerically");
    let records = &result.result.records;
    assert_eq!(records.len(), 2);
    assert_eq!(records[0].get("bucket"), Some(&Value::Integer(20)));
    assert_eq!(records[1].get("bucket"), Some(&Value::Integer(10)));
    let result = runtime
        .execute_query("SELECT r.r_no AS bucket FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no HAVING AVG(l.row_no + r.r_no) + 1.0 > 20.0")
        .expect("AVG values still work with arithmetic in HAVING");
    assert_eq!(result.result.records.len(), 1);
    assert_eq!(
        result.result.records[0].get("bucket"),
        Some(&Value::Integer(20))
    );
}

#[test]
fn having_on_join_checks_group_columns_nulls_and_wide_integer_sums() {
    let runtime = runtime_with_rows();
    let result = runtime
        .execute_query("SELECT COUNT(*) AS pairs FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no HAVING r_no IS NULL AND SUM(r.r_no) IS NULL")
        .expect("HAVING can inspect a hidden group key and NULL aggregate");
    assert_eq!(result.result.records.len(), 1);
    assert_eq!(
        result.result.records[0].get("pairs"),
        Some(&Value::Integer(2))
    );
    let result = runtime
        .execute_query("SELECT r.r_no AS bucket FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no HAVING SUM(9223372036854775807) > 9223372036854775807")
        .expect("HAVING preserves exact comparison of sums above i64");
    assert_eq!(result.result.records.len(), 2);

    let error = runtime
        .execute_query("SELECT COUNT(*) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no HAVING l.row_no > 1")
        .expect_err("HAVING must reject ungrouped input columns");
    assert!(error.to_string().contains("must appear in GROUP BY"));
}

#[test]
fn group_by_outer_join_combines_null_keys_and_omits_empty_groups() {
    let runtime = runtime_with_rows();
    let result = runtime
        .execute_query("SELECT COUNT(*) AS pairs FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no, l.join_code ORDER BY r.r_no DESC NULLS FIRST, l.join_code DESC NULLS LAST")
        .expect("sort by unprojected keys, including NULL");
    let actual: Vec<_> = result
        .result
        .records
        .iter()
        .map(|row| row.get("pairs").cloned())
        .collect();
    assert_eq!(
        actual,
        vec![
            Some(Value::Integer(1)),
            Some(Value::Integer(1)),
            Some(Value::Integer(2)),
            Some(Value::Integer(2)),
        ]
    );
    let result = runtime
        .execute_query("SELECT r.r_no AS bucket, COUNT(*) AS pairs FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no ORDER BY bucket DESC NULLS FIRST")
        .expect("all missing right keys form a single NULL group");
    let records = &result.result.records;
    assert_eq!(records.len(), 3);
    assert_eq!(records[0].get("bucket"), Some(&Value::Null));
    assert_eq!(records[0].get("pairs"), Some(&Value::Integer(2)));
    assert_eq!(records[1].get("bucket"), Some(&Value::Integer(20)));
    assert_eq!(records[2].get("bucket"), Some(&Value::Integer(10)));
    let result = runtime
        .execute_query("SELECT r.r_no AS bucket FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code WHERE l.row_no < 0 GROUP BY r.r_no")
        .expect("empty grouped input");
    assert!(result.result.records.is_empty());
    runtime
        .execute_query("SET CONFIG stream.executor.max_materialized_rows = 1")
        .expect("set group limit");
    let error = runtime
        .execute_query("SELECT COUNT(*) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no")
        .expect_err("second group exceeds the materialization limit");
    assert!(matches!(
        error,
        RedDBError::MaterializationLimitExceeded {
            executor: "aggregation",
            limit: 1,
            current: 2,
        }
    ));
}

#[test]
fn group_by_join_authorizes_unprojected_group_columns() {
    use reddb_server::auth::{
        policies::Policy, store::PrincipalRef, AuthConfig, AuthStore, Role, UserId,
    };
    use reddb_server::runtime::mvcc::{clear_current_auth_identity, set_current_auth_identity};
    use std::sync::Arc;

    let runtime = runtime_with_rows();
    let store = Arc::new(AuthStore::new(AuthConfig::default()));
    store
        .create_user("reader", "p", Role::Write)
        .expect("reader");
    let policy = Policy::from_json_str(r#"{
        "id":"join-group-columns","version":1,"statements":[
            {"effect":"allow","actions":["select"],"resources":["database:*","table:compat_l","table:compat_r"]},
            {"effect":"deny","actions":["select"],"resources":["column:compat_r.r_no"]}
        ]
    }"#).expect("policy");
    store.put_policy(policy).expect("store policy");
    store
        .attach_policy(
            PrincipalRef::User(UserId::platform("reader")),
            "join-group-columns",
        )
        .expect("attach policy");
    runtime.set_auth_store(store);

    set_current_auth_identity("reader".to_string(), Role::Write);
    let allowed = runtime.execute_query("SELECT COUNT(*) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY l.row_no");
    let denied = runtime.execute_query("SELECT COUNT(*) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no");
    let denied_having = runtime.execute_query("SELECT COUNT(*) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY l.row_no HAVING SUM(r.r_no) > 0");
    let denied_filter = runtime.execute_query("SELECT SUM(l.row_no) FILTER (WHERE r.r_no > 0) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code");
    let denied_table_filter =
        runtime.execute_query("SELECT SUM(join_code) FILTER (WHERE r_no > 0) FROM compat_r");
    let denied_distinct = runtime.execute_query("SELECT SUM(DISTINCT r.r_no + 1) FILTER (WHERE FALSE) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code");
    let denied_table_distinct =
        runtime.execute_query("SELECT SUM(DISTINCT r_no + 1) FILTER (WHERE FALSE) FROM compat_r");
    let denied_exists_inner = runtime.execute_query(
        "SELECT COUNT(*) FROM compat_l l GROUP BY join_code
         HAVING EXISTS (SELECT 1 FROM compat_r r WHERE r.r_no = l.join_code)",
    );
    let denied_exists_outer = runtime.execute_query(
        "SELECT COUNT(*) FROM compat_r r GROUP BY join_code
         HAVING EXISTS (SELECT 1 FROM compat_l l WHERE SUM(r.r_no) = l.join_code)",
    );
    clear_current_auth_identity();

    assert_eq!(allowed.expect("allowed grouping").result.records.len(), 2);
    let error = denied.expect_err("protected grouping column").to_string();
    assert!(
        error.contains("cannot select column `compat_r.r_no`"),
        "{error}"
    );
    for denied in [
        denied_filter,
        denied_table_filter,
        denied_distinct,
        denied_table_distinct,
        denied_exists_inner,
        denied_exists_outer,
    ] {
        let error = denied
            .expect_err("protected aggregate filter column")
            .to_string();
        assert!(error.contains("compat_r.r_no"), "{error}");
    }
    let error = denied_having
        .expect_err("protected aggregate argument in HAVING")
        .to_string();
    assert!(
        error.contains("cannot select column `compat_r.r_no`"),
        "{error}"
    );
}

#[test]
fn join_order_uses_select_aliases_before_pagination() {
    let runtime = runtime_with_rows();
    for order in ["left_id DESC, right_id DESC", "1 DESC, 2 DESC"] {
        let result = runtime
            .execute_query(&format!(
                "SELECT l.row_no AS left_id, r.r_no AS right_id FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code ORDER BY {order} LIMIT 2"
            ))
            .expect("ordered join");
        let records = &result.result.records;
        assert_eq!(records.len(), 2);
        assert_eq!(records[0].get("left_id"), Some(&Value::Integer(4)));
        assert_eq!(records[0].get("right_id"), Some(&Value::Integer(20)));
        assert_eq!(records[1].get("left_id"), Some(&Value::Integer(4)));
        assert_eq!(records[1].get("right_id"), Some(&Value::Integer(10)));
    }
}

#[test]
fn distinct_order_by_ordinal_respects_projection_and_limit() {
    let runtime = runtime_with_rows();
    let result = runtime
        .execute_query("SELECT DISTINCT join_code AS code FROM compat_l ORDER BY 1 LIMIT 2")
        .expect("ordered distinct");
    let records = &result.result.records;
    assert_eq!(records.len(), 2);
    assert_eq!(records[0].get("code"), Some(&Value::Integer(7)));
    assert_eq!(records[1].get("code"), Some(&Value::Integer(8)));
    let result = runtime
        .execute_query(
            "SELECT DISTINCT join_code AS code FROM compat_l ORDER BY 1 LIMIT 1 OFFSET 1",
        )
        .expect("offset excludes distinct rows");
    assert_eq!(result.result.records.len(), 1);
    assert_eq!(
        result.result.records[0].get("code"),
        Some(&Value::Integer(8))
    );
    for position in [-1, 0, 2] {
        let error = runtime
            .execute_query(&format!(
                "SELECT DISTINCT join_code FROM compat_l ORDER BY {position}"
            ))
            .expect_err("position outside the SELECT list");
        assert!(error.to_string().contains("is not in the select list"));
    }
}

#[test]
fn unknown_sql_projection_function_fails_even_without_input_rows() {
    let runtime = runtime_with_rows();
    for sql in [
        "SELECT compat_unregistered_90321(row_no) AS result FROM compat_l WHERE row_no = 1",
        "SELECT compat_unregistered_90321(row_no) AS result FROM compat_l WHERE row_no < 0",
        "SELECT compat_unregistered_90321(1) AS result",
        "SELECT COALESCE(compat_unregistered_90321(row_no), 0) FROM compat_l",
        "SELECT compat_unregistered_90321(l.row_no) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code",
    ] {
        let error = runtime.execute_query(sql).expect_err(sql);
        assert!(error.to_string().contains("compat_unregistered_90321"));
    }
    let result = runtime
        .execute_query("SELECT LOWER(NULL) AS result FROM compat_l LIMIT 1")
        .expect("known function may return NULL");
    assert_eq!(result.result.records[0].get("result"), Some(&Value::Null));
    let result = runtime
        .execute_query("SELECT ROW_NUMBER() OVER (ORDER BY row_no) AS result FROM compat_l")
        .expect("window projections use their own evaluator");
    assert_eq!(result.result.records.len(), 4);
}