grafeo-engine 0.5.41

Query engine and database management for Grafeo
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
//! Integration tests targeting `crates/grafeo-engine/src/query/planner/lpg/project.rs`.
//!
//! This suite exercises the projection, RETURN, WITH, LIMIT, SKIP, ORDER BY, and
//! DISTINCT planning branches that are not otherwise covered by the higher level
//! test suites. Each test is focused on a specific branch of plan_return,
//! plan_project, plan_limit, plan_skip, or plan_sort.
//!
//! ```bash
//! cargo test -p grafeo-engine --all-features --test coverage_project
//! ```
//!
//! Test data uses Tarantino characters and European cities per project
//! conventions.

use grafeo_common::types::Value;
use grafeo_engine::GrafeoDB;

// ============================================================================
// Fixtures
// ============================================================================

/// Creates a small social graph used by most tests.
///
/// Nodes:
///   (Vincent:Person {age:30, city:'Amsterdam'})
///   (Jules:Person {age:25, city:'Berlin'})
///   (Mia:Person {age:35, city:'Paris'})
///
/// Edges:
///   Vincent -[:KNOWS {since:2019}]-> Jules
///   Jules   -[:KNOWS {since:2020}]-> Mia
///   Vincent -[:KNOWS {since:2021}]-> Mia
fn tarantino_graph() -> GrafeoDB {
    let db = GrafeoDB::new_in_memory();
    let session = db.session();

    let vincent = session
        .create_node_with_props(
            &["Person"],
            [
                ("name", Value::String("Vincent".into())),
                ("age", Value::Int64(30)),
                ("city", Value::String("Amsterdam".into())),
            ],
        )
        .unwrap();
    let jules = session
        .create_node_with_props(
            &["Person"],
            [
                ("name", Value::String("Jules".into())),
                ("age", Value::Int64(25)),
                ("city", Value::String("Berlin".into())),
            ],
        )
        .unwrap();
    let mia = session
        .create_node_with_props(
            &["Person"],
            [
                ("name", Value::String("Mia".into())),
                ("age", Value::Int64(35)),
                ("city", Value::String("Paris".into())),
            ],
        )
        .unwrap();

    session.create_edge(vincent, jules, "KNOWS");
    session.create_edge(jules, mia, "KNOWS");
    session.create_edge(vincent, mia, "KNOWS");

    drop(session);
    db
}

// ============================================================================
// plan_return: standalone RETURN (Empty input path)
// ============================================================================

/// Exercises the Empty input branch that wraps `SingleRowOperator`.
#[test]
fn standalone_return_literal_expression() {
    let db = GrafeoDB::new_in_memory();
    let session = db.session();

    let result = session.execute("RETURN 2 * 3 AS product").unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::Int64(6));
}

/// Standalone RETURN with a literal expression alias.
#[test]
fn standalone_return_string_literal() {
    let db = GrafeoDB::new_in_memory();
    let session = db.session();

    let result = session
        .execute("RETURN 'Amsterdam' AS city, 42 AS answer")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::String("Amsterdam".into()));
    assert_eq!(result.rows()[0][1], Value::Int64(42));
}

// ============================================================================
// plan_return: RETURN * wildcard (expanded_items path)
// ============================================================================

#[test]
fn return_star_expands_all_user_columns() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute("MATCH (n:Person {name: 'Vincent'}) RETURN *")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    // `n` should be the single expanded column.
    assert!(!result.columns.is_empty());
    assert!(
        result
            .columns
            .iter()
            .any(|col| col == "n" || !col.starts_with('_')),
        "columns: {:?}",
        result.columns
    );
}

#[test]
fn return_star_skips_internal_underscore_columns() {
    // The wildcard expander filters out columns that start with '_' (e.g.
    // _path_nodes_..., _path_edges_...). A variable length path creates such
    // internal columns; RETURN * should not include them.
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute("MATCH (p = (a:Person {name: 'Vincent'})-[:KNOWS]->(b:Person)){1,1} RETURN *")
        .unwrap();
    // Every user-visible column must not start with an underscore.
    for col in &result.columns {
        assert!(
            !col.starts_with('_'),
            "internal column leaked into RETURN *: {col}"
        );
    }
    assert!(!result.rows().is_empty());
}

