-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcypher.rs
More file actions
1409 lines (1246 loc) · 44.6 KB
/
Copy pathcypher.rs
File metadata and controls
1409 lines (1246 loc) · 44.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Cypher Parser and Transpiler
//!
//! Parses Cypher queries and transpiles them to SQL with recursive CTEs.
//! This enables graph queries over the relational Lance storage.
//!
//! # Supported Cypher Features
//!
//! ```cypher
//! -- Simple pattern matching
//! MATCH (a:Thought)-[:CAUSES]->(b:Thought)
//! WHERE a.qidx > 100
//! RETURN b
//!
//! -- Variable-length paths (recursive CTE)
//! MATCH (a)-[:CAUSES*1..5]->(b)
//! WHERE a.id = 'start'
//! RETURN b, path, amplification
//!
//! -- Multiple relationships
//! MATCH (a)-[:CAUSES|ENABLES]->(b)
//! RETURN a, b
//!
//! -- Create operations
//! CREATE (a:Thought {content: 'Hello'})
//! CREATE (a)-[:CAUSES {weight: 0.8}]->(b)
//! ```
use std::collections::HashMap;
use crate::{Error, Result};
// =============================================================================
// AST TYPES
// =============================================================================
/// Parsed Cypher query
#[derive(Debug, Clone)]
pub struct CypherQuery {
pub query_type: QueryType,
pub match_clause: Option<MatchClause>,
pub where_clause: Option<WhereClause>,
pub return_clause: Option<ReturnClause>,
pub order_by: Option<OrderByClause>,
pub limit: Option<u64>,
pub skip: Option<u64>,
pub create_clause: Option<CreateClause>,
pub set_clause: Option<SetClause>,
pub delete_clause: Option<DeleteClause>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum QueryType {
Match,
Create,
Merge,
Delete,
Set,
}
/// MATCH clause: pattern to search for
#[derive(Debug, Clone)]
pub struct MatchClause {
pub patterns: Vec<Pattern>,
}
/// A graph pattern: (node)-[edge]->(node)...
#[derive(Debug, Clone)]
pub struct Pattern {
pub elements: Vec<PatternElement>,
}
#[derive(Debug, Clone)]
pub enum PatternElement {
Node(NodePattern),
Edge(EdgePattern),
}
/// Node pattern: (alias:Label {props})
#[derive(Debug, Clone)]
pub struct NodePattern {
pub alias: Option<String>,
pub labels: Vec<String>,
pub properties: HashMap<String, Value>,
}
/// Edge pattern: -[alias:TYPE*min..max {props}]->
#[derive(Debug, Clone)]
pub struct EdgePattern {
pub alias: Option<String>,
pub types: Vec<String>,
pub direction: EdgeDirection,
pub min_hops: u32,
pub max_hops: u32,
pub properties: HashMap<String, Value>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum EdgeDirection {
Outgoing, // ->
Incoming, // <-
Both, // -
}
/// WHERE clause conditions
#[derive(Debug, Clone)]
pub struct WhereClause {
pub condition: Condition,
}
#[derive(Debug, Clone)]
pub enum Condition {
Comparison {
left: Expr,
op: ComparisonOp,
right: Expr,
},
And(Box<Condition>, Box<Condition>),
Or(Box<Condition>, Box<Condition>),
Not(Box<Condition>),
IsNull(Expr),
IsNotNull(Expr),
In(Expr, Vec<Value>),
}
#[derive(Debug, Clone, PartialEq)]
pub enum ComparisonOp {
Eq, // =
Ne, // <>
Lt, // <
Le, // <=
Gt, // >
Ge, // >=
Contains,
StartsWith,
EndsWith,
}
#[derive(Debug, Clone)]
pub enum Expr {
Property { alias: String, property: String },
Literal(Value),
Function { name: String, args: Vec<Expr> },
Variable(String),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum Value {
String(String),
Integer(i64),
Float(f64),
Boolean(bool),
Null,
List(Vec<Value>),
}
/// RETURN clause
#[derive(Debug, Clone)]
pub struct ReturnClause {
pub items: Vec<ReturnItem>,
pub distinct: bool,
}
#[derive(Debug, Clone)]
pub struct ReturnItem {
pub expr: Expr,
pub alias: Option<String>,
}
/// ORDER BY clause
#[derive(Debug, Clone)]
pub struct OrderByClause {
pub items: Vec<OrderItem>,
}
#[derive(Debug, Clone)]
pub struct OrderItem {
pub expr: Expr,
pub direction: SortDirection,
}
#[derive(Debug, Clone, PartialEq)]
pub enum SortDirection {
Asc,
Desc,
}
/// CREATE clause
#[derive(Debug, Clone)]
pub struct CreateClause {
pub patterns: Vec<Pattern>,
}
/// SET clause
#[derive(Debug, Clone)]
pub struct SetClause {
pub items: Vec<SetItem>,
}
#[derive(Debug, Clone)]
pub struct SetItem {
pub target: Expr,
pub value: Expr,
}
/// DELETE clause
#[derive(Debug, Clone)]
pub struct DeleteClause {
pub items: Vec<String>,
pub detach: bool,
}
// =============================================================================
// PARSER
// =============================================================================
/// Cypher parser
pub struct CypherParser {
tokens: Vec<Token>,
pos: usize,
}
#[derive(Debug, Clone, PartialEq)]
enum Token {
// Keywords
Match,
Where,
Return,
Create,
Merge,
Delete,
Detach,
Set,
OrderBy,
Limit,
Skip,
And,
Or,
Not,
In,
Is,
Null,
Distinct,
As,
Asc,
Desc,
Contains,
StartsWith,
EndsWith,
// Symbols
LParen,
RParen,
LBracket,
RBracket,
LBrace,
RBrace,
Colon,
Comma,
Dot,
Pipe,
Star,
DotDot,
Arrow, // ->
LeftArrow, // <-
Dash, // -
// Operators
Eq,
Ne,
Lt,
Le,
Gt,
Ge,
// Literals
Identifier(String),
StringLit(String),
IntLit(i64),
FloatLit(f64),
BoolLit(bool),
// End
Eof,
}
impl CypherParser {
/// Parse a Cypher query string
pub fn parse(input: &str) -> Result<CypherQuery> {
let tokens = Self::tokenize(input)?;
let mut parser = Self { tokens, pos: 0 };
parser.parse_query()
}
/// Tokenize input string
fn tokenize(input: &str) -> Result<Vec<Token>> {
let mut tokens = Vec::new();
let chars: Vec<char> = input.chars().collect();
let mut i = 0;
while i < chars.len() {
let c = chars[i];
// Skip whitespace
if c.is_whitespace() {
i += 1;
continue;
}
// Skip comments
if c == '/' && i + 1 < chars.len() && chars[i + 1] == '/' {
while i < chars.len() && chars[i] != '\n' {
i += 1;
}
continue;
}
// Symbols
match c {
'(' => { tokens.push(Token::LParen); i += 1; continue; }
')' => { tokens.push(Token::RParen); i += 1; continue; }
'[' => { tokens.push(Token::LBracket); i += 1; continue; }
']' => { tokens.push(Token::RBracket); i += 1; continue; }
'{' => { tokens.push(Token::LBrace); i += 1; continue; }
'}' => { tokens.push(Token::RBrace); i += 1; continue; }
':' => { tokens.push(Token::Colon); i += 1; continue; }
',' => { tokens.push(Token::Comma); i += 1; continue; }
'|' => { tokens.push(Token::Pipe); i += 1; continue; }
'*' => { tokens.push(Token::Star); i += 1; continue; }
'=' => { tokens.push(Token::Eq); i += 1; continue; }
_ => {}
}
// Multi-char operators
if c == '-' {
if i + 1 < chars.len() && chars[i + 1] == '>' {
tokens.push(Token::Arrow);
i += 2;
continue;
} else {
tokens.push(Token::Dash);
i += 1;
continue;
}
}
if c == '<' {
if i + 1 < chars.len() {
match chars[i + 1] {
'-' => { tokens.push(Token::LeftArrow); i += 2; continue; }
'=' => { tokens.push(Token::Le); i += 2; continue; }
'>' => { tokens.push(Token::Ne); i += 2; continue; }
_ => { tokens.push(Token::Lt); i += 1; continue; }
}
} else {
tokens.push(Token::Lt);
i += 1;
continue;
}
}
if c == '>' {
if i + 1 < chars.len() && chars[i + 1] == '=' {
tokens.push(Token::Ge);
i += 2;
continue;
} else {
tokens.push(Token::Gt);
i += 1;
continue;
}
}
if c == '.' {
if i + 1 < chars.len() && chars[i + 1] == '.' {
tokens.push(Token::DotDot);
i += 2;
continue;
} else {
tokens.push(Token::Dot);
i += 1;
continue;
}
}
// String literals
if c == '\'' || c == '"' {
let quote = c;
i += 1;
let start = i;
while i < chars.len() && chars[i] != quote {
if chars[i] == '\\' && i + 1 < chars.len() {
i += 2;
} else {
i += 1;
}
}
let s: String = chars[start..i].iter().collect();
tokens.push(Token::StringLit(s));
i += 1; // skip closing quote
continue;
}
// Numbers (handle range notation like 1..5 - stop at double dot)
if c.is_ascii_digit() || (c == '-' && i + 1 < chars.len() && chars[i + 1].is_ascii_digit()) {
let start = i;
if c == '-' { i += 1; }
let mut has_decimal = false;
while i < chars.len() {
if chars[i].is_ascii_digit() {
i += 1;
} else if chars[i] == '.' && !has_decimal {
// Check for range operator ".." - don't consume if double dot
if i + 1 < chars.len() && chars[i + 1] == '.' {
break; // Stop before range operator
}
has_decimal = true;
i += 1;
} else {
break;
}
}
let num_str: String = chars[start..i].iter().collect();
if has_decimal {
tokens.push(Token::FloatLit(num_str.parse().unwrap()));
} else {
tokens.push(Token::IntLit(num_str.parse().unwrap()));
}
continue;
}
// Identifiers and keywords
if c.is_alphabetic() || c == '_' {
let start = i;
while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '_') {
i += 1;
}
let word: String = chars[start..i].iter().collect();
let token = match word.to_uppercase().as_str() {
"MATCH" => Token::Match,
"WHERE" => Token::Where,
"RETURN" => Token::Return,
"CREATE" => Token::Create,
"MERGE" => Token::Merge,
"DELETE" => Token::Delete,
"DETACH" => Token::Detach,
"SET" => Token::Set,
"ORDER" => {
// Check for ORDER BY
while i < chars.len() && chars[i].is_whitespace() { i += 1; }
if i + 1 < chars.len() {
let by_start = i;
while i < chars.len() && chars[i].is_alphabetic() { i += 1; }
let by_word: String = chars[by_start..i].iter().collect();
if by_word.to_uppercase() == "BY" {
Token::OrderBy
} else {
i = by_start; // reset
Token::Identifier(word)
}
} else {
Token::Identifier(word)
}
}
"BY" => Token::Identifier(word), // handled in ORDER
"LIMIT" => Token::Limit,
"SKIP" => Token::Skip,
"AND" => Token::And,
"OR" => Token::Or,
"NOT" => Token::Not,
"IN" => Token::In,
"IS" => Token::Is,
"NULL" => Token::Null,
"DISTINCT" => Token::Distinct,
"AS" => Token::As,
"ASC" => Token::Asc,
"DESC" => Token::Desc,
"CONTAINS" => Token::Contains,
"STARTS" => {
// STARTS WITH
while i < chars.len() && chars[i].is_whitespace() { i += 1; }
let with_start = i;
while i < chars.len() && chars[i].is_alphabetic() { i += 1; }
let with_word: String = chars[with_start..i].iter().collect();
if with_word.to_uppercase() == "WITH" {
Token::StartsWith
} else {
i = with_start;
Token::Identifier(word)
}
}
"ENDS" => {
// ENDS WITH
while i < chars.len() && chars[i].is_whitespace() { i += 1; }
let with_start = i;
while i < chars.len() && chars[i].is_alphabetic() { i += 1; }
let with_word: String = chars[with_start..i].iter().collect();
if with_word.to_uppercase() == "WITH" {
Token::EndsWith
} else {
i = with_start;
Token::Identifier(word)
}
}
"TRUE" => Token::BoolLit(true),
"FALSE" => Token::BoolLit(false),
_ => Token::Identifier(word),
};
tokens.push(token);
continue;
}
return Err(Error::Query(format!("Unexpected character: {}", c)));
}
tokens.push(Token::Eof);
Ok(tokens)
}
fn current(&self) -> &Token {
&self.tokens[self.pos]
}
fn advance(&mut self) -> Token {
let t = self.tokens[self.pos].clone();
if self.pos < self.tokens.len() - 1 {
self.pos += 1;
}
t
}
fn expect(&mut self, expected: Token) -> Result<()> {
if std::mem::discriminant(self.current()) == std::mem::discriminant(&expected) {
self.advance();
Ok(())
} else {
Err(Error::Query(format!(
"Expected {:?}, got {:?}", expected, self.current()
)))
}
}
fn parse_query(&mut self) -> Result<CypherQuery> {
let mut query = CypherQuery {
query_type: QueryType::Match,
match_clause: None,
where_clause: None,
return_clause: None,
order_by: None,
limit: None,
skip: None,
create_clause: None,
set_clause: None,
delete_clause: None,
};
match self.current() {
Token::Match => {
query.query_type = QueryType::Match;
self.advance();
query.match_clause = Some(self.parse_match()?);
}
Token::Create => {
query.query_type = QueryType::Create;
self.advance();
query.create_clause = Some(self.parse_create()?);
}
_ => return Err(Error::Query("Expected MATCH or CREATE".into())),
}
// Optional WHERE
if matches!(self.current(), Token::Where) {
self.advance();
query.where_clause = Some(self.parse_where()?);
}
// Optional RETURN
if matches!(self.current(), Token::Return) {
self.advance();
query.return_clause = Some(self.parse_return()?);
}
// Optional ORDER BY
if matches!(self.current(), Token::OrderBy) {
self.advance();
query.order_by = Some(self.parse_order_by()?);
}
// Optional LIMIT
if matches!(self.current(), Token::Limit) {
self.advance();
if let Token::IntLit(n) = self.advance() {
query.limit = Some(n as u64);
}
}
// Optional SKIP
if matches!(self.current(), Token::Skip) {
self.advance();
if let Token::IntLit(n) = self.advance() {
query.skip = Some(n as u64);
}
}
Ok(query)
}
fn parse_match(&mut self) -> Result<MatchClause> {
let patterns = vec![self.parse_pattern()?];
Ok(MatchClause { patterns })
}
fn parse_pattern(&mut self) -> Result<Pattern> {
let mut elements = Vec::new();
// First element must be a node
elements.push(PatternElement::Node(self.parse_node_pattern()?));
// Then alternating edges and nodes
loop {
if self.is_edge_start() {
elements.push(PatternElement::Edge(self.parse_edge_pattern()?));
elements.push(PatternElement::Node(self.parse_node_pattern()?));
} else {
break;
}
}
Ok(Pattern { elements })
}
fn is_edge_start(&self) -> bool {
matches!(self.current(), Token::Dash | Token::LeftArrow)
}
fn parse_node_pattern(&mut self) -> Result<NodePattern> {
self.expect(Token::LParen)?;
let mut node = NodePattern {
alias: None,
labels: Vec::new(),
properties: HashMap::new(),
};
// Optional alias
if let Token::Identifier(id) = self.current() {
node.alias = Some(id.clone());
self.advance();
}
// Optional labels
while matches!(self.current(), Token::Colon) {
self.advance();
if let Token::Identifier(label) = self.advance() {
node.labels.push(label);
}
}
// Optional properties
if matches!(self.current(), Token::LBrace) {
node.properties = self.parse_properties()?;
}
self.expect(Token::RParen)?;
Ok(node)
}
fn parse_edge_pattern(&mut self) -> Result<EdgePattern> {
let mut edge = EdgePattern {
alias: None,
types: Vec::new(),
direction: EdgeDirection::Outgoing,
min_hops: 1,
max_hops: 1,
properties: HashMap::new(),
};
// Direction start
if matches!(self.current(), Token::LeftArrow) {
edge.direction = EdgeDirection::Incoming;
self.advance();
} else {
self.expect(Token::Dash)?;
}
// Edge details [...]
if matches!(self.current(), Token::LBracket) {
self.advance();
// Optional alias
if let Token::Identifier(id) = self.current() {
edge.alias = Some(id.clone());
self.advance();
}
// Optional types
while matches!(self.current(), Token::Colon | Token::Pipe) {
if matches!(self.current(), Token::Pipe) {
self.advance();
} else {
self.advance(); // colon
}
if let Token::Identifier(t) = self.advance() {
edge.types.push(t);
}
}
// Optional variable length *min..max
if matches!(self.current(), Token::Star) {
self.advance();
// min
if let Token::IntLit(n) = self.current() {
edge.min_hops = *n as u32;
self.advance();
}
// ..max
if matches!(self.current(), Token::DotDot) {
self.advance();
if let Token::IntLit(n) = self.current() {
edge.max_hops = *n as u32;
self.advance();
} else {
edge.max_hops = 10; // default max
}
} else {
edge.max_hops = edge.min_hops;
}
}
// Optional properties
if matches!(self.current(), Token::LBrace) {
edge.properties = self.parse_properties()?;
}
self.expect(Token::RBracket)?;
}
// Direction end
if edge.direction == EdgeDirection::Incoming {
self.expect(Token::Dash)?;
} else if matches!(self.current(), Token::Arrow) {
self.advance();
} else {
self.expect(Token::Dash)?;
edge.direction = EdgeDirection::Both;
}
Ok(edge)
}
fn parse_properties(&mut self) -> Result<HashMap<String, Value>> {
self.expect(Token::LBrace)?;
let mut props = HashMap::new();
loop {
if matches!(self.current(), Token::RBrace) {
break;
}
// key: value
let key = if let Token::Identifier(k) = self.advance() {
k
} else {
return Err(Error::Query("Expected property key".into()));
};
self.expect(Token::Colon)?;
let value = self.parse_value()?;
props.insert(key, value);
if matches!(self.current(), Token::Comma) {
self.advance();
} else {
break;
}
}
self.expect(Token::RBrace)?;
Ok(props)
}
fn parse_value(&mut self) -> Result<Value> {
match self.advance() {
Token::StringLit(s) => Ok(Value::String(s)),
Token::IntLit(n) => Ok(Value::Integer(n)),
Token::FloatLit(f) => Ok(Value::Float(f)),
Token::BoolLit(b) => Ok(Value::Boolean(b)),
Token::Null => Ok(Value::Null),
t => Err(Error::Query(format!("Expected value, got {:?}", t))),
}
}
fn parse_where(&mut self) -> Result<WhereClause> {
let condition = self.parse_condition()?;
Ok(WhereClause { condition })
}
fn parse_condition(&mut self) -> Result<Condition> {
let mut left = self.parse_comparison()?;
loop {
match self.current() {
Token::And => {
self.advance();
let right = self.parse_comparison()?;
left = Condition::And(Box::new(left), Box::new(right));
}
Token::Or => {
self.advance();
let right = self.parse_comparison()?;
left = Condition::Or(Box::new(left), Box::new(right));
}
_ => break,
}
}
Ok(left)
}
fn parse_comparison(&mut self) -> Result<Condition> {
let left = self.parse_expr()?;
let op = match self.current() {
Token::Eq => ComparisonOp::Eq,
Token::Ne => ComparisonOp::Ne,
Token::Lt => ComparisonOp::Lt,
Token::Le => ComparisonOp::Le,
Token::Gt => ComparisonOp::Gt,
Token::Ge => ComparisonOp::Ge,
Token::Contains => ComparisonOp::Contains,
Token::StartsWith => ComparisonOp::StartsWith,
Token::EndsWith => ComparisonOp::EndsWith,
Token::Is => {
self.advance();
if matches!(self.current(), Token::Not) {
self.advance();
self.expect(Token::Null)?;
return Ok(Condition::IsNotNull(left));
} else {
self.expect(Token::Null)?;
return Ok(Condition::IsNull(left));
}
}
_ => return Ok(Condition::Comparison {
left: left.clone(),
op: ComparisonOp::Eq,
right: Expr::Literal(Value::Boolean(true)),
}),
};
self.advance();
let right = self.parse_expr()?;
Ok(Condition::Comparison { left, op, right })
}
fn parse_expr(&mut self) -> Result<Expr> {
match self.current().clone() {
Token::Identifier(name) => {
self.advance();
if matches!(self.current(), Token::Dot) {
self.advance();
if let Token::Identifier(prop) = self.advance() {
Ok(Expr::Property { alias: name, property: prop })
} else {
Err(Error::Query("Expected property name".into()))
}
} else if matches!(self.current(), Token::LParen) {
// Function call
self.advance();
let mut args = Vec::new();
while !matches!(self.current(), Token::RParen) {
args.push(self.parse_expr()?);
if matches!(self.current(), Token::Comma) {
self.advance();
}
}
self.expect(Token::RParen)?;
Ok(Expr::Function { name, args })
} else {
Ok(Expr::Variable(name))
}
}
Token::StringLit(s) => {
self.advance();
Ok(Expr::Literal(Value::String(s)))
}
Token::IntLit(n) => {
self.advance();
Ok(Expr::Literal(Value::Integer(n)))
}
Token::FloatLit(f) => {
self.advance();
Ok(Expr::Literal(Value::Float(f)))
}
Token::BoolLit(b) => {
self.advance();
Ok(Expr::Literal(Value::Boolean(b)))
}
Token::Null => {
self.advance();
Ok(Expr::Literal(Value::Null))
}
_ => Err(Error::Query(format!("Unexpected token in expression: {:?}", self.current()))),
}
}
fn parse_return(&mut self) -> Result<ReturnClause> {
let distinct = if matches!(self.current(), Token::Distinct) {
self.advance();
true
} else {
false
};
let mut items = Vec::new();
loop {
let expr = self.parse_expr()?;
let alias = if matches!(self.current(), Token::As) {
self.advance();
if let Token::Identifier(a) = self.advance() {
Some(a)
} else {
None
}
} else {
None
};
items.push(ReturnItem { expr, alias });
if matches!(self.current(), Token::Comma) {
self.advance();
} else {
break;
}
}
Ok(ReturnClause { items, distinct })
}
fn parse_order_by(&mut self) -> Result<OrderByClause> {
let mut items = Vec::new();
loop {
let expr = self.parse_expr()?;
let direction = match self.current() {
Token::Desc => { self.advance(); SortDirection::Desc }
Token::Asc => { self.advance(); SortDirection::Asc }
_ => SortDirection::Asc,
};
items.push(OrderItem { expr, direction });
if matches!(self.current(), Token::Comma) {
self.advance();
} else {
break;
}
}
Ok(OrderByClause { items })
}
fn parse_create(&mut self) -> Result<CreateClause> {
let patterns = vec![self.parse_pattern()?];
Ok(CreateClause { patterns })
}
}
// =============================================================================
// TRANSPILER (Cypher → SQL)
// =============================================================================
/// Transpile Cypher AST to SQL
pub struct CypherTranspiler;
impl CypherTranspiler {
/// Transpile a Cypher query to SQL
pub fn transpile(query: &CypherQuery) -> Result<String> {
match query.query_type {
QueryType::Match => Self::transpile_match(query),
QueryType::Create => Self::transpile_create(query),
_ => Err(Error::Query("Unsupported query type".into())),
}
}
fn transpile_match(query: &CypherQuery) -> Result<String> {
let match_clause = query.match_clause.as_ref()
.ok_or_else(|| Error::Query("Missing MATCH clause".into()))?;
let pattern = &match_clause.patterns[0];
// Determine if we need recursive CTE
let needs_recursive = pattern.elements.iter().any(|e| {
if let PatternElement::Edge(edge) = e {
edge.max_hops > 1
} else {
false
}
});