kglite 0.10.26

Pure-Rust knowledge graph engine โ€” Cypher pipeline, snapshot/working CoW transactions, columnar/mmap/disk storage backends, optional dataset loaders (SEC EDGAR, Sodir, Wikidata). PyO3 wrappers live in the sibling kglite-py crate (the Python wheel); embeddable directly from any Rust binary without PyO3 in the dep tree.
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
// src/graph/cypher/tokenizer.rs
// Cypher-level tokenizer handling keywords, operators, dot notation, and comparisons

// ============================================================================
// Token Types
// ============================================================================

#[derive(Debug, Clone, PartialEq)]
pub enum CypherToken {
    // Keywords (case-insensitive)
    Match,
    Optional,
    Where,
    Return,
    With,
    Order,
    By,
    As,
    And,
    Or,
    Not,
    In,
    Is,
    Null,
    /// `NULLS` keyword used in ORDER BY clauses (e.g. `ORDER BY x DESC NULLS LAST`).
    /// 0.9.0 ยง2 โ€” distinct from `Null`.
    Nulls,
    Limit,
    Skip,
    Unwind,
    Union,
    Intersect,
    Except,
    All,
    Distinct,
    Create,
    Set,
    Delete,
    Detach,
    Merge,
    Remove,
    On,
    Asc,
    Desc,
    StartsWith,
    EndsWith,
    Contains,
    Case,
    When,
    Then,
    Else,
    End,
    True,
    False,
    Exists,
    Explain,
    Profile,
    Call,
    Yield,
    Over,
    Partition,
    Having,
    Xor,

    // Parameters
    Parameter(String), // $param_name

    // Symbols
    LParen,      // (
    RParen,      // )
    LBracket,    // [
    RBracket,    // ]
    LBrace,      // {
    RBrace,      // }
    Colon,       // :
    Comma,       // ,
    Dot,         // .
    Semicolon,   // ;
    Dash,        // -
    GreaterThan, // >
    LessThan,    // <
    Star,        // *
    DotDot,      // ..

    // Comparison operators
    Equals,            // =
    NotEquals,         // <>
    LessThanEquals,    // <=
    GreaterThanEquals, // >=

    // Regex
    RegexMatch, // =~

    // Arithmetic
    Plus,       // +
    Slash,      // /
    Percent,    // %
    Pipe,       // |
    DoublePipe, // ||

    // Literals and identifiers
    Identifier(String),
    StringLit(String),
    IntLit(i64),
    FloatLit(f64),
}

// ============================================================================
// Tokenizer
// ============================================================================

/// Position-stripping wrapper kept for the tokenizer's own tests
/// (which assert on `Vec<CypherToken>` directly). Production code
/// goes through [`tokenize_cypher_with_positions`] via
/// `parse_cypher`. 0.9.0 Cluster 3.
#[cfg(test)]
pub fn tokenize_cypher(input: &str) -> Result<Vec<CypherToken>, String> {
    Ok(tokenize_cypher_with_positions(input)?
        .into_iter()
        .map(|(tok, _pos)| tok)
        .collect())
}