// ============================================================================
// plan_return: FunctionCall branches (type, length, nodes, edges)
// ============================================================================

/// Exercises the `type()` function branch (ProjectExpr::EdgeType).
#[test]
fn return_type_of_edge_variable() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute("MATCH (a:Person)-[r:KNOWS]->(b:Person) RETURN type(r) AS rel_type LIMIT 1")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::String("KNOWS".into()));
}

/// Exercises the `length()` branch for a path variable.
#[test]
fn return_length_of_path_variable() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute(
            "MATCH (p = (a:Person {name: 'Vincent'})-[:KNOWS]->(b:Person)){1,2} \
             RETURN length(p) AS len ORDER BY len",
        )
        .unwrap();
    assert!(!result.rows().is_empty());
    let lengths: Vec<i64> = result
        .rows()
        .iter()
        .filter_map(|r| match &r[0] {
            Value::Int64(n) => Some(*n),
            _ => None,
        })
        .collect();
    assert!(lengths.contains(&1), "missing 1 hop, got {lengths:?}");
    assert!(lengths.contains(&2), "missing 2 hop, got {lengths:?}");
}

/// Exercises the `nodes()` branch and the path detail column mapping.
#[test]
fn return_nodes_of_path_variable() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute(
            "MATCH (p = (a:Person {name: 'Vincent'})-[:KNOWS]->(b:Person)){1,1} \
             RETURN nodes(p) AS ns",
        )
        .unwrap();
    assert_eq!(result.rows().len(), 2); // Vincent -> Jules, Vincent -> Mia
    for row in result.rows() {
        match &row[0] {
            Value::List(items) => assert_eq!(items.len(), 2, "expected 2 nodes per hop"),
            other => panic!("expected list, got {other:?}"),
        }
    }
}

/// Exercises the `edges()` branch (edges() is the "edges" case, not
/// "relationships").
#[test]
fn return_edges_of_path_variable() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute(
            "MATCH (p = (a:Person {name: 'Vincent'})-[:KNOWS]->(b:Person)){1,1} \
             RETURN edges(p) AS es",
        )
        .unwrap();
    assert_eq!(result.rows().len(), 2);
    for row in result.rows() {
        match &row[0] {
            Value::List(items) => assert_eq!(items.len(), 1, "expected 1 edge per 1 hop path"),
            other => panic!("expected list, got {other:?}"),
        }
    }
}

// ============================================================================
// plan_return: length() fall through to expression evaluation
// ============================================================================

/// length(string) must fall through to expression evaluation rather than the
/// path length branch.
#[test]
fn return_length_of_string_expression() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute("MATCH (n:Person {name: 'Vincent'}) RETURN size(n.name) AS len")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::Int64(7));
}

// ============================================================================
// plan_return: other function calls fall through to expression evaluation
// ============================================================================

#[test]
fn return_other_builtin_function_falls_through() {
    let db = tarantino_graph();
    let session = db.session();

    // head() exercises the "other functions" default branch in plan_return.
    let result = session
        .execute("MATCH (n:Person {name: 'Vincent'}) RETURN head([n.name, 'placeholder']) AS first")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::String("Vincent".into()));
}

// ============================================================================
// plan_return: Literal branch in projection
// ============================================================================

#[test]
fn return_literal_constant_in_projection() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute("MATCH (n:Person {name: 'Vincent'}) RETURN n.name AS who, 42 AS answer")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::String("Vincent".into()));
    assert_eq!(result.rows()[0][1], Value::Int64(42));
}

// ============================================================================
// plan_return: complex expression branches (Binary/Unary/List/Map/IndexAccess)
// ============================================================================

