graph_d 1.3.2

A native graph database implementation in Rust with built-in JSON support and SQLite-like simplicity
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
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
//! Comprehensive tests for GQL implementation.

#[cfg(test)]
#[allow(clippy::module_inception)]
mod tests {
    use super::super::lexer::TokenKind;
    use super::super::*;
    use crate::{gql::Gql, Graph};
    use serde_json::json;
    use std::cell::RefCell;

    fn setup_test_graph() -> crate::Result<RefCell<Graph>> {
        let mut graph = Graph::new()?;

        // Create test nodes
        let _alice_id = graph.create_node(
            [
                ("type".to_string(), json!("Person")),
                ("name".to_string(), json!("Alice")),
                ("age".to_string(), json!(30)),
                ("city".to_string(), json!("SF")),
            ]
            .into(),
        )?;

        let _bob_id = graph.create_node(
            [
                ("type".to_string(), json!("Person")),
                ("name".to_string(), json!("Bob")),
                ("age".to_string(), json!(25)),
                ("city".to_string(), json!("NYC")),
            ]
            .into(),
        )?;

        let _company_id = graph.create_node(
            [
                ("type".to_string(), json!("Company")),
                ("name".to_string(), json!("TechCorp")),
                ("industry".to_string(), json!("Tech")),
            ]
            .into(),
        )?;

        // Create relationships
        graph.create_relationship(
            1,
            2,
            "KNOWS".to_string(),
            [("since".to_string(), json!("2020"))].into(),
        )?;

        graph.create_relationship(
            1,
            3,
            "WORKS_FOR".to_string(),
            [("role".to_string(), json!("Engineer"))].into(),
        )?;

        Ok(RefCell::new(graph))
    }

    #[test]
    fn test_lexer_basic_tokens() {
        let mut lexer = Lexer::new("MATCH (n) RETURN n");
        let tokens = lexer.tokenize().unwrap();

        assert!(matches!(tokens[0].kind, TokenKind::Match));
        assert!(matches!(tokens[1].kind, TokenKind::LeftParen));
        assert!(matches!(tokens[2].kind, TokenKind::Identifier(_)));
        assert!(matches!(tokens[3].kind, TokenKind::RightParen));
        assert!(matches!(tokens[4].kind, TokenKind::Return));
        assert!(matches!(tokens[5].kind, TokenKind::Identifier(_)));
        assert!(matches!(tokens[6].kind, TokenKind::Eof));
    }

    #[test]
    fn test_lexer_string_literals() {
        let mut lexer = Lexer::new("\"hello\" 'world'");
        let tokens = lexer.tokenize().unwrap();

        assert!(matches!(tokens[0].kind, TokenKind::String(ref s) if s == "hello"));
        assert!(matches!(tokens[1].kind, TokenKind::String(ref s) if s == "world"));
    }

    #[test]
    fn test_lexer_numbers() {
        let mut lexer = Lexer::new("42 3.14");
        let tokens = lexer.tokenize().unwrap();

        assert!(matches!(tokens[0].kind, TokenKind::Integer(42)));
        #[allow(clippy::approx_constant)]
        {
            assert!(
                matches!(tokens[1].kind, TokenKind::Float(f) if (f - 3.14).abs() < f64::EPSILON)
            );
        }
    }

    #[test]
    fn test_lexer_operators() {
        let mut lexer = Lexer::new("= == <> < > <= >= -> + - * /");
        let tokens = lexer.tokenize().unwrap();

        let expected = [
            TokenKind::Assign,
            TokenKind::Equal,
            TokenKind::NotEqual,
            TokenKind::LessThan,
            TokenKind::GreaterThan,
            TokenKind::LessEqual,
            TokenKind::GreaterEqual,
            TokenKind::Arrow,
            TokenKind::Plus,
            TokenKind::Minus,
            TokenKind::Multiply,
            TokenKind::Divide,
        ];

        for (i, expected_kind) in expected.iter().enumerate() {
            assert_eq!(
                std::mem::discriminant(&tokens[i].kind),
                std::mem::discriminant(expected_kind)
            );
        }
    }

    #[test]
    fn test_lexer_keywords() {
        let mut lexer = Lexer::new("MATCH WHERE RETURN AND OR NOT");
        let tokens = lexer.tokenize().unwrap();

        assert!(matches!(tokens[0].kind, TokenKind::Match));
        assert!(matches!(tokens[1].kind, TokenKind::Where));
        assert!(matches!(tokens[2].kind, TokenKind::Return));
        assert!(matches!(tokens[3].kind, TokenKind::And));
        assert!(matches!(tokens[4].kind, TokenKind::Or));
        assert!(matches!(tokens[5].kind, TokenKind::Not));
    }