/// Same as [`tokenize_cypher`] but returns the **char-position** at
/// the start of each token, alongside the token. 0.9.0 Cluster 3 โ€” the
/// parser uses this to format byte-precise `(line, col)` in error
/// messages instead of the prior approximate token re-walk.
///
/// Char-position is the index into `input.chars().collect()` โ€”
/// converted to byte offset / line:col by the consumer on error
/// (rare path; not worth a parallel byte-offset table for the hot
/// path).
pub fn tokenize_cypher_with_positions(input: &str) -> Result<Vec<(CypherToken, usize)>, String> {
    let mut tokens: Vec<(CypherToken, usize)> = Vec::new();
    let chars: Vec<char> = input.chars().collect();
    let len = chars.len();
    let mut i = 0;

    while i < len {
        let ch = chars[i];
        // Position at the start of this token. Captured once per
        // loop iteration; tokens.push(...) callers below pair their
        // CypherToken with `start`. (0.9.0 Cluster 3.)
        let start = i;

        // Skip whitespace
        if ch.is_ascii_whitespace() {
            i += 1;
            continue;
        }

        // Single-line comments: // to end of line
        if ch == '/' && i + 1 < len && chars[i + 1] == '/' {
            while i < len && chars[i] != '\n' {
                i += 1;
            }
            continue;
        }

        match ch {
            '(' => {
                tokens.push((CypherToken::LParen, start));
                i += 1;
            }
            ')' => {
                tokens.push((CypherToken::RParen, start));
                i += 1;
            }
            '[' => {
                tokens.push((CypherToken::LBracket, start));
                i += 1;
            }
            ']' => {
                tokens.push((CypherToken::RBracket, start));
                i += 1;
            }
            '{' => {
                tokens.push((CypherToken::LBrace, start));
                i += 1;
            }
            '}' => {
                tokens.push((CypherToken::RBrace, start));
                i += 1;
            }
            ':' => {
                tokens.push((CypherToken::Colon, start));
                i += 1;
            }
            ',' => {
                tokens.push((CypherToken::Comma, start));
                i += 1;
            }
            ';' => {
                tokens.push((CypherToken::Semicolon, start));
                i += 1;
            }
            '*' => {
                tokens.push((CypherToken::Star, start));
                i += 1;
            }
            '+' => {
                tokens.push((CypherToken::Plus, start));
                i += 1;
            }
            '/' => {
                tokens.push((CypherToken::Slash, start));
                i += 1;
            }
            '%' => {
                tokens.push((CypherToken::Percent, start));
                i += 1;
            }
            '|' => {
                if i + 1 < len && chars[i + 1] == '|' {
                    tokens.push((CypherToken::DoublePipe, start));
                    i += 2;
                } else {
                    tokens.push((CypherToken::Pipe, start));
                    i += 1;
                }
            }
            '=' => {
                if i + 1 < chars.len() && chars[i + 1] == '~' {
                    tokens.push((CypherToken::RegexMatch, start));
                    i += 2;
                } else {
                    tokens.push((CypherToken::Equals, start));
                    i += 1;
                }
            }

            '-' => {
                // Could be dash (edge syntax) or negative number in some contexts,
                // but we always tokenize as Dash and let the parser handle unary negation
                tokens.push((CypherToken::Dash, start));
                i += 1;
            }

            '<' => {
                if i + 1 < len && chars[i + 1] == '>' {
                    tokens.push((CypherToken::NotEquals, start));
                    i += 2;
                } else if i + 1 < len && chars[i + 1] == '=' {
                    tokens.push((CypherToken::LessThanEquals, start));
                    i += 2;
                } else {
                    tokens.push((CypherToken::LessThan, start));
                    i += 1;
                }
            }

            '>' => {
                if i + 1 < len && chars[i + 1] == '=' {
                    tokens.push((CypherToken::GreaterThanEquals, start));
                    i += 2;
                } else {
                    tokens.push((CypherToken::GreaterThan, start));
                    i += 1;
                }
            }

            '!' => {
                if i + 1 < len && chars[i + 1] == '=' {
                    tokens.push((CypherToken::NotEquals, start));
                    i += 2;
                } else {
                    return Err(format!(
                        "Unexpected character '!' at position {}. Did you mean '!='?",
                        i
                    ));
                }
            }

            '.' => {
                if i + 1 < len && chars[i + 1] == '.' {
                    tokens.push((CypherToken::DotDot, start));
                    i += 2;
                } else if i + 1 < len && chars[i + 1].is_ascii_digit() {
                    // Float starting with dot: .5
                    let start = i;
                    i += 1; // skip the dot
                    while i < len && chars[i].is_ascii_digit() {
                        i += 1;
                    }
                    let num_str: String = chars[start..i].iter().collect();
                    let f: f64 = num_str
                        .parse()
                        .map_err(|_| format!("Invalid float: {}", num_str))?;
                    tokens.push((CypherToken::FloatLit(f), start));
                } else {
                    tokens.push((CypherToken::Dot, start));
                    i += 1;
                }
            }

            // String literals
            '"' | '\'' => {
                let quote = ch;
                i += 1; // consume opening quote
                let mut s = String::new();
                let mut closed = false;
                while i < len {
                    if chars[i] == quote {
                        i += 1; // consume closing quote
                        closed = true;
                        break;
                    }
                    if chars[i] == '\\' && i + 1 < len {
                        i += 1;
                        s.push(match chars[i] {
                            'n' => '\n',
                            't' => '\t',
                            'r' => '\r',
                            '\\' => '\\',
                            c if c == quote => c,
                            other => other,
                        });
                        i += 1;
                    } else {
                        s.push(chars[i]);
                        i += 1;
                    }
                }
                if !closed {
                    return Err(format!("Unterminated string literal: {}{}", quote, s));
                }
                tokens.push((CypherToken::StringLit(s), start));
            }

            // Numbers
            c if c.is_ascii_digit() => {
                let start = i;
                let mut has_dot = false;
                while i < len && (chars[i].is_ascii_digit() || (chars[i] == '.' && !has_dot)) {
                    if chars[i] == '.' {
                        // Check for '..' (range operator) - don't consume
                        if i + 1 < len && chars[i + 1] == '.' {
                            break;
                        }
                        // Check if next char is a digit (decimal point) or not (property access after number)
                        if i + 1 >= len || !chars[i + 1].is_ascii_digit() {
                            break;
                        }
                        has_dot = true;
                    }
                    i += 1;
                }
                // Scientific notation: e.g. 1e6, 1.5e-3, 2E+10
                if i < len && (chars[i] == 'e' || chars[i] == 'E') {
                    has_dot = true; // Force float parsing
                    i += 1;
                    if i < len && (chars[i] == '+' || chars[i] == '-') {
                        i += 1;
                    }
                    while i < len && chars[i].is_ascii_digit() {
                        i += 1;
                    }
                }
                let num_str: String = chars[start..i].iter().collect();
                if has_dot {
                    let f: f64 = num_str
                        .parse()
                        .map_err(|_| format!("Invalid float: {}", num_str))?;
                    tokens.push((CypherToken::FloatLit(f), start));
                } else {
                    match num_str.parse::<i64>() {
                        Ok(n) => tokens.push((CypherToken::IntLit(n), start)),
                        Err(_) => {
                            // i64::MIN is the only integer whose magnitude
                            // overflows i64::from_str (i64::MAX is 2^63-1,
                            // |i64::MIN| is 2^63). The unary-minus path is
                            // parsed as a Dash token followed by the
                            // positive literal โ€” so `-9223372036854775808`
                            // is unrepresentable through the normal
                            // route. Look back: if we're directly after a
                            // Dash and the digit string is exactly 2^63,
                            // consume the Dash and emit IntLit(i64::MIN).
                            // Otherwise the literal is genuinely too large.
                            if num_str == "9223372036854775808"
                                && tokens
                                    .last()
                                    .is_some_and(|(t, _)| matches!(t, CypherToken::Dash))
                            {
                                let (_, dash_pos) = tokens.pop().unwrap();
                                tokens.push((CypherToken::IntLit(i64::MIN), dash_pos));
                            } else {
                                return Err(format!("Invalid integer: {}", num_str));
                            }
                        }
                    }
                }
            }

            // Parameter: $name
            '$' => {
                i += 1; // consume $
                let start = i;
                while i < len && (chars[i].is_ascii_alphanumeric() || chars[i] == '_') {
                    i += 1;
                }
                if i == start {
                    return Err(format!(
                        "Expected parameter name after '$' at position {}",
                        start
                    ));
                }
                let name: String = chars[start..i].iter().collect();
                tokens.push((CypherToken::Parameter(name), start));
            }

            // Identifiers and keywords
            c if c.is_ascii_alphabetic() || c == '_' => {
                let start = i;
                while i < len && (chars[i].is_ascii_alphanumeric() || chars[i] == '_') {
                    i += 1;
                }
                let ident: String = chars[start..i].iter().collect();
                tokens.push((identifier_to_token(ident), start));
            }

            // Backtick-quoted identifiers: `My Identifier`
            '`' => {
                i += 1; // consume opening backtick
                let start = i;
                while i < len && chars[i] != '`' {
                    i += 1;
                }
                if i >= len {
                    let ident: String = chars[start..i].iter().collect();
                    return Err(format!("Unterminated backtick identifier: `{}", ident));
                }
                let ident: String = chars[start..i].iter().collect();
                i += 1; // consume closing backtick
                tokens.push((CypherToken::Identifier(ident), start));
            }

            _ => {
                return Err(format!("Unexpected character '{}' at position {}", ch, i));
            }
        }
    }

    Ok(tokens)
}

