interstellar 0.2.0

A high-performance graph database with Gremlin-style traversals and GQL query language
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
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
//! Aggregation tests for GQL.
//!
//! Tests for aggregation functions and grouping including:
//! - COUNT, SUM, AVG, MIN, MAX, COLLECT
//! - COUNT(DISTINCT) and COLLECT(DISTINCT)
//! - GROUP BY clause
//! - HAVING clause
//! - Multiple aggregates in single query
//! - Empty result set handling

#![allow(unused_variables)]
use interstellar::prelude::*;
use interstellar::storage::Graph;
use std::collections::HashMap;
use std::sync::Arc;

// =============================================================================
// Aggregation Tests
// =============================================================================

/// Helper to create a test graph for aggregation tests
fn create_aggregation_test_graph() -> Arc<Graph> {
    let graph = Arc::new(Graph::new());

    // Create Person vertices with various ages and cities
    let people = vec![
        ("Alice", 30i64, "New York"),
        ("Bob", 25i64, "Boston"),
        ("Carol", 35i64, "New York"),
        ("Dave", 28i64, "Boston"),
        ("Eve", 22i64, "Chicago"),
    ];

    for (name, age, city) in people {
        let mut props = HashMap::new();
        props.insert("name".to_string(), Value::from(name));
        props.insert("age".to_string(), Value::from(age));
        props.insert("city".to_string(), Value::from(city));
        graph.add_vertex("Person", props);
    }

    graph
}

/// Test COUNT(*) - count all matches
#[test]
fn test_gql_count_star() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph.gql("MATCH (p:Person) RETURN count(*)").unwrap();

    assert_eq!(results.len(), 1, "COUNT(*) should return single result");
    assert_eq!(results[0], Value::Int(5), "Should count all 5 persons");
}

/// Test COUNT(*) with alias
#[test]
fn test_gql_count_star_with_alias() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) RETURN count(*) AS total")
        .unwrap();

    assert_eq!(results.len(), 1);
    if let Value::Map(map) = &results[0] {
        assert_eq!(map.get("total"), Some(&Value::Int(5)));
    } else {
        panic!("Expected Map result with alias");
    }
}

/// Test COUNT on property
#[test]
fn test_gql_count_property() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph.gql("MATCH (p:Person) RETURN count(p.name)").unwrap();

    assert_eq!(results.len(), 1);
    assert_eq!(results[0], Value::Int(5), "Should count all names");
}

/// Test COUNT(DISTINCT) - count unique values
#[test]
fn test_gql_count_distinct() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) RETURN count(DISTINCT p.city)")
        .unwrap();

    assert_eq!(results.len(), 1);
    // 3 unique cities: New York, Boston, Chicago
    assert_eq!(results[0], Value::Int(3), "Should count 3 unique cities");
}

/// Test SUM on numeric property
#[test]
fn test_gql_sum() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph.gql("MATCH (p:Person) RETURN sum(p.age)").unwrap();

    assert_eq!(results.len(), 1);
    // 30 + 25 + 35 + 28 + 22 = 140
    assert_eq!(results[0], Value::Int(140), "Sum of ages should be 140");
}

/// Test SUM with WHERE clause
#[test]
fn test_gql_sum_with_where() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) WHERE p.age > 25 RETURN sum(p.age)")
        .unwrap();

    assert_eq!(results.len(), 1);
    // 30 + 35 + 28 = 93 (ages > 25)
    assert_eq!(results[0], Value::Int(93), "Sum of ages > 25 should be 93");
}

/// Test AVG on numeric property
#[test]
fn test_gql_avg() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph.gql("MATCH (p:Person) RETURN avg(p.age)").unwrap();

    assert_eq!(results.len(), 1);
    // (30 + 25 + 35 + 28 + 22) / 5 = 140 / 5 = 28.0
    if let Value::Float(avg) = results[0] {
        assert!(
            (avg - 28.0).abs() < 0.0001,
            "Average should be 28.0, got {}",
            avg
        );
    } else {
        panic!("Expected Float result for AVG");
    }
}

