hyperQL 0.1.0

Query language for hyperspatial graph databases with temporal and spatial semantics
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
use crate::ast::*;
use crate::error::*;
use serde::{Deserialize, Serialize};

// Re-export JoinType from AST for use in ExecutionPlan
pub use crate::ast::JoinType;

mod expression;
mod select;
mod statement;
mod traverse;
mod metadata;

use select::SelectCompiler;
use statement::StatementCompiler;
use metadata::{MetadataGenerator, CostEstimator};

pub use metadata::{QueryMetadata, ExecutionCost};

/// Geometric operation types - plans for Hyperspatial to execute
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum GeometricOpType {
    /// Hyperbolic distance calculation
    HyperbolicDistance,
    /// Geodesic distance calculation
    GeodesicDistance,
    /// Within radius check
    WithinRadius,
    /// Near positions query
    NearPositions,
    /// Containment testing
    Contains,
    /// Intersection operations
    Intersects,
}

/// Vector operation types - plans for Hyperspatial to execute
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum VectorOpType {
    /// Cosine similarity calculation
    CosineSimilarity,
    /// Euclidean distance calculation
    EuclideanDistance,
    /// Dot product calculation
    DotProduct,
    /// Vector normalization
    Normalize,
    /// K-nearest neighbors query
    KNN,
    /// Vector similarity search
    SimilaritySearch,
}

/// Stream operation types - plans for Hyperspatial to execute
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum StreamOpType {
    /// Create stream
    CreateStream,
    /// Produce to stream
    ProduceStream,
    /// Consume from stream
    ConsumeStream,
    /// Tumbling window
    TumblingWindow,
    /// Sliding window
    SlidingWindow,
    /// Stream join
    StreamJoin,
}

/// Time series operation types - plans for Hyperspatial to execute
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TimeSeriesOpType {
    /// Time bucket aggregation
    TimeBucket,
    /// Time difference calculation
    TimeDiff,
    /// Extract time component
    ExtractTime,
    /// Moving average
    MovingAverage,
    /// Exponential smoothing
    ExponentialSmoothing,
    /// Lag function
    Lag,
    /// Lead function
    Lead,
}

/// Graph operation types - plans for Hyperspatial to execute
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum GraphOpType {
    /// Shortest path calculation
    ShortestPath,
    /// Page rank calculation
    PageRank,
    /// Community detection
    CommunityDetection,
    /// Graph traversal
    GraphTraversal,
    /// Connected components
    ConnectedComponents,
    /// Centrality measures
    Centrality,
}

pub struct Compiler {
    select_compiler: SelectCompiler,
    statement_compiler: StatementCompiler,
    metadata_generator: MetadataGenerator,
    cost_estimator: CostEstimator,
}

/// Compiled query plan
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompiledQuery {
    /// Execution plan
    pub plan: ExecutionPlan,
    /// Query metadata
    pub metadata: QueryMetadata,
    /// Estimated execution cost
    pub estimated_cost: ExecutionCost,
}