/// Convert an identifier string to the appropriate token (keyword or identifier)
fn identifier_to_token(ident: String) -> CypherToken {
    match ident.to_uppercase().as_str() {
        "MATCH" => CypherToken::Match,
        "OPTIONAL" => CypherToken::Optional,
        "WHERE" => CypherToken::Where,
        "RETURN" => CypherToken::Return,
        "WITH" => CypherToken::With,
        "ORDER" => CypherToken::Order,
        "BY" => CypherToken::By,
        "AS" => CypherToken::As,
        "AND" => CypherToken::And,
        "OR" => CypherToken::Or,
        "NOT" => CypherToken::Not,
        "IN" => CypherToken::In,
        "IS" => CypherToken::Is,
        "NULL" => CypherToken::Null,
        "NULLS" => CypherToken::Nulls,
        "LIMIT" => CypherToken::Limit,
        "SKIP" => CypherToken::Skip,
        "UNWIND" => CypherToken::Unwind,
        "UNION" => CypherToken::Union,
        "INTERSECT" => CypherToken::Intersect,
        "EXCEPT" => CypherToken::Except,
        "ALL" => CypherToken::All,
        "DISTINCT" => CypherToken::Distinct,
        "CREATE" => CypherToken::Create,
        "SET" => CypherToken::Set,
        "DELETE" => CypherToken::Delete,
        "DETACH" => CypherToken::Detach,
        "MERGE" => CypherToken::Merge,
        "REMOVE" => CypherToken::Remove,
        "ON" => CypherToken::On,
        "ASC" | "ASCENDING" => CypherToken::Asc,
        "DESC" | "DESCENDING" => CypherToken::Desc,
        "CASE" => CypherToken::Case,
        "WHEN" => CypherToken::When,
        "THEN" => CypherToken::Then,
        "ELSE" => CypherToken::Else,
        "END" => CypherToken::End,
        "TRUE" => CypherToken::True,
        "FALSE" => CypherToken::False,
        "STARTS" => CypherToken::StartsWith,
        "ENDS" => CypherToken::EndsWith,
        "CONTAINS" => CypherToken::Contains,
        "EXISTS" => CypherToken::Exists,
        "EXPLAIN" => CypherToken::Explain,
        "PROFILE" => CypherToken::Profile,
        "CALL" => CypherToken::Call,
        "YIELD" => CypherToken::Yield,
        "OVER" => CypherToken::Over,
        "PARTITION" => CypherToken::Partition,
        "HAVING" => CypherToken::Having,
        "XOR" => CypherToken::Xor,
        _ => CypherToken::Identifier(ident),
    }
}