/// Test MIN on numeric property
#[test]
fn test_gql_min() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph.gql("MATCH (p:Person) RETURN min(p.age)").unwrap();

    assert_eq!(results.len(), 1);
    assert_eq!(results[0], Value::Int(22), "Min age should be 22");
}

/// Test MAX on numeric property
#[test]
fn test_gql_max() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph.gql("MATCH (p:Person) RETURN max(p.age)").unwrap();

    assert_eq!(results.len(), 1);
    assert_eq!(results[0], Value::Int(35), "Max age should be 35");
}

/// Test MIN on string property
#[test]
fn test_gql_min_string() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph.gql("MATCH (p:Person) RETURN min(p.name)").unwrap();

    assert_eq!(results.len(), 1);
    assert_eq!(
        results[0],
        Value::String("Alice".to_string()),
        "Min name should be Alice (alphabetically first)"
    );
}

/// Test MAX on string property
#[test]
fn test_gql_max_string() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph.gql("MATCH (p:Person) RETURN max(p.name)").unwrap();

    assert_eq!(results.len(), 1);
    assert_eq!(
        results[0],
        Value::String("Eve".to_string()),
        "Max name should be Eve (alphabetically last)"
    );
}

/// Test COLLECT - collect values into list
#[test]
fn test_gql_collect() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) RETURN collect(p.name)")
        .unwrap();

    assert_eq!(results.len(), 1);
    if let Value::List(names) = &results[0] {
        assert_eq!(names.len(), 5, "Should collect all 5 names");
        // Names should include all 5 people (order may vary)
        let names_set: std::collections::HashSet<_> = names.iter().collect();
        assert!(names_set.contains(&Value::String("Alice".to_string())));
        assert!(names_set.contains(&Value::String("Bob".to_string())));
        assert!(names_set.contains(&Value::String("Carol".to_string())));
        assert!(names_set.contains(&Value::String("Dave".to_string())));
        assert!(names_set.contains(&Value::String("Eve".to_string())));
    } else {
        panic!("Expected List result for COLLECT");
    }
}

/// Test COLLECT(DISTINCT) - collect unique values
#[test]
fn test_gql_collect_distinct() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) RETURN collect(DISTINCT p.city)")
        .unwrap();

    assert_eq!(results.len(), 1);
    if let Value::List(cities) = &results[0] {
        assert_eq!(cities.len(), 3, "Should collect 3 unique cities");
        let cities_set: std::collections::HashSet<_> = cities.iter().collect();
        assert!(cities_set.contains(&Value::String("New York".to_string())));
        assert!(cities_set.contains(&Value::String("Boston".to_string())));
        assert!(cities_set.contains(&Value::String("Chicago".to_string())));
    } else {
        panic!("Expected List result for COLLECT DISTINCT");
    }
}

/// Test multiple aggregates in single query
#[test]
fn test_gql_multiple_aggregates() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) RETURN count(*) AS total, sum(p.age) AS total_age, avg(p.age) AS avg_age")
        .unwrap();

    assert_eq!(results.len(), 1);
    if let Value::Map(map) = &results[0] {
        assert_eq!(map.get("total"), Some(&Value::Int(5)));
        assert_eq!(map.get("total_age"), Some(&Value::Int(140)));
        if let Some(Value::Float(avg)) = map.get("avg_age") {
            assert!((avg - 28.0).abs() < 0.0001, "Average should be 28.0");
        } else {
            panic!("Expected Float for avg_age");
        }
    } else {
        panic!("Expected Map result for multiple aggregates");
    }
}

