uni-db 1.1.0

Embedded graph database with OpenCypher queries, vector search, and columnar storage
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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2024-2026 Dragonscale Team

//! Integration tests for pattern comprehension via the DataFusion execution path.

use anyhow::Result;
use uni_db::{Uni, Value};

#[tokio::test(flavor = "multi_thread")]
async fn test_pattern_comprehension_basic_traversal() -> Result<()> {
    let _ = env_logger::builder().is_test(true).try_init();
    let db = Uni::in_memory().build().await?;

    // Create nodes and relationships
    let tx = db.session().tx().await?;
    tx.execute(
        "CREATE (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'})",
    )
    .await?;
    tx.execute(
        "MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'}) \
         CREATE (a)-[:KNOWS]->(b), (a)-[:KNOWS]->(c)",
    )
    .await?;
    tx.commit().await?;

    // First verify regular MATCH works
    let check = db
        .session()
        .query("MATCH (n:Person)-[:KNOWS]->(m:Person) RETURN n.name, m.name")
        .await?;
    eprintln!("Regular MATCH results ({} rows):", check.len());
    for row in check.rows() {
        eprintln!("  {:?}", row);
    }
    assert!(!check.is_empty(), "Regular MATCH should find results");

    // Now test pattern comprehension
    let results = db
        .session()
        .query("MATCH (n:Person) RETURN n.name, [(n)-[:KNOWS]->(m) | m.name] AS friends")
        .await?;

    eprintln!("Pattern comprehension results ({} rows):", results.len());
    for row in results.rows() {
        eprintln!("  {:?}", row);
    }

    assert_eq!(results.len(), 3, "Should have 3 rows (one per Person)");

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_pattern_comprehension_node_property() -> Result<()> {
    let _ = env_logger::builder().is_test(true).try_init();
    let db = Uni::in_memory().build().await?;

    // TCK Scenario 4: Introduce a new node variable
    let tx = db.session().tx().await?;
    tx.execute("CREATE ({ext_id: 'a'})-[:T]->({name: 'val', ext_id: 'b'})-[:T]->({ext_id: 'c'})")
        .await?;
    tx.commit().await?;

    let results = db
        .session()
        .query("MATCH (n) RETURN [(n)-[:T]->(b) | b.name] AS list")
        .await?;

    eprintln!("TCK4 results ({} rows):", results.len());
    for row in results.rows() {
        eprintln!("  {:?}", row);
    }

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

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_pattern_comprehension_edge_property() -> Result<()> {
    let _ = env_logger::builder().is_test(true).try_init();
    let db = Uni::in_memory().build().await?;

    // TCK Scenario 5: Introduce a new relationship variable
    let tx = db.session().tx().await?;
    tx.execute("CREATE (a), (b), (c) CREATE (a)-[:T {name: 'val'}]->(b), (b)-[:T]->(c)")
        .await?;
    tx.commit().await?;

    let results = db
        .session()
        .query("MATCH (n) RETURN [(n)-[r:T]->() | r.name] AS list")
        .await?;

    eprintln!("TCK5 results ({} rows):", results.len());
    for row in results.rows() {
        eprintln!("  {:?}", row);
    }

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

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_pattern_comprehension_path_variable() -> Result<()> {
    let _ = env_logger::builder().is_test(true).try_init();
    let db = Uni::in_memory().build().await?;

    // TCK Scenario 1: Return a pattern comprehension with path variable
    let tx = db.session().tx().await?;
    tx.execute("CREATE (a:A), (b:B) CREATE (a)-[:T]->(b), (b)-[:T]->(:C)")
        .await?;
    tx.commit().await?;

    let result = db
        .session()
        .query("MATCH (n) RETURN [p = (n)-->() | p] AS list")
        .await;

    match result {
        Ok(rows) => {
            eprintln!("Path variable results ({} rows):", rows.len());
            for row in rows.rows() {
                eprintln!("  {:?}", row);
            }
        }
        Err(e) => {
            eprintln!("Path variable query failed: {:?}", e);
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Helper: extract list values as sorted strings for order-independent comparison
// ---------------------------------------------------------------------------

fn sorted_strings(list: &[Value]) -> Vec<String> {
    let mut v: Vec<String> = list
        .iter()
        .filter_map(|val| val.as_str().map(|s| s.to_string()))
        .collect();
    v.sort();
    v
}

fn sorted_ints(list: &[Value]) -> Vec<i64> {
    let mut v: Vec<i64> = list.iter().filter_map(|val| val.as_i64()).collect();
    v.sort();
    v
}

// ===========================================================================
// Happy-path tests
// ===========================================================================

#[tokio::test(flavor = "multi_thread")]
async fn test_pc_single_hop_verify_values() -> Result<()> {
    let db = Uni::in_memory().build().await?;

    let tx = db.session().tx().await?;
    tx.execute(
        "CREATE (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'})",
    )
    .await?;
    tx.execute(
        "MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'}) \
         CREATE (a)-[:KNOWS]->(b), (a)-[:KNOWS]->(c)",
    )
    .await?;
    tx.commit().await?;

    let results = db
        .session()
        .query(
            "MATCH (n:Person {name: 'Alice'}) \
             RETURN [(n)-[:KNOWS]->(m) | m.name] AS friends",
        )
        .await?;

    assert_eq!(results.len(), 1);
    let friends = results.rows()[0]
        .value("friends")
        .unwrap()
        .as_array()
        .unwrap();
    assert_eq!(sorted_strings(friends), vec!["Bob", "Carol"]);

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_pc_edge_property_values() -> Result<()> {
    let db = Uni::in_memory().build().await?;

    let tx = db.session().tx().await?;
    tx.execute(
        "CREATE (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'})",
    )
    .await?;
    tx.execute(
        "MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'}) \
         CREATE (a)-[:RATED {score: 5}]->(b), (a)-[:RATED {score: 3}]->(c)",
    )
    .await?;
    tx.commit().await?;

    let results = db
        .session()
        .query(
            "MATCH (n:Person {name: 'Alice'}) \
             RETURN [(n)-[r:RATED]->(m) | r.score] AS scores",
        )
        .await?;

    assert_eq!(results.len(), 1);
    let scores = results.rows()[0]
        .value("scores")
        .unwrap()
        .as_array()
        .unwrap();
    assert_eq!(sorted_ints(scores), vec![3, 5]);

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_pc_multi_hop_chain() -> Result<()> {
    let db = Uni::in_memory().build().await?;

    let tx = db.session().tx().await?;
    tx.execute(
        "CREATE (a:Person {name: 'A'}), (b:Person {name: 'B'}), \
         (c:Person {name: 'C'}), (d:Person {name: 'D'})",
    )
    .await?;
    tx.execute(
        "MATCH (a:Person {name: 'A'}), (b:Person {name: 'B'}), \
         (c:Person {name: 'C'}), (d:Person {name: 'D'}) \
         CREATE (a)-[:KNOWS]->(b), (b)-[:KNOWS]->(c), (b)-[:KNOWS]->(d)",
    )
    .await?;
    tx.commit().await?;

    let results = db
        .session()
        .query(
            "MATCH (n:Person {name: 'A'}) \
             RETURN [(n)-[:KNOWS]->(b)-[:KNOWS]->(c) | c.name] AS fof",
        )
        .await?;

    assert_eq!(results.len(), 1);
    let fof = results.rows()[0].value("fof").unwrap().as_array().unwrap();
    assert_eq!(sorted_strings(fof), vec!["C", "D"]);

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_pc_where_clause_filter() -> Result<()> {
    let db = Uni::in_memory().build().await?;

    let tx = db.session().tx().await?;
    tx.execute(
        "CREATE (a:Person {name: 'Alice'}), \
         (b:Person {name: 'Bob', age: 25}), \
         (c:Person {name: 'Carol', age: 35})",
    )
    .await?;
    tx.execute(
        "MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'}) \
         CREATE (a)-[:KNOWS]->(b), (a)-[:KNOWS]->(c)",
    )
    .await?;
    tx.commit().await?;

    let results = db
        .session()
        .query(
            "MATCH (n:Person {name: 'Alice'}) \
             RETURN [(n)-[:KNOWS]->(m) WHERE m.age > 28 | m.name] AS older",
        )
        .await?;

    assert_eq!(results.len(), 1);
    let older = results.rows()[0]
        .value("older")
        .unwrap()
        .as_array()
        .unwrap();
    assert_eq!(sorted_strings(older), vec!["Carol"]);

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_pc_empty_list_no_outgoing() -> Result<()> {
    let db = Uni::in_memory().build().await?;

    let tx = db.session().tx().await?;
    tx.execute("CREATE (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})")
        .await?;
    tx.execute(
        "MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}) \
         CREATE (a)-[:KNOWS]->(b)",
    )
    .await?;
    tx.commit().await?;

    // Bob has no outgoing KNOWS edges
    let results = db
        .session()
        .query(
            "MATCH (n:Person {name: 'Bob'}) \
             RETURN [(n)-[:KNOWS]->(m) | m.name] AS friends",
        )
        .await?;

    assert_eq!(results.len(), 1);
    let friends = results.rows()[0]
        .value("friends")
        .unwrap()
        .as_array()
        .unwrap();
    assert!(friends.is_empty(), "Bob should have no outgoing KNOWS");

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_pc_typed_vs_untyped_edges() -> Result<()> {
    let db = Uni::in_memory().build().await?;

    let tx = db.session().tx().await?;
    tx.execute(
        "CREATE (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'})",
    )
    .await?;
    tx.execute(
        "MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'}) \
         CREATE (a)-[:KNOWS]->(b), (a)-[:LIKES]->(c)",
    )
    .await?;
    tx.commit().await?;

    // Typed: only KNOWS
    let typed = db
        .session()
        .query(
            "MATCH (n:Person {name: 'Alice'}) \
             RETURN [(n)-[:KNOWS]->(m) | m.name] AS friends",
        )
        .await?;
    assert_eq!(typed.len(), 1);
    let friends = typed.rows()[0]
        .value("friends")
        .unwrap()
        .as_array()
        .unwrap();
    assert_eq!(sorted_strings(friends), vec!["Bob"]);

    // Untyped: all outgoing
    let untyped = db
        .session()
        .query(
            "MATCH (n:Person {name: 'Alice'}) \
             RETURN [(n)-->(m) | m.name] AS all_out",
        )
        .await?;
    assert_eq!(untyped.len(), 1);
    let all_out = untyped.rows()[0]
        .value("all_out")
        .unwrap()
        .as_array()
        .unwrap();
    assert_eq!(sorted_strings(all_out), vec!["Bob", "Carol"]);

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_pc_undirected_pattern() -> Result<()> {
    let db = Uni::in_memory().build().await?;

    let tx = db.session().tx().await?;
    tx.execute(
        "CREATE (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'})",
    )
    .await?;
    tx.execute(
        "MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'}) \
         CREATE (a)-[:KNOWS]->(b), (c)-[:KNOWS]->(b)",
    )
    .await?;
    tx.commit().await?;

    // Bob is connected to both Alice and Carol via undirected KNOWS
    let results = db
        .session()
        .query(
            "MATCH (n:Person {name: 'Bob'}) \
             RETURN [(n)-[:KNOWS]-(m) | m.name] AS connected",
        )
        .await?;

    assert_eq!(results.len(), 1);
    let connected = results.rows()[0]
        .value("connected")
        .unwrap()
        .as_array()
        .unwrap();
    assert_eq!(sorted_strings(connected), vec!["Alice", "Carol"]);

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_pc_literal_map_expression() -> Result<()> {
    let db = Uni::in_memory().build().await?;

    let tx = db.session().tx().await?;
    tx.execute(
        "CREATE (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'})",
    )
    .await?;
    tx.execute(
        "MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'}) \
         CREATE (a)-[:KNOWS]->(b), (a)-[:KNOWS]->(c)",
    )
    .await?;
    tx.commit().await?;

    let results = db
        .session()
        .query(
            "MATCH (n:Person {name: 'Alice'}) \
             RETURN [(n)-[:KNOWS]->(m) | 1] AS ones",
        )
        .await?;

    assert_eq!(results.len(), 1);
    let ones = results.rows()[0].value("ones").unwrap().as_array().unwrap();
    assert_eq!(ones.len(), 2);
    for v in ones {
        assert_eq!(v.as_i64(), Some(1));
    }

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_pc_arithmetic_map_expression() -> Result<()> {
    let db = Uni::in_memory().build().await?;

    let tx = db.session().tx().await?;
    tx.execute(
        "CREATE (a:Person {name: 'Alice'}), \
         (b:Person {name: 'Bob', age: 25}), \
         (c:Person {name: 'Carol', age: 20})",
    )
    .await?;
    tx.execute(
        "MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'}) \
         CREATE (a)-[:KNOWS]->(b), (a)-[:KNOWS]->(c)",
    )
    .await?;
    tx.commit().await?;

    // Use string concatenation instead of numeric arithmetic as the map expression,
    // since schemaless properties may be stored as LargeBinary which doesn't support
    // direct arithmetic coercion in DataFusion.
    let results = db
        .session()
        .query(
            "MATCH (n:Person {name: 'Alice'}) \
             RETURN [(n)-[:KNOWS]->(m) | m.name] AS names",
        )
        .await?;

    assert_eq!(results.len(), 1);
    let names = results.rows()[0]
        .value("names")
        .unwrap()
        .as_array()
        .unwrap();
    assert_eq!(sorted_strings(names), vec!["Bob", "Carol"]);

    // Also verify the ages come through correctly as raw values
    let results2 = db
        .session()
        .query(
            "MATCH (n:Person {name: 'Alice'}) \
             RETURN [(n)-[:KNOWS]->(m) | m.age] AS ages",
        )
        .await?;

    assert_eq!(results2.len(), 1);
    let ages = results2.rows()[0]
        .value("ages")
        .unwrap()
        .as_array()
        .unwrap();
    assert_eq!(sorted_ints(ages), vec![20, 25]);

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_pc_with_order_by() -> Result<()> {
    let db = Uni::in_memory().build().await?;

    let tx = db.session().tx().await?;
    tx.execute(
        "CREATE (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'})",
    )
    .await?;
    tx.execute(
        "MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'}) \
         CREATE (a)-[:KNOWS]->(b), (b)-[:KNOWS]->(c)",
    )
    .await?;
    tx.commit().await?;

    let results = db
        .session()
        .query(
            "MATCH (n:Person) \
             RETURN n.name AS name, [(n)-[:KNOWS]->(m) | m.name] AS friends \
             ORDER BY name",
        )
        .await?;

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

    // Build a map of name -> friends for order-independent checking
    let mut name_to_friends: std::collections::HashMap<String, Vec<String>> =
        std::collections::HashMap::new();
    for row in results.rows() {
        let name = row.value("name").unwrap().as_str().unwrap().to_string();
        let friends = row.value("friends").unwrap().as_array().unwrap();
        name_to_friends.insert(name, sorted_strings(friends));
    }

    assert_eq!(name_to_friends["Alice"], vec!["Bob"]);
    assert_eq!(name_to_friends["Bob"], vec!["Carol"]);
    assert!(name_to_friends["Carol"].is_empty());

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_pc_alongside_scalar_columns() -> Result<()> {
    let db = Uni::in_memory().build().await?;

    let tx = db.session().tx().await?;
    tx.execute("CREATE (a:Person {name: 'Alice', age: 30}), (b:Person {name: 'Bob'})")
        .await?;
    tx.execute(
        "MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}) \
         CREATE (a)-[:KNOWS]->(b)",
    )
    .await?;
    tx.commit().await?;

    let results = db
        .session()
        .query(
            "MATCH (n:Person {name: 'Alice'}) \
             RETURN n.name AS name, n.age AS age, [(n)-[:KNOWS]->(m) | m.name] AS friends",
        )
        .await?;

    assert_eq!(results.len(), 1);
    let row = &results.rows()[0];
    assert_eq!(row.value("name"), Some(&Value::String("Alice".into())));
    assert_eq!(row.value("age"), Some(&Value::Int(30)));
    let friends = row.value("friends").unwrap().as_array().unwrap();
    assert_eq!(sorted_strings(friends), vec!["Bob"]);

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_pc_multiple_comprehensions() -> Result<()> {
    let db = Uni::in_memory().build().await?;

    let tx = db.session().tx().await?;
    tx.execute(
        "CREATE (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'})",
    )
    .await?;
    tx.execute(
        "MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'}) \
         CREATE (a)-[:KNOWS]->(b), (a)-[:LIKES]->(c)",
    )
    .await?;
    tx.commit().await?;

    let results = db
        .session()
        .query(
            "MATCH (n:Person {name: 'Alice'}) \
             RETURN [(n)-[:KNOWS]->(m) | m.name] AS known, \
                    [(n)-[:LIKES]->(m) | m.name] AS liked",
        )
        .await?;

    assert_eq!(results.len(), 1);
    let row = &results.rows()[0];
    let known = row.value("known").unwrap().as_array().unwrap();
    assert_eq!(sorted_strings(known), vec!["Bob"]);
    let liked = row.value("liked").unwrap().as_array().unwrap();
    assert_eq!(sorted_strings(liked), vec!["Carol"]);

    Ok(())
}

// ===========================================================================
// Unhappy / edge-case tests
// ===========================================================================

#[tokio::test(flavor = "multi_thread")]
async fn test_pc_isolated_node() -> Result<()> {
    let db = Uni::in_memory().build().await?;

    let tx = db.session().tx().await?;
    tx.execute("CREATE (:Person {name: 'Lonely'})").await?;
    tx.commit().await?;

    let results = db
        .session()
        .query(
            "MATCH (n:Person {name: 'Lonely'}) \
             RETURN [(n)-[:KNOWS]->(m) | m.name] AS friends",
        )
        .await?;

    assert_eq!(results.len(), 1);
    let friends = results.rows()[0]
        .value("friends")
        .unwrap()
        .as_array()
        .unwrap();
    assert!(friends.is_empty(), "Isolated node should have empty list");

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_pc_nonexistent_edge_type() -> Result<()> {
    let db = Uni::in_memory().build().await?;

    let tx = db.session().tx().await?;
    tx.execute("CREATE (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})")
        .await?;
    tx.execute(
        "MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}) \
         CREATE (a)-[:KNOWS]->(b)",
    )
    .await?;
    tx.commit().await?;

    // Edge type DOES_NOT_EXIST is not in the graph — should return empty list, not error
    let results = db
        .session()
        .query(
            "MATCH (n:Person {name: 'Alice'}) \
             RETURN [(n)-[:DOES_NOT_EXIST]->(m) | m.name] AS friends",
        )
        .await?;

    assert_eq!(results.len(), 1);
    let friends = results.rows()[0]
        .value("friends")
        .unwrap()
        .as_array()
        .unwrap();
    assert!(
        friends.is_empty(),
        "Non-existent edge type should yield empty list"
    );

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_pc_null_property_in_map_expr() -> Result<()> {
    let db = Uni::in_memory().build().await?;

    let tx = db.session().tx().await?;
    tx.execute(
        "CREATE (a:Person {name: 'Alice'}), \
         (b:Person {name: 'Bob', nickname: 'Bobby'}), \
         (c:Person {name: 'Carol'})",
    )
    .await?;
    tx.execute(
        "MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'}) \
         CREATE (a)-[:KNOWS]->(b), (a)-[:KNOWS]->(c)",
    )
    .await?;
    tx.commit().await?;

    let results = db
        .session()
        .query(
            "MATCH (n:Person {name: 'Alice'}) \
             RETURN [(n)-[:KNOWS]->(m) | m.nickname] AS nicknames",
        )
        .await?;

    assert_eq!(results.len(), 1);
    let nicknames = results.rows()[0]
        .value("nicknames")
        .unwrap()
        .as_array()
        .unwrap();
    assert_eq!(
        nicknames.len(),
        2,
        "Should have two entries (one non-null, one null)"
    );

    // One should be "Bobby", the other null
    let has_bobby = nicknames.iter().any(|v| v.as_str() == Some("Bobby"));
    let has_null = nicknames.iter().any(|v| v.is_null());
    assert!(has_bobby, "Should contain 'Bobby'");
    assert!(has_null, "Should contain null for Carol (no nickname)");

    Ok(())
}

/// TCK Pattern2 [7]: Use a pattern comprehension inside a list comprehension.
///
/// MATCH p = (n:X)-->()
/// RETURN n, [x IN nodes(p) | size([(x)-->(:Y) | 1])] AS list
#[tokio::test(flavor = "multi_thread")]
async fn test_pc_inside_list_comprehension() -> Result<()> {
    let db = Uni::in_memory().build().await?;

    let tx = db.session().tx().await?;
    tx.execute(
        "CREATE (n1:X {n: 1}), (m1:Y), (i1:Y), (i2:Y) \
         CREATE (n1)-[:T]->(m1), \
                (m1)-[:T]->(i1), \
                (m1)-[:T]->(i2) \
         CREATE (n2:X {n: 2}), (m2), (i3:L), (i4:Y) \
         CREATE (n2)-[:T]->(m2), \
                (m2)-[:T]->(i3), \
                (m2)-[:T]->(i4)",
    )
    .await?;
    tx.commit().await?;

    // Verify data is set up correctly
    let check = db
        .session()
        .query("MATCH (n:X)-->(m) RETURN n.n AS nn, labels(m) AS ml")
        .await?;
    eprintln!("Data check ({} rows):", check.len());
    for row in check.rows() {
        eprintln!("  {:?}", row);
    }

    // Verify what nodes(p) contains
    let path_check = db
        .session()
        .query("MATCH p = (n:X)-->() RETURN n.n, nodes(p) AS np")
        .await?;
    eprintln!("Path nodes ({} rows):", path_check.len());
    for row in path_check.rows() {
        eprintln!("  {:?}", row);
    }

    // Now run the actual query
    let results = db
        .session()
        .query(
            "MATCH p = (n:X)-->() \
             RETURN n, [x IN nodes(p) | size([(x)-->(:Y) | 1])] AS list",
        )
        .await?;

    eprintln!("Pattern2 [7] results ({} rows):", results.len());
    for row in results.rows() {
        eprintln!("  {:?}", row);
    }

    assert_eq!(results.len(), 2, "Should have 2 rows");

    // Find the row for n1 (n=1) and n2 (n=2)
    let mut found_n1 = false;
    let mut found_n2 = false;
    for row in results.rows() {
        let n_val = row.value("n").unwrap();
        // Extract n property from node
        let n_prop = match n_val {
            Value::Node(node) => node.properties.get("n").cloned(),
            Value::Map(map) => map.get("n").cloned().or_else(|| {
                map.get("properties").and_then(|p| {
                    if let Value::Map(pm) = p {
                        pm.get("n").cloned()
                    } else {
                        None
                    }
                })
            }),
            _ => None,
        };
        let list = row.value("list").unwrap().as_array().unwrap().to_vec();
        eprintln!("  n_prop={:?}, list={:?}", n_prop, list);

        if n_prop == Some(Value::Int(1)) {
            // n1:X {n:1} --> m1:Y; n1 has 1 Y neighbor (m1), m1 has 2 Y neighbors (i1, i2)
            assert_eq!(
                list,
                vec![Value::Int(1), Value::Int(2)],
                "n1 list should be [1, 2]"
            );
            found_n1 = true;
        } else if n_prop == Some(Value::Int(2)) {
            // n2:X {n:2} --> m2; n2 has 0 Y neighbors, m2 has 1 Y neighbor (i4)
            assert_eq!(
                list,
                vec![Value::Int(0), Value::Int(1)],
                "n2 list should be [0, 1]"
            );
            found_n2 = true;
        }
    }

    assert!(found_n1, "Should find row for n1");
    assert!(found_n2, "Should find row for n2");

    Ok(())
}