/// Convert a keyword token back to its string form for use as an alias name.
/// Returns None for non-keyword tokens (symbols, literals, etc.).
pub fn token_to_keyword_name(token: &CypherToken) -> Option<String> {
    let name = match token {
        CypherToken::Match => "match",
        CypherToken::Optional => "optional",
        CypherToken::Where => "where",
        CypherToken::Return => "return",
        CypherToken::With => "with",
        CypherToken::Order => "order",
        CypherToken::By => "by",
        CypherToken::As => "as",
        CypherToken::And => "and",
        CypherToken::Or => "or",
        CypherToken::Not => "not",
        CypherToken::In => "in",
        CypherToken::Is => "is",
        CypherToken::Null => "null",
        CypherToken::Nulls => "nulls",
        CypherToken::Limit => "limit",
        CypherToken::Skip => "skip",
        CypherToken::Unwind => "unwind",
        CypherToken::Union => "union",
        CypherToken::Intersect => "intersect",
        CypherToken::Except => "except",
        CypherToken::All => "all",
        CypherToken::Distinct => "distinct",
        CypherToken::Create => "create",
        CypherToken::Set => "set",
        CypherToken::Delete => "delete",
        CypherToken::Detach => "detach",
        CypherToken::Merge => "merge",
        CypherToken::Remove => "remove",
        CypherToken::On => "on",
        CypherToken::Asc => "asc",
        CypherToken::Desc => "desc",
        CypherToken::StartsWith => "starts",
        CypherToken::EndsWith => "ends",
        CypherToken::Contains => "contains",
        CypherToken::Case => "case",
        CypherToken::When => "when",
        CypherToken::Then => "then",
        CypherToken::Else => "else",
        CypherToken::End => "end",
        CypherToken::True => "true",
        CypherToken::False => "false",
        CypherToken::Exists => "exists",
        CypherToken::Explain => "explain",
        CypherToken::Profile => "profile",
        CypherToken::Call => "call",
        CypherToken::Yield => "yield",
        CypherToken::Over => "over",
        CypherToken::Partition => "partition",
        CypherToken::Having => "having",
        CypherToken::Xor => "xor",
        _ => return None,
    };
    Some(name.to_string())
}