    #[test]
    fn test_parser_simple_match() {
        let mut lexer = Lexer::new("MATCH (n) RETURN n");
        let tokens = lexer.tokenize().unwrap();
        let mut parser = Parser::new(tokens);

        let ast = parser.parse().unwrap();

        if let GqlStatement::LinearQuery(query) = ast {
            assert_eq!(query.clauses.len(), 2);
            assert!(matches!(query.clauses[0], QueryClause::Match(_)));
            assert!(matches!(query.clauses[1], QueryClause::Return(_)));
        } else {
            panic!("Expected LinearQuery");
        }
    }

    #[test]
    fn test_parser_node_with_label() {
        let mut lexer = Lexer::new("MATCH (p:Person) RETURN p");
        let tokens = lexer.tokenize().unwrap();
        let mut parser = Parser::new(tokens);

        let ast = parser.parse().unwrap();

        if let GqlStatement::LinearQuery(query) = ast {
            if let QueryClause::Match(match_clause) = &query.clauses[0] {
                if let GraphPattern::Node(node) = &match_clause.patterns[0] {
                    assert_eq!(node.variable, Some("p".to_string()));
                    assert_eq!(node.labels, vec!["Person".to_string()]);
                } else {
                    panic!("Expected node pattern");
                }
            } else {
                panic!("Expected match clause");
            }
        } else {
            panic!("Expected LinearQuery");
        }
    }

    #[test]
    fn test_parser_where_clause() {
        let mut lexer = Lexer::new("MATCH (p:Person) WHERE p.age > 30 RETURN p");
        let tokens = lexer.tokenize().unwrap();
        let mut parser = Parser::new(tokens);

        let ast = parser.parse().unwrap();

        if let GqlStatement::LinearQuery(query) = ast {
            assert_eq!(query.clauses.len(), 3);
            assert!(matches!(query.clauses[0], QueryClause::Match(_)));
            assert!(matches!(query.clauses[1], QueryClause::Filter(_)));
            assert!(matches!(query.clauses[2], QueryClause::Return(_)));
        } else {
            panic!("Expected LinearQuery");
        }
    }

    #[test]
    fn test_parser_graph_query() {
        let mut lexer = Lexer::new("GRAPH myGraph MATCH (n) RETURN n");
        let tokens = lexer.tokenize().unwrap();
        let mut parser = Parser::new(tokens);

        let ast = parser.parse().unwrap();

        if let GqlStatement::GraphQuery { graph_name, query } = ast {
            assert_eq!(graph_name, "myGraph");
            assert_eq!(query.clauses.len(), 2);
        } else {
            panic!("Expected GraphQuery");
        }
    }

    #[test]
    fn test_executor_simple_match() {
        let graph = setup_test_graph().unwrap();
        let gql = Gql::new(&graph);

        let result = gql.execute("MATCH (p:Person) RETURN p.name").unwrap();

        assert_eq!(result.columns.len(), 1);
        assert_eq!(result.columns[0], "p.name");
        assert!(result.row_count() > 0);
    }

    #[test]
    fn test_executor_property_access() {
        let graph = setup_test_graph().unwrap();
        let gql = Gql::new(&graph);

        let result = gql
            .execute("MATCH (p:Person) RETURN p.name, p.age")
            .unwrap();

        assert_eq!(result.columns.len(), 2);
        assert_eq!(result.columns[0], "p.name");
        assert_eq!(result.columns[1], "p.age");
    }

    #[test]
    fn test_executor_filtering() {
        let graph = setup_test_graph().unwrap();
        let gql = Gql::new(&graph);

        let result = gql
            .execute("MATCH (p:Person) WHERE p.age > 25 RETURN p.name")
            .unwrap();

        assert_eq!(result.columns.len(), 1);
        // Should filter to only Alice (age 30)
        assert!(result.row_count() <= 1);
    }

    #[test]
    fn test_expression_literal_creation() {
        // Test creating expressions with different literal types
        let int_expr = Expression::literal(json!(42));
        assert!(matches!(int_expr, Expression::Literal(_)));

        let str_expr = Expression::literal(json!("hello"));
        assert!(matches!(str_expr, Expression::Literal(_)));

        let bool_expr = Expression::literal(json!(true));
        assert!(matches!(bool_expr, Expression::Literal(_)));
    }

    #[test]
    fn test_expression_construction() {
        // Test creating variable and property expressions
        let var_expr = Expression::variable("x".to_string());
        assert!(matches!(var_expr, Expression::Variable(_)));

        let prop_expr =
            Expression::property(Expression::variable("node".to_string()), "name".to_string());
        assert!(matches!(prop_expr, Expression::Property { .. }));

        // Test binary expression construction
        let binary_expr = Expression::binary(
            Expression::literal(json!(1)),
            BinaryOperator::Add,
            Expression::literal(json!(2)),
        );
        assert!(matches!(binary_expr, Expression::Binary { .. }));
    }

