1pub mod error;
87pub mod error_context;
88pub mod type_checker;
89pub mod types;
90
91pub mod ast;
93pub mod cascade;
94pub mod compiler;
95pub mod context;
96pub mod executor;
97pub mod optimizer;
98pub mod parser;
99pub mod validator;
100
101pub mod ir;
103pub mod runtime;
104
105pub mod builder;
107pub mod documentation;
108pub mod utils;
109
110pub use error::{HyperQLError, Result};
112pub use types::*;
113
114pub use ast::{Expression, SelectStatement, Statement};
116pub use compiler::{CompiledQuery, Compiler};
117pub use executor::{Executor, MemoryDataSource};
118pub use type_checker::{TypeChecker, TypeInfo, TypeContext};
119pub use optimizer::{QueryOptimizer, OptimizerConfig, OptimizationStats};
120pub use validator::{QueryValidator, ValidationConfig, ValidationResult, ValidationError, ValidationWarning};
121
122pub use builder::HyperQLBuilder;
124pub use documentation::{HyperQLExamples, HyperQLSyntax};
125pub use utils::query_utils;
126
127#[cfg(test)]
128mod integration_tests {
129 use super::*;
130 use std::collections::HashMap;
131
132 #[test]
133 fn test_end_to_end_select_where_functionality() {
134 let mut data_source = MemoryDataSource::new();
138
139 let mut alice = Entity {
141 id: EntityId("alice_001".to_string()),
142 properties: HashMap::new(),
143 position: Some(Position3D {
144 x: 1.0,
145 y: 2.0,
146 z: 3.0,
147 }),
148 embedding: None,
149 };
150 alice.properties.insert(
151 PropertyName("name".to_string()),
152 Value::String("Alice".to_string()),
153 );
154 alice
155 .properties
156 .insert(PropertyName("age".to_string()), Value::Int(30));
157 alice
158 .properties
159 .insert(PropertyName("active".to_string()), Value::Bool(true));
160
161 let mut bob = Entity {
163 id: EntityId("bob_002".to_string()),
164 properties: HashMap::new(),
165 position: Some(Position3D {
166 x: 4.0,
167 y: 5.0,
168 z: 6.0,
169 }),
170 embedding: None,
171 };
172 bob.properties.insert(
173 PropertyName("name".to_string()),
174 Value::String("Bob".to_string()),
175 );
176 bob.properties
177 .insert(PropertyName("age".to_string()), Value::Int(25));
178 bob.properties
179 .insert(PropertyName("active".to_string()), Value::Bool(false));
180
181 let mut charlie = Entity {
183 id: EntityId("charlie_003".to_string()),
184 properties: HashMap::new(),
185 position: None,
186 embedding: None,
187 };
188 charlie.properties.insert(
189 PropertyName("name".to_string()),
190 Value::String("Charlie".to_string()),
191 );
192 charlie
193 .properties
194 .insert(PropertyName("age".to_string()), Value::Int(35));
195
196 data_source.add_entities("entities", vec![alice, bob, charlie]);
197
198 let mut executor = Executor::new(Box::new(data_source));
200 let compiler = Compiler::new();
201
202 println!("Testing: SELECT * FROM entities WHERE name = 'Alice'");
204 let query1 = "SELECT * FROM entities WHERE name = 'Alice'";
205 let statement1 = parse_statement(query1).expect("Query should parse");
206 let compiled1 = compiler.compile(statement1).expect("Query should compile");
207 let result1 = executor.execute(compiled1).expect("Query should execute");
208
209 assert_eq!(result1.rows.len(), 1, "Should return exactly one row");
210 assert_eq!(
211 result1.rows[0].columns.get("name"),
212 Some(&Value::String("Alice".to_string()))
213 );
214 assert_eq!(result1.rows[0].columns.get("age"), Some(&Value::Int(30)));
215 assert_eq!(
216 result1.rows[0].columns.get("active"),
217 Some(&Value::Bool(true))
218 );
219 println!("ā Successfully filtered by name = 'Alice'");
220
221 println!("\nTesting: SELECT name, age FROM entities WHERE age > 30");
223 let query2 = "SELECT name, age FROM entities WHERE age > 30";
224 let statement2 = parse_statement(query2).expect("Query should parse");
225 let compiled2 = compiler.compile(statement2).expect("Query should compile");
226 let result2 = executor.execute(compiled2).expect("Query should execute");
227
228 assert_eq!(result2.rows.len(), 1, "Should return exactly one row");
229 assert_eq!(
230 result2.rows[0].columns.get("name"),
231 Some(&Value::String("Charlie".to_string()))
232 );
233 assert_eq!(result2.rows[0].columns.get("age"), Some(&Value::Int(35)));
234 assert_eq!(
235 result2.rows[0].columns.len(),
236 2,
237 "Should only have name and age columns"
238 );
239 println!("ā Successfully projected specific columns and filtered by age > 30");
240
241 println!("\nTesting: SELECT * FROM entities ORDER BY age DESC LIMIT 2");
243 let query3 = "SELECT * FROM entities ORDER BY age DESC LIMIT 2";
244 let statement3 = parse_statement(query3).expect("Query should parse");
245 let compiled3 = compiler.compile(statement3).expect("Query should compile");
246 let result3 = executor.execute(compiled3).expect("Query should execute");
247
248 assert_eq!(result3.rows.len(), 2, "Should return exactly two rows");
249 assert_eq!(
251 result3.rows[0].columns.get("name"),
252 Some(&Value::String("Charlie".to_string()))
253 );
254 assert_eq!(
255 result3.rows[1].columns.get("name"),
256 Some(&Value::String("Alice".to_string()))
257 );
258 println!("ā Successfully ordered by age DESC and limited to 2 results");
259
260 println!("\nTesting: SELECT name FROM entities WHERE age > 20 AND age < 35");
262 let query4 = "SELECT name FROM entities WHERE age > 20 AND age < 35";
263 let statement4 = parse_statement(query4).expect("Query should parse");
264 let compiled4 = compiler.compile(statement4).expect("Query should compile");
265 let result4 = executor.execute(compiled4).expect("Query should execute");
266
267 assert_eq!(result4.rows.len(), 2, "Should return Alice and Bob");
268 let names: Vec<String> = result4
269 .rows
270 .iter()
271 .map(|row| match row.columns.get("name") {
272 Some(Value::String(name)) => name.clone(),
273 _ => "Unknown".to_string(),
274 })
275 .collect();
276 assert!(names.contains(&"Alice".to_string()));
277 assert!(names.contains(&"Bob".to_string()));
278 println!("ā Successfully used AND condition in WHERE clause");
279
280 println!("\nExecution Statistics:");
282 println!(
283 "- Entities scanned: {}",
284 result4.execution_stats.entities_scanned
285 );
286 println!(
287 "- Execution time: {}ms",
288 result4.execution_stats.execution_time_ms
289 );
290
291 println!(
292 "\nš All end-to-end tests passed! HyperQL basic SELECT WHERE functionality is working."
293 );
294 }
295
296 #[test]
297 fn test_type_checker_integration() {
298 use crate::ast::{BinaryOperator, ColumnRef, Literal};
299 use crate::type_checker::TypeChecker;
300
301 println!("Testing type checker integration...");
302
303 let mut type_checker = TypeChecker::new();
304
305 let expr = Expression::Binary {
307 left: Box::new(Expression::Literal(Literal::Int(42))),
308 op: BinaryOperator::Add,
309 right: Box::new(Expression::Literal(Literal::Float(std::f64::consts::PI))),
310 };
311
312 let result_type = type_checker
313 .check_expression_type(&expr)
314 .expect("Should type check successfully");
315 assert_eq!(
316 result_type,
317 TypeInfo::Float,
318 "Int + Float should result in Float"
319 );
320 println!("ā Basic arithmetic type promotion works");
321
322 let left = Expression::Literal(Literal::String("hello".to_string()));
324 let right = Expression::Literal(Literal::Int(42));
325
326 let result =
327 type_checker.check_operation_compatibility(&left, &BinaryOperator::Add, &right);
328 assert!(result.is_err(), "String + Int should be a type error");
329 println!("ā Type incompatibility detection works");
330
331 let sum_result = type_checker
333 .check_function_type("SUM", &[Expression::Literal(Literal::Int(100))])
334 .expect("SUM should work on integers");
335 assert_eq!(sum_result, TypeInfo::Integer);
336 println!("ā Function type checking works");
337
338 let where_expr = Expression::Binary {
340 left: Box::new(Expression::Column(ColumnRef {
341 table: None,
342 name: "age".to_string(),
343 })),
344 op: BinaryOperator::GreaterThan,
345 right: Box::new(Expression::Literal(Literal::Int(21))),
346 };
347
348 let result = type_checker.check_where_clause(&where_expr);
349 assert!(result.is_ok(), "Valid WHERE clause should pass");
350 println!("ā WHERE clause validation works");
351
352 println!("\nš Type checker integration tests passed!");
353 }
354
355 #[test]
356 fn test_query_plan_generation() {
357 use std::collections::HashMap;
358
359 println!("Testing query plan generation...");
360
361 let mut data_source = MemoryDataSource::new();
363
364 let mut alice = Entity {
366 id: EntityId("alice_001".to_string()),
367 properties: HashMap::new(),
368 position: Some(Position3D {
369 x: 1.0,
370 y: 2.0,
371 z: 3.0,
372 }),
373 embedding: None,
374 };
375 alice.properties.insert(
376 PropertyName("name".to_string()),
377 Value::String("Alice".to_string()),
378 );
379 alice
380 .properties
381 .insert(PropertyName("age".to_string()), Value::Int(30));
382
383 data_source.add_entity("entities", alice);
384
385 let mut executor = Executor::new(Box::new(data_source));
387 let compiler = Compiler::new();
388
389 println!("\nTesting: SELECT * FROM entities");
391 let query = "SELECT * FROM entities";
392 let statement = parse_statement(query).expect("Query should parse");
393 let compiled = compiler.compile(statement).expect("Query should compile");
394
395 match &compiled.plan {
397 crate::compiler::ExecutionPlan::Project { input, .. } => match input.as_ref() {
398 crate::compiler::ExecutionPlan::Scan { .. } => {
399 println!("ā Generated execution plan with Scan -> Project structure");
400 }
401 _ => panic!("Expected Scan as input to Project"),
402 },
403 _ => panic!("Expected Project plan"),
404 }
405
406 let result = executor.execute(compiled).expect("Plan should execute");
408 assert_eq!(result.rows.len(), 1);
409 println!("ā Plan execution returned {} rows", result.rows.len());
410
411 println!("\nTesting: Query metadata generation");
413 let query2 = "SELECT name, age FROM entities WHERE age > 25";
414 let statement2 = parse_statement(query2).expect("Query should parse");
415 let compiled2 = compiler.compile(statement2).expect("Query should compile");
416
417 assert!(
419 compiled2
420 .metadata
421 .tables_accessed
422 .contains(&"entities".to_string())
423 );
424 println!(
425 "ā Metadata captured accessed tables: {:?}",
426 compiled2.metadata.tables_accessed
427 );
428
429 assert!(compiled2.estimated_cost.estimated_rows > 0);
431 assert!(compiled2.estimated_cost.estimated_cpu_cost > 0.0);
432 println!(
433 "ā Cost estimation generated: {} estimated rows, {:.2} CPU cost",
434 compiled2.estimated_cost.estimated_rows, compiled2.estimated_cost.estimated_cpu_cost
435 );
436
437 println!(
438 "\nš All query plan generation tests passed! HyperQL is now a pure query language."
439 );
440 }
441
442 #[test]
443 fn test_comprehensive_type_validation() {
444 use crate::ast::{BinaryOperator, ColumnRef, Literal, VectorExpression};
445
446 println!("Testing comprehensive type validation across HyperQL features...");
447
448 let mut type_checker = TypeChecker::new();
449
450 let geo_expr = Expression::Geometric(crate::ast::geometric::GeometricExpression::Within {
452 target: Box::new(Expression::Column(ColumnRef {
453 table: None,
454 name: "position".to_string(),
455 })),
456 radius: 5.0,
457 reference: Box::new(Expression::Column(ColumnRef {
458 table: None,
459 name: "position".to_string(),
460 })),
461 });
462
463 let geo_type = type_checker
464 .check_expression_type(&geo_expr)
465 .expect("Geometric expression should type check");
466 assert_eq!(geo_type, TypeInfo::Bool, "WITHIN should return boolean");
467 println!("ā Geometric expression type checking works");
468
469 let vector_expr = Expression::Vector(VectorExpression::Similarity {
471 vector_name: "embeddings".to_string(),
472 reference: Box::new(Expression::Literal(Literal::String("query".to_string()))),
473 metric: crate::ast::vector::similarity::SimilarityMetric::Cosine,
474 threshold: Some(0.8),
475 vector_type: crate::ast::vector::similarity::VectorType::Dense { dimensions: 768 },
476 });
477
478 let vector_type = type_checker
479 .check_expression_type(&vector_expr)
480 .expect("Vector expression should type check");
481 assert_eq!(
482 vector_type,
483 TypeInfo::Float,
484 "Vector similarity should return float"
485 );
486 println!("ā Vector expression type checking works");
487
488 let complex_expr = Expression::Binary {
490 left: Box::new(Expression::Function {
491 name: "AVG".to_string(),
492 args: vec![Expression::Literal(Literal::Float(85.5))],
493 }),
494 op: BinaryOperator::GreaterThan,
495 right: Box::new(Expression::Binary {
496 left: Box::new(Expression::Literal(Literal::Int(50))),
497 op: BinaryOperator::Add,
498 right: Box::new(Expression::Literal(Literal::Float(25.0))),
499 }),
500 };
501
502 let complex_type = type_checker
503 .check_expression_type(&complex_expr)
504 .expect("Complex expression should type check");
505 assert_eq!(
506 complex_type,
507 TypeInfo::Bool,
508 "Comparison should return boolean"
509 );
510 println!("ā Complex nested expression type checking works");
511
512 let update_result = type_checker.check_update_assignment(
514 "name",
515 &Expression::Literal(Literal::String("John Doe".to_string())),
516 );
517 assert!(update_result.is_ok(), "Valid UPDATE assignment should pass");
518
519 let invalid_update = type_checker.check_update_assignment(
520 "position",
521 &Expression::Literal(Literal::String("not a point".to_string())),
522 );
523 assert!(
524 invalid_update.is_err(),
525 "Invalid UPDATE assignment should fail"
526 );
527 println!("ā UPDATE assignment validation works");
528
529 println!("\nš Comprehensive type validation tests passed!");
530 }
531
532 #[test]
533 fn test_query_optimizer_integration_basic() {
534 println!("Testing basic query optimizer functionality...");
535
536 let compiler = Compiler::new();
537 let optimizer = QueryOptimizer::new();
538
539 println!("1. Testing optimizer creation:");
541 let custom_config = OptimizerConfig {
542 enable_predicate_pushdown: true,
543 enable_projection_pushdown: false, enable_constant_folding: true,
545 enable_expression_simplify: false,
546 };
547 let custom_optimizer = QueryOptimizer::with_config(custom_config);
548
549 let query = "SELECT name FROM users WHERE age > 25";
551 let statement = parse_statement(query).expect("Should parse");
552
553 let basic_compiled = compiler.compile(statement.clone()).expect("Should compile");
555 println!(" ā Basic compilation successful");
556
557 let optimized_compiled = compiler
559 .compile_with_optimizer(statement.clone(), &optimizer)
560 .expect("Should compile with optimizer");
561 println!(" ā Optimized compilation successful");
562
563 let (stats_compiled, stats) = compiler
565 .compile_with_optimizer_stats(statement, &custom_optimizer)
566 .expect("Should compile with optimizer stats");
567 println!(" ā Stats compilation successful: {:?}", stats);
568
569 println!("\n2. Testing configuration respect:");
571 println!(" ā Custom optimizer created with selective optimizations");
572
573 println!("\n3. Testing plan variation:");
575 let plan_changed = !plans_equivalent(&basic_compiled.plan, &optimized_compiled.plan);
576 println!(
577 " Plan changed: {} (structure difference detected)",
578 plan_changed || stats.plan_changed
579 );
580
581 println!("\nš Basic query optimizer integration test passed!");
582 }
583
584 fn plans_equivalent(
586 plan1: &crate::compiler::ExecutionPlan,
587 plan2: &crate::compiler::ExecutionPlan,
588 ) -> bool {
589 std::mem::discriminant(plan1) == std::mem::discriminant(plan2)
590 }
591
592 #[test]
593 fn test_query_optimizer_integration() {
594 use std::collections::HashMap;
595
596 println!("Testing query optimizer integration...");
597
598 let mut data_source = MemoryDataSource::new();
600
601 let mut alice = Entity {
603 id: EntityId("alice_001".to_string()),
604 properties: HashMap::new(),
605 position: Some(Position3D {
606 x: 1.0,
607 y: 2.0,
608 z: 3.0,
609 }),
610 embedding: None,
611 };
612 alice.properties.insert(
613 PropertyName("name".to_string()),
614 Value::String("Alice".to_string()),
615 );
616 alice
617 .properties
618 .insert(PropertyName("age".to_string()), Value::Int(30));
619 alice
620 .properties
621 .insert(PropertyName("score".to_string()), Value::Float(85.5));
622
623 let mut bob = Entity {
624 id: EntityId("bob_002".to_string()),
625 properties: HashMap::new(),
626 position: Some(Position3D {
627 x: 4.0,
628 y: 5.0,
629 z: 6.0,
630 }),
631 embedding: None,
632 };
633 bob.properties.insert(
634 PropertyName("name".to_string()),
635 Value::String("Bob".to_string()),
636 );
637 bob.properties
638 .insert(PropertyName("age".to_string()), Value::Int(25));
639 bob.properties
640 .insert(PropertyName("score".to_string()), Value::Float(72.3));
641
642 data_source.add_entities("users", vec![alice, bob]);
643
644 let compiler = Compiler::new();
646 let optimizer = QueryOptimizer::new();
647 let mut executor = Executor::new(Box::new(data_source));
648
649 println!("\n1. Testing constant folding optimization:");
651 let query1 = "SELECT name FROM users WHERE age > 20 + 5"; let statement1 = parse_statement(query1).expect("Query should parse");
653
654 let _unoptimized = compiler
656 .compile(statement1.clone())
657 .expect("Should compile");
658 println!(" Unoptimized query compiled successfully");
659
660 let (optimized, stats) = compiler
662 .compile_with_optimizer_stats(statement1, &optimizer)
663 .expect("Should compile with optimizer");
664
665 println!(" Optimizations applied: {:?}", stats);
666 assert!(
667 stats.constant_folding_applied,
668 "Constant folding should be applied"
669 );
670
671 let result = executor.execute(optimized).expect("Should execute");
673 assert_eq!(result.rows.len(), 1, "Should return Alice (age 30 > 25)");
674 assert_eq!(
675 result.rows[0].columns.get("name"),
676 Some(&Value::String("Alice".to_string()))
677 );
678 println!(" ā Query executed correctly with optimizations");
679
680 println!("\n2. Testing expression simplification:");
682 let query2 = "SELECT * FROM users WHERE age > 20 AND age > 20"; let statement2 = parse_statement(query2).expect("Query should parse");
684
685 let (optimized2, stats2) = compiler
686 .compile_with_optimizer_stats(statement2, &optimizer)
687 .expect("Should compile with optimizer");
688
689 println!(" Optimizations applied: {:?}", stats2);
690 let result2 = executor.execute(optimized2).expect("Should execute");
693 assert_eq!(
694 result2.rows.len(),
695 2,
696 "Should return both users (both have age > 20)"
697 );
698 println!(" ā Simplified expression query executed correctly");
699
700 println!("\n3. Testing predicate pushdown optimization:");
702 let query3 = "SELECT name, age FROM users WHERE age > 28 ORDER BY name";
703 let statement3 = parse_statement(query3).expect("Query should parse");
704
705 let (optimized3, stats3) = compiler
706 .compile_with_optimizer_stats(statement3, &optimizer)
707 .expect("Should compile with optimizer");
708
709 println!(" Optimizations applied: {:?}", stats3);
710 let result3 = executor.execute(optimized3).expect("Should execute");
713 assert_eq!(result3.rows.len(), 1, "Should return Alice (age 30 > 28)");
714 println!(" ā Predicate pushdown query executed correctly");
715
716 println!("\n4. Testing custom optimizer configuration:");
718 let custom_config = OptimizerConfig {
719 enable_predicate_pushdown: false,
720 enable_projection_pushdown: false,
721 enable_constant_folding: true,
722 enable_expression_simplify: false,
723 };
724 let custom_optimizer = QueryOptimizer::with_config(custom_config);
725
726 let query4 = "SELECT name FROM users WHERE age > 10 + 15"; let statement4 = parse_statement(query4).expect("Query should parse");
728
729 let (optimized4, stats4) = compiler
730 .compile_with_optimizer_stats(statement4, &custom_optimizer)
731 .expect("Should compile with custom optimizer");
732
733 println!(" Custom optimizations applied: {:?}", stats4);
734 assert!(
735 stats4.constant_folding_applied,
736 "Constant folding should still be enabled"
737 );
738 assert!(
739 !stats4.predicate_pushdown_applied || !stats4.projection_pushdown_applied,
740 "Disabled optimizations should not be applied"
741 );
742
743 let result4 = executor.execute(optimized4).expect("Should execute");
744 assert_eq!(
745 result4.rows.len(),
746 1,
747 "Should return Alice (age 30 > 25, Bob has age 25 which is not > 25)"
748 );
749 assert_eq!(
750 result4.rows[0].columns.get("name"),
751 Some(&Value::String("Alice".to_string()))
752 );
753 println!(" ā Custom optimizer configuration works correctly");
754
755 println!("\n5. Testing complex query with multiple optimizations:");
757 let query5 = "SELECT name FROM users WHERE age > 15 + 10 AND score > 50.0 + 20.0 ORDER BY name LIMIT 10";
758 let statement5 = parse_statement(query5).expect("Query should parse");
759
760 let (optimized5, stats5) = compiler
761 .compile_with_optimizer_stats(statement5, &optimizer)
762 .expect("Should compile with optimizer");
763
764 println!(" Complex query optimizations applied: {:?}", stats5);
765 let result5 = executor.execute(optimized5).expect("Should execute");
769 assert_eq!(
770 result5.rows.len(),
771 1,
772 "Should return Alice (age > 25 AND score > 70.0)"
773 );
774 assert_eq!(
775 result5.rows[0].columns.get("name"),
776 Some(&Value::String("Alice".to_string()))
777 );
778 println!(" ā Complex query with multiple optimizations executed correctly");
779
780 println!("\n6. Demonstrating optimization benefits:");
782 let demo_query = "SELECT * FROM users WHERE age > 2 * 10 + 5";
783 let demo_statement = parse_statement(demo_query).expect("Query should parse");
784
785 let unoptimized_query = compiler
786 .compile(demo_statement.clone())
787 .expect("Should compile");
788 let (optimized_query, optimization_stats) = compiler
789 .compile_with_optimizer_stats(demo_statement, &optimizer)
790 .expect("Should compile with optimizer");
791
792 println!(
793 " Original estimated cost: {:.2} CPU, {} rows",
794 unoptimized_query.estimated_cost.estimated_cpu_cost,
795 unoptimized_query.estimated_cost.estimated_rows
796 );
797 println!(
798 " Optimized estimated cost: {:.2} CPU, {} rows",
799 optimized_query.estimated_cost.estimated_cpu_cost,
800 optimized_query.estimated_cost.estimated_rows
801 );
802 println!(" Optimizations applied: {:?}", optimization_stats);
803
804 println!(
805 "\nš All query optimizer integration tests passed! HyperQL optimization system is working correctly."
806 );
807 }
808
809 #[test]
810 fn test_query_validator_integration() {
811 use std::collections::HashMap;
812
813 println!("Testing query validator integration...");
814
815 let mut data_source = MemoryDataSource::new();
817
818 let mut alice = Entity {
819 id: EntityId("alice_001".to_string()),
820 properties: HashMap::new(),
821 position: Some(Position3D {
822 x: 1.0,
823 y: 2.0,
824 z: 3.0,
825 }),
826 embedding: None,
827 };
828 alice.properties.insert(
829 PropertyName("name".to_string()),
830 Value::String("Alice".to_string()),
831 );
832 alice
833 .properties
834 .insert(PropertyName("age".to_string()), Value::Int(30));
835
836 data_source.add_entity("users", alice);
837
838 let compiler = Compiler::new();
839 let mut executor = Executor::new(Box::new(data_source));
840
841 println!("\n1. Testing valid query validation:");
843 let valid_query = "SELECT name FROM users WHERE age > 25";
844 let statement1 = parse_statement(valid_query).expect("Query should parse");
845
846 let mut validator = QueryValidator::new();
847 let validation_result = validator
848 .validate(&statement1)
849 .expect("Validation should not error");
850
851 assert!(
852 validation_result.valid,
853 "Valid query should pass validation"
854 );
855 assert!(
856 validation_result.errors.is_empty(),
857 "Valid query should have no errors"
858 );
859 println!(" ā Valid query passed validation");
860
861 println!("\n2. Testing invalid query validation (HAVING without GROUP BY):");
863 let invalid_query = "SELECT name FROM users HAVING COUNT(*) > 1";
864 let statement2 = parse_statement(invalid_query).expect("Query should parse");
865
866 let validation_result2 = validator
867 .validate(&statement2)
868 .expect("Validation should not error");
869
870 assert!(
871 !validation_result2.valid,
872 "Invalid query should fail validation"
873 );
874 assert!(
875 !validation_result2.errors.is_empty(),
876 "Invalid query should have errors"
877 );
878 println!(
879 " ā Invalid query failed validation with {} errors",
880 validation_result2.errors.len()
881 );
882 for error in &validation_result2.errors {
883 println!(" - {}", error.message);
884 }
885
886 println!("\n3. Testing query with warnings (OFFSET without LIMIT):");
888 let warning_query = "SELECT * FROM users OFFSET 10";
889 let statement3 = parse_statement(warning_query).expect("Query should parse");
890
891 let validation_result3 = validator
892 .validate(&statement3)
893 .expect("Validation should not error");
894
895 assert!(
896 validation_result3.valid,
897 "Query with warnings should still be valid"
898 );
899 assert!(
900 !validation_result3.warnings.is_empty(),
901 "Query should have warnings"
902 );
903 println!(
904 " ā Query passed validation with {} warnings",
905 validation_result3.warnings.len()
906 );
907 for warning in &validation_result3.warnings {
908 println!(" - {}", warning.message);
909 }
910
911 println!("\n4. Testing compiler integration with validation:");
913 let valid_statement = parse_statement(valid_query).expect("Query should parse");
914
915 let compiled_with_validation = compiler
916 .compile_with_validation(valid_statement, &mut validator)
917 .expect("Compilation with validation should succeed");
918
919 let result = executor
921 .execute(compiled_with_validation)
922 .expect("Execution should succeed");
923 assert_eq!(result.rows.len(), 1, "Should return one result");
924 println!(" ā Validation + compilation + execution pipeline works");
925
926 println!("\n5. Testing schema-aware validation:");
928 let mut schema = HashMap::new();
929 schema.insert(
930 "users".to_string(),
931 vec!["id".to_string(), "name".to_string(), "age".to_string()],
932 );
933
934 let config = ValidationConfig {
935 validate_schema: true,
936 allow_ambiguous_columns: false,
937 ..ValidationConfig::default()
938 };
939
940 let mut schema_validator = QueryValidator::with_config(config);
941
942 let valid_schema_query = "SELECT name FROM users WHERE age > 25";
944 let statement4 = parse_statement(valid_schema_query).expect("Query should parse");
945
946 let schema_result = schema_validator
947 .validate_with_schema(&statement4, &schema)
948 .expect("Schema validation should not error");
949
950 assert!(schema_result.valid, "Valid schema query should pass");
951 println!(" ā Schema-aware validation passed for valid query");
952
953 let invalid_schema_query = "SELECT nonexistent FROM users";
955 let statement5 = parse_statement(invalid_schema_query).expect("Query should parse");
956
957 let schema_result2 = schema_validator
958 .validate_with_schema(&statement5, &schema)
959 .expect("Schema validation should not error");
960
961 assert!(!schema_result2.valid, "Invalid schema query should fail");
962 println!(" ā Schema-aware validation failed for invalid column reference");
963
964 println!("\n6. Testing custom validation configuration:");
966 let strict_config = ValidationConfig {
967 strict_mode: true,
968 allow_ambiguous_columns: false,
969 require_explicit_aliases: true,
970 warn_performance_issues: true,
971 ..ValidationConfig::default()
972 };
973
974 let mut strict_validator = QueryValidator::with_config(strict_config);
975
976 let perf_query = "SELECT * FROM users ORDER BY name";
977 let statement6 = parse_statement(perf_query).expect("Query should parse");
978
979 let strict_result = strict_validator
980 .validate(&statement6)
981 .expect("Validation should not error");
982
983 assert!(
985 !strict_result.warnings.is_empty(),
986 "Should have performance warnings"
987 );
988 println!(
989 " ā Strict validation configuration produced {} warnings",
990 strict_result.warnings.len()
991 );
992
993 println!(
994 "\nš All query validator integration tests passed! HyperQL validation system is working correctly."
995 );
996 }
997}