#[test]
fn return_binary_expression() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute("MATCH (n:Person {name: 'Vincent'}) RETURN n.age + 5 AS bumped")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::Int64(35));
}

#[test]
fn return_unary_expression() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute("MATCH (n:Person {name: 'Vincent'}) RETURN -n.age AS negated")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::Int64(-30));
}

#[test]
fn return_list_literal() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute("MATCH (n:Person {name: 'Vincent'}) RETURN [n.name, n.city] AS info")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    match &result.rows()[0][0] {
        Value::List(items) => {
            assert_eq!(items.len(), 2);
            assert_eq!(items[0], Value::String("Vincent".into()));
            assert_eq!(items[1], Value::String("Amsterdam".into()));
        }
        other => panic!("expected list, got {other:?}"),
    }
}

#[test]
fn return_index_access() {
    let db = GrafeoDB::new_in_memory();
    let session = db.session();

    let result = session
        .execute("UNWIND [['Vincent', 'Jules', 'Mia']] AS names RETURN names[1] AS pick")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::String("Jules".into()));
}

#[test]
fn return_list_comprehension() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute(
            "MATCH (n:Person {name: 'Vincent'}) \
             RETURN [x IN [1, 2, 3] WHERE x > 1 | x * 10] AS doubled",
        )
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    match &result.rows()[0][0] {
        Value::List(items) => {
            assert_eq!(items.len(), 2);
            assert_eq!(items[0], Value::Int64(20));
            assert_eq!(items[1], Value::Int64(30));
        }
        other => panic!("expected list, got {other:?}"),
    }
}

#[test]
fn return_list_predicate_any() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute(
            "MATCH (n:Person {name: 'Vincent'}) \
             RETURN any(x IN [1, 2, 3] WHERE x > 2) AS has_big",
        )
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::Bool(true));
}

// ============================================================================
// plan_return: CASE branch
// ============================================================================

#[test]
fn return_case_when_expression() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute(
            "MATCH (n:Person) \
             RETURN n.name, \
             CASE WHEN n.age >= 30 THEN 'senior' ELSE 'junior' END AS tier \
             ORDER BY n.name",
        )
        .unwrap();
    assert_eq!(result.rows().len(), 3);
    // Jules (25) => junior, Mia (35) => senior, Vincent (30) => senior
    let rows = result.rows();
    assert_eq!(rows[0][0], Value::String("Jules".into()));
    assert_eq!(rows[0][1], Value::String("junior".into()));
    assert_eq!(rows[1][0], Value::String("Mia".into()));
    assert_eq!(rows[1][1], Value::String("senior".into()));
    assert_eq!(rows[2][0], Value::String("Vincent".into()));
    assert_eq!(rows[2][1], Value::String("senior".into()));
}

// ============================================================================
// plan_return simple case (no project operator needed): bare variables only.
// Covers the pass-through branch and edge_columns / scalar_columns routing.
// ============================================================================

#[test]
fn return_bare_node_variable_emits_resolved_map() {
    let db = tarantino_graph();
    let session = db.session();

    // RETURN n (bare node variable) hits plan_return_projection's simple
    // branch, which emits ProjectExpr::NodeResolve.
    let result = session
        .execute("MATCH (n:Person {name: 'Vincent'}) RETURN n")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert!(
        matches!(&result.rows()[0][0], Value::Map(_)),
        "expected node resolved to Map, got {:?}",
        result.rows()[0][0]
    );
}

#[test]
fn return_bare_edge_variable_emits_resolved_map() {
    let db = tarantino_graph();
    let session = db.session();

    // RETURN r (bare edge variable) hits plan_return_projection's simple
    // branch, which emits ProjectExpr::EdgeResolve.
    let result = session
        .execute("MATCH (a:Person)-[r:KNOWS]->(b:Person) RETURN r LIMIT 1")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert!(
        matches!(&result.rows()[0][0], Value::Map(_)),
        "expected edge resolved to Map, got {:?}",
        result.rows()[0][0]
    );
}

