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
//! Tests for session API coverage gaps.
//!
//! Targets: session.rs (73.07%), common.rs optional predicate classification
//!
//! ```bash
//! cargo test -p grafeo-engine --features full --test coverage_session
//! ```

use grafeo_common::types::{EpochId, Value};
use grafeo_engine::GrafeoDB;

/// Creates 2 Person nodes: Alix (age 30) and Gus (age 25).
fn setup() -> GrafeoDB {
    let db = GrafeoDB::new_in_memory();
    let session = db.session();
    session
        .create_node_with_props(
            &["Person"],
            [
                ("name", Value::String("Alix".into())),
                ("age", Value::Int64(30)),
            ],
        )
        .unwrap();
    session
        .create_node_with_props(
            &["Person"],
            [
                ("name", Value::String("Gus".into())),
                ("age", Value::Int64(25)),
            ],
        )
        .unwrap();
    db
}

// ---------------------------------------------------------------------------
// Direct session API: set_parameter / get_parameter
// ---------------------------------------------------------------------------

#[test]
fn test_session_set_and_get_parameter() {
    let db = setup();
    let session = db.session();
    session.set_parameter("threshold", Value::Int64(42));
    let val = session.get_parameter("threshold");
    assert_eq!(val, Some(Value::Int64(42)));
    assert_eq!(session.get_parameter("missing"), None);
}

// ---------------------------------------------------------------------------
// reset_session clears parameters
// ---------------------------------------------------------------------------

#[test]
fn test_reset_session_clears_state() {
    let db = setup();
    let session = db.session();
    session.set_parameter("key", Value::String("val".into()));
    session.reset_session();
    assert_eq!(session.get_parameter("key"), None);
}

// ---------------------------------------------------------------------------
// set_time_zone via direct API
// ---------------------------------------------------------------------------

#[test]
fn test_set_time_zone_direct() {
    let db = setup();
    let session = db.session();
    // Setting timezone should not panic
    session.set_time_zone("Europe/Amsterdam");
}

// ---------------------------------------------------------------------------
// graph_model
// ---------------------------------------------------------------------------

#[test]
fn test_graph_model_default() {
    let db = setup();
    let session = db.session();
    let model = session.graph_model();
    // Default model for in-memory DB should be LPG
    assert_eq!(format!("{model:?}"), "Lpg");
}

// ---------------------------------------------------------------------------
// Viewing epoch (time-travel API)
// ---------------------------------------------------------------------------

#[test]
fn test_viewing_epoch_lifecycle() {
    let db = setup();
    let session = db.session();
    assert_eq!(session.viewing_epoch(), None);
    session.set_viewing_epoch(EpochId::new(1));
    assert_eq!(session.viewing_epoch(), Some(EpochId::new(1)));
    session.clear_viewing_epoch();
    assert_eq!(session.viewing_epoch(), None);
}

#[test]
fn test_execute_at_epoch() {
    let db = GrafeoDB::new_in_memory();
    let session = db.session();
    session
        .create_node_with_props(&["Item"], [("name", Value::String("original".into()))])
        .unwrap();

    let epoch = db.current_epoch();

    // Exercise execute_at_epoch code path (sets viewing_epoch_override, runs query, restores)
    let r = session
        .execute_at_epoch("MATCH (i:Item) RETURN i.name AS name", epoch)
        .unwrap();
    assert_eq!(r.rows().len(), 1);
    // NOTE: In-memory MVCC may not fully support epoch-based time travel for reads.
    // The key coverage goal is exercising the execute_at_epoch code path.
    assert!(matches!(&r.rows()[0][0], Value::String(_)));
}

// ---------------------------------------------------------------------------
// Savepoint edge cases
// ---------------------------------------------------------------------------

#[test]
fn test_savepoint_outside_transaction_fails() {
    let db = setup();
    let session = db.session();
    let result = session.savepoint("sp");
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("transaction") || err.contains("savepoint"),
        "error should mention transaction context, got: {err}"
    );
}

#[test]
fn test_release_savepoint_via_api() {
    let db = setup();
    let mut session = db.session();
    session.begin_transaction().unwrap();
    session.savepoint("sp1").unwrap();
    session
        .execute("MATCH (p:Person {name: 'Alix'}) SET p.age = 99")
        .unwrap();
    session.release_savepoint("sp1").unwrap();
    // After release, rollback to sp1 should fail
    let result = session.rollback_to_savepoint("sp1");
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("savepoint") || err.contains("sp1") || err.contains("not found"),
        "error should mention released savepoint, got: {err}"
    );
    session.commit().unwrap();
}

