use std::fmt;
use vlorql_core::schema::QueryPlan;
use super::semantic;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationErrorKind {
EmptySelect,
MissingFrom,
InvalidProjection,
MissingJoinCondition,
InvalidExpression,
InvalidPredicate,
InvalidLimit,
CteError,
MissingAggregate,
}
#[derive(Debug, Clone)]
pub struct ValidationError {
pub kind: ValidationErrorKind,
pub message: String,
}
impl ValidationError {
pub fn new(kind: ValidationErrorKind, message: impl Into<String>) -> Self {
Self {
kind,
message: message.into(),
}
}
}
impl fmt::Display for ValidationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}: {}", self.kind, self.message)
}
}
pub type ValidationResult = Result<(), Vec<ValidationError>>;
pub fn validate_plan(plan: &QueryPlan) -> ValidationResult {
let errors = semantic::validate(plan);
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
#[cfg(test)]
mod tests {
use super::*;
use vlorql_core::schema::*;
fn valid_plan() -> QueryPlan {
QueryPlan {
select: vec![Projection::Star { table: None }],
from: FromClause::table("users".to_owned(), None),
r#where: None,
group_by: None,
having: None,
order_by: None,
limit: None,
offset: None,
joins: None,
ctes: None,
distinct: false,
distinct_on: None,
set_operation: None,
}
}
#[test]
fn valid_plan_ok() {
let plan = valid_plan();
assert!(validate_plan(&plan).is_ok());
}
#[test]
fn empty_select_errors() {
let mut plan = valid_plan();
plan.select = vec![];
let result = validate_plan(&plan);
assert!(result.is_err());
let errors = result.unwrap_err();
assert!(
errors
.iter()
.any(|e| e.kind == ValidationErrorKind::EmptySelect)
);
}
#[test]
fn multiple_errors_collected() {
let mut plan = valid_plan();
plan.select = vec![];
plan.from = FromClause::table("".to_owned(), None);
let result = validate_plan(&plan);
assert!(result.is_err());
let errors = result.unwrap_err();
assert!(
errors
.iter()
.any(|e| e.kind == ValidationErrorKind::EmptySelect)
);
assert!(
errors
.iter()
.any(|e| e.kind == ValidationErrorKind::MissingFrom)
);
}
#[test]
fn validation_error_display() {
let err = ValidationError::new(ValidationErrorKind::MissingFrom, "FROM clause is missing");
let display = format!("{}", err);
assert!(display.contains("MissingFrom"));
assert!(display.contains("FROM clause is missing"));
}
#[test]
fn validation_error_clone() {
let err = ValidationError::new(ValidationErrorKind::EmptySelect, "SELECT is empty");
let cloned = err.clone();
assert_eq!(err.kind, cloned.kind);
assert_eq!(err.message, cloned.message);
}
}