    #[test]
    fn test_error_handling() {
        // Test lexer error
        let mut lexer = Lexer::new("@invalid");
        let result = lexer.tokenize();
        assert!(result.is_err());

        // Test parser error
        let mut lexer = Lexer::new("MATCH (");
        let tokens = lexer.tokenize().unwrap();
        let mut parser = Parser::new(tokens);
        let result = parser.parse();
        assert!(result.is_err());

        // Test executor error
        let graph = RefCell::new(Graph::new().unwrap());
        let gql = Gql::new(&graph);
        let result = gql.execute("MATCH (p:NonExistent) RETURN p.unknown");
        // This should execute but return empty results
        assert!(result.is_ok());
    }

    #[test]
    fn test_complex_patterns() {
        let graph = setup_test_graph().unwrap();
        let gql = Gql::new(&graph);

        // Test path pattern
        let result = gql.execute("MATCH (p1:Person)-[:KNOWS]->(p2:Person) RETURN p1.name, p2.name");
        assert!(result.is_ok());

        // Test multiple patterns
        let result = gql.execute("MATCH (p:Person), (c:Company) RETURN p.name, c.name");
        assert!(result.is_ok());
    }

    #[test]
    fn test_multi_hop_traversal() {
        let graph = setup_test_graph().unwrap();
        let gql = Gql::new(&graph);

        // Test 2-hop traversal: Person -> Person -> Company
        let result = gql.execute("MATCH (p1:Person)-[:KNOWS]->(p2:Person)-[:WORKS_FOR]->(c:Company) RETURN p1.name, c.name");
        assert!(result.is_ok());

        let result = result.unwrap();
        println!("Multi-hop result: {result:?}");
        // Should find paths where Alice knows Bob and Bob works for TechCorp
        // Note: In our test data, Alice knows Bob but Bob doesn't work for TechCorp
        // So this might return empty results, which is correct
    }

    #[test]
    fn test_path_pattern_execution() {
        let graph = setup_test_graph().unwrap();
        let gql = Gql::new(&graph);

        // Test simple path pattern that should work with our test data
        let result =
            gql.execute("MATCH (p:Person)-[:KNOWS]->(friend:Person) RETURN p.name, friend.name");
        assert!(result.is_ok());

        let result = result.unwrap();
        assert_eq!(result.columns.len(), 2);
        assert_eq!(result.columns[0], "p.name");
        assert_eq!(result.columns[1], "friend.name");
        // Should have at least one result (Alice -> Bob)
        println!("Path pattern result: {result:?}");
    }

    #[test]
    fn test_path_pattern_with_relationship_filtering() {
        let graph = setup_test_graph().unwrap();
        let gql = Gql::new(&graph);

        // Test path pattern with specific relationship type
        let result =
            gql.execute("MATCH (p:Person)-[:WORKS_FOR]->(c:Company) RETURN p.name, c.name");
        assert!(result.is_ok());

        let result = result.unwrap();
        assert_eq!(result.columns.len(), 2);
        // Should find Alice -> TechCorp relationship
        println!("Work relationship result: {result:?}");
    }

    #[test]
    fn test_longer_path_pattern() {
        // Create a more complex graph for testing longer paths
        let mut graph = Graph::new().unwrap();

        // Create a chain: A -> B -> C -> D
        let _a_id = graph
            .create_node(
                [
                    ("type".to_string(), json!("Person")),
                    ("name".to_string(), json!("Alice")),
                ]
                .into(),
            )
            .unwrap();

        let _b_id = graph
            .create_node(
                [
                    ("type".to_string(), json!("Person")),
                    ("name".to_string(), json!("Bob")),
                ]
                .into(),
            )
            .unwrap();

        let _c_id = graph
            .create_node(
                [
                    ("type".to_string(), json!("Person")),
                    ("name".to_string(), json!("Charlie")),
                ]
                .into(),
            )
            .unwrap();

        let _d_id = graph
            .create_node(
                [
                    ("type".to_string(), json!("Person")),
                    ("name".to_string(), json!("David")),
                ]
                .into(),
            )
            .unwrap();

        // Create relationships: A -> B -> C -> D
        graph
            .create_relationship(1, 2, "KNOWS".to_string(), [].into())
            .unwrap();
        graph
            .create_relationship(2, 3, "KNOWS".to_string(), [].into())
            .unwrap();
        graph
            .create_relationship(3, 4, "KNOWS".to_string(), [].into())
            .unwrap();

        let graph = RefCell::new(graph);
        let gql = Gql::new(&graph);

        // Test 3-hop path: A -> B -> C -> D
        let result = gql.execute("MATCH (a:Person)-[:KNOWS]->(b:Person)-[:KNOWS]->(c:Person)-[:KNOWS]->(d:Person) RETURN a.name, d.name");
        assert!(result.is_ok());

        let result = result.unwrap();
        println!("3-hop path result: {result:?}");
        assert_eq!(result.columns.len(), 2);
        // Should find Alice -> David path through Bob and Charlie
    }