/// Execution plan structure - represents operations to be executed by Hyperspatial
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ExecutionPlan {
    /// Sequential scan of entities
    Scan {
        table: String,
        entity_type: String,
        alias: Option<String>,
        filter: Option<CompiledExpression>,
        projection: Vec<CompiledProjection>,
        limit: Option<u64>,
    },
    /// Filtered scan with WHERE clause
    Filter {
        input: Box<ExecutionPlan>,
        predicate: CompiledExpression,
    },
    /// Projection of columns
    Project {
        input: Box<ExecutionPlan>,
        expressions: Vec<CompiledProjection>,
        distinct: bool,
    },
    /// Group by aggregation
    GroupBy {
        input: Box<ExecutionPlan>,
        group_expressions: Vec<CompiledExpression>,
        aggregate_expressions: Vec<CompiledProjection>,
    },
    /// Having filter for grouped results
    Having {
        input: Box<ExecutionPlan>,
        predicate: CompiledExpression,
    },
    /// Sort operation
    Sort {
        input: Box<ExecutionPlan>,
        sort_keys: Vec<CompiledSortKey>,
    },
    /// Limit operation
    Limit {
        input: Box<ExecutionPlan>,
        count: u64,
        offset: Option<u64>,
    },
    /// INSERT operation
    Insert {
        table: String,
        columns: Vec<String>,
        values: Vec<Vec<CompiledExpression>>,
    },
    /// UPDATE operation
    Update {
        table: String,
        assignments: Vec<CompiledAssignment>,
        filter: Option<CompiledExpression>,
    },
    /// DELETE operation
    Delete {
        table: String,
        filter: Option<CompiledExpression>,
    },
    /// TRAVERSE operation for graph pattern matching
    Traverse {
        patterns: Vec<CompiledTraversePattern>,
    },
    /// JOIN operation for combining tables
    Join {
        left: Box<ExecutionPlan>,
        right: Box<ExecutionPlan>,
        join_type: JoinType,
        on_condition: CompiledExpression,
    },
    /// Geometric operation plan
    GeometricOperation {
        op_type: GeometricOpType,
        params: std::collections::HashMap<String, CompiledExpression>,
        input: Option<Box<ExecutionPlan>>,
    },
    /// Vector operation plan
    VectorOperation {
        op_type: VectorOpType,
        params: std::collections::HashMap<String, CompiledExpression>,
        input: Option<Box<ExecutionPlan>>,
    },
    /// Stream operation plan
    StreamOperation {
        op_type: StreamOpType,
        params: std::collections::HashMap<String, CompiledExpression>,
        input: Option<Box<ExecutionPlan>>,
    },
    /// Time series operation plan
    TimeSeriesOperation {
        op_type: TimeSeriesOpType,
        params: std::collections::HashMap<String, CompiledExpression>,
        input: Option<Box<ExecutionPlan>>,
    },
    /// Graph operation plan
    GraphOperation {
        op_type: GraphOpType,
        params: std::collections::HashMap<String, CompiledExpression>,
        input: Option<Box<ExecutionPlan>>,
    },
    /// Schema DDL operation plan
    Schema {
        operation: crate::ast::schema::SchemaOperation,
    },
}

/// Compiled expression
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CompiledExpression {
    /// Literal value
    Literal(Value),
    /// Column reference
    Column {
        table: Option<String>,
        name: String,
        value_type: ValueType,
    },
    /// Binary operation
    Binary {
        left: Box<CompiledExpression>,
        op: BinaryOperator,
        right: Box<CompiledExpression>,
        result_type: ValueType,
    },
    /// Unary operation
    Unary {
        op: UnaryOperator,
        expr: Box<CompiledExpression>,
        result_type: ValueType,
    },
    /// Function call
    Function {
        name: String,
        args: Vec<CompiledExpression>,
        result_type: ValueType,
    },
}

/// Compiled projection item
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompiledProjection {
    pub expression: CompiledExpression,
    pub alias: Option<String>,
    pub output_name: String,
}

/// Compiled sort key
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompiledSortKey {
    pub expression: CompiledExpression,
    pub direction: OrderDirection,
}

/// Compiled assignment for UPDATE statements
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompiledAssignment {
    pub column: String,
    pub value: CompiledExpression,
}

/// Compiled traverse pattern for graph operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompiledTraversePattern {
    pub start_node: CompiledNodePattern,
    pub relationship: CompiledRelationshipPattern,
    pub end_node: CompiledNodePattern,
}

/// Compiled node pattern
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompiledNodePattern {
    pub variable: Option<String>,
    pub label: Option<String>,
    pub properties: Option<CompiledExpression>,
}

/// Compiled relationship pattern
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompiledRelationshipPattern {
    pub variable: Option<String>,
    pub rel_type: Option<String>,
    pub direction: crate::ast::RelationshipDirection,
    pub variable_length: Option<crate::ast::VariableLength>,
    pub optional: bool,
    pub properties: Option<CompiledExpression>,
}

/// Value types in the type system
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ValueType {
    Null,
    Bool,
    Int,
    Float,
    String,
    EntityId,
    Position,
    Distance,
    Vector,
    List(Box<ValueType>),
    Map(Box<ValueType>),
    Timestamp,
    Duration,
}



impl Compiler {
    pub fn new() -> Self {
        Self {
            select_compiler: SelectCompiler::new(),
            statement_compiler: StatementCompiler::new(),
            metadata_generator: MetadataGenerator::new(),
            cost_estimator: CostEstimator::new(),
        }
    }

