vlorql_core/optimizer/rules.rs
1//! The [`PlanRewriter`] trait and the [`RewriterPipeline`] that chains
2//! rewrite rules together.
3//!
4//! A rewriter takes a validated [`QueryPlan`] and returns a
5//! semantically-equivalent plan that is cheaper to execute. Rules are
6//! deliberately small and composable; [`RewriterPipeline`] applies a
7//! sequence of them in order, threading each rule's output into the
8//! next.
9
10use crate::errors::VlorQLError;
11use crate::schema::QueryPlan;
12use std::fmt;
13
14/// A logical rewrite rule over a [`QueryPlan`].
15///
16/// Implementations must preserve query semantics: the rewritten plan
17/// must return the same rows as the input for every database state. A
18/// rule that cannot safely rewrite part of a plan must leave that part
19/// unchanged rather than guess.
20pub trait PlanRewriter: fmt::Debug + Send + Sync {
21 /// Returns a semantically-equivalent, ideally cheaper, plan.
22 fn rewrite(&self, plan: &QueryPlan) -> Result<QueryPlan, VlorQLError>;
23}
24
25/// Applies an ordered list of [`PlanRewriter`]s, feeding each rule's
26/// output into the next.
27///
28/// The pipeline owns its rules as boxed trait objects so heterogeneous
29/// rewriters can be combined. Order matters: constant folding, for
30/// example, is usually run before pushdown so folded literals can be
31/// analyzed as constants.
32///
33/// # Examples
34///
35/// ```
36/// use vlorql_core::optimizer::{ConstantFolding, PlanRewriter, RewriterPipeline};
37/// use vlorql_core::schema::{
38/// BinaryOperator, DataType, Expression, FromClause, Projection, QueryPlan,
39/// };
40///
41/// let plan = QueryPlan {
42/// select: vec![Projection::Expr {
43/// expression: Expression::BinaryOp {
44/// left: Box::new(Expression::Literal { value: 20.into(), data_type: DataType::Int }),
45/// op: BinaryOperator::Add,
46/// right: Box::new(Expression::Literal { value: 5.into(), data_type: DataType::Int }),
47/// },
48/// alias: Some("total".to_owned()),
49/// }],
50/// from: FromClause { table: "t".to_owned(), alias: None },
51/// r#where: None, group_by: None, having: None,
52/// order_by: None, limit: None, offset: None, joins: None, ctes: None, distinct: false, distinct_on: None, set_operation: None,
53/// };
54///
55/// let pipeline = RewriterPipeline::new().with(ConstantFolding);
56/// let rewritten = pipeline.rewrite(&plan).unwrap();
57/// assert_eq!(
58/// rewritten.select[0],
59/// Projection::Expr {
60/// expression: Expression::Literal { value: 25.into(), data_type: DataType::Int },
61/// alias: Some("total".to_owned()),
62/// },
63/// );
64/// ```
65#[derive(Default, Debug)]
66pub struct RewriterPipeline {
67 rules: Vec<Box<dyn PlanRewriter>>,
68}
69
70impl RewriterPipeline {
71 /// Creates an empty pipeline. An empty pipeline is the identity
72 /// rewrite: it returns its input unchanged.
73 pub fn new() -> Self {
74 Self { rules: Vec::new() }
75 }
76
77 /// Appends a rule and returns the pipeline, for builder-style chaining.
78 #[must_use]
79 pub fn with(mut self, rule: impl PlanRewriter + 'static) -> Self {
80 self.rules.push(Box::new(rule));
81 self
82 }
83
84 /// Appends a rule in place.
85 pub fn push(&mut self, rule: impl PlanRewriter + 'static) {
86 self.rules.push(Box::new(rule));
87 }
88
89 /// Returns the number of rules in the pipeline.
90 pub fn len(&self) -> usize {
91 self.rules.len()
92 }
93
94 /// Returns `true` when the pipeline has no rules.
95 pub fn is_empty(&self) -> bool {
96 self.rules.is_empty()
97 }
98
99 /// Applies every rule in order. If any rule fails, the error is
100 /// propagated and no further rules run.
101 pub fn rewrite(&self, plan: &QueryPlan) -> Result<QueryPlan, VlorQLError> {
102 // First rule gets a clone of the input; subsequent rules own
103 // the output of the previous rule so no extra clone is needed.
104 let mut current = plan.clone();
105 for rule in &self.rules {
106 current = rule.rewrite(¤t)?;
107 }
108 Ok(current)
109 }
110
111 /// Applies the pipeline repeatedly (up to `max_rounds` times) until the
112 /// plan stops changing (fixed point).
113 ///
114 /// Constant folding may expose new pushdown opportunities, and pushdown
115 /// may enable more column pruning. Running multiple rounds captures
116 /// these cascading effects. In practice 2–3 rounds are sufficient; the
117 /// default is 3.
118 ///
119 /// # Examples
120 ///
121 /// ```
122 /// use vlorql_core::optimizer::{ConstantFolding, PlanRewriter, RewriterPipeline};
123 /// use vlorql_core::schema::{
124 /// BinaryOperator, DataType, Expression, FromClause, Projection, QueryPlan,
125 /// };
126 ///
127 /// let plan = QueryPlan {
128 /// select: vec![Projection::Expr {
129 /// expression: Expression::BinaryOp {
130 /// left: Box::new(Expression::Literal { value: 20.into(), data_type: DataType::Int }),
131 /// op: BinaryOperator::Add,
132 /// right: Box::new(Expression::Literal { value: 5.into(), data_type: DataType::Int }),
133 /// },
134 /// alias: Some("total".to_owned()),
135 /// }],
136 /// from: FromClause { table: "t".to_owned(), alias: None },
137 /// r#where: None, group_by: None, having: None,
138 /// order_by: None, limit: None, offset: None, joins: None, ctes: None, distinct: false, distinct_on: None, set_operation: None,
139 /// };
140 ///
141 /// let pipeline = RewriterPipeline::new().with(ConstantFolding);
142 /// let rewritten = pipeline.repeat_until_stable(&plan, 3).unwrap();
143 /// assert_eq!(
144 /// rewritten.select[0],
145 /// Projection::Expr {
146 /// expression: Expression::Literal { value: 25.into(), data_type: DataType::Int },
147 /// alias: Some("total".to_owned()),
148 /// },
149 /// );
150 /// ```
151 pub fn repeat_until_stable(
152 &self,
153 plan: &QueryPlan,
154 max_rounds: usize,
155 ) -> Result<QueryPlan, VlorQLError> {
156 let mut current = plan.clone();
157 for _round in 0..max_rounds {
158 let next = self.rewrite(¤t)?;
159 if next == current {
160 return Ok(next);
161 }
162 current = next;
163 }
164 Ok(current)
165 }
166}