/// Canonical UPPERCASE word for a keyword token used as a NAME (relationship
/// type, node label, or property key) โ€” KG-2 soft keywords. Returns `None` for
/// non-keyword tokens AND for keywords that must stay reserved even in name
/// position.
///
/// Distinct from `token_to_keyword_name` (lowercase, for `AS` aliases): names
/// are case-sensitive and must round-trip verbatim (`[:CONTAINS]` stays
/// `CONTAINS`, not `contains`).
///
/// The SAFE set is the operator / comparison / sort / set / mutation keywords โ€”
/// words that, inside a pattern, can only be a name (they appear elsewhere only
/// in WHERE-expression or clause position, which the re-serializer reaches at
/// bracket/paren depth 0, before this is ever consulted). Deliberately kept
/// reserved (โ†’ `None`): the clause-flow words (MATCH / OPTIONAL / WHERE /
/// RETURN / WITH / UNWIND / LIMIT / SKIP, AND / OR), the value literals
/// (NULL / NULLS / TRUE / FALSE), and the value-expression words (CASE / WHEN /
/// THEN / ELSE / END, EXISTS) โ€” because those can legitimately appear as a
/// property *value* in an inline map (`{x: null}`) and must not be mis-read as
/// a name. The backtick escape hatch still works for any excluded word.
pub fn keyword_name_token(token: &CypherToken) -> Option<&'static str> {
    let name = match token {
        CypherToken::Contains => "CONTAINS",
        CypherToken::StartsWith => "STARTS",
        CypherToken::EndsWith => "ENDS",
        CypherToken::In => "IN",
        CypherToken::Is => "IS",
        CypherToken::Not => "NOT",
        CypherToken::Xor => "XOR",
        CypherToken::Order => "ORDER",
        CypherToken::By => "BY",
        CypherToken::Asc => "ASC",
        CypherToken::Desc => "DESC",
        CypherToken::Distinct => "DISTINCT",
        CypherToken::All => "ALL",
        CypherToken::On => "ON",
        CypherToken::Over => "OVER",
        CypherToken::Partition => "PARTITION",
        CypherToken::Having => "HAVING",
        CypherToken::Detach => "DETACH",
        CypherToken::Merge => "MERGE",
        CypherToken::Create => "CREATE",
        CypherToken::Delete => "DELETE",
        CypherToken::Set => "SET",
        CypherToken::Remove => "REMOVE",
        CypherToken::Yield => "YIELD",
        CypherToken::Call => "CALL",
        CypherToken::Union => "UNION",
        CypherToken::Intersect => "INTERSECT",
        CypherToken::Except => "EXCEPT",
        CypherToken::Explain => "EXPLAIN",
        CypherToken::Profile => "PROFILE",
        CypherToken::As => "AS",
        _ => return None,
    };
    Some(name)
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
#[allow(clippy::approx_constant)]
mod tests {
    use super::*;