    pub fn compile(&self, statement: Statement) -> Result<CompiledQuery> {
        let plan = match &statement {
            Statement::Select(select) => self.select_compiler.compile_select(select.clone())?,
            Statement::Insert(insert) => {
                let plan = self.statement_compiler.compile_insert(insert.clone())?;
                let metadata = QueryMetadata {
                    tables_accessed: vec![insert.table.clone()],
                    columns_accessed: vec![],
                    functions_used: vec![],
                    requires_spatial_index: false,
                    requires_vector_index: false,
                };
                let estimated_cost = ExecutionCost {
                    estimated_rows: 1,
                    estimated_cpu_cost: 0.5,
                    estimated_memory_mb: 1.0,
                    estimated_io_ops: 1,
                };
                return Ok(CompiledQuery {
                    plan,
                    metadata,
                    estimated_cost,
                });
            },
            Statement::Update(update) => {
                let plan = self.statement_compiler.compile_update(update.clone())?;
                let metadata = QueryMetadata {
                    tables_accessed: vec![update.table.clone()],
                    columns_accessed: vec![],
                    functions_used: vec![],
                    requires_spatial_index: false,
                    requires_vector_index: false,
                };
                let estimated_cost = ExecutionCost {
                    estimated_rows: 100,
                    estimated_cpu_cost: 2.0,
                    estimated_memory_mb: 5.0,
                    estimated_io_ops: 50,
                };
                return Ok(CompiledQuery {
                    plan,
                    metadata,
                    estimated_cost,
                });
            },
            Statement::Delete(delete) => {
                let plan = self.statement_compiler.compile_delete(delete.clone())?;
                let metadata = QueryMetadata {
                    tables_accessed: vec![delete.table.clone()],
                    columns_accessed: vec![],
                    functions_used: vec![],
                    requires_spatial_index: false,
                    requires_vector_index: false,
                };
                let estimated_cost = ExecutionCost {
                    estimated_rows: 100,
                    estimated_cpu_cost: 1.5,
                    estimated_memory_mb: 3.0,
                    estimated_io_ops: 30,
                };
                return Ok(CompiledQuery {
                    plan,
                    metadata,
                    estimated_cost,
                });
            },
            Statement::Schema(schema_op) => {
                // Schema compilation is straightforward - just wrap in execution plan
                // The actual schema validation and creation happens in the executor
                let plan = ExecutionPlan::Schema {
                    operation: schema_op.clone(),
                };
                let metadata = QueryMetadata {
                    tables_accessed: vec![],
                    columns_accessed: vec![],
                    functions_used: vec![],
                    requires_spatial_index: false,
                    requires_vector_index: false,
                };
                let estimated_cost = ExecutionCost {
                    estimated_rows: 0,
                    estimated_cpu_cost: 0.1,
                    estimated_memory_mb: 0.5,
                    estimated_io_ops: 1,
                };
                return Ok(CompiledQuery {
                    plan,
                    metadata,
                    estimated_cost,
                });
            },
            Statement::Stream(_stream_op) => {
                // TODO: Implement stream DDL compilation
                // Stream statements need to be compiled into stream engine operations
                // for creating streams, producing events, and consuming from streams
                return Err(HyperQLError::SemanticError {
                    message: "Stream DDL compilation not yet implemented".to_string(),
                    context: vec!["Stream operations will be supported in a future release".to_string()],
                });
            },
        };

        let metadata = self.metadata_generator.generate_metadata(&plan);
        let estimated_cost = self.cost_estimator.estimate_cost(&plan);

        Ok(CompiledQuery {
            plan,
            metadata,
            estimated_cost,
        })
    }








    /// Compile a statement with query optimization
    pub fn compile_with_optimizer(
        &self,
        statement: Statement,
        optimizer: &crate::optimizer::QueryOptimizer
    ) -> Result<CompiledQuery> {
        let compiled = self.compile(statement)?;

        // Apply optimizations to the execution plan
        let optimized_plan = optimizer.optimize(compiled.plan)?;

        // Recalculate metadata and cost estimates for the optimized plan
        let optimized_metadata = self.metadata_generator.generate_metadata(&optimized_plan);
        let optimized_cost = self.cost_estimator.estimate_cost(&optimized_plan);

        Ok(CompiledQuery {
            plan: optimized_plan,
            metadata: optimized_metadata,
            estimated_cost: optimized_cost,
        })
    }

