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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! Predicate pushdown: move `WHERE` conjuncts closer to their source.
//!
//! Pushdown reduces the number of rows an upper operator has to process
//! by evaluating a filter as early as possible. In this plan model the
//! only relation that can carry its own `WHERE` is a
//! [`CommonTableExpression`](crate::schema::CommonTableExpression) — the
//! [`FromClause`](crate::schema::FromClause) is a bare table name with
//! no room for a sub-filter. So [`PredicatePushdown`] targets CTEs:
//!
//! * The outer `WHERE` is split into independent `AND` conjuncts.
//! * A conjunct that references **only** columns of a single CTE-backed
//!   relation (by the CTE name or its `FROM`/join alias) is removed from
//!   the outer `WHERE` and `AND`-ed into that CTE's own `WHERE`.
//! * Every other conjunct — anything touching a base table, an
//!   unqualified column, or more than one relation — stays where it is.
//!
//! The rule is deliberately conservative. When it cannot prove a
//! conjunct belongs to exactly one CTE it leaves the conjunct in place,
//! so the rewrite can only ever move a filter earlier, never change
//! which rows survive it. Pushdown is applied recursively so a CTE that
//! is itself defined in terms of other CTEs is optimized too.
//!
//! Outer joins are handled carefully: a filter on the null-supplying
//! side of a `LEFT`/`RIGHT`/`FULL` join is **not** pushed down, because
//! doing so would change the join's semantics (it would suppress the
//! null-extended rows the outer join is meant to keep).

use std::collections::{HashMap, HashSet};

use crate::errors::VlorQLError;
use crate::schema::{Expression, FromClause, JoinType, Predicate, QueryPlan};

use super::analyze::{combine_conjuncts, referenced_tables, split_conjuncts};
use super::rules::PlanRewriter;
use super::visitor::ExpressionFold;

/// Pushes single-relation `WHERE` conjuncts down into the CTEs they
/// filter.
///
/// See the [module documentation](super) for the exact rules and the
/// limitations imposed by the plan model.
///
/// # Examples
///
/// ```
/// use vlorql_core::optimizer::PredicatePushdown;
/// let pushdown = PredicatePushdown;
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct PredicatePushdown;

impl PlanRewriter for PredicatePushdown {
    /// Rewrites `plan` by pushing single-relation predicates down into CTEs.
    ///
    /// # Examples
    ///
    /// ```
    /// use vlorql_core::optimizer::PredicatePushdown;
    /// use vlorql_core::optimizer::PlanRewriter;
    /// use vlorql_core::schema::{FromClause, Projection, QueryPlan};
    ///
    /// let pushdown = PredicatePushdown;
    /// let plan = QueryPlan {
    ///     select: vec![Projection::Star { table: None }],
    ///     from: FromClause::table("t".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,
    /// };
    /// let result = pushdown.rewrite(&plan);
    /// assert!(result.is_ok());
    /// ```
    fn rewrite(&self, plan: &QueryPlan) -> Result<QueryPlan, VlorQLError> {
        Ok(push_plan(plan))
    }
}