/// Test COUNT with empty result set
#[test]
fn test_gql_count_empty() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) WHERE p.age > 100 RETURN count(*)")
        .unwrap();

    assert_eq!(results.len(), 1);
    assert_eq!(results[0], Value::Int(0), "COUNT of empty set should be 0");
}

/// Test AVG with empty result set
#[test]
fn test_gql_avg_empty() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) WHERE p.age > 100 RETURN avg(p.age)")
        .unwrap();

    assert_eq!(results.len(), 1);
    assert_eq!(results[0], Value::Null, "AVG of empty set should be Null");
}

/// Test MIN with empty result set
#[test]
fn test_gql_min_empty() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) WHERE p.age > 100 RETURN min(p.age)")
        .unwrap();

    assert_eq!(results.len(), 1);
    assert_eq!(results[0], Value::Null, "MIN of empty set should be Null");
}

/// Test MAX with empty result set
#[test]
fn test_gql_max_empty() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) WHERE p.age > 100 RETURN max(p.age)")
        .unwrap();

    assert_eq!(results.len(), 1);
    assert_eq!(results[0], Value::Null, "MAX of empty set should be Null");
}

/// Test SUM with empty result set
#[test]
fn test_gql_sum_empty() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) WHERE p.age > 100 RETURN sum(p.age)")
        .unwrap();

    assert_eq!(results.len(), 1);
    assert_eq!(results[0], Value::Int(0), "SUM of empty set should be 0");
}

/// Test COLLECT with empty result set
#[test]
fn test_gql_collect_empty() {
    let graph = create_aggregation_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) WHERE p.age > 100 RETURN collect(p.name)")
        .unwrap();

    assert_eq!(results.len(), 1);
    assert_eq!(
        results[0],
        Value::List(vec![]),
        "COLLECT of empty set should be empty list"
    );
}

// =============================================================================
// GROUP BY Tests
// =============================================================================

/// Helper to create a test graph for GROUP BY tests
fn create_group_by_test_graph() -> Arc<Graph> {
    let graph = Arc::new(Graph::new());

    // Create Person vertices with various cities and ages
    let people = vec![
        ("Alice", 30i64, "New York"),
        ("Bob", 25i64, "Boston"),
        ("Carol", 35i64, "New York"),
        ("Dave", 28i64, "Boston"),
        ("Eve", 22i64, "Chicago"),
        ("Frank", 40i64, "New York"),
    ];

    for (name, age, city) in people {
        let mut props = HashMap::new();
        props.insert("name".to_string(), Value::from(name));
        props.insert("age".to_string(), Value::from(age));
        props.insert("city".to_string(), Value::from(city));
        graph.add_vertex("Person", props);
    }

    graph
}

/// Test GROUP BY with single expression and COUNT(*)
#[test]
fn test_gql_group_by_count() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, count(*) AS cnt GROUP BY p.city")
        .unwrap();

    // Should have 3 groups: New York (3), Boston (2), Chicago (1)
    assert_eq!(results.len(), 3, "Should have 3 city groups");

    // Collect results into a map for easier verification
    let mut city_counts: HashMap<String, i64> = HashMap::new();
    for result in &results {
        if let Value::Map(map) = result {
            if let (Some(Value::String(city)), Some(Value::Int(count))) =
                (map.get("city"), map.get("cnt"))
            {
                city_counts.insert(city.clone(), *count);
            }
        }
    }

    assert_eq!(city_counts.get("New York"), Some(&3));
    assert_eq!(city_counts.get("Boston"), Some(&2));
    assert_eq!(city_counts.get("Chicago"), Some(&1));
}

