Skip to main content

nedb_engine/
sqlpush.rs

1// SPDX-License-Identifier: BUSL-1.1
2// SPDX-FileCopyrightText: © 2026 INTERCHAINED LLC × Claude Sonnet 4.6
3
4//! Predicate pushdown — conservative, and narrower than the phrase sounds.
5//!
6//! # What this is NOT
7//!
8//! It is not a rewrite engine that turns
9//!
10//! ```text
11//!   Filter(Join(A, B))   ->   Join(Filter(A), B)
12//! ```
13//!
14//! on the basis of column ownership. That transformation is unsound in
15//! general, and the specific way it fails is already pinned in the semantic
16//! corpus:
17//!
18//! ```text
19//!   LEFT JOIN ... WHERE d.dname = 'eng'        2 rows
20//!   LEFT JOIN ... ON ... AND d.dname = 'eng'   5 rows
21//! ```
22//!
23//! Moving a predicate from `WHERE` to the join's `ON` changes which rows get
24//! NULL-synthesised, so it changes the answer. Three-valued logic is what
25//! makes it dangerous: the outer rows survive the join and are then dropped by
26//! `WHERE` because a comparison against the synthesised NULL is UNKNOWN.
27//!
28//! # What it IS: a pre-filter on a relation that is never NULL-synthesised
29//!
30//! A qualifying conjunct is COPIED to run against its own relation before the
31//! join. The `WHERE` clause is left untouched and still runs after the join.
32//!
33//! Retaining the original is necessary but **not sufficient**, and getting
34//! that wrong is instructive. The first version of this module argued that a
35//! copy-not-move was safe for every join type, reasoning:
36//!
37//! > Removing rows from a relation can only create MORE unmatched rows on the
38//! > other side; those get NULL-synthesised, and the retained `WHERE` then
39//! > evaluates the same predicate against a NULL, yields UNKNOWN, and drops
40//! > them.
41//!
42//! That is wrong, and the semantic corpus caught it immediately. A predicate
43//! can be SATISFIED by a synthesised NULL:
44//!
45//! ```text
46//!   SELECT e.name FROM emp e LEFT JOIN dept d ON e.dept_id = d.id
47//!    WHERE d.dname IS NULL
48//! ```
49//!
50//! No `dept` row has a NULL `dname`, so pre-filtering `dept` empties it
51//! entirely; every `emp` row then becomes unmatched, gets NULL-extended, and
52//! `IS NULL` is TRUE for all of them. The answer went from 1 row to 5.
53//!
54//! So the real condition is about NULL SYNTHESIS, not about retention:
55//!
56//! > A predicate may be pre-applied to relation `R` only if `R` is never
57//! > NULL-synthesised in this query's output.
58//!
59//! When `R` cannot be synthesised, every output row carries a real `R` row, so
60//! the retained `WHERE` sees exactly the values the pre-filter saw, and the
61//! pre-filter can only remove rows the `WHERE` would have removed. When `R`
62//! CAN be synthesised, removing a row can manufacture an outer row whose
63//! values differ from anything the pre-filter examined — and whether that row
64//! survives depends on the predicate, which is not something to guess at.
65//!
66//! [`nullable_bindings`] computes that set:
67//!
68//! * a join's right binding is nullable when the join is `LEFT` or `FULL`;
69//! * every binding accumulated so far becomes nullable when a LATER join is
70//!   `RIGHT` or `FULL`, because those synthesise NULLs across the whole left
71//!   side — including the `FROM` relation.
72//!
73//! An `INNER` (or `CROSS`) join synthesises nothing, which is why an
74//! all-inner query can push everything and is the common case.
75//!
76//! # Refusals are recorded, not silent
77//!
78//! When a conjunct cannot be pushed, the reason is kept on the plan
79//! (`Filter retained above join: ...`). An optimiser that silently declines is
80//! impossible to audit — you cannot tell "correctly refused" from "forgot to
81//! look". The reasons are inspectable in tests today and are the natural thing
82//! for `EXPLAIN` to show later.
83
84use crate::sqlselect::Expr;
85use std::collections::HashMap;
86
87/// Functions safe to evaluate while pre-filtering.
88///
89/// An allowlist, for the same fail-safe reason as the hash-join key planner:
90/// a volatile function added to the evaluator and not added here is REFUSED
91/// rather than silently evaluated twice with different answers.
92const PURE_FUNCS: &[&str] = &[
93    "lower", "upper", "length", "char_length", "character_length", "coalesce",
94    "nullif", "int2", "int4", "int8", "text", "quote_ident", "format_type",
95    "array_to_string", "current_schema", "current_database", "current_catalog",
96    "current_user", "session_user", "user", "version", "pg_get_userbyid",
97    "pg_table_is_visible", "pg_type_is_visible", "pg_function_is_visible",
98    "pg_encoding_to_char", "pg_get_expr", "pg_get_indexdef",
99    "pg_get_constraintdef",
100];
101
102/// What the planner decided, per relation, plus why it declined the rest.
103#[derive(Debug, Clone, Default)]
104pub struct Pushdown {
105    /// binding (lowercased) -> conjuncts to pre-filter that relation with.
106    pub per_binding: HashMap<String, Vec<Expr>>,
107    /// Human-readable refusal reasons, in the order the conjuncts appeared.
108    pub refusals: Vec<String>,
109}
110
111impl Pushdown {
112    pub fn for_binding(&self, binding: &str) -> Option<&Vec<Expr>> {
113        self.per_binding.get(&binding.to_ascii_lowercase())
114    }
115
116    pub fn pushed_count(&self) -> usize {
117        self.per_binding.values().map(|v| v.len()).sum()
118    }
119}
120
121/// Split an expression into top-level `AND` conjuncts.
122///
123/// Only `AND` may be split. An `OR` branch constrains the row as a whole, so
124/// pre-filtering on one side of it would drop rows the predicate accepts.
125fn conjuncts<'a>(e: &'a Expr, out: &mut Vec<&'a Expr>) {
126    match e {
127        Expr::Binary { op, left, right } if op == "AND" => {
128            conjuncts(left, out);
129            conjuncts(right, out);
130        }
131        other => out.push(other),
132    }
133}
134
135/// Which bindings a predicate reads, and whether it is safe to evaluate early.
136enum Reads {
137    /// Exactly one binding, and nothing that prevents early evaluation.
138    One(String),
139    /// Reads no column at all — a constant. Pre-filtering on it would be
140    /// pointless (it is the same answer for every row) so it is left alone.
141    Constant,
142    Refused(&'static str),
143}
144
145fn reads(e: &Expr, known: &[String]) -> Reads {
146    let mut seen: Vec<String> = vec![];
147    let mut why: Option<&'static str> = None;
148    walk(e, known, &mut seen, &mut why);
149    if let Some(w) = why {
150        return Reads::Refused(w);
151    }
152    match seen.len() {
153        0 => Reads::Constant,
154        1 => Reads::One(seen.pop().expect("one")),
155        _ => Reads::Refused("spans more than one relation"),
156    }
157}
158
159fn walk(e: &Expr, known: &[String], seen: &mut Vec<String>, why: &mut Option<&'static str>) {
160    match e {
161        Expr::Column { qual, .. } => match qual {
162            Some(q) => {
163                let lower = q.to_ascii_lowercase();
164                if !known.iter().any(|b| b.eq_ignore_ascii_case(q)) {
165                    // An unknown binding is a query error, reported with a
166                    // better message by the evaluator than by the planner.
167                    *why = Some("references an unknown relation");
168                } else if !seen.contains(&lower) {
169                    seen.push(lower);
170                }
171            }
172            // A bare column resolves by scanning bindings in order AT
173            // EVALUATION TIME, so it cannot be attributed to one relation
174            // here. Guessing would pre-filter the wrong relation.
175            None => *why = Some("unqualified column cannot be attributed to a relation"),
176        },
177        Expr::Literal(_) => {}
178        Expr::Star | Expr::QualifiedStar(_) => *why = Some("contains `*`"),
179        Expr::Func { name, args } => {
180            if !PURE_FUNCS.iter().any(|f| f.eq_ignore_ascii_case(name)) {
181                *why = Some("calls a function not known to be pure");
182            }
183            for a in args {
184                walk(a, known, seen, why);
185            }
186        }
187        Expr::Case { operand, whens, else_ } => {
188            if let Some(o) = operand {
189                walk(o, known, seen, why);
190            }
191            for (w, t) in whens {
192                walk(w, known, seen, why);
193                walk(t, known, seen, why);
194            }
195            if let Some(x) = else_ {
196                walk(x, known, seen, why);
197            }
198        }
199        Expr::Binary { left, right, .. } => {
200            walk(left, known, seen, why);
201            walk(right, known, seen, why);
202        }
203        Expr::Unary { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
204            walk(expr, known, seen, why)
205        }
206        Expr::InList { expr, list, .. } => {
207            walk(expr, known, seen, why);
208            for i in list {
209                walk(i, known, seen, why);
210            }
211        }
212    }
213}
214
215/// The bindings this query can NULL-synthesise.
216///
217/// Pre-filtering any of these is refused: removing a row can manufacture an
218/// outer row carrying NULLs the pre-filter never examined, and whether that
219/// row survives the retained `WHERE` depends on the predicate.
220pub fn nullable_bindings(sel: &crate::sqlselect::Select) -> Vec<String> {
221    use crate::sqlselect::JoinKind;
222    let mut out: Vec<String> = vec![];
223    let mut accumulated: Vec<String> = sel
224        .from
225        .iter()
226        .map(|t| t.binding().to_ascii_lowercase())
227        .collect();
228
229    for j in &sel.joins {
230        let rb = j.table.binding().to_ascii_lowercase();
231        // LEFT/FULL: the RIGHT side is synthesised when a left row has no
232        // partner.
233        if matches!(j.kind, JoinKind::Left | JoinKind::Full) && !out.contains(&rb) {
234            out.push(rb.clone());
235        }
236        // RIGHT/FULL: the whole accumulated LEFT side is synthesised when a
237        // right row has no partner — which retroactively makes every earlier
238        // binding nullable, the `FROM` relation included.
239        if matches!(j.kind, JoinKind::Right | JoinKind::Full) {
240            for a in &accumulated {
241                if !out.contains(a) {
242                    out.push(a.clone());
243                }
244            }
245        }
246        accumulated.push(rb);
247    }
248    out
249}
250
251/// Decide which `WHERE` conjuncts may be pre-applied to which relation.
252///
253/// `bindings` must list every relation in the query. The returned predicates
254/// are COPIES — the caller keeps evaluating the original `WHERE` after the
255/// join, which is what makes this safe.
256pub fn plan(
257    where_: Option<&Expr>,
258    bindings: &[String],
259    nullable: &[String],
260) -> Pushdown {
261    let mut out = Pushdown::default();
262    let Some(w) = where_ else { return out };
263
264    // With a single relation there is no join to push below, and the filter
265    // already runs directly over it. Pushing would only duplicate the work.
266    if bindings.len() < 2 {
267        return out;
268    }
269
270    let mut parts = vec![];
271    conjuncts(w, &mut parts);
272    for p in parts {
273        match reads(p, bindings) {
274            Reads::One(b) if nullable.iter().any(|n| n.eq_ignore_ascii_case(&b)) => {
275                // Oracle's wording, because it names the actual hazard rather
276                // than restating the rule.
277                out.refusals.push(format!(
278                    "Filter retained above join: predicate references nullable \
279                     side of an outer join ({b})"
280                ));
281            }
282            Reads::One(b) => out.per_binding.entry(b).or_default().push(p.clone()),
283            Reads::Constant => out
284                .refusals
285                .push("Filter retained above join: predicate reads no column".into()),
286            Reads::Refused(why) => out
287                .refusals
288                .push(format!("Filter retained above join: {why}")),
289        }
290    }
291    out
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297    use crate::sqlselect::parse;
298
299    fn plan_for(sql: &str) -> Pushdown {
300        let sel = parse(sql).expect("parses");
301        let mut b = vec![];
302        if let Some(f) = &sel.from {
303            b.push(f.binding());
304        }
305        for j in &sel.joins {
306            b.push(j.table.binding());
307        }
308        let nullable = nullable_bindings(&sel);
309        plan(sel.where_.as_ref(), &b, &nullable)
310    }
311
312    #[test]
313    fn a_single_relation_predicate_is_pushed_to_that_relation() {
314        let p = plan_for("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE a.v > 5");
315        assert_eq!(p.pushed_count(), 1);
316        assert_eq!(p.for_binding("a").map(|v| v.len()), Some(1));
317        assert!(p.for_binding("b").is_none());
318        assert!(p.refusals.is_empty(), "{:?}", p.refusals);
319    }
320
321    #[test]
322    fn conjuncts_are_pushed_to_their_own_relations_independently() {
323        let p = plan_for(
324            "SELECT 1 FROM a JOIN b ON a.x = b.x WHERE a.v > 5 AND b.w < 2 AND a.z = 'q'",
325        );
326        assert_eq!(p.pushed_count(), 3);
327        assert_eq!(p.for_binding("a").map(|v| v.len()), Some(2));
328        assert_eq!(p.for_binding("b").map(|v| v.len()), Some(1));
329    }
330
331    #[test]
332    fn a_predicate_on_the_nullable_side_of_a_left_join_is_REFUSED() {
333        // This test asserted the opposite in the first version of this module,
334        // and it was wrong. `WHERE d.dname IS NULL` over a LEFT JOIN is
335        // SATISFIED by the synthesised NULL, so emptying the right relation
336        // manufactures outer rows that pass the retained WHERE — 1 row became
337        // 5. The semantic corpus caught it.
338        let p = plan_for("SELECT 1 FROM a LEFT JOIN b ON a.x = b.x WHERE b.w = 5");
339        assert_eq!(p.pushed_count(), 0);
340        assert!(p.refusals[0].contains("nullable side"), "{:?}", p.refusals);
341    }
342
343    #[test]
344    fn the_non_nullable_side_of_a_left_join_is_still_pushed() {
345        // `a` is never synthesised by a LEFT JOIN, so its own predicates are
346        // safe. This is the case that matters in practice — a selective filter
347        // on the driving relation.
348        let p = plan_for("SELECT 1 FROM a LEFT JOIN b ON a.x = b.x WHERE a.v > 5");
349        assert_eq!(p.for_binding("a").map(|v| v.len()), Some(1));
350        assert!(p.refusals.is_empty(), "{:?}", p.refusals);
351    }
352
353    #[test]
354    fn a_right_join_makes_the_LEFT_side_nullable_including_the_from_relation() {
355        let p = plan_for("SELECT 1 FROM a RIGHT JOIN b ON a.x = b.x WHERE a.v > 5");
356        assert_eq!(p.pushed_count(), 0, "a is synthesised by the RIGHT join");
357        assert!(p.refusals[0].contains("nullable side"), "{:?}", p.refusals);
358        // The right side of a RIGHT join is never synthesised.
359        let p = plan_for("SELECT 1 FROM a RIGHT JOIN b ON a.x = b.x WHERE b.w > 5");
360        assert_eq!(p.for_binding("b").map(|v| v.len()), Some(1));
361    }
362
363    #[test]
364    fn a_full_join_makes_both_sides_nullable() {
365        for w in ["a.v > 5", "b.w > 5"] {
366            let p = plan_for(&format!("SELECT 1 FROM a FULL JOIN b ON a.x = b.x WHERE {w}"));
367            assert_eq!(p.pushed_count(), 0, "{w}");
368        }
369    }
370
371    #[test]
372    fn a_later_right_join_retroactively_protects_earlier_relations() {
373        // `a` and `b` are fine on their own, but the RIGHT join to `c`
374        // synthesises NULLs across BOTH of them — so neither may be
375        // pre-filtered. Missing this would be a wrong answer that only shows
376        // up in three-relation queries.
377        let sel = parse(
378            "SELECT 1 FROM a JOIN b ON a.x = b.x RIGHT JOIN c ON b.y = c.y \
379             WHERE a.v > 1 AND b.w > 1 AND c.z > 1",
380        )
381        .expect("parses");
382        let nullable = nullable_bindings(&sel);
383        assert!(nullable.contains(&"a".to_string()), "{nullable:?}");
384        assert!(nullable.contains(&"b".to_string()), "{nullable:?}");
385        assert!(!nullable.contains(&"c".to_string()), "c is never synthesised");
386
387        let p = plan_for(
388            "SELECT 1 FROM a JOIN b ON a.x = b.x RIGHT JOIN c ON b.y = c.y \
389             WHERE a.v > 1 AND b.w > 1 AND c.z > 1",
390        );
391        assert_eq!(p.pushed_count(), 1, "only c");
392        assert_eq!(p.for_binding("c").map(|v| v.len()), Some(1));
393        assert_eq!(p.refusals.len(), 2);
394    }
395
396    #[test]
397    fn an_all_inner_query_can_push_everything() {
398        let p = plan_for(
399            "SELECT 1 FROM a JOIN b ON a.x = b.x JOIN c ON b.y = c.y \
400             WHERE a.v > 1 AND b.w > 1 AND c.z > 1",
401        );
402        assert_eq!(p.pushed_count(), 3);
403        assert!(p.refusals.is_empty());
404        assert!(nullable_bindings(&parse(
405            "SELECT 1 FROM a JOIN b ON a.x = b.x JOIN c ON b.y = c.y"
406        ).unwrap()).is_empty());
407    }
408
409    #[test]
410    fn a_predicate_spanning_two_relations_is_refused_with_a_reason() {
411        let p = plan_for("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE a.v > b.w");
412        assert_eq!(p.pushed_count(), 0);
413        assert_eq!(p.refusals.len(), 1);
414        assert!(p.refusals[0].contains("spans more than one relation"), "{:?}", p.refusals);
415    }
416
417    #[test]
418    fn or_is_never_split() {
419        // `a.v > 5 OR b.w < 2` accepts a row when EITHER holds, so filtering
420        // `a` by the left half alone would drop rows the predicate accepts.
421        let p = plan_for("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE a.v > 5 OR b.w < 2");
422        assert_eq!(p.pushed_count(), 0);
423        assert_eq!(p.refusals.len(), 1);
424    }
425
426    #[test]
427    fn an_or_of_one_relation_is_also_refused_today() {
428        // `a.v > 5 OR a.v < 1` COULD be pushed, since it reads only `a`. It is
429        // allowed, because `reads` looks at the whole conjunct rather than
430        // splitting the OR.
431        let p = plan_for("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE a.v > 5 OR a.v < 1");
432        assert_eq!(p.pushed_count(), 1, "one conjunct, one relation");
433    }
434
435    #[test]
436    fn an_unqualified_column_is_refused() {
437        let p = plan_for("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE v > 5");
438        assert_eq!(p.pushed_count(), 0);
439        assert!(p.refusals[0].contains("unqualified"), "{:?}", p.refusals);
440    }
441
442    #[test]
443    fn a_constant_predicate_is_refused_as_pointless() {
444        let p = plan_for("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE 1 = 1");
445        assert_eq!(p.pushed_count(), 0);
446        assert!(p.refusals[0].contains("reads no column"), "{:?}", p.refusals);
447    }
448
449    #[test]
450    fn a_volatile_function_is_refused_because_the_allowlist_is_fail_safe() {
451        let sel = parse("SELECT 1 FROM a JOIN b ON a.x = b.x").expect("parses");
452        let _ = sel;
453        let pred = Expr::Binary {
454            op: "=".into(),
455            left: Box::new(Expr::Func {
456                name: "random".into(),
457                args: vec![Expr::Column { qual: Some("a".into()), name: "v".into() }],
458            }),
459            right: Box::new(Expr::Literal(serde_json::json!(1))),
460        };
461        let p = plan(Some(&pred), &["a".into(), "b".into()], &[]);
462        assert_eq!(p.pushed_count(), 0);
463        assert!(p.refusals[0].contains("not known to be pure"), "{:?}", p.refusals);
464    }
465
466    #[test]
467    fn pure_functions_and_postfix_operators_are_pushable() {
468        // `BETWEEN` desugars to `>= AND <=`, so it legitimately yields TWO
469        // pushable conjuncts. Stating the real count rather than rounding it
470        // to one — the parser's shape is part of what is being asserted.
471        for (w, want) in [
472            ("lower(a.name) = 'x'", 1),
473            ("a.v IS NULL", 1),
474            ("a.v IS NOT NULL", 1),
475            ("a.v IN (1, 2, 3)", 1),
476            ("a.v NOT IN (1, 2)", 1),
477            ("a.v BETWEEN 1 AND 9", 2),
478            ("a.v NOT BETWEEN 1 AND 9", 1),
479            ("coalesce(a.v, 0) > 1", 1),
480            ("a.v::text = '5'", 1),
481            ("NOT (a.v = 3)", 1),
482            ("CASE WHEN a.v > 1 THEN true ELSE false END", 1),
483        ] {
484            let p = plan_for(&format!("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE {w}"));
485            assert_eq!(
486                p.pushed_count(), want,
487                "{w} should push {want}: {:?}", p.refusals
488            );
489            assert!(p.refusals.is_empty(), "{w}: {:?}", p.refusals);
490        }
491    }
492
493    #[test]
494    fn nothing_is_pushed_without_a_join_because_there_is_nothing_to_push_below() {
495        let p = plan_for("SELECT 1 FROM a WHERE a.v > 5");
496        assert_eq!(p.pushed_count(), 0);
497        // Not a refusal either — there is simply no join.
498        assert!(p.refusals.is_empty());
499    }
500
501    #[test]
502    fn an_unknown_relation_is_left_to_the_evaluator_to_report() {
503        let p = plan_for("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE zz.v > 5");
504        assert_eq!(p.pushed_count(), 0);
505        assert!(p.refusals[0].contains("unknown relation"), "{:?}", p.refusals);
506    }
507
508    #[test]
509    fn a_binding_is_matched_case_insensitively() {
510        // Binding resolution ignores case, so the planner must too or it would
511        // attribute `A.v` to no relation and refuse a pushable predicate.
512        let p = plan_for("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE A.v > 5");
513        assert_eq!(p.for_binding("a").map(|v| v.len()), Some(1));
514        assert_eq!(p.for_binding("A").map(|v| v.len()), Some(1));
515    }
516}