vlorql-core 0.5.0

A high-performance SQL query optimizer with constant folding, predicate pushdown, column pruning, and cost-based join reordering
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Shared tree-traversal infrastructure for rewrite rules.
//!
//! Two patterns are provided:
//!
//! * **`ExpressionFold`** — transform an expression/predicate/plan tree
//!   by recursively rebuilding nodes. The default implementations are
//!   the identity (every node is cloned unchanged); override specific
//!   methods to apply a transformation.
//!
//! * **`ExpressionVisit`** — read-only traversal that collects
//!   information. The default implementations recurse into every child;
//!   override `visit_expression` / `visit_predicate` / `visit_plan` to
//!   observe specific nodes.
//!
//! Both patterns eliminate the duplicated recursion that would
//! otherwise appear in every rule.
#![allow(missing_docs)]

use crate::schema::{
    CommonTableExpression, Expression, InTarget, JoinClause, OrderByTerm, Predicate, Projection,
    QueryPlan, SetOperationClause,
};

// ---------------------------------------------------------------------------
// Fold (transform) pattern
// ---------------------------------------------------------------------------

/// Transforms an expression/predicate/plan tree by recursively
/// rebuilding nodes. The default implementation for every method is the
/// identity — call one of the `default_*` functions inside your
/// override to recurse into children.
///
/// # Examples
///
/// ```
/// use vlorql_core::optimizer::visitor::ExpressionFold;
/// use vlorql_core::schema::Expression;
///
/// struct MyFold;
/// impl ExpressionFold for MyFold {
///     fn fold_expression(&mut self, expr: &Expression) -> Expression { expr.clone() }
/// }
/// ```
pub trait ExpressionFold {
    fn fold_expression(&mut self, expr: &Expression) -> Expression {
        default_fold_expression(self, expr)
    }

    fn fold_predicate(&mut self, pred: &Predicate) -> Predicate {
        default_fold_predicate(self, pred)
    }

    fn fold_projection(&mut self, proj: &Projection) -> Projection {
        default_fold_projection(self, proj)
    }

    fn fold_plan(&mut self, plan: &QueryPlan) -> QueryPlan {
        default_fold_plan(self, plan)
    }
}

impl<T: ExpressionFold + ?Sized> ExpressionFold for &mut T {
    fn fold_expression(&mut self, expr: &Expression) -> Expression {
        T::fold_expression(self, expr)
    }
    fn fold_predicate(&mut self, pred: &Predicate) -> Predicate {
        T::fold_predicate(self, pred)
    }
    fn fold_projection(&mut self, proj: &Projection) -> Projection {
        T::fold_projection(self, proj)
    }
    fn fold_plan(&mut self, plan: &QueryPlan) -> QueryPlan {
        T::fold_plan(self, plan)
    }
}

// -- default fold implementations ------------------------------------------

pub fn default_fold_expression<F: ExpressionFold + ?Sized>(
    folder: &mut F,
    expr: &Expression,
) -> Expression {
    match expr {
        Expression::BinaryOp { left, op, right } => Expression::BinaryOp {
            left: Box::new(folder.fold_expression(left)),
            op: *op,
            right: Box::new(folder.fold_expression(right)),
        },
        Expression::FunctionCall {
            name,
            args,
            distinct,
        } => Expression::FunctionCall {
            name: name.clone(),
            args: Box::new(args.iter().map(|a| folder.fold_expression(a)).collect()),
            distinct: *distinct,
        },
        Expression::SubQuery { query } => Expression::SubQuery {
            query: Box::new(folder.fold_plan(query)),
        },
        // Literals, column references, and Star are leaves.
        other => other.clone(),
    }
}

pub fn default_fold_predicate<F: ExpressionFold + ?Sized>(
    folder: &mut F,
    pred: &Predicate,
) -> Predicate {
    match pred {
        Predicate::Comparison { left, op, right } => Predicate::Comparison {
            left: Box::new(folder.fold_expression(left)),
            op: *op,
            right: Box::new(folder.fold_expression(right)),
        },
        Predicate::And { left, right } => Predicate::And {
            left: Box::new(folder.fold_predicate(left)),
            right: Box::new(folder.fold_predicate(right)),
        },
        Predicate::Or { left, right } => Predicate::Or {
            left: Box::new(folder.fold_predicate(left)),
            right: Box::new(folder.fold_predicate(right)),
        },
        Predicate::Not { child } => Predicate::Not {
            child: Box::new(folder.fold_predicate(child)),
        },
        Predicate::Between { expr, low, high } => Predicate::Between {
            expr: Box::new(folder.fold_expression(expr)),
            low: Box::new(folder.fold_expression(low)),
            high: Box::new(folder.fold_expression(high)),
        },
        Predicate::In { expr, target } => Predicate::In {
            expr: Box::new(folder.fold_expression(expr)),
            target: match target {
                InTarget::Values(values) => {
                    InTarget::Values(values.iter().map(|v| folder.fold_expression(v)).collect())
                }
                InTarget::SubQuery(query) => InTarget::SubQuery(query.clone()),
            },
        },
        Predicate::Exists { query } => Predicate::Exists {
            query: query.clone(),
        },
        Predicate::Like { expr, pattern } => Predicate::Like {
            expr: Box::new(folder.fold_expression(expr)),
            pattern: pattern.clone(),
        },
        Predicate::IsNull { expr } => Predicate::IsNull {
            expr: Box::new(folder.fold_expression(expr)),
        },
        Predicate::True => Predicate::True,
        Predicate::False => Predicate::False,
    }
}

