linkrs-query 0.1.0

Query engine, parser, and executor for Linkrs
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
//! DDL Tag Basic Tests
//!
//! Test coverage:
//! - CREATE TAG - Create vertex tag (including TTL expiry configuration)
//! - DROP TAG - Delete vertex tag (single, batch, IF EXISTS)
//! - DESC TAG - Describe tag schema
//! - TTL - Expiry filtering and physical purge of expired vertices

use super::common;

use common::test_scenario::TestScenario;
use linkrs_core::Value;
use linkrs_query::parser::Parser;
use std::collections::HashMap;

// ==================== CREATE TAG Parser Tests ====================

#[test]
fn test_create_tag_parser_basic() {
    let query = "CREATE TAG Person(name: STRING, age: INT)";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "CREATE TAG basic parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("CREATE TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "CREATE");
}

#[test]
fn test_create_tag_parser_with_if_not_exists() {
    let query = "CREATE TAG IF NOT EXISTS Person(name: STRING, age: INT)";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "CREATE TAG with IF NOT EXISTS parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("CREATE TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "CREATE");
}

#[test]
fn test_create_tag_parser_single_property() {
    let query = "CREATE TAG Person(name: STRING)";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "CREATE TAG single property parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("CREATE TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "CREATE");
}

#[test]
fn test_create_tag_parser_multiple_properties() {
    let query = "CREATE TAG Person(name: STRING, age: INT, created_at: TIMESTAMP)";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "CREATE TAG multiple properties parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("CREATE TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "CREATE");
}

#[test]
fn test_create_tag_parser_various_types() {
    let query = "CREATE TAG Test(name: STRING, age: INT, score: DOUBLE, active: BOOL, birth: DATE)";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "CREATE TAG various types parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("CREATE TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "CREATE");
}

// ==================== CREATE TAG Execution Tests ====================

#[test]
fn test_create_tag_execution_basic() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG Person(id: INT, name: STRING, age: INT)")
        .assert_success()
        .assert_tag_exists("Person");
}

#[test]
fn test_create_tag_execution_with_if_not_exists() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG IF NOT EXISTS Person(id: INT, name: STRING, age: INT)")
        .assert_success()
        .assert_tag_exists("Person")
        .exec_ddl("CREATE TAG IF NOT EXISTS Person(id: INT, name: STRING, age: INT)")
        .assert_success()
        .assert_tag_exists("Person");
}

#[test]
fn test_create_tag_execution_with_data() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG Person(id: INT, name: STRING, age: INT)")
        .assert_success()
        .assert_tag_exists("Person")
        .exec_dml("INSERT VERTEX Person(name, age) VALUES 1:('Alice', 30)")
        .assert_success()
        .assert_vertex_exists(1, "Person")
        .assert_vertex_props(
            1,
            "Person",
            HashMap::from([("name", Value::string("Alice")), ("age", Value::Int(30))]),
        );
}

// ==================== DROP TAG Parser Tests ====================

#[test]
fn test_drop_tag_parser_basic() {
    let query = "DROP TAG Person";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "DROP TAG basic parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("DROP TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "DROP");
}

#[test]
fn test_drop_tag_parser_with_if_exists() {
    let query = "DROP TAG IF EXISTS Person";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "DROP TAG with IF EXISTS parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("DROP TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "DROP");
}

#[test]
fn test_drop_tag_parser_multiple() {
    let query = "DROP TAG Person, Company, Location";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "DROP TAG multiple tags parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("DROP TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "DROP");
}

#[test]
fn test_drop_tag_parser_multiple_with_if_exists() {
    let query = "DROP TAG IF EXISTS Person, Company";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "DROP TAG multiple tags with IF EXISTS parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("DROP TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "DROP");
}

// ==================== DROP TAG Execution Tests ====================

#[test]
fn test_drop_tag_execution_basic() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG Person(id: INT, name: STRING)")
        .assert_success()
        .assert_tag_exists("Person")
        .exec_ddl("DROP TAG Person")
        .assert_success()
        .assert_tag_not_exists("Person");
}

#[test]
fn test_drop_tag_execution_with_if_exists() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("DROP TAG IF EXISTS NonExistentTag")
        .assert_success()
        .exec_ddl("CREATE TAG Person(id: INT, name: STRING)")
        .assert_success()
        .exec_ddl("DROP TAG IF EXISTS Person")
        .assert_success()
        .assert_tag_not_exists("Person");
}