    #[test]
    fn test_complex_multi_hop_scenarios() {
        // Create a more comprehensive test graph
        let mut graph = Graph::new().unwrap();

        // Create nodes: Person nodes and Company nodes
        let _alice_id = graph
            .create_node(
                [
                    ("type".to_string(), json!("Person")),
                    ("name".to_string(), json!("Alice")),
                    ("city".to_string(), json!("SF")),
                ]
                .into(),
            )
            .unwrap();

        let _bob_id = graph
            .create_node(
                [
                    ("type".to_string(), json!("Person")),
                    ("name".to_string(), json!("Bob")),
                    ("city".to_string(), json!("NYC")),
                ]
                .into(),
            )
            .unwrap();

        let _charlie_id = graph
            .create_node(
                [
                    ("type".to_string(), json!("Person")),
                    ("name".to_string(), json!("Charlie")),
                    ("city".to_string(), json!("LA")),
                ]
                .into(),
            )
            .unwrap();

        let _techcorp_id = graph
            .create_node(
                [
                    ("type".to_string(), json!("Company")),
                    ("name".to_string(), json!("TechCorp")),
                    ("industry".to_string(), json!("Tech")),
                ]
                .into(),
            )
            .unwrap();

        let _startup_id = graph
            .create_node(
                [
                    ("type".to_string(), json!("Company")),
                    ("name".to_string(), json!("StartupCo")),
                    ("industry".to_string(), json!("AI")),
                ]
                .into(),
            )
            .unwrap();

        // Create relationships to test various traversal scenarios
        // Alice knows Bob, Bob knows Charlie
        graph
            .create_relationship(1, 2, "KNOWS".to_string(), [].into())
            .unwrap();
        graph
            .create_relationship(2, 3, "KNOWS".to_string(), [].into())
            .unwrap();

        // Alice works for TechCorp, Charlie works for StartupCo
        graph
            .create_relationship(1, 4, "WORKS_FOR".to_string(), [].into())
            .unwrap();
        graph
            .create_relationship(3, 5, "WORKS_FOR".to_string(), [].into())
            .unwrap();

        // Bob also works for TechCorp
        graph
            .create_relationship(2, 4, "WORKS_FOR".to_string(), [].into())
            .unwrap();

        let graph = RefCell::new(graph);
        let gql = Gql::new(&graph);

        // Test 1: 2-hop relationship traversal - "friend of friend"
        let result = gql.execute(
            "MATCH (a:Person)-[:KNOWS]->(b:Person)-[:KNOWS]->(c:Person) RETURN a.name, c.name",
        );
        assert!(result.is_ok());
        let result = result.unwrap();
        println!("Friend of friend: {result:?}");
        assert_eq!(result.columns.len(), 2);
        // Should find Alice -> Charlie through Bob

        // Test 2: 2-hop with different relationship types - "colleague through friendship"
        let result = gql.execute("MATCH (p1:Person)-[:KNOWS]->(p2:Person)-[:WORKS_FOR]->(c:Company) RETURN p1.name, c.name");
        assert!(result.is_ok());
        let result = result.unwrap();
        println!("Friend's company: {result:?}");
        // Should find Alice -> TechCorp (through Bob) and Bob -> StartupCo (through Charlie)

        // Test 3: Same company colleagues
        let result = gql.execute("MATCH (p1:Person)-[:WORKS_FOR]->(c:Company)<-[:WORKS_FOR]-(p2:Person) RETURN p1.name, p2.name, c.name");
        assert!(result.is_ok());
        let result = result.unwrap();
        println!("Same company colleagues: {result:?}");
        // Should find Alice and Bob both work for TechCorp

        // Test 4: WHERE clause filtering with path patterns
        let result = gql.execute("MATCH (p:Person)-[:KNOWS]->(friend:Person) WHERE friend.city = 'NYC' RETURN p.name, friend.name");
        assert!(result.is_ok());
        let result = result.unwrap();
        println!("Friends in NYC: {result:?}");
        assert_eq!(result.columns.len(), 2);
        assert!(
            !result.rows.is_empty(),
            "Should find Alice -> Bob where Bob is in NYC"
        );

        // Test 5: WHERE clause with multiple conditions
        let result = gql.execute("MATCH (p:Person)-[:WORKS_FOR]->(c:Company) WHERE c.industry = 'Tech' RETURN p.name, c.name");
        assert!(result.is_ok());
        let result = result.unwrap();
        println!("Tech workers: {result:?}");
        // Should find people working for TechCorp (Alice and Bob)
    }