pub fn default_fold_projection<F: ExpressionFold + ?Sized>(
    folder: &mut F,
    proj: &Projection,
) -> Projection {
    match proj {
        Projection::Column {
            table,
            column,
            alias,
        } => Projection::Column {
            table: table.clone(),
            column: column.clone(),
            alias: alias.clone(),
        },
        Projection::Expr { expression, alias } => Projection::Expr {
            expression: folder.fold_expression(expression),
            alias: alias.clone(),
        },
        Projection::Star { table } => Projection::Star {
            table: table.clone(),
        },
    }
}

pub fn default_fold_plan<F: ExpressionFold + ?Sized>(
    folder: &mut F,
    plan: &QueryPlan,
) -> QueryPlan {
    QueryPlan {
        select: plan
            .select
            .iter()
            .map(|p| folder.fold_projection(p))
            .collect(),
        distinct: plan.distinct,
        distinct_on: plan.distinct_on.clone(),
        from: plan.from.clone(),
        r#where: plan.r#where.as_ref().map(|p| folder.fold_predicate(p)),
        group_by: plan
            .group_by
            .as_ref()
            .map(|exprs| exprs.iter().map(|e| folder.fold_expression(e)).collect()),
        having: plan.having.as_ref().map(|p| folder.fold_predicate(p)),
        order_by: plan.order_by.as_ref().map(|terms| {
            terms
                .iter()
                .map(|t| OrderByTerm {
                    expr: folder.fold_expression(&t.expr),
                    descending: t.descending,
                })
                .collect()
        }),
        limit: plan.limit,
        offset: plan.offset,
        joins: plan.joins.as_ref().map(|joins| {
            joins
                .iter()
                .map(|j| JoinClause {
                    join_type: j.join_type,
                    right_table: j.right_table.clone(),
                    on: folder.fold_predicate(&j.on),
                })
                .collect()
        }),
        ctes: plan.ctes.as_ref().map(|ctes| {
            ctes.iter()
                .map(|cte| CommonTableExpression {
                    name: cte.name.clone(),
                    recursive: cte.recursive,
                    query: Box::new(folder.fold_plan(&cte.query)),
                })
                .collect()
        }),
        set_operation: plan
            .set_operation
            .as_ref()
            .map(|set_op| SetOperationClause {
                operation: set_op.operation,
                right: Box::new(folder.fold_plan(&set_op.right)),
            }),
    }
}

// ---------------------------------------------------------------------------
// Visit (read-only) pattern
// ---------------------------------------------------------------------------

/// Read-only traversal over an expression/predicate/plan tree. The
/// default implementation of every method recurses into every child.
/// Override specific methods to observe nodes of interest.
///
/// # Examples
///
/// ```
/// use vlorql_core::optimizer::visitor::ExpressionVisit;
/// use vlorql_core::schema::Expression;
/// use std::collections::HashSet;
///
/// struct MyVisitor;
/// impl ExpressionVisit for MyVisitor {
///     type Ctx = HashSet<String>;
///     fn visit_expression(&mut self, expr: &Expression, ctx: &mut Self::Ctx) {
///         if let Expression::ColumnRef { column, .. } = expr {
///             ctx.insert(column.clone());
///         }
///     }
/// }
/// ```
pub trait ExpressionVisit {
    type Ctx;

    fn visit_expression(&mut self, expr: &Expression, ctx: &mut Self::Ctx) {
        default_visit_expression(self, expr, ctx)
    }

    fn visit_predicate(&mut self, pred: &Predicate, ctx: &mut Self::Ctx) {
        default_visit_predicate(self, pred, ctx)
    }