#[test]
fn test_drop_tag_execution_multiple() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG BatchA(id: INT)")
        .assert_success()
        .exec_ddl("CREATE TAG BatchB(id: INT)")
        .assert_success()
        .exec_ddl("CREATE TAG BatchC(id: INT)")
        .assert_success()
        .exec_ddl("DROP TAG BatchA, BatchB, BatchC")
        .assert_success()
        .assert_tag_not_exists("BatchA")
        .assert_tag_not_exists("BatchB")
        .assert_tag_not_exists("BatchC");
}

#[test]
fn test_drop_tag_execution_multiple_with_if_exists() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG BatchX(id: INT)")
        .assert_success()
        .exec_ddl("DROP TAG IF EXISTS BatchX, BatchMissing")
        .assert_success()
        .assert_tag_not_exists("BatchX");
}

#[test]
fn test_drop_tag_execution_multiple_missing_errors() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG BatchY(id: INT)")
        .assert_success()
        .exec_ddl("DROP TAG BatchY, BatchMissing")
        .assert_error();
}

#[test]
fn test_drop_tag_execution_missing_errors() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("DROP TAG no_such_tag")
        .assert_error();
}

// ==================== DESC TAG Tests ====================

#[test]
fn test_desc_parser_tag() {
    let query = "DESCRIBE TAG Person";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "DESCRIBE TAG parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("DESCRIBE TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "DESC");
}

#[test]
fn test_desc_parser_short_tag() {
    let query = "DESC TAG Person";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "DESC TAG parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("DESC TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "DESC");
}

#[test]
fn test_desc_execution_tag() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG Person(id: INT, name: STRING, age: INT)")
        .assert_success()
        .query("DESCRIBE TAG Person")
        .assert_success()
        .assert_result_count(3)
        .assert_result_contains(vec![Value::string("name"), Value::string("STRING")])
        .assert_result_contains(vec![Value::string("age"), Value::string("INT")]);
}

#[test]
fn test_desc_execution_tag_with_constraints() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG Person(id: INT, name: STRING NOT NULL, age: INT DEFAULT 0)")
        .assert_success()
        .query("DESCRIBE TAG Person")
        .assert_success()
        .assert_result_count(3);
}

// ==================== Tag Lifecycle Tests ====================

#[test]
fn test_ddl_tag_lifecycle() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG TestTag(id: INT, name: STRING, age: INT)")
        .assert_success()
        .assert_tag_exists("TestTag")
        .query("DESCRIBE TAG TestTag")
        .assert_success()
        .exec_ddl("ALTER TAG TestTag ADD (email: STRING)")
        .assert_success()
        .exec_dml(
            "INSERT VERTEX TestTag(name, age, email) VALUES 1:('Alice', 30, 'alice@test.com')",
        )
        .assert_success()
        .assert_vertex_exists(1, "TestTag")
        .exec_ddl("ALTER TAG TestTag DROP (email)")
        .assert_success()
        .exec_dml("DELETE VERTEX TestTag FROM 1")
        .assert_success()
        .exec_ddl("DROP TAG TestTag")
        .assert_success()
        .assert_tag_not_exists("TestTag");
}

#[test]
fn test_ddl_if_not_exists_if_exists() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG IF NOT EXISTS Person(id: INT, name: STRING)")
        .assert_success()
        .assert_tag_exists("Person")
        .exec_ddl("CREATE TAG IF NOT EXISTS Person(id: INT, name: STRING)")
        .assert_success()
        .exec_ddl("DROP TAG IF EXISTS Person")
        .assert_success()
        .assert_tag_not_exists("Person")
        .exec_ddl("DROP TAG IF EXISTS Person")
        .assert_success();
}

// ==================== GEOGRAPHY Type Tests ====================

/// TC-GEO-TYPE-001: Parse CREATE TAG with GEOGRAPHY type (keyword)
#[test]
fn test_create_tag_parser_geography_keyword() {
    let query = "CREATE TAG Location(name: STRING, coord: GEOGRAPHY)";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "CREATE TAG with GEOGRAPHY type parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("CREATE TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "CREATE");
}

/// TC-GEO-TYPE-002: Parse CREATE TAG with multiple GEOGRAPHY fields
#[test]
fn test_create_tag_parser_multiple_geography_fields() {
    let query = "CREATE TAG City(name: STRING, center: GEOGRAPHY, boundary: GEOGRAPHY)";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "CREATE TAG with multiple GEOGRAPHY fields parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("CREATE TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "CREATE");
}