/// Applies pushdown to `plan` and, recursively, to every CTE it defines.
fn push_plan(plan: &QueryPlan) -> QueryPlan {
    // Optimize nested CTE bodies first (bottom-up), then push the outer
    // query's conjuncts into them.
    let ctes: Vec<_> = plan
        .ctes
        .as_ref()
        .map(|ctes| {
            ctes.iter()
                .map(|cte| crate::schema::CommonTableExpression {
                    name: cte.name.clone(),
                    query: Box::new(push_plan(&cte.query)),
                    recursive: false,
                })
                .collect()
        })
        .unwrap_or_default();

    let mut plan = QueryPlan {
        ctes: if ctes.is_empty() { None } else { Some(ctes) },
        ..plan.clone()
    };

    // Nothing to push without both a `WHERE` and at least one CTE.
    let Some(where_clause) = plan.r#where.clone() else {
        return plan;
    };
    if plan.ctes.as_ref().is_none_or(Vec::is_empty) {
        return plan;
    }

    // Map every relation alias visible in this query to the CTE it
    // resolves to. A relation whose table name is not a CTE (i.e. a base
    // table) is intentionally absent, so conjuncts over it never move.
    let cte_names: HashSet<&str> = plan
        .ctes
        .as_ref()
        .into_iter()
        .flatten()
        .map(|cte| cte.name.as_str())
        .collect();
    let alias_to_cte = cte_relation_aliases(&plan, &cte_names);

    // Aliases on the null-supplying side of an outer join must not
    // receive pushed filters.
    let protected = outer_join_protected_aliases(&plan);

    let mut kept: Vec<Predicate> = Vec::new();
    // CTE name -> conjuncts to inject into that CTE's WHERE.
    let mut pushed: HashMap<String, Vec<Predicate>> = HashMap::new();

    for conjunct in split_conjuncts(&where_clause) {
        match single_cte_target(&conjunct, &alias_to_cte, &protected) {
            Some(cte) => pushed.entry(cte).or_default().push(conjunct),
            None => kept.push(conjunct),
        }
    }

    if pushed.is_empty() {
        return plan;
    }

    // Rebuild the outer WHERE from the conjuncts that stayed.
    plan.r#where = combine_conjuncts(kept);

    // Inject each pushed conjunct into its CTE's WHERE. For CTEs whose
    // body's FROM clause references another CTE at the same level, try to
    // cascade the pushdown further (multi-layer CTE support).
    //
    // We use a two-phase approach to avoid borrow conflicts:
    // Phase 1: collect cascade targets (inner CTE → conditions).
    // Phase 2: apply cascades and local injections.
    if let Some(ctes) = plan.ctes.as_mut() {
        let cte_names_set: HashSet<&str> = ctes.iter().map(|cte| cte.name.as_str()).collect();

        // Phase 1: decide what goes where.
        let mut cascade_targets: Vec<(String, Vec<Predicate>)> = Vec::new();
        // Phase 1b: conditions that stay in the outer CTE, keyed by CTE name.
        let mut local_injections: Vec<(String, Vec<Predicate>)> = Vec::new();

        for cte in ctes.iter() {
            let Some(conjuncts) = pushed.get(&cte.name) else {
                continue;
            };

            let inner_table = cte.query.from.table_name();
            if inner_table.is_none() {
                // Subquery in FROM — cannot cascade; keep all conditions local.
                local_injections.push((cte.name.clone(), conjuncts.clone()));
                continue;
            }
            let inner_table = inner_table.unwrap();
            if cte_names_set.contains(inner_table) {
                let inner_alias = cte
                    .query
                    .from
                    .alias()
                    .unwrap_or_else(|| inner_table.to_owned());

                let mut cascade: Vec<Predicate> = Vec::new();
                let mut local: Vec<Predicate> = Vec::new();

                for conjunct in conjuncts {
                    let translated = translate_qualifier(conjunct, &cte.name, &inner_alias);

                    let mut inner_alias_map = HashMap::new();
                    inner_alias_map.insert(inner_alias.to_owned(), inner_table.to_owned());
                    let inner_protected = outer_join_protected_aliases(&cte.query);

                    if single_cte_target(&translated, &inner_alias_map, &inner_protected).is_some()
                    {
                        cascade.push(translated);
                    } else {
                        local.push(conjunct.clone());
                    }
                }

                if !cascade.is_empty() {
                    cascade_targets.push((inner_table.to_owned(), cascade));
                }
                if !local.is_empty() {
                    local_injections.push((cte.name.clone(), local));
                }
            } else {
                // Normal case: all conditions stay in this CTE.
                local_injections.push((cte.name.clone(), conjuncts.clone()));
            }
        }

        // Phase 2: apply injections.
        for cte in ctes.iter_mut() {
            // First, apply cascaded conditions from outer CTEs targeting this one.
            if let Some((_, conds)) = cascade_targets.iter().find(|(name, _)| name == &cte.name) {
                inject_into_cte(&mut cte.query, conds.clone());
            }
            // Then, apply local conditions (conditions that target this CTE directly).
            if let Some((_, conds)) = local_injections.iter().find(|(name, _)| name == &cte.name) {
                inject_into_cte(&mut cte.query, conds.clone());
            }
        }
    }

    plan
}