    /// Compile with optimizer and return optimization statistics
    pub fn compile_with_optimizer_stats(
        &self,
        statement: Statement,
        optimizer: &crate::optimizer::QueryOptimizer
    ) -> Result<(CompiledQuery, crate::optimizer::OptimizationStats)> {
        let compiled = self.compile(statement)?;

        // Apply optimizations with statistics tracking
        let (optimized_plan, stats) = optimizer.optimize_with_stats(compiled.plan)?;

        // Recalculate metadata and cost estimates for the optimized plan
        let optimized_metadata = self.metadata_generator.generate_metadata(&optimized_plan);
        let optimized_cost = self.cost_estimator.estimate_cost(&optimized_plan);

        let optimized_query = CompiledQuery {
            plan: optimized_plan,
            metadata: optimized_metadata,
            estimated_cost: optimized_cost,
        };

        Ok((optimized_query, stats))
    }

    /// Compile a statement with validation
    pub fn compile_with_validation(
        &self,
        statement: Statement,
        validator: &mut crate::validator::QueryValidator,
    ) -> Result<CompiledQuery> {
        // Validate first
        let validation_result = validator.validate(&statement)?;

        if !validation_result.valid {
            return Err(HyperQLError::ValidationError {
                message: format!("Query validation failed with {} errors", validation_result.errors.len()),
                field: None,
            });
        }

        // If validation passes, compile normally
        self.compile(statement)
    }

    /// Compile with both validation and optimization
    pub fn compile_with_validation_and_optimization(
        &self,
        statement: Statement,
        validator: &mut crate::validator::QueryValidator,
        optimizer: &crate::optimizer::QueryOptimizer,
    ) -> Result<(CompiledQuery, crate::validator::ValidationResult, crate::optimizer::OptimizationStats)> {
        // Validate first
        let validation_result = validator.validate(&statement)?;

        if !validation_result.valid {
            return Err(HyperQLError::ValidationError {
                message: format!("Query validation failed with {} errors", validation_result.errors.len()),
                field: None,
            });
        }

        // Compile and optimize
        let (compiled_query, optimization_stats) = self.compile_with_optimizer_stats(statement, optimizer)?;

        Ok((compiled_query, validation_result, optimization_stats))
    }
}


impl Default for Compiler {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::parse_statement;

    #[test]
    fn test_compile_simple_select() {
        let compiler = Compiler::new();
        let query = "SELECT * FROM test.Entity";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        match compiled.plan {
            ExecutionPlan::Project { input, distinct, .. } => {
                assert!(!distinct, "DISTINCT should be false by default");
                match *input {
                    ExecutionPlan::Scan { table, entity_type, .. } => {
                        assert_eq!(table, "test");
                        assert_eq!(entity_type, "Entity");
                    }
                    _ => panic!("Expected scan as input to project"),
                }
            }
            _ => panic!("Expected project plan"),
        }
    }

    #[test]
    fn test_compile_select_with_where() {
        let compiler = Compiler::new();
        let query = "SELECT name FROM test.Entity WHERE name = 'Alice'";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        // Should have Project -> Filter -> Scan structure
        match compiled.plan {
            ExecutionPlan::Project { input, .. } => {
                match *input {
                    ExecutionPlan::Filter { input, .. } => {
                        match *input {
                            ExecutionPlan::Scan { table, entity_type, .. } => {
                                assert_eq!(table, "test");
                                assert_eq!(entity_type, "Entity");
                            }
                            _ => panic!("Expected scan as input to filter"),
                        }
                    }
                    _ => panic!("Expected filter as input to project"),
                }
            }
            _ => panic!("Expected project plan"),
        }
    }

    #[test]
    fn test_compile_select_with_order_by_limit() {
        let compiler = Compiler::new();
        let query = "SELECT * FROM test.Entity ORDER BY name LIMIT 10";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        // Should have Limit -> Sort -> Project -> Scan structure
        match compiled.plan {
            ExecutionPlan::Limit { input, count, .. } => {
                assert_eq!(count, 10);
                match *input {
                    ExecutionPlan::Sort { input, .. } => {
                        match *input {
                            ExecutionPlan::Project { input, .. } => {
                                match *input {
                                    ExecutionPlan::Scan { .. } => {
                                        // Success
                                    }
                                    _ => panic!("Expected scan"),
                                }
                            }
                            _ => panic!("Expected project"),
                        }
                    }
                    _ => panic!("Expected sort"),
                }
            }
            _ => panic!("Expected limit plan"),
        }
    }