/// Test GROUP BY with AVG aggregation
#[test]
fn test_gql_group_by_avg() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, avg(p.age) AS avg_age GROUP BY p.city")
        .unwrap();

    assert_eq!(results.len(), 3, "Should have 3 city groups");

    // Collect results
    let mut city_avgs: HashMap<String, f64> = HashMap::new();
    for result in &results {
        if let Value::Map(map) = result {
            if let Some(Value::String(city)) = map.get("city") {
                let avg = match map.get("avg_age") {
                    Some(Value::Float(f)) => *f,
                    Some(Value::Int(i)) => *i as f64,
                    _ => panic!("Expected numeric avg_age"),
                };
                city_avgs.insert(city.clone(), avg);
            }
        }
    }

    // New York: (30 + 35 + 40) / 3 = 35.0
    // Boston: (25 + 28) / 2 = 26.5
    // Chicago: 22 / 1 = 22.0
    assert!((city_avgs.get("New York").unwrap() - 35.0).abs() < 0.001);
    assert!((city_avgs.get("Boston").unwrap() - 26.5).abs() < 0.001);
    assert!((city_avgs.get("Chicago").unwrap() - 22.0).abs() < 0.001);
}

/// Test GROUP BY with SUM aggregation
#[test]
fn test_gql_group_by_sum() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, sum(p.age) AS total_age GROUP BY p.city")
        .unwrap();

    assert_eq!(results.len(), 3);

    let mut city_sums: HashMap<String, i64> = HashMap::new();
    for result in &results {
        if let Value::Map(map) = result {
            if let (Some(Value::String(city)), Some(Value::Int(sum))) =
                (map.get("city"), map.get("total_age"))
            {
                city_sums.insert(city.clone(), *sum);
            }
        }
    }

    // New York: 30 + 35 + 40 = 105
    // Boston: 25 + 28 = 53
    // Chicago: 22
    assert_eq!(city_sums.get("New York"), Some(&105));
    assert_eq!(city_sums.get("Boston"), Some(&53));
    assert_eq!(city_sums.get("Chicago"), Some(&22));
}

/// Test GROUP BY with MIN/MAX aggregations
#[test]
fn test_gql_group_by_min_max() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, min(p.age) AS min_age, max(p.age) AS max_age GROUP BY p.city")
        .unwrap();

    assert_eq!(results.len(), 3);

    for result in &results {
        if let Value::Map(map) = result {
            if let Some(Value::String(city)) = map.get("city") {
                let min = map.get("min_age").and_then(|v| {
                    if let Value::Int(i) = v {
                        Some(*i)
                    } else {
                        None
                    }
                });
                let max = map.get("max_age").and_then(|v| {
                    if let Value::Int(i) = v {
                        Some(*i)
                    } else {
                        None
                    }
                });

                match city.as_str() {
                    "New York" => {
                        assert_eq!(min, Some(30), "New York min should be 30");
                        assert_eq!(max, Some(40), "New York max should be 40");
                    }
                    "Boston" => {
                        assert_eq!(min, Some(25), "Boston min should be 25");
                        assert_eq!(max, Some(28), "Boston max should be 28");
                    }
                    "Chicago" => {
                        assert_eq!(min, Some(22), "Chicago min should be 22");
                        assert_eq!(max, Some(22), "Chicago max should be 22");
                    }
                    _ => panic!("Unexpected city: {}", city),
                }
            }
        }
    }
}

/// Test GROUP BY with COLLECT aggregation
#[test]
fn test_gql_group_by_collect() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, collect(p.name) AS names GROUP BY p.city")
        .unwrap();

    assert_eq!(results.len(), 3);

    for result in &results {
        if let Value::Map(map) = result {
            if let (Some(Value::String(city)), Some(Value::List(names))) =
                (map.get("city"), map.get("names"))
            {
                match city.as_str() {
                    "New York" => {
                        assert_eq!(names.len(), 3);
                        assert!(names.contains(&Value::String("Alice".to_string())));
                        assert!(names.contains(&Value::String("Carol".to_string())));
                        assert!(names.contains(&Value::String("Frank".to_string())));
                    }
                    "Boston" => {
                        assert_eq!(names.len(), 2);
                        assert!(names.contains(&Value::String("Bob".to_string())));
                        assert!(names.contains(&Value::String("Dave".to_string())));
                    }
                    "Chicago" => {
                        assert_eq!(names.len(), 1);
                        assert!(names.contains(&Value::String("Eve".to_string())));
                    }
                    _ => panic!("Unexpected city: {}", city),
                }
            }
        }
    }
}