    #[test]
    fn test_gql_integration() {
        let graph = setup_test_graph().unwrap();
        let gql = Gql::new(&graph);

        // Test complete query workflow
        let queries = vec![
            "MATCH (n) RETURN n",
            "MATCH (p:Person) RETURN p.name",
            "MATCH (p:Person) WHERE p.age > 20 RETURN p.name, p.age",
            "MATCH (p:Person)-[:KNOWS]->(f) RETURN p.name, f.name",
            "MATCH (p:Person)-[:WORKS_FOR]->(c:Company) RETURN p.name, c.name",
        ];

        for query in queries {
            let result = gql.execute(query);
            assert!(result.is_ok(), "Query failed: {query}");

            let result = result.unwrap();
            assert!(
                !result.columns.is_empty(),
                "No columns returned for: {query}"
            );
        }
    }

    #[test]
    fn test_variable_length_patterns() {
        // Create a chain graph: A -> B -> C -> D -> E
        let mut graph = Graph::new().unwrap();

        let _a_id = graph
            .create_node(
                [
                    ("type".to_string(), json!("Person")),
                    ("name".to_string(), json!("Alice")),
                ]
                .into(),
            )
            .unwrap();

        let _b_id = graph
            .create_node(
                [
                    ("type".to_string(), json!("Person")),
                    ("name".to_string(), json!("Bob")),
                ]
                .into(),
            )
            .unwrap();

        let _c_id = graph
            .create_node(
                [
                    ("type".to_string(), json!("Person")),
                    ("name".to_string(), json!("Charlie")),
                ]
                .into(),
            )
            .unwrap();

        let _d_id = graph
            .create_node(
                [
                    ("type".to_string(), json!("Person")),
                    ("name".to_string(), json!("David")),
                ]
                .into(),
            )
            .unwrap();

        let _e_id = graph
            .create_node(
                [
                    ("type".to_string(), json!("Person")),
                    ("name".to_string(), json!("Eve")),
                ]
                .into(),
            )
            .unwrap();

        // Create chain relationships: A -> B -> C -> D -> E
        graph
            .create_relationship(1, 2, "KNOWS".to_string(), [].into())
            .unwrap();
        graph
            .create_relationship(2, 3, "KNOWS".to_string(), [].into())
            .unwrap();
        graph
            .create_relationship(3, 4, "KNOWS".to_string(), [].into())
            .unwrap();
        graph
            .create_relationship(4, 5, "KNOWS".to_string(), [].into())
            .unwrap();

        let graph = RefCell::new(graph);
        let gql = Gql::new(&graph);

        // Test that basic functionality works
        let simple_result = gql.execute("MATCH (a)-[:KNOWS]->(b) RETURN a.name, b.name");
        assert!(simple_result.is_ok());

        let all_nodes = gql.execute("MATCH (n) RETURN n.name");
        assert!(all_nodes.is_ok());
        assert_eq!(all_nodes.unwrap().row_count(), 5);

        // Test exact variable length: *2 (should find 2-hop paths like A->C, B->D, C->E)
        let result = gql.execute("MATCH (a)-[:KNOWS*2]->(b) RETURN a.name, b.name");
        assert!(result.is_ok());
        let result = result.unwrap();
        assert_eq!(result.row_count(), 3, "Should find exactly 3 2-hop paths");

        // Test range: *1..3 (should find paths of length 1, 2, and 3)
        let result = gql.execute("MATCH (a)-[:KNOWS*1..3]->(b) RETURN a.name, b.name");
        assert!(result.is_ok());
        let result = result.unwrap();
        assert!(
            result.row_count() >= 4,
            "Should find multiple 1-3 hop paths"
        );

        // Test basic variable length: * (should find all reachable paths)
        let result = gql.execute("MATCH (a)-[:KNOWS*]->(b) RETURN a.name, b.name");
        assert!(result.is_ok());
        let result = result.unwrap();
        assert!(
            result.row_count() >= 4,
            "Should find multiple variable length paths"
        );
    }

    #[test]
    fn test_query_result_structure() {
        let mut result = QueryResult::new();

        result.add_column("name".to_string());
        result.add_column("age".to_string());

        result.add_row(vec![
            QueryValue::String("Alice".to_string()),
            QueryValue::Integer(30),
        ]);

        result.add_row(vec![
            QueryValue::String("Bob".to_string()),
            QueryValue::Integer(25),
        ]);

        assert_eq!(result.columns.len(), 2);
        assert_eq!(result.row_count(), 2);
        assert!(!result.is_empty());

        assert_eq!(result.columns[0], "name");
        assert_eq!(result.columns[1], "age");

        if let QueryValue::String(name) = &result.rows[0][0] {
            assert_eq!(name, "Alice");
        } else {
            panic!("Expected string value");
        }
    }