    fn visit_projection(&mut self, proj: &Projection, ctx: &mut Self::Ctx) {
        default_visit_projection(self, proj, ctx)
    }

    fn visit_plan(&mut self, plan: &QueryPlan, ctx: &mut Self::Ctx) {
        default_visit_plan(self, plan, ctx)
    }
}

// -- default visit implementations -----------------------------------------

pub fn default_visit_expression<F: ExpressionVisit + ?Sized>(
    visitor: &mut F,
    expr: &Expression,
    ctx: &mut F::Ctx,
) {
    match expr {
        Expression::BinaryOp { left, right, .. } => {
            visitor.visit_expression(left, ctx);
            visitor.visit_expression(right, ctx);
        }
        Expression::FunctionCall { args, .. } => {
            for arg in args.iter() {
                visitor.visit_expression(arg, ctx);
            }
        }
        Expression::SubQuery { query } => visitor.visit_plan(query, ctx),
        Expression::Case {
            operand,
            when_thens,
            else_result,
        } => {
            if let Some(op) = operand {
                visitor.visit_expression(op, ctx);
            }
            for wt in when_thens.iter() {
                visitor.visit_expression(&wt.when, ctx);
                visitor.visit_expression(&wt.then, ctx);
            }
            if let Some(el) = else_result {
                visitor.visit_expression(el, ctx);
            }
        }
        Expression::ColumnRef { .. } | Expression::Literal { .. } | Expression::Star => {}
        Expression::WindowFunction { args, over, .. } => {
            for arg in args.iter() {
                visitor.visit_expression(arg, ctx);
            }
            if let Some(partition_by) = &over.partition_by {
                for expr in partition_by {
                    visitor.visit_expression(expr, ctx);
                }
            }
            if let Some(order_by) = &over.order_by {
                for term in order_by {
                    visitor.visit_expression(&term.expr, ctx);
                }
            }
        }
    }
}

pub fn default_visit_predicate<F: ExpressionVisit + ?Sized>(
    visitor: &mut F,
    pred: &Predicate,
    ctx: &mut F::Ctx,
) {
    match pred {
        Predicate::Comparison { left, right, .. } => {
            visitor.visit_expression(left, ctx);
            visitor.visit_expression(right, ctx);
        }
        Predicate::And { left, right } | Predicate::Or { left, right } => {
            visitor.visit_predicate(left, ctx);
            visitor.visit_predicate(right, ctx);
        }
        Predicate::Not { child } => visitor.visit_predicate(child, ctx),
        Predicate::Between { expr, low, high } => {
            visitor.visit_expression(expr, ctx);
            visitor.visit_expression(low, ctx);
            visitor.visit_expression(high, ctx);
        }
        Predicate::In { expr, target } => {
            visitor.visit_expression(expr, ctx);
            match target {
                InTarget::Values(values) => {
                    for value in values {
                        visitor.visit_expression(value, ctx);
                    }
                }
                InTarget::SubQuery(query) => visitor.visit_plan(query, ctx),
            }
        }
        Predicate::Exists { query } => visitor.visit_plan(query, ctx),
        Predicate::Like { expr, .. } | Predicate::IsNull { expr } => {
            visitor.visit_expression(expr, ctx)
        }
        Predicate::True | Predicate::False => {}
    }
}

pub fn default_visit_projection<F: ExpressionVisit + ?Sized>(
    visitor: &mut F,
    proj: &Projection,
    ctx: &mut F::Ctx,
) {
    match proj {
        Projection::Expr { expression, .. } => visitor.visit_expression(expression, ctx),
        Projection::Column { .. } | Projection::Star { .. } => {}
    }
}

pub fn default_visit_plan<F: ExpressionVisit + ?Sized>(
    visitor: &mut F,
    plan: &QueryPlan,
    ctx: &mut F::Ctx,
) {
    for proj in &plan.select {
        visitor.visit_projection(proj, ctx);
    }
    if let Some(pred) = &plan.r#where {
        visitor.visit_predicate(pred, ctx);
    }
    if let Some(exprs) = &plan.group_by {
        for expr in exprs {
            visitor.visit_expression(expr, ctx);
        }
    }
    if let Some(pred) = &plan.having {
        visitor.visit_predicate(pred, ctx);
    }
    if let Some(terms) = &plan.order_by {
        for term in terms {
            visitor.visit_expression(&term.expr, ctx);
        }
    }
    if let Some(joins) = &plan.joins {
        for join in joins {
            visitor.visit_predicate(&join.on, ctx);
        }
    }
    if let Some(ctes) = &plan.ctes {
        for cte in ctes {
            visitor.visit_plan(&cte.query, ctx);
        }
    }
}