// ---------------------------------------------------------------------------
// Transaction isolation levels
// ---------------------------------------------------------------------------

#[test]
fn test_begin_transaction_with_serializable_isolation() {
    let db = setup();
    let mut session = db.session();
    // Use GQL SET SESSION to test serializable isolation
    session.begin_transaction().unwrap();
    session
        .execute("MATCH (p:Person) RETURN count(p) AS cnt")
        .unwrap();
    session.commit().unwrap();
}

// ---------------------------------------------------------------------------
// execute_with_params
// ---------------------------------------------------------------------------

#[test]
fn test_execute_with_params_direct() {
    let db = setup();
    let session = db.session();
    let params = std::collections::HashMap::from([("min_age".to_string(), Value::Int64(28))]);
    let r = session
        .execute_with_params(
            "MATCH (p:Person) WHERE p.age > $min_age RETURN p.name AS name ORDER BY name",
            params,
        )
        .unwrap();
    assert_eq!(r.rows().len(), 1);
    assert_eq!(r.rows()[0][0], Value::String("Alix".into()));
}

// ---------------------------------------------------------------------------
// use_graph (named graph switching)
// ---------------------------------------------------------------------------

#[test]
fn test_use_graph_via_gql() {
    let db = GrafeoDB::new_in_memory();
    let session = db.session();
    session.execute("CREATE GRAPH test_graph").unwrap();
    session.execute("USE GRAPH test_graph").unwrap();
}

// ---------------------------------------------------------------------------
// OPTIONAL MATCH (exercises classify_optional_predicates in common.rs)
// ---------------------------------------------------------------------------

#[test]
fn test_optional_match_no_match() {
    let db = setup();
    let session = db.session();
    let r = session
        .execute(
            "MATCH (p:Person {name: 'Alix'}) \
             OPTIONAL MATCH (p)-[:MANAGES]->(e:Employee) \
             RETURN p.name AS name, e.name AS emp",
        )
        .unwrap();
    assert_eq!(r.rows().len(), 1);
    assert_eq!(r.rows()[0][0], Value::String("Alix".into()));
    assert_eq!(r.rows()[0][1], Value::Null);
}

#[test]
fn test_optional_match_with_where() {
    let db = GrafeoDB::new_in_memory();
    let session = db.session();
    let a = session
        .create_node_with_props(&["Person"], [("name", Value::String("Alix".into()))])
        .unwrap();
    let b = session
        .create_node_with_props(&["Person"], [("name", Value::String("Gus".into()))])
        .unwrap();
    session.create_edge(a, b, "KNOWS");

    let r = session
        .execute(
            "MATCH (p:Person {name: 'Alix'}) \
             OPTIONAL MATCH (p)-[:KNOWS]->(f:Person) WHERE f.name = 'Nonexistent' \
             RETURN p.name AS name, f.name AS friend",
        )
        .unwrap();
    assert_eq!(r.rows().len(), 1);
    assert_eq!(r.rows()[0][1], Value::Null);
}

// ---------------------------------------------------------------------------
// Standalone RETURN (no preceding MATCH)
// ---------------------------------------------------------------------------

#[test]
fn test_standalone_return_arithmetic() {
    let db = GrafeoDB::new_in_memory();
    let s = db.session();
    let r = s.execute("RETURN 1 + 2 AS result").unwrap();
    assert_eq!(r.rows().len(), 1);
    assert_eq!(r.rows()[0][0], Value::Int64(3));
}

#[test]
fn test_standalone_return_string() {
    let db = GrafeoDB::new_in_memory();
    let s = db.session();
    let r = s.execute("RETURN 'hello' AS greeting").unwrap();
    assert_eq!(r.rows().len(), 1);
    assert_eq!(r.rows()[0][0], Value::String("hello".into()));
}

#[test]
fn test_standalone_return_list() {
    let db = GrafeoDB::new_in_memory();
    let s = db.session();
    let r = s.execute("RETURN [1, 2, 3] AS nums").unwrap();
    assert_eq!(r.rows().len(), 1);
    if let Value::List(items) = &r.rows()[0][0] {
        assert_eq!(items.len(), 3);
    } else {
        panic!("expected list, got {:?}", r.rows()[0][0]);
    }
}