    #[test]
    fn test_simple_match_return() {
        let tokens = tokenize_cypher("MATCH (n:Person) RETURN n").unwrap();
        assert_eq!(
            tokens,
            vec![
                CypherToken::Match,
                CypherToken::LParen,
                CypherToken::Identifier("n".to_string()),
                CypherToken::Colon,
                CypherToken::Identifier("Person".to_string()),
                CypherToken::RParen,
                CypherToken::Return,
                CypherToken::Identifier("n".to_string()),
            ]
        );
    }

    #[test]
    fn test_where_with_comparison() {
        let tokens = tokenize_cypher("WHERE n.age > 30 AND n.name = 'Alice'").unwrap();
        assert_eq!(
            tokens,
            vec![
                CypherToken::Where,
                CypherToken::Identifier("n".to_string()),
                CypherToken::Dot,
                CypherToken::Identifier("age".to_string()),
                CypherToken::GreaterThan,
                CypherToken::IntLit(30),
                CypherToken::And,
                CypherToken::Identifier("n".to_string()),
                CypherToken::Dot,
                CypherToken::Identifier("name".to_string()),
                CypherToken::Equals,
                CypherToken::StringLit("Alice".to_string()),
            ]
        );
    }

    #[test]
    fn test_not_equals() {
        let tokens = tokenize_cypher("n.x <> 5").unwrap();
        assert!(tokens.contains(&CypherToken::NotEquals));
    }

    #[test]
    fn test_less_than_equals() {
        let tokens = tokenize_cypher("n.x <= 10").unwrap();
        assert!(tokens.contains(&CypherToken::LessThanEquals));
    }

    #[test]
    fn test_greater_than_equals() {
        let tokens = tokenize_cypher("n.x >= 10").unwrap();
        assert!(tokens.contains(&CypherToken::GreaterThanEquals));
    }

    #[test]
    fn test_return_with_alias() {
        let tokens = tokenize_cypher("RETURN n.name AS name, count(n) AS total").unwrap();
        assert!(tokens.contains(&CypherToken::As));
        assert!(tokens.contains(&CypherToken::Return));
    }

    #[test]
    fn test_order_by_limit() {
        let tokens = tokenize_cypher("ORDER BY n.age DESC LIMIT 10").unwrap();
        assert!(tokens.contains(&CypherToken::Order));
        assert!(tokens.contains(&CypherToken::By));
        assert!(tokens.contains(&CypherToken::Desc));
        assert!(tokens.contains(&CypherToken::Limit));
    }