/// Test GROUP BY with WHERE clause
#[test]
fn test_gql_group_by_with_where() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    // Only include people age >= 25
    let results = graph
        .gql("MATCH (p:Person) WHERE p.age >= 25 RETURN p.city AS city, count(*) AS cnt GROUP BY p.city")
        .unwrap();

    // Eve (22) should be excluded, so Chicago has 0 people
    // This should result in only 2 groups (New York: 3, Boston: 2)
    // Note: Chicago group won't exist since no elements pass the filter
    assert_eq!(
        results.len(),
        2,
        "Should have 2 groups (Chicago filtered out)"
    );

    let mut city_counts: HashMap<String, i64> = HashMap::new();
    for result in &results {
        if let Value::Map(map) = result {
            if let (Some(Value::String(city)), Some(Value::Int(count))) =
                (map.get("city"), map.get("cnt"))
            {
                city_counts.insert(city.clone(), *count);
            }
        }
    }

    assert_eq!(city_counts.get("New York"), Some(&3));
    assert_eq!(city_counts.get("Boston"), Some(&2));
    assert_eq!(city_counts.get("Chicago"), None); // Eve filtered out
}

/// Test GROUP BY validation error - expression not in GROUP BY
#[test]
fn test_gql_group_by_validation_error() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    // p.name is not in GROUP BY and not an aggregate - should error
    let result = graph.gql("MATCH (p:Person) RETURN p.city, p.name, count(*) GROUP BY p.city");

    assert!(
        result.is_err(),
        "Should fail when expression not in GROUP BY"
    );

    let err = result.unwrap_err();
    let err_msg = format!("{}", err);
    assert!(
        err_msg.contains("p.name") || err_msg.contains("GROUP BY"),
        "Error should mention the problematic expression or GROUP BY: {}",
        err_msg
    );
}

/// Test GROUP BY with ORDER BY
#[test]
fn test_gql_group_by_with_order_by() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, count(*) AS cnt GROUP BY p.city ORDER BY cnt DESC")
        .unwrap();

    assert_eq!(results.len(), 3);

    // Results should be ordered by count descending: New York (3), Boston (2), Chicago (1)
    let counts: Vec<i64> = results
        .iter()
        .filter_map(|r| {
            if let Value::Map(map) = r {
                if let Some(Value::Int(cnt)) = map.get("cnt") {
                    return Some(*cnt);
                }
            }
            None
        })
        .collect();

    assert_eq!(
        counts,
        vec![3, 2, 1],
        "Should be ordered by count descending"
    );
}

/// Test GROUP BY with LIMIT
#[test]
fn test_gql_group_by_with_limit() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, count(*) AS cnt GROUP BY p.city ORDER BY cnt DESC LIMIT 2")
        .unwrap();

    // Should only return top 2 groups
    assert_eq!(results.len(), 2, "Should have only 2 results due to LIMIT");

    let counts: Vec<i64> = results
        .iter()
        .filter_map(|r| {
            if let Value::Map(map) = r {
                if let Some(Value::Int(cnt)) = map.get("cnt") {
                    return Some(*cnt);
                }
            }
            None
        })
        .collect();

    // Top 2 by count: New York (3), Boston (2)
    assert_eq!(counts, vec![3, 2]);
}

/// Test GROUP BY without alias (property access in RETURN)
#[test]
fn test_gql_group_by_no_alias() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    // No alias on p.city - the key should default to "p.city" (variable.property format)
    let results = graph
        .gql("MATCH (p:Person) RETURN p.city, count(*) GROUP BY p.city")
        .unwrap();

    assert_eq!(results.len(), 3);

    // Verify we can access the city by the full "p.city" key
    for result in &results {
        if let Value::Map(map) = result {
            assert!(
                map.contains_key("p.city"),
                "Map should have 'p.city' key: {:?}",
                map
            );
        }
    }
}