/// TC-GEO-TYPE-003: Execute CREATE TAG with GEOGRAPHY type
#[test]
fn test_create_tag_execution_geography() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG Location(id: INT, name: STRING, coord: GEOGRAPHY)")
        .assert_success()
        .assert_tag_exists("Location");
}

/// TC-GEO-TYPE-004: Execute CREATE TAG with GEOGRAPHY and insert data
#[test]
fn test_create_tag_geography_with_data() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG City(id: INT, name: STRING, center: GEOGRAPHY)")
        .assert_success()
        .assert_tag_exists("City")
        .exec_dml("INSERT VERTEX City(name) VALUES 1:('Beijing')")
        .assert_success()
        .assert_vertex_exists(1, "City");
}

// ==================== VECTOR Type Tests ====================

/// TC-VEC-TYPE-001: Parse CREATE TAG with VECTOR type (keyword)
#[test]
fn test_create_tag_parser_vector_keyword() {
    let query = "CREATE TAG Document(id: STRING, embedding: VECTOR(128))";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "CREATE TAG with VECTOR type parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("CREATE TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "CREATE");
}

/// TC-VEC-TYPE-002: Parse CREATE TAG with VECTOR type (identifier)
#[test]
fn test_create_tag_parser_vector_identifier() {
    let query = "CREATE TAG Product(id: STRING, embedding: VECTOR(256))";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "CREATE TAG with VECTOR type (identifier format) parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("CREATE TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "CREATE");
}

/// TC-VEC-TYPE-003: Parse CREATE TAG with multiple VECTOR fields
#[test]
fn test_create_tag_parser_multiple_vector_fields() {
    let query =
        "CREATE TAG MultiVector(id: STRING, title_emb: VECTOR(128), content_emb: VECTOR(256))";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "CREATE TAG with multiple VECTOR fields parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("CREATE TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "CREATE");
}

/// TC-VEC-TYPE-004: Execute CREATE TAG with VECTOR type
#[test]
fn test_create_tag_execution_vector() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG Document(vid: INT, id: STRING, embedding: VECTOR(128))")
        .assert_success()
        .assert_tag_exists("Document");
}

// ==================== Mixed Extended Types Tests ====================

/// TC-EXT-TYPE-001: Parse CREATE TAG with mixed extended types
#[test]
fn test_create_tag_parser_mixed_extended_types() {
    let query = "CREATE TAG Article(id: STRING, content: STRING, location: GEOGRAPHY, embedding: VECTOR(128))";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "CREATE TAG with mixed extended types parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("CREATE TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "CREATE");
}

/// TC-EXT-TYPE-002: Execute CREATE TAG with mixed extended types
#[test]
fn test_create_tag_execution_mixed_extended_types() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG Article(vid: INT, id: STRING, content: STRING, location: GEOGRAPHY, embedding: VECTOR(128))")
        .assert_success()
        .assert_tag_exists("Article");
}

/// TC-EXT-TYPE-003: Parse CREATE TAG with all standard and extended types
#[test]
fn test_create_tag_parser_all_types() {
    let query = r#"CREATE TAG AllTypes(
        name: STRING,
        age: INT,
        score: DOUBLE,
        active: BOOL,
        birth: DATE,
        created: TIMESTAMP,
        location: GEOGRAPHY,
        embedding: VECTOR(64)
    )"#;
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "CREATE TAG with all types parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("CREATE TAG statement parsing should succeed");
    assert_eq!(stmt.ast.stmt.kind(), "CREATE");
}

// ==================== TTL Parser Tests ====================

#[test]
fn test_create_tag_parser_with_ttl() {
    let query = "CREATE TAG UserSession(sid: INT64, token: STRING, created_at: INT64, ttl_duration=31536000, ttl_col=created_at)";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "CREATE TAG with TTL parsing should succeed: {:?}",
        result.err()
    );

    let stmt = result.expect("CREATE TAG statement parsing should succeed");
    match stmt.ast.stmt() {
        linkrs_query::parser::ast::Stmt::Create(create) => match &create.target {
            linkrs_query::parser::ast::CreateTarget::Tag {
                ttl_duration,
                ttl_col,
                ..
            } => {
                assert_eq!(*ttl_duration, Some(31536000));
                assert_eq!(ttl_col.as_deref(), Some("created_at"));
            }
            other => panic!("expected tag target, got {:?}", other),
        },
        other => panic!("expected create statement, got {:?}", other),
    }
}

