-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsemantic.rs
More file actions
1719 lines (1591 loc) · 65.8 KB
/
Copy pathsemantic.rs
File metadata and controls
1719 lines (1591 loc) · 65.8 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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors
//! Semantic analysis for graph queries
//!
//! This module implements the semantic analysis phase of the query pipeline:
//! Parse → **Semantic Analysis** → Logical Plan → Physical Plan
//!
//! Semantic analysis validates the query and enriches the AST with type information.
use super::ast::*;
use super::case_insensitive::CaseInsensitiveLookup;
use super::config::GraphConfig;
use super::super::error::{QueryError, Result};
use std::collections::{HashMap, HashSet};
/// Semantic analyzer - validates and enriches the AST
pub struct SemanticAnalyzer {
config: GraphConfig,
variables: HashMap<String, VariableInfo>,
current_scope: ScopeType,
}
/// Information about a variable in the query
#[derive(Debug, Clone)]
pub struct VariableInfo {
pub name: String,
pub variable_type: VariableType,
pub labels: Vec<String>,
pub properties: HashSet<String>,
pub defined_in: ScopeType,
}
/// Type of a variable
#[derive(Debug, Clone, PartialEq)]
pub enum VariableType {
Node,
Relationship,
Path,
Property,
}
/// Scope where a variable is defined
#[derive(Debug, Clone, PartialEq)]
pub enum ScopeType {
Match,
Where,
With,
PostWithWhere,
Return,
OrderBy,
}
/// Semantic analysis result with validated and enriched AST
#[derive(Debug, Clone)]
pub struct SemanticResult {
/// The AST with parameters substituted and validated
pub ast: CypherQuery,
pub variables: HashMap<String, VariableInfo>,
pub errors: Vec<String>,
pub warnings: Vec<String>,
}
impl SemanticAnalyzer {
pub fn new(config: GraphConfig) -> Self {
Self {
config,
variables: HashMap::new(),
current_scope: ScopeType::Match,
}
}
/// Analyze a Cypher query AST
pub fn analyze(
&mut self,
query: &CypherQuery,
parameters: &HashMap<String, super::parameter_substitution::ParamValue>,
) -> Result<SemanticResult> {
// Clone the query to perform parameter substitution
let mut analyzed_query = query.clone();
// Perform parameter substitution
self.substitute_parameters(&mut analyzed_query, parameters)?;
let mut errors = Vec::new();
let mut warnings = Vec::new();
// Phase 1: Variable discovery in READING clauses (MATCH/UNWIND)
self.current_scope = ScopeType::Match;
for clause in &analyzed_query.reading_clauses {
match clause {
ReadingClause::Match(match_clause) => {
if let Err(e) = self.analyze_match_clause(match_clause) {
errors.push(format!("MATCH clause error: {}", e));
}
}
ReadingClause::Unwind(unwind_clause) => {
if let Err(e) = self.analyze_unwind_clause(unwind_clause) {
errors.push(format!("UNWIND clause error: {}", e));
}
}
}
}
// Phase 2: Validate WHERE clause (before WITH)
if let Some(where_clause) = &analyzed_query.where_clause {
self.current_scope = ScopeType::Where;
if let Err(e) = self.analyze_where_clause(where_clause) {
errors.push(format!("WHERE clause error: {}", e));
}
}
// Phase 3: Validate WITH clause if present
if let Some(with_clause) = &analyzed_query.with_clause {
self.current_scope = ScopeType::With;
if let Err(e) = self.analyze_with_clause(with_clause) {
errors.push(format!("WITH clause error: {}", e));
}
}
// Phase 4: Variable discovery in post-WITH READING clauses (query chaining)
self.current_scope = ScopeType::Match;
for clause in &analyzed_query.post_with_reading_clauses {
match clause {
ReadingClause::Match(match_clause) => {
if let Err(e) = self.analyze_match_clause(match_clause) {
errors.push(format!("Post-WITH MATCH clause error: {}", e));
}
}
ReadingClause::Unwind(unwind_clause) => {
if let Err(e) = self.analyze_unwind_clause(unwind_clause) {
errors.push(format!("Post-WITH UNWIND clause error: {}", e));
}
}
}
}
// Phase 4: Validate post-WITH WHERE clause if present
if let Some(post_where) = &analyzed_query.post_with_where_clause {
self.current_scope = ScopeType::PostWithWhere;
if let Err(e) = self.analyze_where_clause(post_where) {
errors.push(format!("Post-WITH WHERE clause error: {}", e));
}
}
// Phase 5: Validate RETURN clause
self.current_scope = ScopeType::Return;
if let Err(e) = self.analyze_return_clause(&analyzed_query.return_clause) {
errors.push(format!("RETURN clause error: {}", e));
}
// Phase 6: Validate ORDER BY clause
if let Some(order_by) = &analyzed_query.order_by {
self.current_scope = ScopeType::OrderBy;
if let Err(e) = self.analyze_order_by_clause(order_by) {
errors.push(format!("ORDER BY clause error: {}", e));
}
}
// Phase 7: Schema validation
self.validate_schema(&mut warnings);
// Phase 8: Type checking
self.validate_types(&mut errors);
Ok(SemanticResult {
ast: analyzed_query,
variables: self.variables.clone(),
errors,
warnings,
})
}
/// Analyze MATCH clause and discover variables
fn analyze_match_clause(&mut self, match_clause: &MatchClause) -> Result<()> {
for pattern in &match_clause.patterns {
self.analyze_graph_pattern(pattern)?;
}
Ok(())
}
/// Analyze UNWIND clause and register variables
fn analyze_unwind_clause(&mut self, unwind_clause: &UnwindClause) -> Result<()> {
self.analyze_value_expression(&unwind_clause.expression)?;
// Register the aliased variable (normalize to lowercase for case-insensitive behavior)
let var_name = &unwind_clause.alias;
let var_name_lower = var_name.to_lowercase();
if let Some(existing) = self.variables.get_mut(&var_name_lower) {
// Shadowing or redefinition - in Cypher variables can be bound multiple times in some contexts
// But here we enforce uniqueness of types mostly.
// For now, treat UNWIND alias as a Property type variable.
if existing.variable_type != VariableType::Property {
return Err(QueryError::PlanError {
message: format!("Variable '{}' redefined with different type", var_name),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
} else {
let var_info = VariableInfo {
name: var_name.clone(),
variable_type: VariableType::Property,
labels: vec![],
properties: HashSet::new(),
defined_in: self.current_scope.clone(),
};
self.variables.insert(var_name_lower, var_info);
}
Ok(())
}
/// Analyze a graph pattern and register variables
fn analyze_graph_pattern(&mut self, pattern: &GraphPattern) -> Result<()> {
match pattern {
GraphPattern::Node(node) => {
self.register_node_variable(node)?;
}
GraphPattern::Path(path) => {
// Register start node
self.register_node_variable(&path.start_node)?;
// Register variables in each segment
for segment in &path.segments {
// Validate relationship length constraints if present
self.validate_length_range(&segment.relationship)?;
// Register relationship variable if present
if let Some(rel_var) = &segment.relationship.variable {
self.register_relationship_variable(rel_var, &segment.relationship)?;
}
// Register end node
self.register_node_variable(&segment.end_node)?;
}
}
}
Ok(())
}
/// Register a node variable
fn register_node_variable(&mut self, node: &NodePattern) -> Result<()> {
if let Some(var_name) = &node.variable {
// Normalize to lowercase for case-insensitive behavior
let var_name_lower = var_name.to_lowercase();
if let Some(existing) = self.variables.get_mut(&var_name_lower) {
if existing.variable_type != VariableType::Node {
return Err(QueryError::PlanError {
message: format!("Variable '{}' redefined with different type", var_name),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
for label in &node.labels {
if !existing.labels.contains(label) {
existing.labels.push(label.clone());
}
}
for prop in node.properties.keys() {
existing.properties.insert(prop.clone());
}
} else {
let var_info = VariableInfo {
name: var_name.clone(),
variable_type: VariableType::Node,
labels: node.labels.clone(),
properties: node.properties.keys().cloned().collect(),
defined_in: self.current_scope.clone(),
};
self.variables.insert(var_name_lower, var_info);
}
}
Ok(())
}
/// Register a relationship variable
fn register_relationship_variable(
&mut self,
var_name: &str,
rel: &RelationshipPattern,
) -> Result<()> {
// Normalize to lowercase for case-insensitive behavior
let var_name_lower = var_name.to_lowercase();
if let Some(existing) = self.variables.get_mut(&var_name_lower) {
if existing.variable_type != VariableType::Relationship {
return Err(QueryError::PlanError {
message: format!("Variable '{}' redefined with different type", var_name),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
for rel_type in &rel.types {
if !existing.labels.contains(rel_type) {
existing.labels.push(rel_type.clone());
}
}
for prop in rel.properties.keys() {
existing.properties.insert(prop.clone());
}
} else {
let var_info = VariableInfo {
name: var_name.to_string(),
variable_type: VariableType::Relationship,
labels: rel.types.clone(), // Relationship types are like labels
properties: rel.properties.keys().cloned().collect(),
defined_in: self.current_scope.clone(),
};
self.variables.insert(var_name_lower, var_info);
}
Ok(())
}
/// Analyze WHERE clause
fn analyze_where_clause(&mut self, where_clause: &WhereClause) -> Result<()> {
self.analyze_boolean_expression(&where_clause.expression)
}
/// Analyze boolean expression and check variable references
fn analyze_boolean_expression(&mut self, expr: &BooleanExpression) -> Result<()> {
match expr {
BooleanExpression::Comparison { left, right, .. } => {
self.analyze_value_expression(left)?;
self.analyze_value_expression(right)?;
}
BooleanExpression::And(left, right) | BooleanExpression::Or(left, right) => {
self.analyze_boolean_expression(left)?;
self.analyze_boolean_expression(right)?;
}
BooleanExpression::Not(inner) => {
self.analyze_boolean_expression(inner)?;
}
BooleanExpression::Exists(prop_ref) => {
self.validate_property_reference(prop_ref)?;
}
BooleanExpression::In { expression, list } => {
self.analyze_value_expression(expression)?;
for item in list {
self.analyze_value_expression(item)?;
}
}
BooleanExpression::Like { expression, .. } => {
self.analyze_value_expression(expression)?;
}
BooleanExpression::ILike { expression, .. } => {
self.analyze_value_expression(expression)?;
}
BooleanExpression::Contains { expression, .. } => {
self.analyze_value_expression(expression)?;
}
BooleanExpression::StartsWith { expression, .. } => {
self.analyze_value_expression(expression)?;
}
BooleanExpression::EndsWith { expression, .. } => {
self.analyze_value_expression(expression)?;
}
BooleanExpression::IsNull(expression) => {
self.analyze_value_expression(expression)?;
}
BooleanExpression::IsNotNull(expression) => {
self.analyze_value_expression(expression)?;
}
}
Ok(())
}
/// Analyze value expression and check variable references
fn analyze_value_expression(&mut self, expr: &ValueExpression) -> Result<()> {
match expr {
ValueExpression::Property(prop_ref) => {
self.validate_property_reference(prop_ref)?;
}
ValueExpression::Literal(_) => {
// Literals are always valid
}
ValueExpression::Variable(var) => {
// Use case-insensitive lookup
if !self.variables.contains_key_ci(var) {
return Err(QueryError::PlanError {
message: format!("Undefined variable: '{}'", var),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
}
ValueExpression::ScalarFunction { name, args } => {
let function_name = name.to_lowercase();
// Validate arity and known functions
match function_name.as_str() {
"tolower" | "lower" | "toupper" | "upper" => {
if args.len() != 1 {
return Err(QueryError::PlanError {
message: format!(
"{} requires exactly 1 argument, got {}",
name.to_uppercase(),
args.len()
),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
}
_ => {
// Unknown scalar function - reject early with helpful error
return Err(QueryError::UnsupportedFeature {
feature: format!(
"Cypher function '{}' is not implemented. Supported scalar functions: toLower, lower, toUpper, upper. Supported aggregate functions: COUNT, SUM, AVG, MIN, MAX, COLLECT.",
name
),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
}
// Validate arguments recursively
for arg in args {
self.analyze_value_expression(arg)?;
}
}
ValueExpression::AggregateFunction {
name,
args,
distinct,
} => {
let function_name = name.to_lowercase();
// Validate known aggregate functions
match function_name.as_str() {
"count" | "sum" | "avg" | "min" | "max" | "collect" => {
// DISTINCT is only supported for COUNT
// Other aggregates silently ignore it in execution, so reject early
if *distinct && function_name != "count" {
return Err(QueryError::UnsupportedFeature {
feature: format!(
"DISTINCT is only supported with COUNT, not {}",
function_name.to_uppercase()
),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
// COUNT(DISTINCT *) is semantically meaningless
// It would count distinct values of lit(1) which is always 1
if *distinct && function_name == "count" {
if let Some(ValueExpression::Variable(v)) = args.first() {
if v == "*" {
return Err(QueryError::PlanError {
message: "COUNT(DISTINCT *) is not supported. \
Use COUNT(*) to count all rows, or \
COUNT(DISTINCT property) to count distinct values."
.to_string(),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
}
}
// All aggregates require exactly 1 argument
if args.len() != 1 {
return Err(QueryError::PlanError {
message: format!(
"{} requires exactly 1 argument, got {}",
function_name.to_uppercase(),
args.len()
),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
// Additional validation for SUM, AVG, MIN, MAX: they require properties, not bare variables
// Only COUNT and COLLECT allow bare variables (COUNT(*), COUNT(p), COLLECT(p))
if matches!(function_name.as_str(), "sum" | "avg" | "min" | "max") {
if let Some(ValueExpression::Variable(v)) = args.first() {
return Err(QueryError::PlanError {
message: format!(
"{}({}) is invalid - {} requires a property like {}({}.property). You cannot {} a node/entity.",
function_name.to_uppercase(), v, function_name.to_uppercase(), function_name.to_uppercase(), v, function_name
),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
}
}
_ => {
// Unknown aggregate function - reject early
return Err(QueryError::UnsupportedFeature {
feature: format!(
"Cypher aggregate function '{}' is not implemented. Supported aggregate functions: COUNT, SUM, AVG, MIN, MAX, COLLECT.",
name
),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
}
// Validate arguments recursively.
// Special-case COUNT(*) where '*' isn't a real variable.
for arg in args {
if function_name == "count"
&& matches!(arg, ValueExpression::Variable(v) if v == "*")
{
continue;
}
self.analyze_value_expression(arg)?;
}
}
ValueExpression::Arithmetic { left, right, .. } => {
// Validate arithmetic operands recursively
self.analyze_value_expression(left)?;
self.analyze_value_expression(right)?;
// If both sides are literals, ensure they are numeric
let is_numeric_literal = |pv: &PropertyValue| {
matches!(pv, PropertyValue::Integer(_) | PropertyValue::Float(_))
};
if let (ValueExpression::Literal(l1), ValueExpression::Literal(l2)) =
(&**left, &**right)
{
if !(is_numeric_literal(l1) && is_numeric_literal(l2)) {
return Err(QueryError::PlanError {
message: "Arithmetic requires numeric literal operands".to_string(),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
}
}
ValueExpression::VectorDistance { left, right, .. } => {
// Validate vector distance function arguments
self.analyze_value_expression(left)?;
self.analyze_value_expression(right)?;
// Check that at least one argument references a property
let has_property = matches!(**left, ValueExpression::Property(_))
|| matches!(**right, ValueExpression::Property(_));
if !has_property {
return Err(QueryError::PlanError {
message: "vector_distance() requires at least one argument to be a property reference".to_string(),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
}
ValueExpression::VectorSimilarity { left, right, .. } => {
// Validate vector similarity function arguments
self.analyze_value_expression(left)?;
self.analyze_value_expression(right)?;
// Check that at least one argument references a property
let has_property = matches!(**left, ValueExpression::Property(_))
|| matches!(**right, ValueExpression::Property(_));
if !has_property {
return Err(QueryError::PlanError {
message: "vector_similarity() requires at least one argument to be a property reference".to_string(),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
}
ValueExpression::VectorLiteral(values) => {
// Validate non-empty
if values.is_empty() {
return Err(QueryError::PlanError {
message: "Vector literal cannot be empty".to_string(),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
// Note: Very large vectors (>4096 dimensions) may impact performance
// but we don't enforce a hard limit here
}
ValueExpression::Parameter(_) => {
// Parameters are always valid (resolved at runtime)
}
}
Ok(())
}
fn register_projection_alias(&mut self, alias: &str) {
// Use case-insensitive lookup and store normalized key
if self.variables.contains_key_ci(alias) {
return;
}
let var_info = VariableInfo {
name: alias.to_string(),
variable_type: VariableType::Property,
labels: vec![],
properties: HashSet::new(),
defined_in: self.current_scope.clone(),
};
self.variables.insert(alias.to_lowercase(), var_info);
}
/// Validate property reference
fn validate_property_reference(&self, prop_ref: &PropertyRef) -> Result<()> {
// Use case-insensitive lookup
if !self.variables.contains_key_ci(&prop_ref.variable) {
return Err(QueryError::PlanError {
message: format!("Undefined variable: '{}'", prop_ref.variable),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
Ok(())
}
/// Analyze RETURN clause
fn analyze_return_clause(&mut self, return_clause: &ReturnClause) -> Result<()> {
for item in &return_clause.items {
self.analyze_value_expression(&item.expression)?;
if let Some(alias) = &item.alias {
self.register_projection_alias(alias);
}
}
Ok(())
}
/// Analyze WITH clause
fn analyze_with_clause(&mut self, with_clause: &WithClause) -> Result<()> {
// Validate WITH item expressions (similar to RETURN)
for item in &with_clause.items {
self.analyze_value_expression(&item.expression)?;
if let Some(alias) = &item.alias {
self.register_projection_alias(alias);
}
}
// Validate ORDER BY within WITH if present
if let Some(order_by) = &with_clause.order_by {
for item in &order_by.items {
self.analyze_value_expression(&item.expression)?;
}
}
Ok(())
}
/// Analyze ORDER BY clause
fn analyze_order_by_clause(&mut self, order_by: &OrderByClause) -> Result<()> {
for item in &order_by.items {
self.analyze_value_expression(&item.expression)?;
}
Ok(())
}
/// Validate schema references against configuration
fn validate_schema(&self, warnings: &mut Vec<String>) {
for var_info in self.variables.values() {
match var_info.variable_type {
VariableType::Node => {
for label in &var_info.labels {
if self.config.get_node_mapping(label).is_none() {
warnings.push(format!("Node label '{}' not found in schema", label));
}
}
}
VariableType::Relationship => {
for rel_type in &var_info.labels {
if self.config.get_relationship_mapping(rel_type).is_none() {
warnings.push(format!(
"Relationship type '{}' not found in schema",
rel_type
));
}
}
}
_ => {}
}
}
}
/// Validate types and operations
fn validate_types(&self, errors: &mut Vec<String>) {
// TODO: Implement type checking
// - Check that properties exist on nodes/relationships
// - Check that comparison operations are valid for data types
// - Check that arithmetic operations are valid
// Check that properties referenced in patterns exist in schema when property fields are defined
for var_info in self.variables.values() {
match var_info.variable_type {
VariableType::Node => {
// Collect property_fields from all known label mappings that specify properties
let mut label_property_sets: Vec<&[String]> = Vec::new();
for label in &var_info.labels {
if let Some(mapping) = self.config.get_node_mapping(label) {
if !mapping.property_fields.is_empty() {
label_property_sets.push(&mapping.property_fields);
}
}
}
if !label_property_sets.is_empty() {
'prop: for prop in &var_info.properties {
// Property is valid if present in at least one label's property_fields
// Use case-insensitive comparison
let prop_lower = prop.to_lowercase();
for fields in &label_property_sets {
if fields.iter().any(|f| f.to_lowercase() == prop_lower) {
continue 'prop;
}
}
errors.push(format!(
"Property '{}' not found on labels {:?}",
prop, var_info.labels
));
}
}
}
VariableType::Relationship => {
// Collect property_fields from all known relationship mappings that specify properties
let mut rel_property_sets: Vec<&[String]> = Vec::new();
for rel_type in &var_info.labels {
if let Some(mapping) = self.config.get_relationship_mapping(rel_type) {
if !mapping.property_fields.is_empty() {
rel_property_sets.push(&mapping.property_fields);
}
}
}
if !rel_property_sets.is_empty() {
'prop_rel: for prop in &var_info.properties {
// Use case-insensitive comparison for relationship properties
let prop_lower = prop.to_lowercase();
for fields in &rel_property_sets {
if fields.iter().any(|f| f.to_lowercase() == prop_lower) {
continue 'prop_rel;
}
}
errors.push(format!(
"Property '{}' not found on relationship types {:?}",
prop, var_info.labels
));
}
}
}
_ => {}
}
}
}
}
impl SemanticAnalyzer {
fn validate_length_range(&self, rel: &RelationshipPattern) -> Result<()> {
if let Some(len) = &rel.length {
if let (Some(min), Some(max)) = (len.min, len.max) {
if min > max {
return Err(QueryError::PlanError {
message: "Invalid path length range: min > max".to_string(),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
}
}
Ok(())
}
/// Substitute parameters with literal values in the AST
fn substitute_parameters(
&self,
query: &mut CypherQuery,
parameters: &HashMap<String, super::parameter_substitution::ParamValue>,
) -> Result<()> {
super::parameter_substitution::substitute_parameters(query, parameters)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::query::lance_parser::ast::{
ArithmeticOperator, BooleanExpression, CypherQuery, GraphPattern, LengthRange, MatchClause,
NodePattern, PathPattern, PathSegment, PropertyRef, PropertyValue, RelationshipDirection,
RelationshipPattern, ReturnClause, ReturnItem, ValueExpression, WhereClause,
};
use crate::query::lance_parser::config::{GraphConfig, NodeMapping};
fn test_config() -> GraphConfig {
GraphConfig::builder()
.with_node_label("Person", "id")
.with_node_label("Employee", "id")
.with_node_label("Company", "id")
.with_relationship("KNOWS", "src_id", "dst_id")
.build()
.unwrap()
}
// Helper: analyze a query that only has a single RETURN expression
fn analyze_return_expr(expr: ValueExpression) -> Result<SemanticResult> {
let query = CypherQuery {
reading_clauses: vec![],
where_clause: None,
with_clause: None,
post_with_reading_clauses: vec![],
post_with_where_clause: None,
return_clause: ReturnClause {
distinct: false,
items: vec![ReturnItem {
expression: expr,
alias: None,
}],
},
limit: None,
order_by: None,
skip: None,
};
let mut analyzer = SemanticAnalyzer::new(test_config());
analyzer.analyze(&query, &HashMap::new())
}
// Helper: analyze a query with a single MATCH (var:label) and a RETURN expression
fn analyze_return_with_match(
var: &str,
label: &str,
expr: ValueExpression,
) -> Result<SemanticResult> {
let node = NodePattern::new(Some(var.to_string())).with_label(label);
let query = CypherQuery {
reading_clauses: vec![ReadingClause::Match(MatchClause {
patterns: vec![GraphPattern::Node(node)],
})],
where_clause: None,
with_clause: None,
post_with_reading_clauses: vec![],
post_with_where_clause: None,
return_clause: ReturnClause {
distinct: false,
items: vec![ReturnItem {
expression: expr,
alias: None,
}],
},
limit: None,
order_by: None,
skip: None,
};
let mut analyzer = SemanticAnalyzer::new(test_config());
analyzer.analyze(&query, &HashMap::new())
}
#[test]
fn test_merge_node_variable_metadata() {
// MATCH (n:Person {age: 30}), (n:Employee {dept: "X"})
let node1 = NodePattern::new(Some("n".to_string()))
.with_label("Person")
.with_property("age", PropertyValue::Integer(30));
let node2 = NodePattern::new(Some("n".to_string()))
.with_label("Employee")
.with_property("dept", PropertyValue::String("X".to_string()));
let query = CypherQuery {
reading_clauses: vec![ReadingClause::Match(MatchClause {
patterns: vec![GraphPattern::Node(node1), GraphPattern::Node(node2)],
})],
where_clause: None,
with_clause: None,
post_with_reading_clauses: vec![],
post_with_where_clause: None,
return_clause: ReturnClause {
distinct: false,
items: vec![],
},
limit: None,
order_by: None,
skip: None,
};
let mut analyzer = SemanticAnalyzer::new(test_config());
let result = analyzer.analyze(&query, &HashMap::new()).unwrap();
assert!(result.errors.is_empty());
let n = result.variables.get("n").expect("variable n present");
// Labels merged
assert!(n.labels.contains(&"Person".to_string()));
assert!(n.labels.contains(&"Employee".to_string()));
// Properties unioned
assert!(n.properties.contains("age"));
assert!(n.properties.contains("dept"));
}
#[test]
fn test_invalid_length_range_collects_error() {
let start = NodePattern::new(Some("a".to_string())).with_label("Person");
let end = NodePattern::new(Some("b".to_string())).with_label("Person");
let mut rel = RelationshipPattern::new(RelationshipDirection::Outgoing)
.with_variable("r")
.with_type("KNOWS");
rel.length = Some(LengthRange {
min: Some(3),
max: Some(2),
});
let path = PathPattern {
start_node: start,
segments: vec![PathSegment {
relationship: rel,
end_node: end,
}],
};
let query = CypherQuery {
reading_clauses: vec![ReadingClause::Match(MatchClause {
patterns: vec![GraphPattern::Path(path)],
})],
where_clause: None,
with_clause: None,
post_with_reading_clauses: vec![],
post_with_where_clause: None,
return_clause: ReturnClause {
distinct: false,
items: vec![],
},
limit: None,
order_by: None,
skip: None,
};
let mut analyzer = SemanticAnalyzer::new(test_config());
let result = analyzer.analyze(&query, &HashMap::new()).unwrap();
assert!(result
.errors
.iter()
.any(|e| e.contains("Invalid path length range")));
}
#[test]
fn test_undefined_variable_in_where() {
// MATCH (n:Person) WHERE EXISTS(m.name)
let node = NodePattern::new(Some("n".to_string())).with_label("Person");
let where_clause = WhereClause {
expression: BooleanExpression::Exists(PropertyRef::new("m", "name")),
};
let query = CypherQuery {
reading_clauses: vec![ReadingClause::Match(MatchClause {
patterns: vec![GraphPattern::Node(node)],
})],
where_clause: Some(where_clause),
with_clause: None,
post_with_reading_clauses: vec![],
post_with_where_clause: None,
return_clause: ReturnClause {
distinct: false,
items: vec![],
},
limit: None,
order_by: None,
skip: None,
};
let mut analyzer = SemanticAnalyzer::new(test_config());
let result = analyzer.analyze(&query, &HashMap::new()).unwrap();
assert!(result
.errors
.iter()
.any(|e| e.contains("Undefined variable: 'm'")));
}
#[test]
fn test_variable_redefinition_between_node_and_relationship() {
// MATCH (n:Person)-[n:KNOWS]->(m:Person)
let start = NodePattern::new(Some("n".to_string())).with_label("Person");
let end = NodePattern::new(Some("m".to_string())).with_label("Person");
let rel = RelationshipPattern::new(RelationshipDirection::Outgoing)
.with_variable("n")
.with_type("KNOWS");
let path = PathPattern {
start_node: start,
segments: vec![PathSegment {
relationship: rel,
end_node: end,
}],
};
let query = CypherQuery {
reading_clauses: vec![ReadingClause::Match(MatchClause {
patterns: vec![GraphPattern::Path(path)],
})],
where_clause: None,
with_clause: None,
post_with_reading_clauses: vec![],
post_with_where_clause: None,
return_clause: ReturnClause {
distinct: false,
items: vec![],
},
limit: None,
order_by: None,
skip: None,
};
let mut analyzer = SemanticAnalyzer::new(test_config());
let result = analyzer.analyze(&query, &HashMap::new()).unwrap();
assert!(result
.errors
.iter()
.any(|e| e.contains("redefined with different type")));
}
#[test]
fn test_unknown_node_label_warns() {
// MATCH (x:Unknown)
let node = NodePattern::new(Some("x".to_string())).with_label("Unknown");
let query = CypherQuery {
reading_clauses: vec![ReadingClause::Match(MatchClause {
patterns: vec![GraphPattern::Node(node)],
})],
post_with_reading_clauses: vec![],
post_with_where_clause: None,
where_clause: None,
with_clause: None,
return_clause: ReturnClause {
distinct: false,