/// Test GROUP BY with multiple aggregates
#[test]
fn test_gql_group_by_multiple_aggregates() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    let results = graph
        .gql(
            "MATCH (p:Person) RETURN p.city AS city, count(*) AS cnt, sum(p.age) AS total, avg(p.age) AS avg_age GROUP BY p.city",
        )
        .unwrap();

    assert_eq!(results.len(), 3);

    for result in &results {
        if let Value::Map(map) = result {
            if let Some(Value::String(city)) = map.get("city") {
                let cnt = map.get("cnt");
                let total = map.get("total");
                let avg = map.get("avg_age");

                match city.as_str() {
                    "New York" => {
                        assert_eq!(cnt, Some(&Value::Int(3)));
                        assert_eq!(total, Some(&Value::Int(105))); // 30+35+40
                        if let Some(Value::Float(f)) = avg {
                            assert!((f - 35.0).abs() < 0.001);
                        }
                    }
                    "Boston" => {
                        assert_eq!(cnt, Some(&Value::Int(2)));
                        assert_eq!(total, Some(&Value::Int(53))); // 25+28
                        if let Some(Value::Float(f)) = avg {
                            assert!((f - 26.5).abs() < 0.001);
                        }
                    }
                    "Chicago" => {
                        assert_eq!(cnt, Some(&Value::Int(1)));
                        assert_eq!(total, Some(&Value::Int(22)));
                        if let Some(Value::Float(f)) = avg {
                            assert!((f - 22.0).abs() < 0.001);
                        }
                    }
                    _ => panic!("Unexpected city: {}", city),
                }
            }
        }
    }
}

/// Test GROUP BY single return item without alias
#[test]
fn test_gql_group_by_single_return_count_only() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    // This is a bit unusual - GROUP BY city but only return the count
    // The city value is computed but not returned
    let results = graph
        .gql("MATCH (p:Person) RETURN count(*) AS cnt GROUP BY p.city")
        .unwrap();

    // Should have 3 groups, each with a count
    assert_eq!(results.len(), 3);

    let mut counts: Vec<i64> = results
        .iter()
        .filter_map(|r| {
            if let Value::Map(map) = r {
                if let Some(Value::Int(cnt)) = map.get("cnt") {
                    return Some(*cnt);
                }
            }
            None
        })
        .collect();

    counts.sort();
    assert_eq!(counts, vec![1, 2, 3], "Should have counts 1, 2, 3");
}

// =============================================================================
// HAVING Clause Tests
// =============================================================================

/// Test HAVING with count(*) filter
#[test]
fn test_gql_having_count_filter() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    // Only return groups with more than 1 person
    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, count(*) AS cnt GROUP BY p.city HAVING count(*) > 1")
        .unwrap();

    // New York has 3 people, Boston has 2, Chicago has 1
    // HAVING count(*) > 1 should return only New York and Boston
    assert_eq!(results.len(), 2, "Should have 2 groups with count > 1");

    let mut cities: Vec<String> = results
        .iter()
        .filter_map(|r| {
            if let Value::Map(map) = r {
                if let Some(Value::String(city)) = map.get("city") {
                    return Some(city.clone());
                }
            }
            None
        })
        .collect();

    cities.sort();
    assert_eq!(cities, vec!["Boston", "New York"]);
}

/// Test HAVING with count(*) >= filter
#[test]
fn test_gql_having_count_gte() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    // Only return groups with 2 or more people
    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, count(*) AS cnt GROUP BY p.city HAVING count(*) >= 2")
        .unwrap();

    assert_eq!(results.len(), 2, "Should have 2 groups with count >= 2");
}