#[test]
fn return_bare_scalar_variable_pass_through() {
    let db = GrafeoDB::new_in_memory();
    let session = db.session();

    // UNWIND binds `x` as a scalar column, then RETURN x hits the
    // scalar_columns branch in plan_return_projection.
    let result = session
        .execute("UNWIND [10, 20, 30] AS x RETURN x ORDER BY x")
        .unwrap();
    assert_eq!(result.rows().len(), 3);
    assert_eq!(result.rows()[0][0], Value::Int64(10));
    assert_eq!(result.rows()[1][0], Value::Int64(20));
    assert_eq!(result.rows()[2][0], Value::Int64(30));
}

// ============================================================================
// plan_return: DISTINCT
// ============================================================================

#[test]
fn return_distinct_deduplicates_values() {
    let db = tarantino_graph();
    let session = db.session();

    // Amsterdam, Berlin, Paris are all distinct.
    let result = session
        .execute("MATCH (n:Person) RETURN DISTINCT n.city")
        .unwrap();
    assert_eq!(result.rows().len(), 3);
}

#[test]
fn return_distinct_with_duplicates() {
    let db = GrafeoDB::new_in_memory();
    let session = db.session();

    // Insert two persons in the same city so DISTINCT actually drops a row.
    session
        .create_node_with_props(
            &["Person"],
            [
                ("name", Value::String("Butch".into())),
                ("city", Value::String("Prague".into())),
            ],
        )
        .unwrap();
    session
        .create_node_with_props(
            &["Person"],
            [
                ("name", Value::String("Django".into())),
                ("city", Value::String("Prague".into())),
            ],
        )
        .unwrap();
    drop(session);
    let session = db.session();

    let result = session
        .execute("MATCH (n:Person) RETURN DISTINCT n.city")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::String("Prague".into()));
}

// ============================================================================
// plan_project (WITH): Variable, Property, Literal, complex branches
// ============================================================================

#[test]
fn with_variable_node_passthrough() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute("MATCH (n:Person {name: 'Vincent'}) WITH n RETURN n.name")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::String("Vincent".into()));
}

#[test]
fn with_property_access_registers_as_scalar() {
    let db = tarantino_graph();
    let session = db.session();

    // WITH n.name AS name forces the Property branch in plan_project.
    let result = session
        .execute("MATCH (n:Person) WITH n.name AS name WHERE name = 'Jules' RETURN name")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::String("Jules".into()));
}

#[test]
fn with_literal_constant() {
    let db = tarantino_graph();
    let session = db.session();

    // WITH 123 AS answer forces the Literal branch in plan_project.
    let result = session
        .execute("MATCH (n:Person {name: 'Vincent'}) WITH n, 123 AS answer RETURN n.name, answer")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::String("Vincent".into()));
    assert_eq!(result.rows()[0][1], Value::Int64(123));
}

#[test]
fn with_complex_expression_is_registered_scalar() {
    let db = tarantino_graph();
    let session = db.session();

    // WITH n.age + 1 AS plus forces the catch-all branch (expression
    // evaluation) in plan_project.
    let result = session
        .execute("MATCH (n:Person {name: 'Jules'}) WITH n.age + 1 AS plus RETURN plus")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::Int64(26));
}

#[test]
fn with_edge_variable_preserved_as_edge_column() {
    let db = tarantino_graph();
    let session = db.session();

    // WITH r (bare edge variable) must preserve edge_columns metadata so the
    // downstream RETURN resolves it as an edge, not a node.
    let result = session
        .execute("MATCH (a:Person)-[r:KNOWS]->(b:Person) WITH r RETURN type(r) AS rel_type LIMIT 1")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::String("KNOWS".into()));
}

// ============================================================================
// plan_project: Empty input (standalone WITH)
// ============================================================================