    #[test]
    fn test_compile_insert_statement() {
        let compiler = Compiler::new();
        let query = "INSERT INTO users (name, age) VALUES ('Alice', 30)";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        match compiled.plan {
            ExecutionPlan::Insert { table, columns, values } => {
                assert_eq!(table, "users");
                assert_eq!(columns, vec!["name", "age"]);
                assert_eq!(values.len(), 1);
                assert_eq!(values[0].len(), 2);
            }
            _ => panic!("Expected INSERT plan"),
        }
    }

    #[test]
    fn test_compile_update_statement() {
        let compiler = Compiler::new();
        let query = "UPDATE users SET age = 31 WHERE name = 'Alice'";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        match compiled.plan {
            ExecutionPlan::Update { table, assignments, filter } => {
                assert_eq!(table, "users");
                assert_eq!(assignments.len(), 1);
                assert_eq!(assignments[0].column, "age");
                assert!(filter.is_some());
            }
            _ => panic!("Expected UPDATE plan"),
        }
    }

    #[test]
    fn test_compile_delete_statement() {
        let compiler = Compiler::new();
        let query = "DELETE FROM users WHERE age < 18";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        match compiled.plan {
            ExecutionPlan::Delete { table, filter } => {
                assert_eq!(table, "users");
                assert!(filter.is_some());
            }
            _ => panic!("Expected DELETE plan"),
        }
    }

    #[test]
    fn test_compile_group_by_statement() {
        let compiler = Compiler::new();
        let query = "SELECT category, COUNT(*) FROM shop.Product GROUP BY category";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        match compiled.plan {
            ExecutionPlan::GroupBy { group_expressions, aggregate_expressions, .. } => {
                assert_eq!(group_expressions.len(), 1);
                assert_eq!(aggregate_expressions.len(), 2); // category and COUNT(*)
            }
            _ => panic!("Expected GROUP BY plan"),
        }
    }

    #[test]
    fn test_compile_having_statement() {
        let compiler = Compiler::new();
        let query = "SELECT category, COUNT(*) FROM shop.Product GROUP BY category HAVING COUNT(*) > 5";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        // Should have Having -> GroupBy -> Scan structure
        match compiled.plan {
            ExecutionPlan::Having { input, .. } => {
                match *input {
                    ExecutionPlan::GroupBy { .. } => {
                        // Success - correct structure
                    }
                    _ => panic!("Expected GROUP BY as input to HAVING"),
                }
            }
            _ => panic!("Expected HAVING plan"),
        }
    }

    #[test]
    fn test_compile_traverse_statement() {
        let compiler = Compiler::new();
        let query = "SELECT * FROM social.User TRAVERSE (a:User)-[r:follows]->(b:User)";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        // Check for traverse plan (as input to project)
        match &compiled.plan {
            ExecutionPlan::Project { input, .. } => {
                match input.as_ref() {
                    ExecutionPlan::Traverse { patterns } => {
                        assert_eq!(patterns.len(), 1);
                        let pattern = &patterns[0];
                        assert_eq!(pattern.start_node.variable, Some("a".to_string()));
                        assert_eq!(pattern.start_node.label, Some("User".to_string()));
                        assert_eq!(pattern.end_node.variable, Some("b".to_string()));
                        assert_eq!(pattern.end_node.label, Some("User".to_string()));
                        assert_eq!(pattern.relationship.variable, Some("r".to_string()));
                        assert_eq!(pattern.relationship.rel_type, Some("follows".to_string()));
                    }
                    other => panic!("Expected TRAVERSE as input to project, got: {:?}", other),
                }
            }
            other => panic!("Expected PROJECT plan with TRAVERSE input, got: {:?}", other),
        }
    }

    #[test]
    fn test_compile_variable_length_traverse() {
        let compiler = Compiler::new();
        let query = "SELECT * FROM social.User TRAVERSE (a)-[follows*1..3]->(b)";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        match &compiled.plan {
            ExecutionPlan::Project { input, .. } => {
                match input.as_ref() {
                    ExecutionPlan::Traverse { patterns } => {
                        let pattern = &patterns[0];
                        let var_len = pattern.relationship.variable_length.as_ref().unwrap();
                        assert_eq!(var_len.min_hops, Some(1));
                        assert_eq!(var_len.max_hops, Some(3));
                    }
                    _ => panic!("Expected TRAVERSE as input"),
                }
            }
            _ => panic!("Expected PROJECT plan with TRAVERSE input"),
        }
    }