/// Rewrites the conjuncts to reference the CTE's own output columns and
/// `AND`s them into the CTE body's `WHERE`.
fn inject_into_cte(cte_query: &mut QueryPlan, conjuncts: Vec<Predicate>) {
    // The pushed conjuncts are expressed against the *outer* qualifier
    // (the CTE name or alias). Inside the CTE those columns are produced
    // by its own `select`, so we strip the qualifier and let the CTE's
    // validation re-resolve it against the CTE's own `from`.
    let mut existing = cte_query
        .r#where
        .as_ref()
        .map(split_conjuncts)
        .unwrap_or_default();
    for conjunct in conjuncts {
        existing.push(strip_qualifiers(&conjunct));
    }
    cte_query.r#where = combine_conjuncts(existing);
}

/// Returns the CTE a conjunct can be pushed into, if it references
/// exactly one CTE-backed relation and nothing else.
///
/// Returns `None` (keep the conjunct in place) when the conjunct:
/// * references an unqualified column (`None` qualifier),
/// * references more than one relation,
/// * references a base table rather than a CTE, or
/// * targets a relation on the null-supplying side of an outer join.
fn single_cte_target(
    conjunct: &Predicate,
    alias_to_cte: &HashMap<String, String>,
    protected: &HashSet<String>,
) -> Option<String> {
    let tables = referenced_tables(conjunct);

    // Any unqualified column means we cannot attribute the conjunct to a
    // single relation safely.
    if tables.contains(&None) {
        return None;
    }
    if tables.len() != 1 {
        return None;
    }

    let alias = tables.into_iter().next().flatten()?;
    if protected.contains(&alias) {
        return None;
    }
    alias_to_cte.get(&alias).cloned()
}

/// Builds a map from every relation alias in `plan` (the `FROM` table
/// and each join's right table) to the CTE it resolves to.
///
/// The key is the identifier a `WHERE` column would use to qualify
/// itself: the alias when present, otherwise the table name. Only
/// relations whose underlying table is a CTE are included.
fn cte_relation_aliases(plan: &QueryPlan, cte_names: &HashSet<&str>) -> HashMap<String, String> {
    let mut map = HashMap::new();

    let mut record = |table: &str, alias: Option<&str>| {
        if cte_names.contains(table) {
            let key = alias.unwrap_or(table).to_owned();
            map.insert(key, table.to_owned());
        }
    };

    if let Some(table) = plan.from.table_name() {
        record(table, plan.from.alias().as_deref());
    }
    if let Some(joins) = plan.joins.as_ref() {
        for join in joins {
            if let Some(table) = join.right_table.table_name() {
                record(table, join.right_table.alias().as_deref());
            }
        }
    }

    map
}