    #[test]
    fn test_order_by_functionality() {
        let graph = setup_test_graph().unwrap();
        let gql = Gql::new(&graph);

        // Test ORDER BY with string values (names)
        let result = gql
            .execute("MATCH (p:Person) RETURN p.name ORDER BY p.name ASC")
            .unwrap();
        assert_eq!(result.columns.len(), 1);
        assert_eq!(result.columns[0], "p.name");

        // Check if results are sorted (Alice should come before Bob)
        assert!(result.row_count() >= 2);
        if let (QueryValue::String(first), QueryValue::String(second)) =
            (&result.rows[0][0], &result.rows[1][0])
        {
            assert!(
                first <= second,
                "Results should be sorted in ascending order"
            );
        }

        // Test ORDER BY with numeric values (age)
        let result = gql
            .execute("MATCH (p:Person) RETURN p.name, p.age ORDER BY p.age DESC")
            .unwrap();
        assert_eq!(result.columns.len(), 2);

        // Test ORDER BY with multiple columns
        let result =
            gql.execute("MATCH (p:Person) RETURN p.name, p.age ORDER BY p.age ASC, p.name DESC");
        assert!(result.is_ok());
    }

    #[test]
    fn test_limit_functionality() {
        let graph = setup_test_graph().unwrap();
        let gql = Gql::new(&graph);

        // Test LIMIT with constant value
        let result = gql
            .execute("MATCH (p:Person) RETURN p.name LIMIT 1")
            .unwrap();
        assert_eq!(result.row_count(), 1);

        // Test LIMIT with larger value than available rows
        let result = gql
            .execute("MATCH (p:Person) RETURN p.name LIMIT 100")
            .unwrap();
        assert!(result.row_count() <= 100);

        // Test LIMIT 0
        let result = gql
            .execute("MATCH (p:Person) RETURN p.name LIMIT 0")
            .unwrap();
        assert_eq!(result.row_count(), 0);
    }

    #[test]
    fn test_offset_functionality() {
        let graph = setup_test_graph().unwrap();
        let gql = Gql::new(&graph);

        // First get all results
        let all_results = gql
            .execute("MATCH (p:Person) RETURN p.name ORDER BY p.name")
            .unwrap();
        let total_rows = all_results.row_count();

        if total_rows > 1 {
            // Test OFFSET 1
            let result = gql
                .execute("MATCH (p:Person) RETURN p.name ORDER BY p.name OFFSET 1")
                .unwrap();
            assert_eq!(result.row_count(), total_rows - 1);

            // Test OFFSET larger than available rows
            let result = gql
                .execute("MATCH (p:Person) RETURN p.name OFFSET 100")
                .unwrap();
            assert_eq!(result.row_count(), 0);
        }

        // Test OFFSET 0 (should return all rows)
        let result = gql
            .execute("MATCH (p:Person) RETURN p.name OFFSET 0")
            .unwrap();
        assert_eq!(result.row_count(), total_rows);
    }

    #[test]
    fn test_combined_order_limit_offset() {
        // Create a more comprehensive test graph for pagination testing
        let mut graph = Graph::new().unwrap();

        // Create multiple person nodes
        for i in 1..=5 {
            graph
                .create_node(
                    [
                        ("type".to_string(), json!("Person")),
                        ("name".to_string(), json!(format!("Person{}", i))),
                        ("age".to_string(), json!(20 + i)),
                        ("score".to_string(), json!(100 - i * 10)),
                    ]
                    .into(),
                )
                .unwrap();
        }

        let graph = RefCell::new(graph);
        let gql = Gql::new(&graph);

        // Test ORDER BY + LIMIT
        let result = gql
            .execute("MATCH (p:Person) RETURN p.name, p.age ORDER BY p.age ASC LIMIT 2")
            .unwrap();
        assert_eq!(result.row_count(), 2);

        // Test ORDER BY + OFFSET
        let result = gql
            .execute("MATCH (p:Person) RETURN p.name, p.age ORDER BY p.age ASC OFFSET 2")
            .unwrap();
        assert_eq!(result.row_count(), 3); // 5 total - 2 offset = 3

        // Test ORDER BY + LIMIT + OFFSET (pagination)
        let result = gql
            .execute("MATCH (p:Person) RETURN p.name, p.age ORDER BY p.age ASC LIMIT 2 OFFSET 1")
            .unwrap();
        assert_eq!(result.row_count(), 2);

        // Test different ORDER BY directions
        let asc_result = gql
            .execute("MATCH (p:Person) RETURN p.name ORDER BY p.name ASC")
            .unwrap();
        let desc_result = gql
            .execute("MATCH (p:Person) RETURN p.name ORDER BY p.name DESC")
            .unwrap();

        // Results should be in reverse order
        assert_eq!(asc_result.row_count(), desc_result.row_count());
        if asc_result.row_count() > 1 {
            // First item in ASC should be last item in DESC
            assert_eq!(
                asc_result.rows[0][0],
                desc_result.rows[desc_result.row_count() - 1][0]
            );
        }
    }