    #[test]
    fn test_compile_optional_relationship() {
        let compiler = Compiler::new();
        let query = "SELECT * FROM social.User TRAVERSE (a)-[follows?]->(b)";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        match &compiled.plan {
            ExecutionPlan::Project { input, .. } => {
                match input.as_ref() {
                    ExecutionPlan::Traverse { patterns } => {
                        let pattern = &patterns[0];
                        assert!(pattern.relationship.optional);
                    }
                    _ => panic!("Expected TRAVERSE as input"),
                }
            }
            _ => panic!("Expected PROJECT plan with TRAVERSE input"),
        }
    }

    #[test]
    fn test_compile_multiple_traverse_patterns() {
        let compiler = Compiler::new();
        let query = "SELECT * FROM social.User TRAVERSE (a)-[follows]->(b), (b)-[likes]->(c)";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        match &compiled.plan {
            ExecutionPlan::Project { input, .. } => {
                match input.as_ref() {
                    ExecutionPlan::Traverse { patterns } => {
                        assert_eq!(patterns.len(), 2);
                        // Check first pattern
                        assert_eq!(patterns[0].relationship.rel_type, Some("follows".to_string()));
                        // Check second pattern
                        assert_eq!(patterns[1].relationship.rel_type, Some("likes".to_string()));
                    }
                    _ => panic!("Expected TRAVERSE as input"),
                }
            }
            _ => panic!("Expected PROJECT plan with TRAVERSE input"),
        }
    }

    #[test]
    fn test_compile_vector_similarity_in_where() {
        let compiler = Compiler::new();
        // Use column reference instead of array literal (parser limitation)
        let query = r#"SELECT * FROM docs.Document
                       WHERE SIMILARITY(embedding, query_vec, 'cosine') > 0.8"#;
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        // Should generate VectorOperation plan (not Filter plan)
        match &compiled.plan {
            ExecutionPlan::Project { input, .. } => {
                match input.as_ref() {
                    ExecutionPlan::VectorOperation { op_type, params, input } => {
                        assert!(matches!(op_type, VectorOpType::CosineSimilarity));
                        assert!(params.contains_key("vector_name"));
                        assert!(params.contains_key("reference"));
                        assert!(input.is_some());
                    }
                    other => panic!("Expected VectorOperation as input to project, got: {:?}", other),
                }
            }
            _ => panic!("Expected PROJECT plan with VectorOperation input"),
        }
    }

    #[test]
    fn test_compile_knn_query_with_order_by() {
        let compiler = Compiler::new();
        // Use SIMILARITY with column reference for ORDER BY
        let query = r#"SELECT * FROM docs.Document
                       ORDER BY SIMILARITY(embedding, query_vec, 'euclidean')
                       LIMIT 10"#;
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        // Should generate VectorOperation with KNN type
        match &compiled.plan {
            ExecutionPlan::Limit { input, count, .. } => {
                assert_eq!(*count, 10);
                match input.as_ref() {
                    ExecutionPlan::VectorOperation { op_type, params, .. } => {
                        assert!(matches!(op_type, VectorOpType::KNN));
                        assert!(params.contains_key("k"));
                        assert!(params.contains_key("vector_name"));
                        assert!(params.contains_key("reference"));
                    }
                    other => panic!("Expected VectorOperation for k-NN, got: {:?}", other),
                }
            }
            _ => panic!("Expected LIMIT plan with VectorOperation input"),
        }
    }

    #[test]
    fn test_compile_cosine_similarity_function() {
        let compiler = Compiler::new();
        // SIMILARITY function with cosine metric
        let query = r#"SELECT * FROM docs.Document
                       WHERE SIMILARITY(text_embedding, query_vec, 'cosine') > 0.7"#;
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        // Verify VectorOperation is generated
        match &compiled.plan {
            ExecutionPlan::Project { input, .. } => {
                match input.as_ref() {
                    ExecutionPlan::VectorOperation { op_type, params, .. } => {
                        assert!(matches!(op_type, VectorOpType::CosineSimilarity));

                        // Check key parameters are captured
                        assert!(params.contains_key("vector_name"), "Missing vector_name parameter");
                        assert!(params.contains_key("reference"), "Missing reference parameter");
                        assert!(params.contains_key("metric"), "Missing metric parameter");
                    }
                    other => panic!("Expected VectorOperation, got: {:?}", other),
                }
            }
            other => panic!("Expected PROJECT plan, got: {:?}", other),
        }
    }

