use super::audit::AuditStage;
use super::dialect::DialectValidator;
use super::operand::OperandValidator;
use super::schema::validate_schema;
use crate::errors::{ValidationErrors, VlorQLError};
use crate::fix;
use crate::optimizer::QueryOptimizer;
use crate::policy::PolicyEngine;
use crate::schema::{ArcSchemaSnapshot, DialectProfile, Predicate, QueryPlan, SchemaSnapshot};
use std::ops::Deref;
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq)]
pub struct ValidatedPlan(pub Arc<QueryPlan>);
impl ValidatedPlan {
pub fn as_plan(&self) -> &QueryPlan {
self.0.as_ref()
}
pub fn into_inner(self) -> Arc<QueryPlan> {
self.0
}
}
impl Deref for ValidatedPlan {
type Target = QueryPlan;
fn deref(&self) -> &Self::Target {
self.as_plan()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct OptimizedPlan(ValidatedPlan);
impl OptimizedPlan {
pub fn as_validated(&self) -> &ValidatedPlan {
&self.0
}
pub fn into_validated(self) -> ValidatedPlan {
self.0
}
pub fn into_inner(self) -> Arc<QueryPlan> {
self.0.into_inner()
}
}
impl From<ValidatedPlan> for OptimizedPlan {
fn from(plan: ValidatedPlan) -> Self {
Self(plan)
}
}
impl Deref for OptimizedPlan {
type Target = ValidatedPlan;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Debug, Clone)]
pub struct ValidationPipeline {
schema: ArcSchemaSnapshot,
dialect: DialectProfile,
policy: PolicyEngine,
optimizer: Option<QueryOptimizer>,
audit_stage: Option<AuditStage>,
}
impl ValidationPipeline {
pub fn new(schema: Arc<SchemaSnapshot>, dialect: DialectProfile, policy: PolicyEngine) -> Self {
Self {
schema,
dialect,
policy,
optimizer: None,
audit_stage: None,
}
}
#[must_use]
pub fn with_optimizer(mut self, optimizer: QueryOptimizer) -> Self {
self.optimizer = Some(optimizer);
self
}
#[must_use]
pub fn with_audit(mut self, enable: bool) -> Self {
if enable {
self.audit_stage = Some(AuditStage::new());
} else {
self.audit_stage = None;
}
self
}
pub fn validate(&self, plan: &QueryPlan) -> Result<ValidatedPlan, ValidationErrors> {
let mut plan = plan.clone();
let _span = tracing::info_span!("vlorql.validate.fix").entered();
let _ = fix::schema_aware_fix(&mut plan, &self.schema);
drop(_span);
let mut errors = Vec::new();
{
let _span = tracing::info_span!("vlorql.validate.schema").entered();
if let Err(stage_errors) = self.validate_schema(&plan) {
extend_unique(&mut errors, stage_errors);
}
}
{
let _span = tracing::info_span!("vlorql.validate.policy").entered();
if let Err(stage_errors) = self.policy.validate(&plan, &self.schema) {
extend_unique(&mut errors, stage_errors);
}
}
{
let _span = tracing::info_span!("vlorql.validate.operand").entered();
if let Err(stage_errors) = OperandValidator::validate(&plan, &self.schema) {
extend_unique(&mut errors, stage_errors);
}
}
{
let _span = tracing::info_span!("vlorql.validate.dialect").entered();
if let Err(stage_errors) = DialectValidator::validate(&plan, &self.dialect) {
extend_unique(&mut errors, stage_errors);
}
}
if let Some(ref audit) = self.audit_stage
&& let Err(audit_errors) = audit.audit(&plan, &self.schema)
{
let (critical, others): (Vec<_>, Vec<_>) =
audit_errors.into_iter().partition(|e| !e.is_retryable());
if !critical.is_empty() {
return Err(ValidationErrors(critical));
}
extend_unique(&mut errors, others);
}
if !errors.is_empty() {
return Err(ValidationErrors(errors));
}
if let Some(row_filter) = self.policy.apply_row_filters(&plan) {
plan.r#where = Some(match plan.r#where {
Some(existing) => Predicate::And {
left: Box::new(existing),
right: Box::new(row_filter),
},
None => row_filter,
});
}
if let Err(stage_errors) = self.validate_schema(&plan) {
return Err(ValidationErrors(stage_errors));
}
Ok(ValidatedPlan(Arc::new(plan)))
}
pub fn validate_repairing(&self, plan: &QueryPlan) -> Result<ValidatedPlan, ValidationErrors> {
let mut repaired = plan.clone();
let _ = fix::drop_hallucinated_joins(&mut repaired, &self.schema);
if let Some(ref audit) = self.audit_stage
&& let Err(audit_errors) = audit.audit(&repaired, &self.schema)
{
let (critical, others): (Vec<_>, Vec<_>) =
audit_errors.into_iter().partition(|e| !e.is_retryable());
if !critical.is_empty() {
return Err(ValidationErrors(critical));
}
if !others.is_empty() {
return Err(ValidationErrors(others));
}
}
self.validate(&repaired)
}
pub async fn validate_and_optimize(
&self,
plan: &QueryPlan,
) -> Result<OptimizedPlan, ValidationErrors> {
let this = self.clone();
let plan_clone = plan.clone();
let validated = tokio::task::spawn_blocking(move || this.validate(&plan_clone))
.await
.map_err(|join_err| {
ValidationErrors::new(vec![VlorQLError::config(
crate::errors::ConfigErrorKind::InternalError {
reason: format!("validate spawn_blocking join failed: {join_err}"),
},
serde_json::json!({"operation": "validate_and_optimize"}),
)])
})??;
let Some(ref optimizer) = self.optimizer else {
return Ok(OptimizedPlan::from(validated));
};
let optimized_plan = match optimizer.optimize_async(validated.as_plan()).await {
Ok(p) => p,
Err(e) => {
return Err(ValidationErrors::new(vec![e]));
}
};
let this = self.clone();
let opt_clone = optimized_plan.clone();
if let Err(stage_errors) =
tokio::task::spawn_blocking(move || this.policy.validate(&opt_clone, &this.schema))
.await
.map_err(|join_err| {
ValidationErrors::new(vec![VlorQLError::config(
crate::errors::ConfigErrorKind::InternalError {
reason: format!(
"policy validate spawn_blocking join failed: {join_err}"
),
},
serde_json::json!({"operation": "validate_and_optimize"}),
)])
})?
{
return Err(ValidationErrors(stage_errors));
}
Ok(OptimizedPlan::from(ValidatedPlan(Arc::new(optimized_plan))))
}
pub fn validate_schema(&self, plan: &QueryPlan) -> Result<(), Vec<VlorQLError>> {
validate_schema(plan, &self.schema)
}
pub fn schema(&self) -> &ArcSchemaSnapshot {
&self.schema
}
pub fn dialect(&self) -> &DialectProfile {
&self.dialect
}
pub fn policy(&self) -> &PolicyEngine {
&self.policy
}
}
fn extend_unique(errors: &mut Vec<VlorQLError>, stage_errors: Vec<VlorQLError>) {
for error in stage_errors {
if !errors.contains(&error) {
errors.push(error);
}
}
}