/// Collects the aliases (or table names) that sit on the null-supplying
/// side of an outer join and therefore must not receive pushed filters.
///
/// For a `LEFT` join the right side is null-supplying; for a `RIGHT`
/// join the left side (`FROM` and every preceding relation) is; a `FULL`
/// join protects both. `INNER`/`CROSS` joins protect nothing.
fn outer_join_protected_aliases(plan: &QueryPlan) -> HashSet<String> {
    let mut protected = HashSet::new();
    let Some(joins) = plan.joins.as_ref() else {
        return protected;
    };

    let from_key = match &plan.from {
        FromClause::Table { table, alias } => alias.clone().unwrap_or_else(|| table.clone()),
        FromClause::Subquery { alias, .. } => {
            alias.clone().unwrap_or_else(|| "<subquery>".to_owned())
        }
    };

    for (index, join) in joins.iter().enumerate() {
        let right_key = match &join.right_table {
            FromClause::Table { table, alias } => alias.clone().unwrap_or_else(|| table.clone()),
            FromClause::Subquery { alias, .. } => {
                alias.clone().unwrap_or_else(|| "<subquery>".to_owned())
            }
        };
        match join.join_type {
            JoinType::Left => {
                protected.insert(right_key);
            }
            JoinType::Right => {
                // Everything to the left of this join is null-supplying.
                protected.insert(from_key.clone());
                for earlier in joins.iter().take(index) {
                    protected.insert(match &earlier.right_table {
                        FromClause::Table { table, alias } => {
                            alias.clone().unwrap_or_else(|| table.clone())
                        }
                        FromClause::Subquery { alias, .. } => {
                            alias.clone().unwrap_or_else(|| "<subquery>".to_owned())
                        }
                    });
                }
            }
            JoinType::Full => {
                protected.insert(from_key.clone());
                protected.insert(right_key);
                for earlier in joins.iter().take(index) {
                    protected.insert(match &earlier.right_table {
                        FromClause::Table { table, alias } => {
                            alias.clone().unwrap_or_else(|| table.clone())
                        }
                        FromClause::Subquery { alias, .. } => {
                            alias.clone().unwrap_or_else(|| "<subquery>".to_owned())
                        }
                    });
                }
            }
            JoinType::Inner | JoinType::Cross => {}
        }
    }

    protected
}

/// Removes the table qualifier from every column reference in a
/// predicate, so a conjunct written against the outer CTE alias resolves
/// against the CTE body's own relations.
fn strip_qualifiers(pred: &Predicate) -> Predicate {
    QualifierStripper.fold_predicate(pred)
}

/// Replaces the table qualifier on every column reference in a predicate,
/// translating from `from_qualifier` to `to_qualifier`. This is used for
/// multi-layer CTE pushdown: when a condition qualified with the outer CTE
/// name is pushed into a CTE whose FROM clause references another CTE, the
/// qualifier is translated to the inner CTE's alias so the condition can be
/// pushed further.
fn translate_qualifier(pred: &Predicate, from_qualifier: &str, to_qualifier: &str) -> Predicate {
    QualifierTranslator {
        from: from_qualifier.to_owned(),
        to: to_qualifier.to_owned(),
    }
    .fold_predicate(pred)
}

struct QualifierStripper;

impl ExpressionFold for QualifierStripper {
    fn fold_expression(&mut self, expr: &Expression) -> Expression {
        match expr {
            Expression::ColumnRef { column, .. } => Expression::ColumnRef {
                table: None,
                column: column.clone(),
            },
            other => super::visitor::default_fold_expression(self, other),
        }
    }
}

/// A fold that replaces a specific table qualifier with another.
struct QualifierTranslator {
    from: String,
    to: String,
}