    #[test]
    fn test_order_by_with_path_patterns() {
        let graph = setup_test_graph().unwrap();
        let gql = Gql::new(&graph);

        // Test ORDER BY with path pattern results
        let result = gql.execute(
            "MATCH (p:Person)-[:KNOWS]->(f:Person) RETURN p.name, f.name ORDER BY p.name, f.name"
        ).unwrap();

        assert_eq!(result.columns.len(), 2);
        println!("Path pattern with ORDER BY: {result:?}");

        // Test with LIMIT on path patterns
        let result = gql.execute(
            "MATCH (p:Person)-[:WORKS_FOR]->(c:Company) RETURN p.name, c.name ORDER BY c.name LIMIT 1"
        ).unwrap();

        assert!(result.row_count() <= 1);
        println!("Limited path pattern: {result:?}");
    }

    #[test]
    fn test_aggregation_functions() {
        let graph = setup_test_graph().unwrap();
        let gql = Gql::new(&graph);

        // Test COUNT(*) - count all person nodes
        let result = gql.execute("MATCH (p:Person) RETURN COUNT(*)").unwrap();
        assert_eq!(result.columns.len(), 1);
        assert_eq!(result.columns[0], "COUNT(*)");
        assert_eq!(result.row_count(), 1);
        if let QueryValue::Integer(count) = &result.rows[0][0] {
            assert!(*count >= 2, "Should count at least Alice and Bob");
        }

        // Test COUNT(property) - count non-null values
        let result = gql
            .execute("MATCH (p:Person) RETURN COUNT(p.name)")
            .unwrap();
        assert_eq!(result.columns.len(), 1);
        assert_eq!(result.row_count(), 1);
        if let QueryValue::Integer(count) = &result.rows[0][0] {
            assert!(*count >= 2, "Should count non-null names");
        }

        // Test AVG with numeric values
        let result = gql.execute("MATCH (p:Person) RETURN AVG(p.age)").unwrap();
        assert_eq!(result.columns.len(), 1);
        assert_eq!(result.row_count(), 1);
        // Should return a valid average (Alice=30, Bob=25, avg=27.5)
        match &result.rows[0][0] {
            QueryValue::Float(avg) => assert!(*avg > 0.0),
            QueryValue::Integer(avg) => assert!(*avg > 0),
            _ => panic!("Expected numeric average"),
        }

        // Test MIN and MAX
        let result = gql
            .execute("MATCH (p:Person) RETURN MIN(p.age), MAX(p.age)")
            .unwrap();
        assert_eq!(result.columns.len(), 2);
        assert_eq!(result.row_count(), 1);

        // Test SUM
        let result = gql.execute("MATCH (p:Person) RETURN SUM(p.age)").unwrap();
        assert_eq!(result.columns.len(), 1);
        assert_eq!(result.row_count(), 1);
        match &result.rows[0][0] {
            QueryValue::Integer(sum) => assert!(*sum > 0),
            QueryValue::Float(sum) => assert!(*sum > 0.0),
            _ => panic!("Expected numeric sum"),
        }

        println!("Aggregation test results: {result:?}");
    }

    #[test]
    fn test_aggregation_with_where_clause() {
        let graph = setup_test_graph().unwrap();
        let gql = Gql::new(&graph);

        // Test COUNT with WHERE clause
        let result = gql
            .execute("MATCH (p:Person) WHERE p.age > 25 RETURN COUNT(p)")
            .unwrap();
        assert_eq!(result.row_count(), 1);
        if let QueryValue::Integer(count) = &result.rows[0][0] {
            assert!(*count >= 1, "Should count at least Alice (age 30)");
        }

        // Test aggregation with relationship patterns
        let result = gql
            .execute("MATCH (p:Person)-[:KNOWS]->(f:Person) RETURN COUNT(*)")
            .unwrap();
        assert_eq!(result.row_count(), 1);
        println!("Relationship count: {result:?}");
    }