// ---------------------------------------------------------------------------
// UNWIND / FOR clause
// ---------------------------------------------------------------------------

#[test]
fn test_unwind_list() {
    let db = GrafeoDB::new_in_memory();
    let session = db.session();
    let r = session.execute("UNWIND [1, 2, 3] AS x RETURN x").unwrap();
    assert_eq!(r.rows().len(), 3);
}

// ---------------------------------------------------------------------------
// Subquery with CALL
// ---------------------------------------------------------------------------

#[test]
fn test_call_subquery() {
    let db = setup();
    let session = db.session();
    let r = session
        .execute(
            "MATCH (p:Person) CALL { WITH p RETURN p.age * 2 AS doubled } RETURN p.name, doubled ORDER BY p.name",
        )
        .unwrap();
    assert_eq!(r.rows().len(), 2);
}

// ---------------------------------------------------------------------------
// Error recovery: session should remain usable after failures
// ---------------------------------------------------------------------------

#[test]
fn test_session_recovers_after_parse_error() {
    let db = setup();
    let session = db.session();
    // Invalid syntax
    let err = session.execute("MATCH (n:Person RETURN n.name");
    assert!(err.is_err());
    // Session should still work for valid queries
    let result = session
        .execute("MATCH (n:Person) RETURN n.name ORDER BY n.name")
        .unwrap();
    assert!(!result.rows().is_empty());
}

#[test]
fn test_session_recovers_after_runtime_error() {
    let db = setup();
    let session = db.session();
    // Reference a non-existent property in a way that causes an error
    let err = session.execute("MATCH (n:NonExistent) SET n.x = 1/0 RETURN n");
    // Whether this errors or returns empty, session should remain usable
    let _ = err;
    let result = session.execute("MATCH (n:Person) RETURN count(n)").unwrap();
    assert_eq!(result.rows().len(), 1);
}

#[test]
fn test_session_recovers_after_rollback() {
    let db = setup();
    let mut session = db.session();
    session.begin_transaction().unwrap();
    session
        .execute("INSERT (:Temp {value: 'should be rolled back'})")
        .unwrap();
    session.rollback().unwrap();

    // Session should work normally after rollback
    let result = session.execute("MATCH (t:Temp) RETURN count(t)").unwrap();
    assert_eq!(result.rows()[0][0], Value::Int64(0));

    // And can start a new transaction
    session.begin_transaction().unwrap();
    session.execute("INSERT (:Valid {ok: true})").unwrap();
    session.commit().unwrap();

    let result = session.execute("MATCH (v:Valid) RETURN count(v)").unwrap();
    assert_eq!(result.rows()[0][0], Value::Int64(1));
}

// ---------------------------------------------------------------------------
// prepare_commit() lifecycle
// ---------------------------------------------------------------------------

#[test]
fn test_prepare_commit_lifecycle() {
    let db = GrafeoDB::new_in_memory();
    let mut session = db.session();
    session.begin_transaction().unwrap();
    session.execute("INSERT (:Person {name: 'Alix'})").unwrap();

    let mut prepared = session.prepare_commit().unwrap();
    // Inspect commit info (nodes_written uses node_count_delta which cannot
    // see PENDING-epoch nodes, so it reports 0 before finalization at commit)
    let info = prepared.info();
    assert_eq!(info.nodes_written, 0);

    // Attach metadata
    prepared.set_metadata("audit_user", "admin");
    let metadata = prepared.metadata();
    assert_eq!(
        metadata.get("audit_user").map(|s| s.as_str()),
        Some("admin")
    );

    // Commit and get epoch
    let epoch = prepared.commit().unwrap();
    assert!(epoch.as_u64() > 0, "commit should return a valid epoch");

    // After commit, the node should be visible
    let reader = db.session();
    let result = reader.execute("MATCH (n:Person) RETURN n").unwrap();
    assert_eq!(result.row_count(), 1, "committed node should be visible");
}

#[test]
fn test_prepare_commit_abort() {
    let db = GrafeoDB::new_in_memory();
    let mut session = db.session();
    session.begin_transaction().unwrap();
    session.execute("INSERT (:Temp {val: 1})").unwrap();

    let prepared = session.prepare_commit().unwrap();
    prepared.abort().unwrap();

    // Data should not persist after abort
    let r = session.execute("MATCH (t:Temp) RETURN count(t)").unwrap();
    assert_eq!(r.rows()[0][0], Value::Int64(0));
}