    #[test]
    fn test_compile_dot_product_function() {
        let compiler = Compiler::new();
        // SIMILARITY with dotproduct metric
        let query = r#"SELECT * FROM docs.Document
                       WHERE SIMILARITY(feature_vec, target_vec, 'dotproduct') > 0.5"#;
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        match &compiled.plan {
            ExecutionPlan::Project { input, .. } => {
                match input.as_ref() {
                    ExecutionPlan::VectorOperation { op_type, .. } => {
                        assert!(matches!(op_type, VectorOpType::DotProduct));
                    }
                    other => panic!("Expected VectorOperation, got: {:?}", other),
                }
            }
            other => panic!("Expected PROJECT plan, got: {:?}", other),
        }
    }

    #[test]
    fn test_compile_euclidean_distance_function() {
        let compiler = Compiler::new();
        // DISTANCE/SIMILARITY with euclidean metric
        let query = r#"SELECT * FROM docs.Document
                       WHERE DISTANCE(embedding, query_vec, 'euclidean') < 2.0"#;
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        match &compiled.plan {
            ExecutionPlan::Project { input, .. } => {
                match input.as_ref() {
                    ExecutionPlan::VectorOperation { op_type, .. } => {
                        assert!(matches!(op_type, VectorOpType::EuclideanDistance));
                    }
                    other => panic!("Expected VectorOperation, got: {:?}", other),
                }
            }
            other => panic!("Expected PROJECT plan, got: {:?}", other),
        }
    }

    #[test]
    fn test_regular_where_clause_not_vector() {
        let compiler = Compiler::new();
        let query = "SELECT * FROM docs.Document WHERE title = 'test'";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        // Should generate regular Filter plan (not VectorOperation)
        match &compiled.plan {
            ExecutionPlan::Project { input, .. } => {
                match input.as_ref() {
                    ExecutionPlan::Filter { .. } => {
                        // Correct - regular filter for non-vector operations
                    }
                    ExecutionPlan::VectorOperation { .. } => {
                        panic!("Should not generate VectorOperation for non-vector WHERE clause");
                    }
                    other => panic!("Expected Filter, got: {:?}", other),
                }
            }
            other => panic!("Expected PROJECT plan, got: {:?}", other),
        }
    }

    #[test]
    fn test_regular_order_by_not_vector() {
        let compiler = Compiler::new();
        let query = "SELECT * FROM docs.Document ORDER BY created_at DESC LIMIT 10";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        // Should generate regular Sort plan (not VectorOperation)
        match &compiled.plan {
            ExecutionPlan::Limit { input, .. } => {
                match input.as_ref() {
                    ExecutionPlan::Sort { .. } => {
                        // Correct - regular sort for non-vector ORDER BY
                    }
                    ExecutionPlan::VectorOperation { .. } => {
                        panic!("Should not generate VectorOperation for non-vector ORDER BY");
                    }
                    other => panic!("Expected Sort, got: {:?}", other),
                }
            }
            other => panic!("Expected LIMIT plan, got: {:?}", other),
        }
    }

    #[test]
    fn test_compile_geometric_near_query() {
        let compiler = Compiler::new();
        let query = "SELECT * FROM docs.Document WHERE position NEAR origin WITHIN 2.0";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        // Should generate GeometricOperation plan (not Filter plan)
        match &compiled.plan {
            ExecutionPlan::Project { input, .. } => {
                match input.as_ref() {
                    ExecutionPlan::GeometricOperation { op_type, params, input } => {
                        // Parser creates "near" function which maps to NearPositions
                        assert!(matches!(op_type, GeometricOpType::NearPositions));
                        assert!(params.contains_key("reference"));
                        assert!(params.contains_key("radius"));
                        assert!(input.is_some());
                    }
                    other => panic!("Expected GeometricOperation as input to project, got: {:?}", other),
                }
            }
            _ => panic!("Expected PROJECT plan with GeometricOperation input"),
        }
    }

