Skip to main content

vlorql_core/optimizer/
pushdown.rs

1//! Predicate pushdown: move `WHERE` conjuncts closer to their source.
2//!
3//! Pushdown reduces the number of rows an upper operator has to process
4//! by evaluating a filter as early as possible. In this plan model the
5//! only relation that can carry its own `WHERE` is a
6//! [`CommonTableExpression`](crate::schema::CommonTableExpression) — the
7//! [`FromClause`](crate::schema::FromClause) is a bare table name with
8//! no room for a sub-filter. So [`PredicatePushdown`] targets CTEs:
9//!
10//! * The outer `WHERE` is split into independent `AND` conjuncts.
11//! * A conjunct that references **only** columns of a single CTE-backed
12//!   relation (by the CTE name or its `FROM`/join alias) is removed from
13//!   the outer `WHERE` and `AND`-ed into that CTE's own `WHERE`.
14//! * Every other conjunct — anything touching a base table, an
15//!   unqualified column, or more than one relation — stays where it is.
16//!
17//! The rule is deliberately conservative. When it cannot prove a
18//! conjunct belongs to exactly one CTE it leaves the conjunct in place,
19//! so the rewrite can only ever move a filter earlier, never change
20//! which rows survive it. Pushdown is applied recursively so a CTE that
21//! is itself defined in terms of other CTEs is optimized too.
22//!
23//! Outer joins are handled carefully: a filter on the null-supplying
24//! side of a `LEFT`/`RIGHT`/`FULL` join is **not** pushed down, because
25//! doing so would change the join's semantics (it would suppress the
26//! null-extended rows the outer join is meant to keep).
27
28use std::collections::{HashMap, HashSet};
29
30use crate::errors::VlorQLError;
31use crate::schema::{Expression, JoinType, Predicate, QueryPlan};
32
33use super::analyze::{combine_conjuncts, referenced_tables, split_conjuncts};
34use super::rules::PlanRewriter;
35use super::visitor::ExpressionFold;
36
37/// Pushes single-relation `WHERE` conjuncts down into the CTEs they
38/// filter.
39///
40/// See the [module documentation](super) for the exact rules and the
41/// limitations imposed by the plan model.
42#[derive(Debug, Clone, Copy, Default)]
43pub struct PredicatePushdown;
44
45impl PlanRewriter for PredicatePushdown {
46    fn rewrite(&self, plan: &QueryPlan) -> Result<QueryPlan, VlorQLError> {
47        Ok(push_plan(plan))
48    }
49}
50
51/// Applies pushdown to `plan` and, recursively, to every CTE it defines.
52fn push_plan(plan: &QueryPlan) -> QueryPlan {
53    // Optimize nested CTE bodies first (bottom-up), then push the outer
54    // query's conjuncts into them.
55    let ctes: Vec<_> = plan
56        .ctes
57        .as_ref()
58        .map(|ctes| {
59            ctes.iter()
60                .map(|cte| crate::schema::CommonTableExpression {
61                    name: cte.name.clone(),
62                    query: Box::new(push_plan(&cte.query)), recursive: false
63                })
64                .collect()
65        })
66        .unwrap_or_default();
67
68    let mut plan = QueryPlan {
69        ctes: if ctes.is_empty() { None } else { Some(ctes) },
70        ..plan.clone()
71    };
72
73    // Nothing to push without both a `WHERE` and at least one CTE.
74    let Some(where_clause) = plan.r#where.clone() else {
75        return plan;
76    };
77    if plan.ctes.as_ref().is_none_or(Vec::is_empty) {
78        return plan;
79    }
80
81    // Map every relation alias visible in this query to the CTE it
82    // resolves to. A relation whose table name is not a CTE (i.e. a base
83    // table) is intentionally absent, so conjuncts over it never move.
84    let cte_names: HashSet<&str> = plan
85        .ctes
86        .as_ref()
87        .into_iter()
88        .flatten()
89        .map(|cte| cte.name.as_str())
90        .collect();
91    let alias_to_cte = cte_relation_aliases(&plan, &cte_names);
92
93    // Aliases on the null-supplying side of an outer join must not
94    // receive pushed filters.
95    let protected = outer_join_protected_aliases(&plan);
96
97    let mut kept: Vec<Predicate> = Vec::new();
98    // CTE name -> conjuncts to inject into that CTE's WHERE.
99    let mut pushed: HashMap<String, Vec<Predicate>> = HashMap::new();
100
101    for conjunct in split_conjuncts(&where_clause) {
102        match single_cte_target(&conjunct, &alias_to_cte, &protected) {
103            Some(cte) => pushed.entry(cte).or_default().push(conjunct),
104            None => kept.push(conjunct),
105        }
106    }
107
108    if pushed.is_empty() {
109        return plan;
110    }
111
112    // Rebuild the outer WHERE from the conjuncts that stayed.
113    plan.r#where = combine_conjuncts(kept);
114
115    // Inject each pushed conjunct into its CTE's WHERE. For CTEs whose
116    // body's FROM clause references another CTE at the same level, try to
117    // cascade the pushdown further (multi-layer CTE support).
118    //
119    // We use a two-phase approach to avoid borrow conflicts:
120    // Phase 1: collect cascade targets (inner CTE → conditions).
121    // Phase 2: apply cascades and local injections.
122    if let Some(ctes) = plan.ctes.as_mut() {
123        let cte_names_set: HashSet<&str> = ctes.iter().map(|cte| cte.name.as_str()).collect();
124
125        // Phase 1: decide what goes where.
126        let mut cascade_targets: Vec<(String, Vec<Predicate>)> = Vec::new();
127        // Phase 1b: conditions that stay in the outer CTE, keyed by CTE name.
128        let mut local_injections: Vec<(String, Vec<Predicate>)> = Vec::new();
129
130        for cte in ctes.iter() {
131            let Some(conjuncts) = pushed.get(&cte.name) else {
132                continue;
133            };
134
135            let inner_table = cte.query.from.table.as_str();
136            if cte_names_set.contains(inner_table) {
137                let inner_alias = cte.query.from.alias.as_deref().unwrap_or(inner_table);
138
139                let mut cascade: Vec<Predicate> = Vec::new();
140                let mut local: Vec<Predicate> = Vec::new();
141
142                for conjunct in conjuncts {
143                    let translated = translate_qualifier(conjunct, &cte.name, inner_alias);
144
145                    let mut inner_alias_map = HashMap::new();
146                    inner_alias_map.insert(inner_alias.to_owned(), inner_table.to_owned());
147                    let inner_protected = outer_join_protected_aliases(&cte.query);
148
149                    if single_cte_target(&translated, &inner_alias_map, &inner_protected).is_some()
150                    {
151                        cascade.push(translated);
152                    } else {
153                        local.push(conjunct.clone());
154                    }
155                }
156
157                if !cascade.is_empty() {
158                    cascade_targets.push((inner_table.to_owned(), cascade));
159                }
160                if !local.is_empty() {
161                    local_injections.push((cte.name.clone(), local));
162                }
163            } else {
164                // Normal case: all conditions stay in this CTE.
165                local_injections.push((cte.name.clone(), conjuncts.clone()));
166            }
167        }
168
169        // Phase 2: apply injections.
170        for cte in ctes.iter_mut() {
171            // First, apply cascaded conditions from outer CTEs targeting this one.
172            if let Some((_, conds)) = cascade_targets.iter().find(|(name, _)| name == &cte.name) {
173                inject_into_cte(&mut cte.query, conds.clone());
174            }
175            // Then, apply local conditions (conditions that target this CTE directly).
176            if let Some((_, conds)) = local_injections.iter().find(|(name, _)| name == &cte.name) {
177                inject_into_cte(&mut cte.query, conds.clone());
178            }
179        }
180    }
181
182    plan
183}
184
185/// Rewrites the conjuncts to reference the CTE's own output columns and
186/// `AND`s them into the CTE body's `WHERE`.
187fn inject_into_cte(cte_query: &mut QueryPlan, conjuncts: Vec<Predicate>) {
188    // The pushed conjuncts are expressed against the *outer* qualifier
189    // (the CTE name or alias). Inside the CTE those columns are produced
190    // by its own `select`, so we strip the qualifier and let the CTE's
191    // validation re-resolve it against the CTE's own `from`.
192    let mut existing = cte_query
193        .r#where
194        .as_ref()
195        .map(split_conjuncts)
196        .unwrap_or_default();
197    for conjunct in conjuncts {
198        existing.push(strip_qualifiers(&conjunct));
199    }
200    cte_query.r#where = combine_conjuncts(existing);
201}
202
203/// Returns the CTE a conjunct can be pushed into, if it references
204/// exactly one CTE-backed relation and nothing else.
205///
206/// Returns `None` (keep the conjunct in place) when the conjunct:
207/// * references an unqualified column (`None` qualifier),
208/// * references more than one relation,
209/// * references a base table rather than a CTE, or
210/// * targets a relation on the null-supplying side of an outer join.
211fn single_cte_target(
212    conjunct: &Predicate,
213    alias_to_cte: &HashMap<String, String>,
214    protected: &HashSet<String>,
215) -> Option<String> {
216    let tables = referenced_tables(conjunct);
217
218    // Any unqualified column means we cannot attribute the conjunct to a
219    // single relation safely.
220    if tables.contains(&None) {
221        return None;
222    }
223    if tables.len() != 1 {
224        return None;
225    }
226
227    let alias = tables.into_iter().next().flatten()?;
228    if protected.contains(&alias) {
229        return None;
230    }
231    alias_to_cte.get(&alias).cloned()
232}
233
234/// Builds a map from every relation alias in `plan` (the `FROM` table
235/// and each join's right table) to the CTE it resolves to.
236///
237/// The key is the identifier a `WHERE` column would use to qualify
238/// itself: the alias when present, otherwise the table name. Only
239/// relations whose underlying table is a CTE are included.
240fn cte_relation_aliases(plan: &QueryPlan, cte_names: &HashSet<&str>) -> HashMap<String, String> {
241    let mut map = HashMap::new();
242
243    let mut record = |table: &str, alias: &Option<String>| {
244        if cte_names.contains(table) {
245            let key = alias.clone().unwrap_or_else(|| table.to_owned());
246            map.insert(key, table.to_owned());
247        }
248    };
249
250    record(&plan.from.table, &plan.from.alias);
251    if let Some(joins) = plan.joins.as_ref() {
252        for join in joins {
253            record(&join.right_table.table, &join.right_table.alias);
254        }
255    }
256
257    map
258}
259
260/// Collects the aliases (or table names) that sit on the null-supplying
261/// side of an outer join and therefore must not receive pushed filters.
262///
263/// For a `LEFT` join the right side is null-supplying; for a `RIGHT`
264/// join the left side (`FROM` and every preceding relation) is; a `FULL`
265/// join protects both. `INNER`/`CROSS` joins protect nothing.
266fn outer_join_protected_aliases(plan: &QueryPlan) -> HashSet<String> {
267    let mut protected = HashSet::new();
268    let Some(joins) = plan.joins.as_ref() else {
269        return protected;
270    };
271
272    let from_key = plan
273        .from
274        .alias
275        .clone()
276        .unwrap_or_else(|| plan.from.table.clone());
277
278    for (index, join) in joins.iter().enumerate() {
279        let right_key = join
280            .right_table
281            .alias
282            .clone()
283            .unwrap_or_else(|| join.right_table.table.clone());
284        match join.join_type {
285            JoinType::Left => {
286                protected.insert(right_key);
287            }
288            JoinType::Right => {
289                // Everything to the left of this join is null-supplying.
290                protected.insert(from_key.clone());
291                for earlier in joins.iter().take(index) {
292                    protected.insert(
293                        earlier
294                            .right_table
295                            .alias
296                            .clone()
297                            .unwrap_or_else(|| earlier.right_table.table.clone()),
298                    );
299                }
300            }
301            JoinType::Full => {
302                protected.insert(from_key.clone());
303                protected.insert(right_key);
304                for earlier in joins.iter().take(index) {
305                    protected.insert(
306                        earlier
307                            .right_table
308                            .alias
309                            .clone()
310                            .unwrap_or_else(|| earlier.right_table.table.clone()),
311                    );
312                }
313            }
314            JoinType::Inner | JoinType::Cross => {}
315        }
316    }
317
318    protected
319}
320
321/// Removes the table qualifier from every column reference in a
322/// predicate, so a conjunct written against the outer CTE alias resolves
323/// against the CTE body's own relations.
324fn strip_qualifiers(pred: &Predicate) -> Predicate {
325    QualifierStripper.fold_predicate(pred)
326}
327
328/// Replaces the table qualifier on every column reference in a predicate,
329/// translating from `from_qualifier` to `to_qualifier`. This is used for
330/// multi-layer CTE pushdown: when a condition qualified with the outer CTE
331/// name is pushed into a CTE whose FROM clause references another CTE, the
332/// qualifier is translated to the inner CTE's alias so the condition can be
333/// pushed further.
334fn translate_qualifier(pred: &Predicate, from_qualifier: &str, to_qualifier: &str) -> Predicate {
335    QualifierTranslator {
336        from: from_qualifier.to_owned(),
337        to: to_qualifier.to_owned(),
338    }
339    .fold_predicate(pred)
340}
341
342struct QualifierStripper;
343
344impl ExpressionFold for QualifierStripper {
345    fn fold_expression(&mut self, expr: &Expression) -> Expression {
346        match expr {
347            Expression::ColumnRef { column, .. } => Expression::ColumnRef {
348                table: None,
349                column: column.clone(),
350            },
351            other => super::visitor::default_fold_expression(self, other),
352        }
353    }
354}
355
356/// A fold that replaces a specific table qualifier with another.
357struct QualifierTranslator {
358    from: String,
359    to: String,
360}
361
362impl ExpressionFold for QualifierTranslator {
363    fn fold_expression(&mut self, expr: &Expression) -> Expression {
364        match expr {
365            Expression::ColumnRef {
366                table: Some(t),
367                column,
368            } if t == &self.from => Expression::ColumnRef {
369                table: Some(self.to.clone()),
370                column: column.clone(),
371            },
372            other => super::visitor::default_fold_expression(self, other),
373        }
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380    use crate::schema::{
381        CommonTableExpression, ComparisonOperator, DataType, Expression, FromClause, JoinClause,
382        Projection,
383    };
384
385    fn col(table: Option<&str>, column: &str) -> Expression {
386        Expression::ColumnRef {
387            table: table.map(str::to_owned),
388            column: column.to_owned(),
389        }
390    }
391
392    fn lit(value: i64) -> Expression {
393        Expression::Literal {
394            value: value.into(),
395            data_type: DataType::Int,
396        }
397    }
398
399    fn gt(left: Expression, right: Expression) -> Predicate {
400        Predicate::Comparison {
401            left,
402            op: ComparisonOperator::Gt,
403            right,
404        }
405    }
406
407    fn select_col(table: &str, column: &str) -> Projection {
408        Projection::Column {
409            table: Some(table.to_owned()),
410            column: column.to_owned(),
411            alias: None,
412        }
413    }
414
415    /// A CTE `active` selecting `id`/`amount` from a base table, wrapped
416    /// by an outer query that filters on both the CTE and a base table.
417    fn plan_with_cte(outer_where: Predicate) -> QueryPlan {
418        let cte = CommonTableExpression {
419            name: "active".to_owned(),
420            recursive: false,
421            query: Box::new(QueryPlan {
422                select: vec![select_col("orders", "id"), select_col("orders", "amount")],
423                from: FromClause {
424                    table: "orders".to_owned(),
425                    alias: None,
426                },
427                r#where: None,
428                group_by: None,
429                having: None,
430                order_by: None,
431                limit: None,
432                offset: None,
433                joins: None,
434                ctes: None,
435            distinct: false,
436            distinct_on: None,
437            set_operation: None,            }),
438        };
439        QueryPlan {
440            select: vec![select_col("active", "id")],
441            from: FromClause {
442                table: "active".to_owned(),
443                alias: None,
444            },
445            r#where: Some(outer_where),
446            group_by: None,
447            having: None,
448            order_by: None,
449            limit: None,
450            offset: None,
451            joins: None,
452            ctes: Some(vec![cte]),
453            distinct: false,
454            distinct_on: None,
455            set_operation: None,
456        }
457    }
458
459    #[test]
460    fn pushes_single_cte_conjunct_into_cte() {
461        // WHERE active.amount > 100
462        let plan = plan_with_cte(gt(col(Some("active"), "amount"), lit(100)));
463        let rewritten = PredicatePushdown.rewrite(&plan).unwrap();
464
465        // The only conjunct referenced just the CTE, so the outer WHERE
466        // becomes empty and the CTE gains the filter.
467        assert!(rewritten.r#where.is_none());
468        let cte_where = rewritten.ctes.as_ref().unwrap()[0]
469            .query
470            .r#where
471            .as_ref()
472            .expect("cte should have received the pushed filter");
473        // The qualifier is stripped inside the CTE.
474        assert_eq!(*cte_where, gt(col(None, "amount"), lit(100)),);
475    }
476
477    #[test]
478    fn keeps_multi_relation_conjunct_in_place() {
479        // WHERE active.amount > active.id  (single relation, still pushable)
480        // AND   active.id > 5
481        let pred = Predicate::And {
482            left: Box::new(gt(col(Some("active"), "amount"), lit(100))),
483            right: Box::new(gt(col(Some("base"), "x"), lit(1))),
484        };
485        let plan = plan_with_cte(pred);
486        let rewritten = PredicatePushdown.rewrite(&plan).unwrap();
487
488        // `base` is not a CTE, so that conjunct stays in the outer WHERE.
489        let outer = rewritten.r#where.as_ref().expect("outer where remains");
490        assert_eq!(split_conjuncts(outer).len(), 1);
491        assert!(rewritten.ctes.as_ref().unwrap()[0].query.r#where.is_some());
492    }
493
494    #[test]
495    fn does_not_push_onto_null_supplying_side_of_left_join() {
496        // Outer query LEFT JOINs the CTE; a filter on the CTE must not be
497        // pushed because that would drop null-extended rows.
498        let mut plan = plan_with_cte(gt(col(Some("active"), "amount"), lit(100)));
499        plan.from = FromClause {
500            table: "base".to_owned(),
501            alias: None,
502        };
503        plan.select = vec![select_col("base", "id")];
504        plan.joins = Some(vec![JoinClause {
505            join_type: JoinType::Left,
506            right_table: FromClause {
507                table: "active".to_owned(),
508                alias: None,
509            },
510            on: gt(col(Some("base"), "id"), col(Some("active"), "id")),
511        }]);
512
513        let rewritten = PredicatePushdown.rewrite(&plan).unwrap();
514        // Filter stayed in the outer WHERE; CTE untouched.
515        assert!(rewritten.r#where.is_some());
516        assert!(rewritten.ctes.as_ref().unwrap()[0].query.r#where.is_none());
517    }
518
519    #[test]
520    fn unqualified_conjunct_is_not_pushed() {
521        let plan = plan_with_cte(gt(col(None, "amount"), lit(100)));
522        let rewritten = PredicatePushdown.rewrite(&plan).unwrap();
523        assert!(rewritten.r#where.is_some());
524        assert!(rewritten.ctes.as_ref().unwrap()[0].query.r#where.is_none());
525    }
526}