#[test]
fn test_prepare_commit_without_transaction_fails() {
    let db = GrafeoDB::new_in_memory();
    let mut session = db.session();
    let result = session.prepare_commit();
    match result {
        Ok(_) => panic!("expected error when no transaction is active"),
        Err(err) => {
            let msg = err.to_string();
            assert!(
                msg.contains("transaction") || msg.contains("active"),
                "error should mention no active transaction, got: {msg}"
            );
        }
    }
}

// ---------------------------------------------------------------------------
// begin_transaction_with_isolation()
// ---------------------------------------------------------------------------

#[test]
fn test_begin_transaction_with_read_committed() {
    let db = setup();
    let mut session = db.session();
    session
        .begin_transaction_with_isolation(grafeo_engine::transaction::IsolationLevel::ReadCommitted)
        .unwrap();
    let r = session.execute("MATCH (p:Person) RETURN count(p)").unwrap();
    assert_eq!(r.rows()[0][0], Value::Int64(2));
    session.commit().unwrap();
}

#[test]
fn test_begin_transaction_with_serializable() {
    let db = setup();
    let mut session = db.session();
    session
        .begin_transaction_with_isolation(grafeo_engine::transaction::IsolationLevel::Serializable)
        .unwrap();
    let r = session.execute("MATCH (p:Person) RETURN count(p)").unwrap();
    assert_eq!(r.rows()[0][0], Value::Int64(2));
    session.commit().unwrap();
}

#[test]
fn test_begin_transaction_with_isolation_nested_creates_savepoint() {
    let db = setup();
    let mut session = db.session();
    session
        .begin_transaction_with_isolation(
            grafeo_engine::transaction::IsolationLevel::SnapshotIsolation,
        )
        .unwrap();
    // A second begin creates a nested savepoint rather than failing
    session
        .begin_transaction_with_isolation(grafeo_engine::transaction::IsolationLevel::ReadCommitted)
        .unwrap();
    // Queries should still work inside the nested transaction
    let r = session.execute("MATCH (p:Person) RETURN count(p)").unwrap();
    assert_eq!(r.rows()[0][0], Value::Int64(2));
    session.rollback().unwrap();
}

// ---------------------------------------------------------------------------
// query_scalar()
// ---------------------------------------------------------------------------

#[test]
fn test_query_scalar_int64() {
    let db = setup();
    let count: i64 = db.query_scalar("MATCH (p:Person) RETURN count(p)").unwrap();
    assert_eq!(count, 2);
}

#[test]
fn test_query_scalar_string() {
    let db = setup();
    let name: String = db
        .query_scalar("MATCH (p:Person {name: 'Alix'}) RETURN p.name")
        .unwrap();
    assert_eq!(name, "Alix");
}

// ---------------------------------------------------------------------------
// clear_plan_cache()
// ---------------------------------------------------------------------------

#[test]
fn test_clear_plan_cache() {
    let db = setup();
    let session = db.session();
    // Execute a query to populate the cache
    session.execute("MATCH (p:Person) RETURN p.name").unwrap();
    // Clear should not panic
    db.clear_plan_cache();
    // Queries should still work after clearing
    let r = session.execute("MATCH (p:Person) RETURN count(p)").unwrap();
    assert_eq!(r.rows()[0][0], Value::Int64(2));
}

// ---------------------------------------------------------------------------
// buffer_manager() and query_cache() accessors
// ---------------------------------------------------------------------------

#[test]
fn test_buffer_manager_accessible() {
    let db = GrafeoDB::new_in_memory();
    let bm = db.buffer_manager();
    // Should return a valid budget > 0
    assert!(
        bm.budget() > 0,
        "buffer manager should have a positive budget"
    );
}

#[test]
fn test_query_cache_accessible() {
    let db = GrafeoDB::new_in_memory();
    let cache = db.query_cache();
    // After fresh creation, stats should be zero
    let stats = cache.stats();
    assert_eq!(stats.parsed_hits, 0);
    assert_eq!(stats.parsed_misses, 0);
}

// ---------------------------------------------------------------------------
// execute_sparql_with_params()
// ---------------------------------------------------------------------------