    #[test]
    fn test_string_escapes() {
        let tokens = tokenize_cypher(r#"'it\'s a \"test\"'"#).unwrap();
        if let CypherToken::StringLit(s) = &tokens[0] {
            assert_eq!(s, "it's a \"test\"");
        } else {
            panic!("Expected string literal");
        }
    }

    #[test]
    fn test_float_literal() {
        let tokens = tokenize_cypher("3.14").unwrap();
        assert_eq!(tokens, vec![CypherToken::FloatLit(3.14)]);
    }

    #[test]
    fn test_case_insensitive_keywords() {
        let tokens = tokenize_cypher("match (n) where n.x = 1 return n").unwrap();
        assert_eq!(tokens[0], CypherToken::Match);
        assert_eq!(tokens[4], CypherToken::Where);
        assert_eq!(tokens[10], CypherToken::Return);
    }

    #[test]
    fn test_edge_pattern_tokens() {
        let tokens = tokenize_cypher("(a)-[:KNOWS]->(b)").unwrap();
        assert_eq!(
            tokens,
            vec![
                CypherToken::LParen,
                CypherToken::Identifier("a".to_string()),
                CypherToken::RParen,
                CypherToken::Dash,
                CypherToken::LBracket,
                CypherToken::Colon,
                CypherToken::Identifier("KNOWS".to_string()),
                CypherToken::RBracket,
                CypherToken::Dash,
                CypherToken::GreaterThan,
                CypherToken::LParen,
                CypherToken::Identifier("b".to_string()),
                CypherToken::RParen,
            ]
        );
    }

    #[test]
    fn test_null_checks() {
        let tokens = tokenize_cypher("WHERE n.x IS NULL").unwrap();
        assert!(tokens.contains(&CypherToken::Is));
        assert!(tokens.contains(&CypherToken::Null));
    }

    #[test]
    fn test_not_null() {
        let tokens = tokenize_cypher("WHERE n.x IS NOT NULL").unwrap();
        assert!(tokens.contains(&CypherToken::Is));
        assert!(tokens.contains(&CypherToken::Not));
        assert!(tokens.contains(&CypherToken::Null));
    }

    #[test]
    fn test_backtick_identifier() {
        let tokens = tokenize_cypher("`My Node`").unwrap();
        assert_eq!(tokens, vec![CypherToken::Identifier("My Node".to_string())]);
    }

    #[test]
    fn test_in_list() {
        let tokens = tokenize_cypher("WHERE n.x IN [1, 2, 3]").unwrap();
        assert!(tokens.contains(&CypherToken::In));
        assert!(tokens.contains(&CypherToken::LBracket));
        assert!(tokens.contains(&CypherToken::RBracket));
    }

    #[test]
    fn test_var_length_path() {
        let tokens = tokenize_cypher("-[:KNOWS*1..3]->").unwrap();
        assert!(tokens.contains(&CypherToken::Star));
        assert!(tokens.contains(&CypherToken::DotDot));
    }

    #[test]
    fn test_case_tokens() {
        let tokens = tokenize_cypher("CASE WHEN x THEN 1 ELSE 0 END").unwrap();
        assert_eq!(tokens[0], CypherToken::Case);
        assert_eq!(tokens[1], CypherToken::When);
        assert_eq!(tokens[3], CypherToken::Then);
        assert_eq!(tokens[5], CypherToken::Else);
        assert_eq!(tokens[7], CypherToken::End);
    }

    #[test]
    fn test_case_insensitive_case() {
        let tokens = tokenize_cypher("case when x then 1 else 0 end").unwrap();
        assert_eq!(tokens[0], CypherToken::Case);
        assert_eq!(tokens[1], CypherToken::When);
    }

    #[test]
    fn test_parameter_token() {
        let tokens = tokenize_cypher("$min_age").unwrap();
        assert_eq!(tokens, vec![CypherToken::Parameter("min_age".to_string())]);
    }

    #[test]
    fn test_parameter_in_query() {
        let tokens = tokenize_cypher("WHERE n.age > $age AND n.city = $city").unwrap();
        assert!(tokens.contains(&CypherToken::Parameter("age".to_string())));
        assert!(tokens.contains(&CypherToken::Parameter("city".to_string())));
    }

    #[test]
    fn test_parameter_empty_name_error() {
        let result = tokenize_cypher("$");
        assert!(result.is_err());
    }

    #[test]
    fn test_merge_remove_on_tokens() {
        let tokens = tokenize_cypher("MERGE REMOVE ON").unwrap();
        assert_eq!(tokens[0], CypherToken::Merge);
        assert_eq!(tokens[1], CypherToken::Remove);
        assert_eq!(tokens[2], CypherToken::On);
    }
}