    #[test]
    fn test_compile_geometric_distance_query() {
        let compiler = Compiler::new();
        // Use ORDER BY with DISTANCE which the parser supports
        let query = "SELECT * FROM entities.Position ORDER BY position DISTANCE FROM origin LIMIT 10";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        // Should generate GeometricOperation plan for distance-based ordering
        // Note: This becomes a k-NN pattern which might use VectorOperation or Sort
        // Let's check what plan is generated
        match &compiled.plan {
            ExecutionPlan::Limit { input, .. } => {
                // Could be Sort or GeometricOperation depending on optimization
                match input.as_ref() {
                    ExecutionPlan::Sort { .. } => {
                        // OK - distance ordering compiled to sort
                    }
                    ExecutionPlan::GeometricOperation { op_type, params, .. } => {
                        assert!(matches!(op_type, GeometricOpType::HyperbolicDistance));
                        assert!(params.contains_key("entity1"));
                        assert!(params.contains_key("entity2"));
                    }
                    other => panic!("Expected Sort or GeometricOperation, got: {:?}", other),
                }
            }
            other => panic!("Expected LIMIT plan, got: {:?}", other),
        }
    }

    #[test]
    fn test_regular_where_clause_not_geometric() {
        let compiler = Compiler::new();
        let query = "SELECT * FROM docs.Document WHERE title = 'test'";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        // Should generate regular Filter plan (not GeometricOperation)
        match &compiled.plan {
            ExecutionPlan::Project { input, .. } => {
                match input.as_ref() {
                    ExecutionPlan::Filter { .. } => {
                        // Correct - regular filter for non-geometric WHERE clause
                    }
                    ExecutionPlan::GeometricOperation { .. } => {
                        panic!("Should not generate GeometricOperation for non-geometric WHERE clause");
                    }
                    other => panic!("Expected Filter, got: {:?}", other),
                }
            }
            other => panic!("Expected PROJECT plan, got: {:?}", other),
        }
    }

    #[test]
    fn test_compile_create_schema() {
        let compiler = Compiler::new();
        let query = "CREATE SCHEMA documents (title STRING REQUIRED, content STRING)";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        // Verify Schema execution plan
        match &compiled.plan {
            ExecutionPlan::Schema { operation } => {
                use crate::ast::schema::SchemaOperation;
                match operation {
                    SchemaOperation::Create(create_op) => {
                        assert_eq!(create_op.collection_name, "documents");
                        assert_eq!(create_op.fields.len(), 2);
                    }
                    _ => panic!("Expected CREATE schema operation"),
                }
            }
            _ => panic!("Expected Schema execution plan"),
        }

        // Verify metadata - Schema operations have empty tables_accessed in initial metadata
        // (the actual collection name is in the operation itself)
        assert_eq!(compiled.metadata.tables_accessed.len(), 0);
        assert_eq!(compiled.estimated_cost.estimated_rows, 0);
        assert_eq!(compiled.estimated_cost.estimated_cpu_cost, 0.1);
    }

    #[test]
    fn test_compile_alter_schema() {
        let compiler = Compiler::new();
        let query = "ALTER SCHEMA documents ADD FIELD author STRING";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        match &compiled.plan {
            ExecutionPlan::Schema { operation } => {
                use crate::ast::schema::SchemaOperation;
                match operation {
                    SchemaOperation::Alter(alter_op) => {
                        assert_eq!(alter_op.collection_name, "documents");
                    }
                    _ => panic!("Expected ALTER schema operation"),
                }
            }
            _ => panic!("Expected Schema execution plan"),
        }

        // Schema operations have empty tables_accessed in initial metadata
        assert_eq!(compiled.metadata.tables_accessed.len(), 0);
    }

    #[test]
    fn test_compile_drop_schema() {
        let compiler = Compiler::new();
        let query = "DROP SCHEMA documents";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        match &compiled.plan {
            ExecutionPlan::Schema { operation } => {
                use crate::ast::schema::SchemaOperation;
                match operation {
                    SchemaOperation::Drop(drop_op) => {
                        assert_eq!(drop_op.collection_name, "documents");
                    }
                    _ => panic!("Expected DROP schema operation"),
                }
            }
            _ => panic!("Expected Schema execution plan"),
        }
    }

    #[test]
    fn test_compile_describe_schema() {
        let compiler = Compiler::new();
        let query = "DESCRIBE SCHEMA documents";
        let statement = parse_statement(query).unwrap();

        let compiled = compiler.compile(statement).unwrap();

        match &compiled.plan {
            ExecutionPlan::Schema { operation } => {
                use crate::ast::schema::SchemaOperation;
                match operation {
                    SchemaOperation::Describe(describe_op) => {
                        assert_eq!(describe_op.collection_name, "documents");
                        assert!(!describe_op.detailed);
                    }
                    _ => panic!("Expected DESCRIBE schema operation"),
                }
            }
            _ => panic!("Expected Schema execution plan"),
        }
    }
}