impl ExpressionFold for QualifierTranslator {
    fn fold_expression(&mut self, expr: &Expression) -> Expression {
        match expr {
            Expression::ColumnRef {
                table: Some(t),
                column,
            } if t == &self.from => Expression::ColumnRef {
                table: Some(self.to.clone()),
                column: column.clone(),
            },
            other => super::visitor::default_fold_expression(self, other),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::{
        CommonTableExpression, ComparisonOperator, DataType, Expression, FromClause, JoinClause,
        Projection,
    };

    fn col(table: Option<&str>, column: &str) -> Expression {
        Expression::ColumnRef {
            table: table.map(str::to_owned),
            column: column.to_owned(),
        }
    }

    fn lit(value: i64) -> Expression {
        Expression::Literal {
            value: value.into(),
            data_type: DataType::Int,
        }
    }

    fn gt(left: Expression, right: Expression) -> Predicate {
        Predicate::Comparison {
            left: Box::new(left),
            op: ComparisonOperator::Gt,
            right: Box::new(right),
        }
    }

    fn select_col(table: &str, column: &str) -> Projection {
        Projection::Column {
            table: Some(table.to_owned()),
            column: column.to_owned(),
            alias: None,
        }
    }

    /// A CTE `active` selecting `id`/`amount` from a base table, wrapped
    /// by an outer query that filters on both the CTE and a base table.
    fn plan_with_cte(outer_where: Predicate) -> QueryPlan {
        let cte = CommonTableExpression {
            name: "active".to_owned(),
            recursive: false,
            query: Box::new(QueryPlan {
                select: vec![select_col("orders", "id"), select_col("orders", "amount")],
                from: FromClause::table("orders".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,
            }),
        };
        QueryPlan {
            select: vec![select_col("active", "id")],
            from: FromClause::table("active".to_owned(), None),
            r#where: Some(outer_where),
            group_by: None,
            having: None,
            order_by: None,
            limit: None,
            offset: None,
            joins: None,
            ctes: Some(vec![cte]),
            distinct: false,
            distinct_on: None,
            set_operation: None,
        }
    }

    #[test]
    fn pushes_single_cte_conjunct_into_cte() {
        // WHERE active.amount > 100
        let plan = plan_with_cte(gt(col(Some("active"), "amount"), lit(100)));
        let rewritten = PredicatePushdown.rewrite(&plan).unwrap();

        // The only conjunct referenced just the CTE, so the outer WHERE
        // becomes empty and the CTE gains the filter.
        assert!(rewritten.r#where.is_none());
        let cte_where = rewritten.ctes.as_ref().unwrap()[0]
            .query
            .r#where
            .as_ref()
            .expect("cte should have received the pushed filter");
        // The qualifier is stripped inside the CTE.
        assert_eq!(*cte_where, gt(col(None, "amount"), lit(100)),);
    }

    #[test]
    fn keeps_multi_relation_conjunct_in_place() {
        // WHERE active.amount > active.id  (single relation, still pushable)
        // AND   active.id > 5
        let pred = Predicate::And {
            left: Box::new(gt(col(Some("active"), "amount"), lit(100))),
            right: Box::new(gt(col(Some("base"), "x"), lit(1))),
        };
        let plan = plan_with_cte(pred);
        let rewritten = PredicatePushdown.rewrite(&plan).unwrap();

        // `base` is not a CTE, so that conjunct stays in the outer WHERE.
        let outer = rewritten.r#where.as_ref().expect("outer where remains");
        assert_eq!(split_conjuncts(outer).len(), 1);
        assert!(rewritten.ctes.as_ref().unwrap()[0].query.r#where.is_some());
    }

    #[test]
    fn does_not_push_onto_null_supplying_side_of_left_join() {
        // Outer query LEFT JOINs the CTE; a filter on the CTE must not be
        // pushed because that would drop null-extended rows.
        let mut plan = plan_with_cte(gt(col(Some("active"), "amount"), lit(100)));
        plan.from = FromClause::table("base".to_owned(), None);
        plan.select = vec![select_col("base", "id")];
        plan.joins = Some(vec![JoinClause {
            join_type: JoinType::Left,
            right_table: FromClause::table("active".to_owned(), None),
            on: gt(col(Some("base"), "id"), col(Some("active"), "id")),
        }]);

        let rewritten = PredicatePushdown.rewrite(&plan).unwrap();
        // Filter stayed in the outer WHERE; CTE untouched.
        assert!(rewritten.r#where.is_some());
        assert!(rewritten.ctes.as_ref().unwrap()[0].query.r#where.is_none());
    }

    #[test]
    fn unqualified_conjunct_is_not_pushed() {
        let plan = plan_with_cte(gt(col(None, "amount"), lit(100)));
        let rewritten = PredicatePushdown.rewrite(&plan).unwrap();
        assert!(rewritten.r#where.is_some());
        assert!(rewritten.ctes.as_ref().unwrap()[0].query.r#where.is_none());
    }
}