#[test]
fn test_create_tag_parser_with_ttl_quoted_col() {
    let query = r#"CREATE TAG UserSession(token: STRING, created_at: INT64, ttl_duration=100, ttl_col="created_at")"#;
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_ok(),
        "CREATE TAG with quoted ttl_col parsing should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_create_tag_parser_with_half_ttl_rejected() {
    for query in [
        "CREATE TAG Bad1(x: INT, ttl_duration=100)",
        "CREATE TAG Bad2(x: INT, ttl_col=x)",
    ] {
        let mut parser = Parser::new(query);
        let result = parser.parse();
        assert!(
            result.is_err(),
            "one-sided TTL should be rejected: {}",
            query
        );
        let collected = format!("{:?}", parser.take_errors());
        assert!(
            collected.contains("both ttl_duration and ttl_col"),
            "TTL rejection should name both ttl_duration and ttl_col for {}: {}",
            query,
            collected
        );
    }
}

#[test]
fn test_create_tag_parser_with_non_positive_ttl_rejected() {
    let query = "CREATE TAG Bad(x: INT, ttl_duration=0, ttl_col=x)";
    let mut parser = Parser::new(query);

    let result = parser.parse();
    assert!(
        result.is_err(),
        "non-positive ttl_duration should be rejected: {:?}",
        result.ok()
    );
}

// ==================== TTL Execution Tests ====================

#[test]
fn test_create_tag_execution_with_ttl() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG UserSession(sid: INT64, token: STRING, created_at: INT64, ttl_duration=31536000, ttl_col=created_at)")
        .assert_success()
        .assert_tag_exists("UserSession");
}

#[test]
fn test_create_tag_execution_with_timestamp_ttl_col() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG UserSession(sid: INT64, token: STRING, created_at: TIMESTAMP, ttl_duration=31536000, ttl_col=created_at)")
        .assert_success()
        .assert_tag_exists("UserSession");
}

#[test]
fn test_create_tag_execution_with_ttl_type_mismatch_rejected() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG Bad(name: STRING, ttl_duration=100, ttl_col=name)")
        .assert_error();
}

#[test]
fn test_create_tag_execution_with_ttl_unknown_col_rejected() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG Bad(x: INT, ttl_duration=100, ttl_col=missing)")
        .assert_error();
}

#[test]
fn test_ttl_expired_vertex_is_filtered() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("test_space")
        .exec_ddl("CREATE TAG UserSession(sid: INT64, token: STRING, created_at: INT64, ttl_duration=100, ttl_col=created_at)")
        .assert_success()
        .exec_dml("INSERT VERTEX UserSession(token, created_at) VALUES 1:('old', 0)")
        .assert_success()
        .exec_dml("INSERT VERTEX UserSession(token, created_at) VALUES 2:('fresh', 9999999999)")
        .assert_success()
        .assert_vertex_not_exists(1, "UserSession")
        .assert_vertex_exists(2, "UserSession");
}

#[test]
fn test_ttl_purge_removes_expired_vertices() {
    use linkrs_query::storage::{StorageReader, StorageSchemaOps, StorageWriter};

    let holder = common::TestStorage::new().expect("Failed to create test storage");
    let storage = holder.storage();
    {
        let mut guard = storage.write();
        let mut space = linkrs_core::types::SpaceInfo::new("ttl_space".to_string());
        StorageSchemaOps::create_space(&mut *guard, &mut space).expect("create space");
        let tag = linkrs_core::types::TagInfo::new("T".to_string())
            .with_properties(vec![
                linkrs_core::types::PropertyDef::new(
                    "id".to_string(),
                    linkrs_core::DataType::BigInt,
                ),
                linkrs_core::types::PropertyDef::new(
                    "ts".to_string(),
                    linkrs_core::DataType::BigInt,
                ),
            ])
            .with_ttl(Some(100), Some("ts".to_string()));
        StorageSchemaOps::create_tag(&mut *guard, "ttl_space", &tag).expect("create tag");
        let vid_old = linkrs_core::types::VertexId::try_from_int64(1).expect("vid");
        let vid_fresh = linkrs_core::types::VertexId::try_from_int64(2).expect("vid");
        let mut old_props = std::collections::HashMap::new();
        old_props.insert(
            std::sync::Arc::<str>::from("id"),
            linkrs_core::Value::BigInt(1),
        );
        old_props.insert(
            std::sync::Arc::<str>::from("ts"),
            linkrs_core::Value::BigInt(0),
        );
        let mut fresh_props = std::collections::HashMap::new();
        fresh_props.insert(
            std::sync::Arc::<str>::from("id"),
            linkrs_core::Value::BigInt(2),
        );
        fresh_props.insert(
            std::sync::Arc::<str>::from("ts"),
            linkrs_core::Value::BigInt(9999999999),
        );
        StorageWriter::insert_vertex(
            &mut *guard,
            "ttl_space",
            linkrs_core::Vertex::new(vid_old, linkrs_core::Tag::new("T".to_string(), old_props)),
        )
        .expect("insert old vertex");
        StorageWriter::insert_vertex(
            &mut *guard,
            "ttl_space",
            linkrs_core::Vertex::new(
                vid_fresh,
                linkrs_core::Tag::new("T".to_string(), fresh_props),
            ),
        )
        .expect("insert fresh vertex");
    }
    {
        let guard = storage.read();
        let visible = guard.scan_vertices_by_tag("ttl_space", "T").expect("scan");
        assert_eq!(visible.len(), 1, "expired vertex must be filtered");
    }
    {
        let guard = storage.read();
        let removed = guard
            .purge_expired_vertices("ttl_space", "T")
            .expect("purge");
        assert_eq!(removed, 1, "purge must remove exactly the expired vertex");
    }
}