#[cfg(all(feature = "sparql", feature = "triple-store"))]
#[test]
fn test_execute_sparql_with_params() {
    use grafeo_engine::config::{Config, GraphModel};

    let db = GrafeoDB::with_config(Config::in_memory().with_graph_model(GraphModel::Rdf)).unwrap();
    let session = db.session();

    // Insert RDF triples via SPARQL
    session
        .execute_sparql(
            r#"INSERT DATA {
                <http://ex.org/alix> <http://ex.org/age> "30" .
                <http://ex.org/gus>  <http://ex.org/age> "25" .
            }"#,
        )
        .unwrap();

    // Exercise the execute_sparql_with_params code path.
    // SPARQL doesn't produce Parameter nodes in the logical plan, so the
    // params HashMap is traversed but no substitution occurs. The key goal
    // is covering the with_params pipeline (parse, substitute, optimize, plan, execute).
    let params = std::collections::HashMap::from([("unused".to_string(), Value::Int64(1))]);
    let r = session
        .execute_sparql_with_params(
            r#"SELECT ?s ?age WHERE {
                ?s <http://ex.org/age> ?age .
            }"#,
            params,
        )
        .unwrap();
    assert_eq!(
        r.rows().len(),
        2,
        "should return two rows, got {}",
        r.rows().len()
    );
}

// ---------------------------------------------------------------------------
// CDC (Change Data Capture) session methods
// ---------------------------------------------------------------------------

#[cfg(feature = "cdc")]
mod cdc_tests {
    use grafeo_common::types::{EpochId, Value};
    use grafeo_engine::{Config, GrafeoDB};

    fn cdc_db() -> GrafeoDB {
        GrafeoDB::with_config(Config::in_memory().with_cdc()).unwrap()
    }

    #[test]
    fn test_cdc_history_records_create() {
        let db = cdc_db();
        let node_id = db.create_node(&["Person"]);
        db.set_node_property(node_id, "name", Value::String("Alix".into()));

        let session = db.session();
        let history = session.history(node_id).unwrap();
        // At minimum, the create event should be recorded
        assert!(
            !history.is_empty(),
            "CDC history should contain at least the create event"
        );
        assert!(
            history
                .iter()
                .any(|e| e.kind == grafeo_engine::cdc::ChangeKind::Create),
            "Should contain a Create event"
        );
    }

    #[test]
    fn test_cdc_history_records_update() {
        let db = cdc_db();
        let node_id = db.create_node(&["Person"]);
        db.set_node_property(node_id, "name", Value::String("Alix".into()));
        db.set_node_property(node_id, "name", Value::String("Gus".into()));

        let session = db.session();
        let history = session.history(node_id).unwrap();
        let update_count = history
            .iter()
            .filter(|e| e.kind == grafeo_engine::cdc::ChangeKind::Update)
            .count();
        assert!(
            update_count >= 2,
            "Should have at least 2 update events for 2 set_node_property calls, got {update_count}"
        );
    }

    #[test]
    fn test_cdc_history_since_filters_by_epoch() {
        let db = cdc_db();
        let node_id = db.create_node(&["Person"]);
        db.set_node_property(node_id, "name", Value::String("Alix".into()));

        let session = db.session();
        // history_since with a very high epoch should return nothing
        let history = session
            .history_since(node_id, EpochId::new(u64::MAX))
            .unwrap();
        assert!(
            history.is_empty(),
            "history_since with future epoch should return empty"
        );

        // history_since with epoch 0 should return everything
        let history = session.history_since(node_id, EpochId::new(0)).unwrap();
        assert!(
            !history.is_empty(),
            "history_since epoch 0 should return all events"
        );
    }

    #[test]
    fn test_cdc_changes_between_epoch_range() {
        let db = cdc_db();
        db.create_node(&["Person"]);
        db.create_node(&["Person"]);

        let session = db.session();
        // Get all changes from epoch 0 to a large epoch
        let changes = session
            .changes_between(EpochId::new(0), EpochId::new(u64::MAX))
            .unwrap();
        assert!(
            changes.len() >= 2,
            "Should have at least 2 change events for 2 node creations, got {}",
            changes.len()
        );
    }
}

// ============================================================================
// GQL Questioned Edge (->?) Tests
// ============================================================================

/// Creates a partial network: Alix->Gus, Vincent has no outgoing edges.
fn setup_questioned_edge() -> GrafeoDB {
    let db = GrafeoDB::new_in_memory();
    let session = db.session();
    let alix = session
        .create_node_with_props(&["Person"], [("name", Value::String("Alix".into()))])
        .unwrap();
    let gus = session
        .create_node_with_props(&["Person"], [("name", Value::String("Gus".into()))])
        .unwrap();
    let vincent = session
        .create_node_with_props(&["Person"], [("name", Value::String("Vincent".into()))])
        .unwrap();

    session.create_edge(alix, gus, "KNOWS");
    let _ = vincent;
    db
}