#[test]
fn with_literal_list_and_size() {
    // Exercises the plan_project path with a literal list, feeding into a
    // later WITH that evaluates size(). GQL requires WITH to follow a leading
    // statement, so we prefix with UNWIND on a single row.
    let db = GrafeoDB::new_in_memory();
    let session = db.session();

    let result = session
        .execute(
            "UNWIND [1] AS seed \
             WITH seed, [1, 2, 3] AS nums \
             RETURN size(nums) AS n",
        )
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::Int64(3));
}

#[test]
fn with_multiple_literal_bindings() {
    // Multiple literal WITH bindings exercise the Literal branch in
    // plan_project.
    let db = GrafeoDB::new_in_memory();
    let session = db.session();

    let result = session
        .execute(
            "UNWIND [1] AS seed \
             WITH 'Prague' AS city, 100 AS score \
             RETURN city, score",
        )
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::String("Prague".into()));
    assert_eq!(result.rows()[0][1], Value::Int64(100));
}

// ============================================================================
// plan_project with pass_through_input (GQL LET clause)
// ============================================================================

#[test]
fn let_clause_passes_through_inputs_and_appends() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute(
            "MATCH (n:Person {name: 'Vincent'}) \
             LET bonus = n.age * 2 \
             RETURN n.name, bonus",
        )
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::String("Vincent".into()));
    assert_eq!(result.rows()[0][1], Value::Int64(60));
}

// ============================================================================
// plan_limit / plan_skip
// ============================================================================

#[test]
fn limit_restricts_output_count() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute("MATCH (n:Person) RETURN n.name ORDER BY n.name LIMIT 2")
        .unwrap();
    assert_eq!(result.rows().len(), 2);
}

#[test]
fn skip_offsets_output() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute("MATCH (n:Person) RETURN n.name ORDER BY n.name SKIP 1")
        .unwrap();
    assert_eq!(result.rows().len(), 2);
    assert_eq!(result.rows()[0][0], Value::String("Mia".into()));
    assert_eq!(result.rows()[1][0], Value::String("Vincent".into()));
}

#[test]
fn skip_then_limit_combines() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute("MATCH (n:Person) RETURN n.name ORDER BY n.name SKIP 1 LIMIT 1")
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert_eq!(result.rows()[0][0], Value::String("Mia".into()));
}

// ============================================================================
// plan_sort: all branches
// ============================================================================

#[test]
fn order_by_property_ascending_pre_return_projection() {
    let db = tarantino_graph();
    let session = db.session();

    // RETURN projects only n.name, so ORDER BY n.age requires pre-Return
    // property projection (the needs_pre_return path).
    let result = session
        .execute("MATCH (n:Person) RETURN n.name ORDER BY n.age")
        .unwrap();
    assert_eq!(result.rows().len(), 3);
    assert_eq!(result.rows()[0][0], Value::String("Jules".into())); // 25
    assert_eq!(result.rows()[1][0], Value::String("Vincent".into())); // 30
    assert_eq!(result.rows()[2][0], Value::String("Mia".into())); // 35
    // Output has only the 1 user column (the extra sort-key column is stripped).
    assert_eq!(result.columns.len(), 1);
}

#[test]
fn order_by_property_descending_pre_return_projection() {
    let db = tarantino_graph();
    let session = db.session();

    let result = session
        .execute("MATCH (n:Person) RETURN n.name ORDER BY n.age DESC")
        .unwrap();
    assert_eq!(result.rows().len(), 3);
    assert_eq!(result.rows()[0][0], Value::String("Mia".into()));
    assert_eq!(result.rows()[1][0], Value::String("Vincent".into()));
    assert_eq!(result.rows()[2][0], Value::String("Jules".into()));
}