    #[test]
    fn test_aggregation_with_path_patterns() {
        let graph = setup_test_graph().unwrap();
        let gql = Gql::new(&graph);

        // Test COUNT with path patterns
        let result = gql
            .execute("MATCH (p:Person)-[:WORKS_FOR]->(c:Company) RETURN COUNT(p), COUNT(c)")
            .unwrap();
        assert_eq!(result.columns.len(), 2);
        assert_eq!(result.row_count(), 1);
        println!("Path pattern aggregation: {result:?}");

        // Test aggregation with relationship filtering
        let result = gql
            .execute("MATCH (p:Person)-[:KNOWS]->(friend:Person) RETURN COUNT(friend)")
            .unwrap();
        assert_eq!(result.row_count(), 1);
    }

    #[test]
    fn test_complex_aggregation_scenario() {
        // Create a more comprehensive test graph for aggregation
        let mut graph = Graph::new().unwrap();

        // Create multiple person nodes with different ages and salaries
        for i in 1..=5 {
            graph
                .create_node(
                    [
                        ("type".to_string(), json!("Person")),
                        ("name".to_string(), json!(format!("Person{}", i))),
                        ("age".to_string(), json!(20 + i * 5)),
                        ("salary".to_string(), json!(30000 + i * 10000)),
                    ]
                    .into(),
                )
                .unwrap();
        }

        let graph = RefCell::new(graph);
        let gql = Gql::new(&graph);

        // Test multiple aggregations in one query
        let result = gql.execute("MATCH (p:Person) RETURN COUNT(p), AVG(p.age), SUM(p.salary), MIN(p.age), MAX(p.salary)").unwrap();
        assert_eq!(result.columns.len(), 5);
        assert_eq!(result.row_count(), 1);

        // Verify the results
        let row = &result.rows[0];

        // COUNT should be 5
        if let QueryValue::Integer(count) = &row[0] {
            assert_eq!(*count, 5);
        }

        // AVG(age) should be reasonable (ages are 25, 30, 35, 40, 45, avg=35)
        match &row[1] {
            QueryValue::Float(avg) => assert_eq!(*avg, 35.0),
            QueryValue::Integer(avg) => assert_eq!(*avg, 35),
            _ => panic!("Expected numeric average"),
        }

        // SUM(salary) should be sum of 40000, 50000, 60000, 70000, 80000 = 300000
        match &row[2] {
            QueryValue::Integer(sum) => assert_eq!(*sum, 300000),
            QueryValue::Float(sum) => assert_eq!(*sum, 300000.0),
            _ => panic!("Expected numeric sum"),
        }

        // MIN(age) should be 25
        match &row[3] {
            QueryValue::Integer(min_age) => assert_eq!(*min_age, 25),
            _ => panic!("Expected integer minimum age"),
        }

        // MAX(salary) should be 80000
        match &row[4] {
            QueryValue::Integer(max_salary) => assert_eq!(*max_salary, 80000),
            _ => panic!("Expected integer maximum salary"),
        }

        println!("Complex aggregation results: {result:?}");
    }

    #[test]
    fn test_aggregation_with_nulls() {
        // Test aggregation behavior with null values
        let mut graph = Graph::new().unwrap();

        // Create nodes with some missing properties
        graph
            .create_node(
                [
                    ("type".to_string(), json!("Person")),
                    ("name".to_string(), json!("Alice")),
                    ("age".to_string(), json!(30)),
                ]
                .into(),
            )
            .unwrap();

        graph
            .create_node(
                [
                    ("type".to_string(), json!("Person")),
                    ("name".to_string(), json!("Bob")),
                    // No age property - should be treated as null
                ]
                .into(),
            )
            .unwrap();

        graph
            .create_node(
                [
                    ("type".to_string(), json!("Person")),
                    ("name".to_string(), json!("Charlie")),
                    ("age".to_string(), json!(25)),
                ]
                .into(),
            )
            .unwrap();

        let graph = RefCell::new(graph);
        let gql = Gql::new(&graph);

        // COUNT(*) should count all nodes
        let result = gql.execute("MATCH (p:Person) RETURN COUNT(*)").unwrap();
        if let QueryValue::Integer(count) = &result.rows[0][0] {
            assert_eq!(*count, 3, "COUNT(*) should count all 3 nodes");
        }

        // COUNT(p.age) should only count non-null age values
        let result = gql.execute("MATCH (p:Person) RETURN COUNT(p.age)").unwrap();
        if let QueryValue::Integer(count) = &result.rows[0][0] {
            assert_eq!(*count, 2, "COUNT(p.age) should count only 2 non-null ages");
        }

        // AVG(p.age) should average only non-null values (30 + 25) / 2 = 27.5
        let result = gql.execute("MATCH (p:Person) RETURN AVG(p.age)").unwrap();
        if let QueryValue::Float(avg) = &result.rows[0][0] {
            assert_eq!(*avg, 27.5, "AVG should ignore null values");
        }
    }
}