#[test]
fn test_questioned_edge_preserves_source_rows() {
    let db = setup_questioned_edge();
    let session = db.session();

    // ->? means optional edge: source rows without matching edges are preserved
    let result = session
        .execute("MATCH (a:Person)-[:KNOWS]->?(b:Person) RETURN a.name, b.name")
        .unwrap();

    // All 3 persons should appear (Alix with match, Gus and Vincent without)
    assert_eq!(
        result.row_count(),
        3,
        "Questioned edge should preserve all source rows"
    );

    let names: Vec<&str> = result
        .rows()
        .iter()
        .map(|r| r[0].as_str().unwrap_or("NULL"))
        .collect();
    assert!(names.contains(&"Alix"));
    assert!(names.contains(&"Gus"));
    assert!(names.contains(&"Vincent"));
}

#[test]
fn test_questioned_edge_null_when_no_match() {
    let db = setup_questioned_edge();
    let session = db.session();

    let result = session
        .execute("MATCH (a:Person)-[:KNOWS]->?(b:Person) RETURN a.name, b.name")
        .unwrap();

    // Vincent's b.name should be NULL
    let vincent_row = result
        .rows()
        .iter()
        .find(|r| r[0].as_str() == Some("Vincent"))
        .unwrap();
    assert!(
        vincent_row[1].is_null(),
        "Vincent's target should be NULL (no KNOWS edge)"
    );
}

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

    let alix = session
        .create_node_with_props(&["Person"], [("name", Value::String("Alix".into()))])
        .unwrap();
    let amsterdam = session
        .create_node_with_props(&["City"], [("name", Value::String("Amsterdam".into()))])
        .unwrap();
    let gus = session
        .create_node_with_props(&["Person"], [("name", Value::String("Gus".into()))])
        .unwrap();

    // Alix -> Amsterdam (LIVES_IN) and Alix -> Gus (KNOWS)
    session.create_edge(alix, amsterdam, "LIVES_IN");
    session.create_edge(alix, gus, "KNOWS");

    // Questioned edge with label filter: only Person targets
    let result = session
        .execute("MATCH (a:Person)-[:KNOWS]->?(b:Person) RETURN a.name, b.name")
        .unwrap();

    // Alix matches Gus via KNOWS; Gus has no KNOWS edges -> NULL
    assert_eq!(result.row_count(), 2, "Two Person nodes should appear");

    let alix_row = result
        .rows()
        .iter()
        .find(|r| r[0].as_str() == Some("Alix"))
        .unwrap();
    assert_eq!(
        alix_row[1].as_str(),
        Some("Gus"),
        "Alix's target should be Gus (KNOWS edge to Person)"
    );

    let gus_row = result
        .rows()
        .iter()
        .find(|r| r[0].as_str() == Some("Gus"))
        .unwrap();
    assert!(
        gus_row[1].is_null(),
        "Gus's target should be NULL (no outgoing KNOWS)"
    );
}

#[test]
fn test_questioned_edge_combined_with_optional_match() {
    let db = setup_questioned_edge();
    let session = db.session();

    // Add a City node that only Alix lives in
    session
        .execute(
            "MATCH (a:Person {name: 'Alix'}) INSERT (a)-[:LIVES_IN]->(:City {name: 'Amsterdam'})",
        )
        .unwrap();

    // Combine OPTIONAL MATCH with a questioned edge in the first MATCH
    let result = session
        .execute(
            "MATCH (a:Person)-[:KNOWS]->?(b:Person) \
             OPTIONAL MATCH (a)-[:LIVES_IN]->(c:City) \
             RETURN a.name, b.name, c.name",
        )
        .unwrap();

    // All persons appear (questioned edge preserves rows), OPTIONAL MATCH adds city
    assert_eq!(
        result.row_count(),
        3,
        "All persons should appear with both questioned edge and optional match"
    );

    // Alix should have both a friend and a city
    let alix_row = result
        .rows()
        .iter()
        .find(|r| r[0].as_str() == Some("Alix"))
        .unwrap();
    assert_eq!(alix_row[1].as_str(), Some("Gus"));
    assert_eq!(alix_row[2].as_str(), Some("Amsterdam"));
}