/// Test HAVING with count(*) = filter
#[test]
fn test_gql_having_count_equals() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    // Only return groups with exactly 3 people
    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, count(*) AS cnt GROUP BY p.city HAVING count(*) = 3")
        .unwrap();

    assert_eq!(results.len(), 1, "Should have 1 group with count = 3");

    if let Value::Map(map) = &results[0] {
        assert_eq!(
            map.get("city"),
            Some(&Value::String("New York".to_string()))
        );
        assert_eq!(map.get("cnt"), Some(&Value::Int(3)));
    } else {
        panic!("Expected Value::Map");
    }
}

/// Test HAVING with avg() filter
#[test]
fn test_gql_having_avg_filter() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    // Only return groups with average age >= 30
    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, avg(p.age) AS avg_age GROUP BY p.city HAVING avg(p.age) >= 30")
        .unwrap();

    // Verify all returned groups have avg_age >= 30
    for result in &results {
        if let Value::Map(map) = result {
            if let Some(Value::Float(avg)) = map.get("avg_age") {
                assert!(*avg >= 30.0, "avg_age should be >= 30, got {}", avg);
            } else if let Some(Value::Int(avg)) = map.get("avg_age") {
                assert!(*avg >= 30, "avg_age should be >= 30, got {}", avg);
            }
        }
    }
}

/// Test HAVING with alias reference
#[test]
fn test_gql_having_with_alias() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    // Use alias in HAVING clause
    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, count(*) AS cnt GROUP BY p.city HAVING cnt > 1")
        .unwrap();

    assert_eq!(results.len(), 2, "Should have 2 groups with cnt > 1");
}

/// Test HAVING with AND logic
#[test]
fn test_gql_having_and_condition() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    // Multiple conditions with AND
    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, count(*) AS cnt, avg(p.age) AS avg_age GROUP BY p.city HAVING count(*) > 1 AND avg(p.age) < 35")
        .unwrap();

    // Each result should satisfy both conditions
    for result in &results {
        if let Value::Map(map) = result {
            if let Some(Value::Int(cnt)) = map.get("cnt") {
                assert!(*cnt > 1, "cnt should be > 1");
            }
            if let Some(Value::Float(avg)) = map.get("avg_age") {
                assert!(*avg < 35.0, "avg_age should be < 35");
            }
        }
    }
}

/// Test HAVING with OR logic
#[test]
fn test_gql_having_or_condition() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    // Multiple conditions with OR
    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, count(*) AS cnt GROUP BY p.city HAVING count(*) = 1 OR count(*) = 3")
        .unwrap();

    // Should return Chicago (1 person) and New York (3 people), but not Boston (2)
    assert_eq!(
        results.len(),
        2,
        "Should have 2 groups with count = 1 OR count = 3"
    );

    let mut counts: Vec<i64> = results
        .iter()
        .filter_map(|r| {
            if let Value::Map(map) = r {
                if let Some(Value::Int(cnt)) = map.get("cnt") {
                    return Some(*cnt);
                }
            }
            None
        })
        .collect();

    counts.sort();
    assert_eq!(counts, vec![1, 3], "Should have counts 1 and 3");
}

/// Test HAVING filters all groups (empty result)
#[test]
fn test_gql_having_filters_all() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    // No group has count > 10
    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, count(*) AS cnt GROUP BY p.city HAVING count(*) > 10")
        .unwrap();

    assert_eq!(results.len(), 0, "Should have 0 groups with count > 10");
}

/// Test HAVING with sum() filter
#[test]
fn test_gql_having_sum_filter() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    // Only return groups where sum of ages > 50
    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, sum(p.age) AS total_age GROUP BY p.city HAVING sum(p.age) > 50")
        .unwrap();

    // Verify all returned groups have total_age > 50
    for result in &results {
        if let Value::Map(map) = result {
            if let Some(Value::Int(total)) = map.get("total_age") {
                assert!(*total > 50, "total_age should be > 50, got {}", total);
            }
        }
    }
}