// ==================== PURGE EXPIRED Statement Tests ====================

#[test]
fn test_purge_expired_vertex_physical_delete() {
    // The expired vertex is already filtered from reads; the purge must
    // physically delete it and report the removed-row count, and a second
    // purge finds nothing left.
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("ttl_space")
        .exec_ddl("CREATE TAG UserSession(sid: INT64, tok: STRING, created_at: INT64, ttl_duration=100, ttl_col=created_at)")
        .assert_success()
        .exec_dml("INSERT VERTEX UserSession(tok, created_at) VALUES 1:('old', 0)")
        .assert_success()
        .exec_dml("INSERT VERTEX UserSession(tok, created_at) VALUES 2:('fresh', 9999999999)")
        .assert_success()
        .assert_vertex_not_exists(1, "UserSession")
        .assert_vertex_exists(2, "UserSession")
        .exec_ddl("PURGE EXPIRED TAG UserSession IN ttl_space")
        .assert_success()
        .assert_result_columns(&["space_name", "schema_name", "schema_type", "removed_rows"])
        .assert_result_contains(vec![
            Value::string("ttl_space".to_string()),
            Value::string("UserSession".to_string()),
            Value::string("TAG".to_string()),
            Value::BigInt(1),
        ])
        .exec_ddl("PURGE EXPIRED TAG UserSession IN ttl_space")
        .assert_success()
        .assert_result_contains(vec![Value::BigInt(0)]);
}

#[test]
fn test_purge_expired_all_schemas_without_target() {
    // Omitting the target scans every TTL-configured schema and reports one
    // row per schema.
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("ttl_space")
        .exec_ddl("CREATE TAG UserSession(sid: INT64, created_at: INT64, ttl_duration=100, ttl_col=created_at)")
        .assert_success()
        .exec_dml("INSERT VERTEX UserSession(created_at) VALUES 1:(0)")
        .assert_success()
        .exec_ddl("PURGE EXPIRED IN ttl_space")
        .assert_success()
        .assert_result_columns(&["space_name", "schema_name", "schema_type", "removed_rows"])
        .assert_result_contains(vec![
            Value::string("UserSession".to_string()),
            Value::string("TAG".to_string()),
            Value::BigInt(1),
        ]);
}

#[test]
fn test_purge_expired_without_ttl_reports_zero() {
    // A schema that exists but has no TTL is scanned and reports zero removed
    // rows rather than erroring.
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("ttl_space")
        .exec_ddl("CREATE TAG Keep(sid: INT64)")
        .assert_success()
        .exec_dml("INSERT VERTEX Keep(sid) VALUES 1:(1)")
        .assert_success()
        .exec_ddl("PURGE EXPIRED TAG Keep IN ttl_space")
        .assert_success()
        .assert_result_contains(vec![
            Value::string("Keep".to_string()),
            Value::string("TAG".to_string()),
            Value::BigInt(0),
        ]);
}

#[test]
fn test_purge_expired_unknown_space_errors() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .exec_ddl("PURGE EXPIRED IN no_such_space")
        .assert_error();
}

#[test]
fn test_purge_expired_unknown_target_errors() {
    TestScenario::new()
        .expect("Failed to create test scenario")
        .setup_space("ttl_space")
        .exec_ddl("PURGE EXPIRED TAG Missing IN ttl_space")
        .assert_error();
}