1use crate::errors::{ValidationErrorKind, VlorQLError};
4use crate::query::QuerySource;
5use crate::schema::{
6 BinaryOperator, ComparisonOperator, DataType, Expression, InTarget, Predicate, Projection,
7 QueryPlan, SchemaSnapshot, WindowFrameBound,
8};
9use serde_json::{Value, json};
10use std::collections::HashSet;
11
12pub struct OperandValidator<'a> {
14 schema: &'a SchemaSnapshot,
15}
16
17impl<'a> OperandValidator<'a> {
18 pub fn new(schema: &'a SchemaSnapshot) -> Self {
20 Self { schema }
21 }
22
23 pub fn validate(plan: &QueryPlan, schema: &'a SchemaSnapshot) -> Result<(), Vec<VlorQLError>> {
25 Self::new(schema).validate_plan(plan)
26 }
27
28 pub fn validate_plan(&self, plan: &QueryPlan) -> Result<(), Vec<VlorQLError>> {
30 let mut errors = Vec::new();
31 self.validate_plan_inner(plan, &mut errors);
32 if errors.is_empty() {
33 Ok(())
34 } else {
35 Err(errors)
36 }
37 }
38
39 pub fn validate_expression(
41 &self,
42 expression: &Expression,
43 ) -> Result<DataType, Vec<VlorQLError>> {
44 let scope = OperandScope::from_schema(self.schema);
45 let mut errors = Vec::new();
46 let data_type = self
47 .validate_expression_inner(expression, &scope, &mut errors)
48 .unwrap_or(DataType::Null);
49 if errors.is_empty() {
50 Ok(data_type)
51 } else {
52 Err(errors)
53 }
54 }
55
56 pub fn validate_predicate(&self, predicate: &Predicate) -> Result<(), Vec<VlorQLError>> {
58 let scope = OperandScope::from_schema(self.schema);
59 let mut errors = Vec::new();
60 self.validate_predicate_inner(predicate, &scope, &mut errors);
61 if errors.is_empty() {
62 Ok(())
63 } else {
64 Err(errors)
65 }
66 }
67
68 fn validate_plan_inner(&self, plan: &QueryPlan, errors: &mut Vec<VlorQLError>) {
69 if let Some(ctes) = &plan.ctes {
70 for cte in ctes {
71 self.validate_plan_inner(&cte.query, errors);
72 }
73 }
74
75 let scope = OperandScope::from_plan(plan, self.schema);
76 for projection in &plan.select {
77 if let Projection::Expr { expression, .. } = projection {
78 self.validate_expression_inner(expression, &scope, errors);
79 }
80 }
81 if let Some(predicate) = &plan.r#where {
82 self.validate_predicate_inner(predicate, &scope, errors);
83 }
84 if let Some(expressions) = &plan.group_by {
85 for expression in expressions {
86 self.validate_expression_inner(expression, &scope, errors);
87 }
88 }
89 if let Some(predicate) = &plan.having {
90 self.validate_predicate_inner(predicate, &scope, errors);
91 }
92 if let Some(terms) = &plan.order_by {
93 for term in terms {
94 self.validate_expression_inner(&term.expr, &scope, errors);
95 }
96 }
97 if let Some(joins) = &plan.joins {
98 for join in joins {
99 self.validate_predicate_inner(&join.on, &scope, errors);
100 }
101 }
102 }
103
104 fn validate_expression_inner(
105 &self,
106 expression: &Expression,
107 scope: &OperandScope,
108 errors: &mut Vec<VlorQLError>,
109 ) -> Option<DataType> {
110 match expression {
111 Expression::Literal { value, data_type } => {
112 if !literal_matches_type(value, *data_type) {
113 if *data_type == DataType::Null && !value.is_null() {
118 let inferred = match value {
119 Value::String(_) => DataType::String,
120 Value::Bool(_) => DataType::Boolean,
121 Value::Number(n) if n.is_f64() => DataType::Float,
122 Value::Number(_) => DataType::Int,
123 _ => DataType::Null,
124 };
125 tracing::debug!(
126 "Literal with declared data_type=null and non-null value; inferred {inferred:?}"
127 );
128 return Some(inferred);
129 }
130 errors.push(type_mismatch_error(
131 data_type_name(*data_type),
132 json_value_type(value),
133 "literal",
134 json!({"value": value, "declared_type": data_type}),
135 ));
136 }
137 Some(*data_type)
138 }
139 Expression::ColumnRef { table, column } => {
140 scope.resolve_column_type(table.as_deref(), column, self.schema)
141 }
142 Expression::FunctionCall { name, args, .. } => {
143 let argument_types = args
144 .iter()
145 .map(|argument| self.validate_expression_inner(argument, scope, errors))
146 .collect::<Vec<_>>();
147 Some(self.validate_function(name, &argument_types, errors))
148 }
149 Expression::BinaryOp { left, op, right } => {
150 let left_type = self.validate_expression_inner(left, scope, errors);
151 let right_type = self.validate_expression_inner(right, scope, errors);
152 match (left_type, right_type) {
153 (Some(left_type), Some(right_type)) => Some(validate_binary_operation(
154 *op, left_type, right_type, errors,
155 )),
156 _ => None,
157 }
158 }
159 Expression::Star => None,
160 Expression::SubQuery { query } => {
161 self.validate_plan_inner(query, errors);
162 None
163 }
164 Expression::Case {
165 operand,
166 when_thens,
167 else_result,
168 } => {
169 if let Some(op) = operand {
170 self.validate_expression_inner(op, scope, errors);
171 }
172 for wt in when_thens {
173 self.validate_expression_inner(&wt.when, scope, errors);
174 self.validate_expression_inner(&wt.then, scope, errors);
175 }
176 if let Some(el) = else_result {
177 self.validate_expression_inner(el, scope, errors);
178 }
179 let then_types: Vec<DataType> = when_thens
181 .iter()
182 .filter_map(|wt| {
183 self.validate_expression_inner(&wt.then, scope, errors)
184 })
185 .collect();
186 let else_type = else_result
187 .as_ref()
188 .and_then(|el| self.validate_expression_inner(el, scope, errors));
189 then_types
190 .into_iter()
191 .chain(else_type)
192 .reduce(|a, b| if a == b { a } else { DataType::String })
193 }
194 Expression::WindowFunction {
195 name, args, over, ..
196 } => {
197 let argument_types = args
198 .iter()
199 .map(|argument| self.validate_expression_inner(argument, scope, errors))
200 .collect::<Vec<_>>();
201 if let Some(partition_by) = &over.partition_by {
203 for expr in partition_by {
204 self.validate_expression_inner(expr, scope, errors);
205 }
206 }
207 if let Some(order_by) = &over.order_by {
208 for term in order_by {
209 self.validate_expression_inner(&term.expr, scope, errors);
210 }
211 }
212 if let Some(frame) = &over.frame {
213 if let Some(start) = frame_bound_expr(&frame.start) {
214 self.validate_expression_inner(start, scope, errors);
215 }
216 if let Some(end) = &frame.end {
217 if let Some(expr) = frame_bound_expr(end) {
218 self.validate_expression_inner(expr, scope, errors);
219 }
220 }
221 }
222 Some(self.validate_function(name, &argument_types, errors))
223 }
224 }
225 }
226
227 fn validate_predicate_inner(
228 &self,
229 predicate: &Predicate,
230 scope: &OperandScope,
231 errors: &mut Vec<VlorQLError>,
232 ) {
233 match predicate {
234 Predicate::Comparison { left, op, right } => {
235 let left_type = self.validate_expression_inner(left, scope, errors);
236 let right_type = self.validate_expression_inner(right, scope, errors);
237 if let (Some(left_type), Some(right_type)) = (left_type, right_type) {
238 validate_comparison(*op, left_type, right_type, errors);
239 }
240 }
241 Predicate::And { left, right } | Predicate::Or { left, right } => {
242 self.validate_predicate_inner(left, scope, errors);
243 self.validate_predicate_inner(right, scope, errors);
244 }
245 Predicate::Not { child } => self.validate_predicate_inner(child, scope, errors),
246 Predicate::Between { expr, low, high } => {
247 let expr_type = self.validate_expression_inner(expr, scope, errors);
248 let low_type = self.validate_expression_inner(low, scope, errors);
249 let high_type = self.validate_expression_inner(high, scope, errors);
250 if let (Some(expr_type), Some(low_type)) = (expr_type, low_type) {
251 validate_compatible_types("BETWEEN lower bound", expr_type, low_type, errors);
252 }
253 if let (Some(expr_type), Some(high_type)) = (expr_type, high_type) {
254 validate_compatible_types("BETWEEN upper bound", expr_type, high_type, errors);
255 }
256 }
257 Predicate::In { expr, target } => {
258 let expr_type = self.validate_expression_inner(expr, scope, errors);
259 match target {
260 InTarget::Values(values) => {
261 for value in values {
262 let value_type = self.validate_expression_inner(value, scope, errors);
263 if let (Some(expr_type), Some(value_type)) = (expr_type, value_type) {
264 validate_compatible_types(
265 "IN value", expr_type, value_type, errors,
266 );
267 }
268 }
269 }
270 InTarget::SubQuery(query) => {
271 self.validate_plan_inner(query, errors);
272 }
273 }
274 }
275 Predicate::Exists { query } => {
276 self.validate_plan_inner(query, errors);
277 }
278 Predicate::Like { expr, .. } => {
279 if let Some(data_type) = self.validate_expression_inner(expr, scope, errors) {
280 require_string("LIKE expression", data_type, errors);
281 }
282 }
283 Predicate::IsNull { expr } => {
284 self.validate_expression_inner(expr, scope, errors);
285 }
286 }
287 }
288
289 fn validate_function(
290 &self,
291 name: &str,
292 argument_types: &[Option<DataType>],
293 errors: &mut Vec<VlorQLError>,
294 ) -> DataType {
295 if name.eq_ignore_ascii_case("count") {
297 require_arity_range(name, argument_types.len(), 0, 1, errors);
298 DataType::Int
299 } else if is_any_of_ignore_case(name, &["sum", "avg", "abs"]) {
300 require_arity(name, argument_types.len(), 1, errors);
301 if let Some(Some(argument_type)) = argument_types.first() {
302 require_numeric(
303 &format!("function `{name}` argument"),
304 *argument_type,
305 errors,
306 );
307 }
308 if name.eq_ignore_ascii_case("avg") {
309 DataType::Float
310 } else {
311 argument_types
312 .first()
313 .copied()
314 .flatten()
315 .unwrap_or(DataType::Null)
316 }
317 } else if is_any_of_ignore_case(name, &["min", "max"]) {
318 require_arity(name, argument_types.len(), 1, errors);
319 argument_types
320 .first()
321 .copied()
322 .flatten()
323 .unwrap_or(DataType::Null)
324 } else if is_any_of_ignore_case(name, &["lower", "upper"]) {
325 require_arity(name, argument_types.len(), 1, errors);
326 if let Some(Some(argument_type)) = argument_types.first() {
327 require_string(
328 &format!("function `{name}` argument"),
329 *argument_type,
330 errors,
331 );
332 }
333 DataType::String
334 } else if name.eq_ignore_ascii_case("length") {
335 require_arity(name, argument_types.len(), 1, errors);
336 if let Some(Some(argument_type)) = argument_types.first() {
337 require_string(
338 &format!("function `{name}` argument"),
339 *argument_type,
340 errors,
341 );
342 }
343 DataType::Int
344 } else if name.eq_ignore_ascii_case("concat") {
345 require_min_arity(name, argument_types.len(), 1, errors);
346 for argument_type in argument_types.iter().flatten() {
347 require_string(
348 &format!("function `{name}` argument"),
349 *argument_type,
350 errors,
351 );
352 }
353 DataType::String
354 } else if name.eq_ignore_ascii_case("coalesce") {
355 require_min_arity(name, argument_types.len(), 1, errors);
356 let result = argument_types
357 .iter()
358 .flatten()
359 .copied()
360 .find(|data_type| *data_type != DataType::Null)
361 .unwrap_or(DataType::Null);
362 for argument_type in argument_types.iter().flatten() {
363 validate_compatible_types(
364 &format!("function `{name}` argument"),
365 result,
366 *argument_type,
367 errors,
368 );
369 }
370 result
371 } else {
372 DataType::Null
373 }
374 }
375}
376
377#[derive(Debug)]
378struct OperandScope {
379 sources: Vec<QuerySource>,
380 cte_names: HashSet<String>,
381}
382
383impl OperandScope {
384 fn from_plan(plan: &QueryPlan, schema: &SchemaSnapshot) -> Self {
385 let scope = crate::query::QueryScope::from_plan(plan);
386 let mut sources = scope.sources;
387 sources.retain(|source| {
388 scope.cte_names.contains(&source.table) || schema.get_table(&source.table).is_some()
389 });
390 Self {
391 sources,
392 cte_names: scope.cte_names,
393 }
394 }
395
396 fn from_schema(schema: &SchemaSnapshot) -> Self {
397 Self {
398 sources: schema
399 .tables
400 .iter()
401 .map(|table| QuerySource {
402 table: table.name.clone(),
403 alias: None,
404 })
405 .collect(),
406 cte_names: HashSet::new(),
407 }
408 }
409
410 fn resolve_column_type(
411 &self,
412 qualifier: Option<&str>,
413 column: &str,
414 schema: &SchemaSnapshot,
415 ) -> Option<DataType> {
416 if let Some(qualifier) = qualifier {
417 let source = self.sources.iter().find(|source| {
418 source.table == qualifier || source.alias.as_deref() == Some(qualifier)
419 })?;
420 if self.cte_names.contains(&source.table) {
421 return None;
422 }
423 return schema
424 .get_column(&source.table, column)
425 .map(|column| column.data_type);
426 }
427
428 self.sources
429 .iter()
430 .filter(|source| !self.cte_names.contains(&source.table))
431 .filter_map(|source| schema.get_column(&source.table, column))
432 .map(|column| column.data_type)
433 .next()
434 }
435}
436
437fn validate_binary_operation(
438 operator: BinaryOperator,
439 left: DataType,
440 right: DataType,
441 errors: &mut Vec<VlorQLError>,
442) -> DataType {
443 match operator {
444 BinaryOperator::Add
445 | BinaryOperator::Sub
446 | BinaryOperator::Mul
447 | BinaryOperator::Div
448 | BinaryOperator::Mod => {
449 if !are_numeric(left, right) {
450 errors.push(type_mismatch_error(
451 "compatible numeric operands",
452 format!("{} and {}", data_type_name(left), data_type_name(right)),
453 format!("binary operator {operator:?}"),
454 json!({"left": left, "right": right, "operator": operator}),
455 ));
456 }
457 numeric_result_type(left, right)
458 }
459 BinaryOperator::And | BinaryOperator::Or => {
460 if left != DataType::Boolean || right != DataType::Boolean {
461 errors.push(type_mismatch_error(
462 "boolean operands",
463 format!("{} and {}", data_type_name(left), data_type_name(right)),
464 format!("binary operator {operator:?}"),
465 json!({"left": left, "right": right, "operator": operator}),
466 ));
467 }
468 DataType::Boolean
469 }
470 BinaryOperator::Eq
471 | BinaryOperator::Neq
472 | BinaryOperator::Gt
473 | BinaryOperator::Lt
474 | BinaryOperator::Gte
475 | BinaryOperator::Lte => {
476 validate_compatible_types(
477 &format!("binary operator {operator:?}"),
478 left,
479 right,
480 errors,
481 );
482 DataType::Boolean
483 }
484 BinaryOperator::Like | BinaryOperator::ILike => {
485 if !is_string_compatible(left) || !is_string_compatible(right) {
486 errors.push(type_mismatch_error(
487 "string operands",
488 format!("{} and {}", data_type_name(left), data_type_name(right)),
489 format!("binary operator {operator:?}"),
490 json!({"left": left, "right": right, "operator": operator}),
491 ));
492 }
493 DataType::Boolean
494 }
495 }
496}
497
498fn validate_comparison(
499 operator: ComparisonOperator,
500 left: DataType,
501 right: DataType,
502 errors: &mut Vec<VlorQLError>,
503) {
504 match operator {
505 ComparisonOperator::Like | ComparisonOperator::ILike => {
506 if !is_string_compatible(left) || !is_string_compatible(right) {
507 errors.push(type_mismatch_error(
508 "string operands",
509 format!("{} and {}", data_type_name(left), data_type_name(right)),
510 format!("comparison {operator:?}"),
511 json!({"left": left, "right": right, "operator": operator}),
512 ));
513 }
514 }
515 _ => validate_compatible_types(&format!("comparison {operator:?}"), left, right, errors),
516 }
517}
518
519fn validate_compatible_types(
520 expression: &str,
521 left: DataType,
522 right: DataType,
523 errors: &mut Vec<VlorQLError>,
524) {
525 if !types_compatible(left, right) {
526 errors.push(type_mismatch_error(
527 format!("{} (left)", data_type_name(left)),
531 format!("{} (right)", data_type_name(right)),
532 expression,
533 json!({"left": left, "right": right}),
534 ));
535 }
536}
537
538fn require_numeric(expression: &str, actual: DataType, errors: &mut Vec<VlorQLError>) {
539 if !is_numeric(actual) && actual != DataType::Null {
540 errors.push(type_mismatch_error(
541 "numeric",
542 data_type_name(actual),
543 expression,
544 json!({"actual": actual}),
545 ));
546 }
547}
548
549fn require_string(expression: &str, actual: DataType, errors: &mut Vec<VlorQLError>) {
550 if !is_string_compatible(actual) {
551 errors.push(type_mismatch_error(
552 "string",
553 data_type_name(actual),
554 expression,
555 json!({"actual": actual}),
556 ));
557 }
558}
559
560fn require_arity(name: &str, actual: usize, expected: usize, errors: &mut Vec<VlorQLError>) {
561 if actual != expected {
562 errors.push(type_mismatch_error(
563 format!("{expected} argument(s)"),
564 format!("{actual} argument(s)"),
565 format!("function `{name}`"),
566 json!({"function": name, "expected_arguments": expected, "actual_arguments": actual}),
567 ));
568 }
569}
570
571fn require_min_arity(name: &str, actual: usize, min: usize, errors: &mut Vec<VlorQLError>) {
572 if actual < min {
573 errors.push(type_mismatch_error(
574 format!("at least {min} argument(s)"),
575 format!("{actual} argument(s)"),
576 format!("function `{name}`"),
577 json!({"function": name, "minimum_arguments": min, "actual_arguments": actual}),
578 ));
579 }
580}
581
582fn require_arity_range(
583 name: &str,
584 actual: usize,
585 min: usize,
586 max: usize,
587 errors: &mut Vec<VlorQLError>,
588) {
589 if !(min..=max).contains(&actual) {
590 errors.push(type_mismatch_error(
591 format!("between {min} and {max} argument(s)"),
592 format!("{actual} argument(s)"),
593 format!("function `{name}`"),
594 json!({
595 "function": name,
596 "minimum_arguments": min,
597 "maximum_arguments": max,
598 "actual_arguments": actual,
599 }),
600 ));
601 }
602}
603
604fn type_mismatch_error(
605 expected: impl Into<String>,
606 found: impl Into<String>,
607 expression: impl Into<String>,
608 details: Value,
609) -> VlorQLError {
610 VlorQLError::validation(
611 ValidationErrorKind::TypeMismatch {
612 expected: expected.into(),
613 found: found.into(),
614 expr: expression.into(),
615 },
616 details,
617 )
618}
619
620fn literal_matches_type(value: &Value, data_type: DataType) -> bool {
621 match data_type {
622 DataType::Int => value.as_i64().is_some() || value.as_u64().is_some(),
623 DataType::Float => value.is_number(),
624 DataType::String | DataType::Date | DataType::Timestamp | DataType::Uuid => {
625 value.is_string()
626 }
627 DataType::Boolean => value.is_boolean(),
628 DataType::Json => true,
629 DataType::Null => value.is_null(),
630 }
631}
632
633fn json_value_type(value: &Value) -> &'static str {
634 match value {
635 Value::Null => "null",
636 Value::Bool(_) => "boolean",
637 Value::Number(number) if number.is_i64() || number.is_u64() => "integer",
638 Value::Number(_) => "float",
639 Value::String(_) => "string",
640 Value::Array(_) => "array",
641 Value::Object(_) => "object",
642 }
643}
644
645fn data_type_name(data_type: DataType) -> &'static str {
646 match data_type {
647 DataType::Int => "int",
648 DataType::Float => "float",
649 DataType::String => "string",
650 DataType::Boolean => "boolean",
651 DataType::Date => "date",
652 DataType::Timestamp => "timestamp",
653 DataType::Json => "json",
654 DataType::Null => "null",
655 DataType::Uuid => "uuid",
656 }
657}
658
659fn is_numeric(data_type: DataType) -> bool {
660 matches!(data_type, DataType::Int | DataType::Float)
661}
662
663fn are_numeric(left: DataType, right: DataType) -> bool {
664 (is_numeric(left) || left == DataType::Null) && (is_numeric(right) || right == DataType::Null)
665}
666
667fn is_string_compatible(data_type: DataType) -> bool {
668 matches!(data_type, DataType::String | DataType::Null)
669}
670
671fn types_compatible(left: DataType, right: DataType) -> bool {
672 left == right || left == DataType::Null || right == DataType::Null || are_numeric(left, right)
673}
674
675fn numeric_result_type(left: DataType, right: DataType) -> DataType {
676 if left == DataType::Float || right == DataType::Float {
677 DataType::Float
678 } else if left == DataType::Int || right == DataType::Int {
679 DataType::Int
680 } else {
681 DataType::Null
682 }
683}
684
685fn is_any_of_ignore_case(name: &str, candidates: &[&str]) -> bool {
687 candidates
688 .iter()
689 .any(|candidate| candidate.eq_ignore_ascii_case(name))
690}
691
692fn frame_bound_expr(bound: &WindowFrameBound) -> Option<&Expression> {
694 match bound {
695 WindowFrameBound::Preceding(expr) | WindowFrameBound::Following(expr) => Some(expr),
696 _ => None,
697 }
698}