/// Test HAVING combined with ORDER BY and LIMIT
#[test]
fn test_gql_having_with_order_by_limit() {
    let graph = create_group_by_test_graph();
    let snapshot = graph.snapshot();

    // Filter, order, and limit
    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, count(*) AS cnt GROUP BY p.city HAVING count(*) > 1 ORDER BY cnt DESC LIMIT 1")
        .unwrap();

    assert_eq!(results.len(), 1, "Should have 1 result after LIMIT");

    // Should be New York with the highest count (3) among filtered groups
    if let Value::Map(map) = &results[0] {
        assert_eq!(
            map.get("city"),
            Some(&Value::String("New York".to_string()))
        );
        assert_eq!(map.get("cnt"), Some(&Value::Int(3)));
    }
}

// =============================================================================
// HAVING Without Explicit GROUP BY (Bug #1 regression tests)
// =============================================================================
//
// HAVING with implicit grouping (i.e. no explicit GROUP BY clause) used to be
// silently ignored — the predicate was parsed but never applied. These tests
// pin the corrected behavior.

/// HAVING with a global aggregate (no GROUP BY) that is satisfied: row passes.
#[test]
fn test_gql_having_implicit_global_pass() {
    let graph = create_group_by_test_graph();
    let _snapshot = graph.snapshot();

    // 6 people total; 6 > 1 is true → row passes through.
    let results = graph
        .gql("MATCH (p:Person) RETURN count(*) AS cnt HAVING count(*) > 1")
        .unwrap();

    assert_eq!(results.len(), 1);
    if let Value::Map(map) = &results[0] {
        assert_eq!(map.get("cnt"), Some(&Value::Int(6)));
    } else {
        panic!("Expected Value::Map row, got {:?}", results[0]);
    }
}

/// HAVING with a global aggregate (no GROUP BY) that is NOT satisfied: row dropped.
#[test]
fn test_gql_having_implicit_global_filter() {
    let graph = create_group_by_test_graph();
    let _snapshot = graph.snapshot();

    // 6 people total; 6 > 100 is false → no rows.
    let results = graph
        .gql("MATCH (p:Person) RETURN count(*) AS cnt HAVING count(*) > 100")
        .unwrap();

    assert!(
        results.is_empty(),
        "Expected zero rows when HAVING fails, got {:?}",
        results
    );
}

/// HAVING with implicit grouping (non-aggregate column + aggregate, no GROUP BY).
///
/// `RETURN p.city, count(*)` without GROUP BY uses the implicit-aggregation path.
/// HAVING should filter the resulting groups.
#[test]
fn test_gql_having_implicit_grouped_filter() {
    let graph = create_group_by_test_graph();
    let _snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, count(*) AS cnt HAVING count(*) > 1")
        .unwrap();

    // New York has 3, Boston has 2, Chicago has 1 → only NY and Boston pass.
    assert_eq!(results.len(), 2, "Expected 2 cities with count > 1");

    let mut cities: Vec<String> = results
        .iter()
        .filter_map(|r| {
            if let Value::Map(map) = r {
                if let Some(Value::String(city)) = map.get("city") {
                    return Some(city.clone());
                }
            }
            None
        })
        .collect();
    cities.sort();
    assert_eq!(cities, vec!["Boston", "New York"]);
}

/// HAVING using an alias defined in RETURN works in the implicit-grouping path.
#[test]
fn test_gql_having_implicit_alias_reference() {
    let graph = create_group_by_test_graph();
    let _snapshot = graph.snapshot();

    let results = graph
        .gql("MATCH (p:Person) RETURN p.city AS city, count(*) AS cnt HAVING cnt >= 2")
        .unwrap();

    assert_eq!(results.len(), 2, "Expected 2 cities with cnt >= 2");
}