#[test]
fn order_by_property_already_in_return() {
    let db = tarantino_graph();
    let session = db.session();

    // ORDER BY n.name references a property the Return has already projected
    // as "n.name": no extra pre-Return projection needed.
    let result = session
        .execute("MATCH (n:Person) RETURN n.name ORDER BY n.name")
        .unwrap();
    assert_eq!(result.rows().len(), 3);
    assert_eq!(result.rows()[0][0], Value::String("Jules".into()));
    assert_eq!(result.rows()[1][0], Value::String("Mia".into()));
    assert_eq!(result.rows()[2][0], Value::String("Vincent".into()));
    // No extra columns leaked.
    assert_eq!(result.columns.len(), 1);
}

#[test]
fn order_by_with_aliased_property() {
    let db = tarantino_graph();
    let session = db.session();

    // RETURN n.name AS who: the alias is what the caller sees. ORDER BY uses
    // the original variable path. Exercises the alias registration branch in
    // plan_sort.
    let result = session
        .execute("MATCH (n:Person) RETURN n.name AS who ORDER BY n.name")
        .unwrap();
    assert_eq!(result.rows().len(), 3);
    assert_eq!(result.rows()[0][0], Value::String("Jules".into()));
}

#[test]
fn order_by_on_labels_index_access() {
    // Complex expression: labels(n)[0] forces the expression-extras branch
    // in plan_sort (Labels + IndexAccess).
    let db = GrafeoDB::new_in_memory();
    let session = db.session();
    session
        .create_node_with_props(&["Bot"], [("name", Value::String("Hans".into()))])
        .unwrap();
    session
        .create_node_with_props(&["Person"], [("name", Value::String("Beatrix".into()))])
        .unwrap();
    drop(session);
    let session = db.session();

    let result = session
        .execute("MATCH (n) RETURN n.name ORDER BY labels(n)[0]")
        .unwrap();
    assert_eq!(result.rows().len(), 2);
    // Bot < Person lexicographically
    assert_eq!(result.rows()[0][0], Value::String("Hans".into()));
    assert_eq!(result.rows()[1][0], Value::String("Beatrix".into()));
    // The synthetic __expr_ column must be stripped.
    assert_eq!(result.columns.len(), 1);
}

#[test]
fn order_by_on_edge_type_function() {
    // type(r) as an ORDER BY expression forces the expression extras branch.
    let db = GrafeoDB::new_in_memory();
    let session = db.session();
    let a = session
        .create_node_with_props(&["Person"], [("name", Value::String("Shosanna".into()))])
        .unwrap();
    let b = session
        .create_node_with_props(&["Person"], [("name", Value::String("Hans".into()))])
        .unwrap();
    let c = session
        .create_node_with_props(&["Person"], [("name", Value::String("Beatrix".into()))])
        .unwrap();
    session.create_edge(a, b, "LIKES");
    session.create_edge(a, c, "ADMIRES");
    drop(session);
    let session = db.session();

    let result = session
        .execute(
            "MATCH (a:Person {name: 'Shosanna'})-[r]->(b:Person) \
             RETURN b.name ORDER BY type(r)",
        )
        .unwrap();
    assert_eq!(result.rows().len(), 2);
    // ADMIRES < LIKES => Beatrix first, Hans second
    assert_eq!(result.rows()[0][0], Value::String("Beatrix".into()));
    assert_eq!(result.rows()[1][0], Value::String("Hans".into()));
    assert_eq!(result.columns.len(), 1);
}

#[test]
fn order_by_nulls_first_explicit() {
    let db = GrafeoDB::new_in_memory();
    let session = db.session();
    session
        .create_node_with_props(
            &["Item"],
            [
                ("name", Value::String("first".into())),
                ("score", Value::Int64(10)),
            ],
        )
        .unwrap();
    session
        .create_node_with_props(&["Item"], [("name", Value::String("missing".into()))])
        .unwrap();
    drop(session);
    let session = db.session();

    let result = session
        .execute("MATCH (n:Item) RETURN n.name ORDER BY n.score ASC NULLS FIRST")
        .unwrap();
    assert_eq!(result.rows().len(), 2);
    // NULL comes first
    assert_eq!(result.rows()[0][0], Value::String("missing".into()));
    assert_eq!(result.rows()[1][0], Value::String("first".into()));
}

#[test]
fn order_by_nulls_last_explicit() {
    let db = GrafeoDB::new_in_memory();
    let session = db.session();
    session
        .create_node_with_props(
            &["Item"],
            [
                ("name", Value::String("valued".into())),
                ("score", Value::Int64(42)),
            ],
        )
        .unwrap();
    session
        .create_node_with_props(&["Item"], [("name", Value::String("unknown".into()))])
        .unwrap();
    drop(session);
    let session = db.session();

    let result = session
        .execute("MATCH (n:Item) RETURN n.name ORDER BY n.score ASC NULLS LAST")
        .unwrap();
    assert_eq!(result.rows().len(), 2);
    // NULL comes last
    assert_eq!(result.rows()[0][0], Value::String("valued".into()));
    assert_eq!(result.rows()[1][0], Value::String("unknown".into()));
}

#[test]
fn order_by_on_scalar_column_from_with() {
    let db = tarantino_graph();
    let session = db.session();

    // ORDER BY on a plain variable (the "Already in variable_columns" branch
    // in plan_sort and the no-extra-projections path). Include `age` in the
    // RETURN list so it is available to the sort.
    let result = session
        .execute(
            "MATCH (n:Person) \
             WITH n.name AS name, n.age AS age \
             RETURN name, age ORDER BY age",
        )
        .unwrap();
    assert_eq!(result.rows().len(), 3);
    assert_eq!(result.rows()[0][0], Value::String("Jules".into()));
    assert_eq!(result.rows()[1][0], Value::String("Vincent".into()));
    assert_eq!(result.rows()[2][0], Value::String("Mia".into()));
}

#[test]
fn order_by_multiple_keys_mixed_directions() {
    let db = GrafeoDB::new_in_memory();
    let session = db.session();
    for (n, c, a) in [
        ("Vincent", "Amsterdam", 30),
        ("Jules", "Amsterdam", 40),
        ("Butch", "Berlin", 25),
        ("Django", "Berlin", 35),
    ] {
        session
            .create_node_with_props(
                &["Person"],
                [
                    ("name", Value::String(n.into())),
                    ("city", Value::String(c.into())),
                    ("age", Value::Int64(a)),
                ],
            )
            .unwrap();
    }
    drop(session);
    let session = db.session();

    // Primary: city ASC, secondary: age DESC
    let result = session
        .execute("MATCH (n:Person) RETURN n.name ORDER BY n.city ASC, n.age DESC")
        .unwrap();
    assert_eq!(result.rows().len(), 4);
    // Amsterdam (Jules age 40, Vincent age 30), Berlin (Django age 35, Butch age 25)
    assert_eq!(result.rows()[0][0], Value::String("Jules".into()));
    assert_eq!(result.rows()[1][0], Value::String("Vincent".into()));
    assert_eq!(result.rows()[2][0], Value::String("Django".into()));
    assert_eq!(result.rows()[3][0], Value::String("Butch".into()));
    assert_eq!(result.columns.len(), 1);
}

// ============================================================================
// derive_schema_from_columns: indirectly exercised via an edge column RETURN
// ============================================================================

#[test]
fn schema_derivation_preserves_edge_column_type() {
    let db = tarantino_graph();
    let session = db.session();

    // WITH r keeps r in edge_columns; downstream RETURN invokes
    // derive_schema_from_columns on the surviving columns. The subsequent
    // RETURN still resolves r as an edge Map.
    let result = session
        .execute(
            "MATCH (a:Person)-[r:KNOWS]->(b:Person) \
             WITH r \
             RETURN r LIMIT 1",
        )
        .unwrap();
    assert_eq!(result.rows().len(), 1);
    assert!(
        matches!(&result.rows()[0][0], Value::Map(_)),
        "edge should be resolved to Map, got {:?}",
        result.rows()[0][0]
    );
}