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        Expr::Index { expr, index } => {
213            walk(expr, known, seen, why);
214            walk(index, known, seen, why);
215        }
216        Expr::ArrayLit(items) => {
217            for i in items {
218                walk(i, known, seen, why);
219            }
220        }
221        // A subquery may read ANY binding of the enclosing query through
222        // correlation, and which ones cannot be told without running it. So a
223        // predicate containing one is never pushed below a join.
224        Expr::Subquery(_) | Expr::Exists { .. } | Expr::ArrayQuery(_) | Expr::InSubquery { .. } => {
225            *why = Some("contains a subquery")
226        }
227        Expr::Quantified { left, right, .. } => {
228            walk(left, known, seen, why);
229            walk(right, known, seen, why);
230        }
231    }
232}
233
234/// The bindings this query can NULL-synthesise.
235///
236/// Pre-filtering any of these is refused: removing a row can manufacture an
237/// outer row carrying NULLs the pre-filter never examined, and whether that
238/// row survives the retained `WHERE` depends on the predicate.
239pub fn nullable_bindings(sel: &crate::sqlselect::Select) -> Vec<String> {
240    use crate::sqlselect::JoinKind;
241    let mut out: Vec<String> = vec![];
242    let mut accumulated: Vec<String> = sel
243        .from
244        .iter()
245        .map(|t| t.binding().to_ascii_lowercase())
246        .collect();
247
248    for j in &sel.joins {
249        let rb = j.table.binding().to_ascii_lowercase();
250        // LEFT/FULL: the RIGHT side is synthesised when a left row has no
251        // partner.
252        if matches!(j.kind, JoinKind::Left | JoinKind::Full) && !out.contains(&rb) {
253            out.push(rb.clone());
254        }
255        // RIGHT/FULL: the whole accumulated LEFT side is synthesised when a
256        // right row has no partner — which retroactively makes every earlier
257        // binding nullable, the `FROM` relation included.
258        if matches!(j.kind, JoinKind::Right | JoinKind::Full) {
259            for a in &accumulated {
260                if !out.contains(a) {
261                    out.push(a.clone());
262                }
263            }
264        }
265        accumulated.push(rb);
266    }
267    out
268}
269
270/// Decide which `WHERE` conjuncts may be pre-applied to which relation.
271///
272/// `bindings` must list every relation in the query. The returned predicates
273/// are COPIES — the caller keeps evaluating the original `WHERE` after the
274/// join, which is what makes this safe.
275pub fn plan(
276    where_: Option<&Expr>,
277    bindings: &[String],
278    nullable: &[String],
279) -> Pushdown {
280    let mut out = Pushdown::default();
281    let Some(w) = where_ else { return out };
282
283    // With a single relation there is no join to push below, and the filter
284    // already runs directly over it. Pushing would only duplicate the work.
285    if bindings.len() < 2 {
286        return out;
287    }
288
289    let mut parts = vec![];
290    conjuncts(w, &mut parts);
291    for p in parts {
292        match reads(p, bindings) {
293            Reads::One(b) if nullable.iter().any(|n| n.eq_ignore_ascii_case(&b)) => {
294                // Oracle's wording, because it names the actual hazard rather
295                // than restating the rule.
296                out.refusals.push(format!(
297                    "Filter retained above join: predicate references nullable \
298                     side of an outer join ({b})"
299                ));
300            }
301            Reads::One(b) => out.per_binding.entry(b).or_default().push(p.clone()),
302            Reads::Constant => out
303                .refusals
304                .push("Filter retained above join: predicate reads no column".into()),
305            Reads::Refused(why) => out
306                .refusals
307                .push(format!("Filter retained above join: {why}")),
308        }
309    }
310    out
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316    use crate::sqlselect::parse;
317
318    fn plan_for(sql: &str) -> Pushdown {
319        let sel = parse(sql).expect("parses");
320        let mut b = vec![];
321        if let Some(f) = &sel.from {
322            b.push(f.binding());
323        }
324        for j in &sel.joins {
325            b.push(j.table.binding());
326        }
327        let nullable = nullable_bindings(&sel);
328        plan(sel.where_.as_ref(), &b, &nullable)
329    }
330
331    #[test]
332    fn a_single_relation_predicate_is_pushed_to_that_relation() {
333        let p = plan_for("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE a.v > 5");
334        assert_eq!(p.pushed_count(), 1);
335        assert_eq!(p.for_binding("a").map(|v| v.len()), Some(1));
336        assert!(p.for_binding("b").is_none());
337        assert!(p.refusals.is_empty(), "{:?}", p.refusals);
338    }
339
340    #[test]
341    fn conjuncts_are_pushed_to_their_own_relations_independently() {
342        let p = plan_for(
343            "SELECT 1 FROM a JOIN b ON a.x = b.x WHERE a.v > 5 AND b.w < 2 AND a.z = 'q'",
344        );
345        assert_eq!(p.pushed_count(), 3);
346        assert_eq!(p.for_binding("a").map(|v| v.len()), Some(2));
347        assert_eq!(p.for_binding("b").map(|v| v.len()), Some(1));
348    }
349
350    #[test]
351    fn a_predicate_on_the_nullable_side_of_a_left_join_is_REFUSED() {
352        // This test asserted the opposite in the first version of this module,
353        // and it was wrong. `WHERE d.dname IS NULL` over a LEFT JOIN is
354        // SATISFIED by the synthesised NULL, so emptying the right relation
355        // manufactures outer rows that pass the retained WHERE — 1 row became
356        // 5. The semantic corpus caught it.
357        let p = plan_for("SELECT 1 FROM a LEFT JOIN b ON a.x = b.x WHERE b.w = 5");
358        assert_eq!(p.pushed_count(), 0);
359        assert!(p.refusals[0].contains("nullable side"), "{:?}", p.refusals);
360    }
361
362    #[test]
363    fn the_non_nullable_side_of_a_left_join_is_still_pushed() {
364        // `a` is never synthesised by a LEFT JOIN, so its own predicates are
365        // safe. This is the case that matters in practice — a selective filter
366        // on the driving relation.
367        let p = plan_for("SELECT 1 FROM a LEFT JOIN b ON a.x = b.x WHERE a.v > 5");
368        assert_eq!(p.for_binding("a").map(|v| v.len()), Some(1));
369        assert!(p.refusals.is_empty(), "{:?}", p.refusals);
370    }
371
372    #[test]
373    fn a_right_join_makes_the_LEFT_side_nullable_including_the_from_relation() {
374        let p = plan_for("SELECT 1 FROM a RIGHT JOIN b ON a.x = b.x WHERE a.v > 5");
375        assert_eq!(p.pushed_count(), 0, "a is synthesised by the RIGHT join");
376        assert!(p.refusals[0].contains("nullable side"), "{:?}", p.refusals);
377        // The right side of a RIGHT join is never synthesised.
378        let p = plan_for("SELECT 1 FROM a RIGHT JOIN b ON a.x = b.x WHERE b.w > 5");
379        assert_eq!(p.for_binding("b").map(|v| v.len()), Some(1));
380    }
381
382    #[test]
383    fn a_full_join_makes_both_sides_nullable() {
384        for w in ["a.v > 5", "b.w > 5"] {
385            let p = plan_for(&format!("SELECT 1 FROM a FULL JOIN b ON a.x = b.x WHERE {w}"));
386            assert_eq!(p.pushed_count(), 0, "{w}");
387        }
388    }
389
390    #[test]
391    fn a_later_right_join_retroactively_protects_earlier_relations() {
392        // `a` and `b` are fine on their own, but the RIGHT join to `c`
393        // synthesises NULLs across BOTH of them — so neither may be
394        // pre-filtered. Missing this would be a wrong answer that only shows
395        // up in three-relation queries.
396        let sel = parse(
397            "SELECT 1 FROM a JOIN b ON a.x = b.x RIGHT JOIN c ON b.y = c.y \
398             WHERE a.v > 1 AND b.w > 1 AND c.z > 1",
399        )
400        .expect("parses");
401        let nullable = nullable_bindings(&sel);
402        assert!(nullable.contains(&"a".to_string()), "{nullable:?}");
403        assert!(nullable.contains(&"b".to_string()), "{nullable:?}");
404        assert!(!nullable.contains(&"c".to_string()), "c is never synthesised");
405
406        let p = plan_for(
407            "SELECT 1 FROM a JOIN b ON a.x = b.x RIGHT JOIN c ON b.y = c.y \
408             WHERE a.v > 1 AND b.w > 1 AND c.z > 1",
409        );
410        assert_eq!(p.pushed_count(), 1, "only c");
411        assert_eq!(p.for_binding("c").map(|v| v.len()), Some(1));
412        assert_eq!(p.refusals.len(), 2);
413    }
414
415    #[test]
416    fn an_all_inner_query_can_push_everything() {
417        let p = plan_for(
418            "SELECT 1 FROM a JOIN b ON a.x = b.x JOIN c ON b.y = c.y \
419             WHERE a.v > 1 AND b.w > 1 AND c.z > 1",
420        );
421        assert_eq!(p.pushed_count(), 3);
422        assert!(p.refusals.is_empty());
423        assert!(nullable_bindings(&parse(
424            "SELECT 1 FROM a JOIN b ON a.x = b.x JOIN c ON b.y = c.y"
425        ).unwrap()).is_empty());
426    }
427
428    #[test]
429    fn a_predicate_spanning_two_relations_is_refused_with_a_reason() {
430        let p = plan_for("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE a.v > b.w");
431        assert_eq!(p.pushed_count(), 0);
432        assert_eq!(p.refusals.len(), 1);
433        assert!(p.refusals[0].contains("spans more than one relation"), "{:?}", p.refusals);
434    }
435
436    #[test]
437    fn or_is_never_split() {
438        // `a.v > 5 OR b.w < 2` accepts a row when EITHER holds, so filtering
439        // `a` by the left half alone would drop rows the predicate accepts.
440        let p = plan_for("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE a.v > 5 OR b.w < 2");
441        assert_eq!(p.pushed_count(), 0);
442        assert_eq!(p.refusals.len(), 1);
443    }
444
445    #[test]
446    fn an_or_of_one_relation_is_also_refused_today() {
447        // `a.v > 5 OR a.v < 1` COULD be pushed, since it reads only `a`. It is
448        // allowed, because `reads` looks at the whole conjunct rather than
449        // splitting the OR.
450        let p = plan_for("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE a.v > 5 OR a.v < 1");
451        assert_eq!(p.pushed_count(), 1, "one conjunct, one relation");
452    }
453
454    #[test]
455    fn an_unqualified_column_is_refused() {
456        let p = plan_for("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE v > 5");
457        assert_eq!(p.pushed_count(), 0);
458        assert!(p.refusals[0].contains("unqualified"), "{:?}", p.refusals);
459    }
460
461    #[test]
462    fn a_constant_predicate_is_refused_as_pointless() {
463        let p = plan_for("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE 1 = 1");
464        assert_eq!(p.pushed_count(), 0);
465        assert!(p.refusals[0].contains("reads no column"), "{:?}", p.refusals);
466    }
467
468    #[test]
469    fn a_volatile_function_is_refused_because_the_allowlist_is_fail_safe() {
470        let sel = parse("SELECT 1 FROM a JOIN b ON a.x = b.x").expect("parses");
471        let _ = sel;
472        let pred = Expr::Binary {
473            op: "=".into(),
474            left: Box::new(Expr::Func {
475                name: "random".into(),
476                args: vec![Expr::Column { qual: Some("a".into()), name: "v".into() }],
477            }),
478            right: Box::new(Expr::Literal(serde_json::json!(1))),
479        };
480        let p = plan(Some(&pred), &["a".into(), "b".into()], &[]);
481        assert_eq!(p.pushed_count(), 0);
482        assert!(p.refusals[0].contains("not known to be pure"), "{:?}", p.refusals);
483    }
484
485    #[test]
486    fn pure_functions_and_postfix_operators_are_pushable() {
487        // `BETWEEN` desugars to `>= AND <=`, so it legitimately yields TWO
488        // pushable conjuncts. Stating the real count rather than rounding it
489        // to one — the parser's shape is part of what is being asserted.
490        for (w, want) in [
491            ("lower(a.name) = 'x'", 1),
492            ("a.v IS NULL", 1),
493            ("a.v IS NOT NULL", 1),
494            ("a.v IN (1, 2, 3)", 1),
495            ("a.v NOT IN (1, 2)", 1),
496            ("a.v BETWEEN 1 AND 9", 2),
497            ("a.v NOT BETWEEN 1 AND 9", 1),
498            ("coalesce(a.v, 0) > 1", 1),
499            ("a.v::text = '5'", 1),
500            ("NOT (a.v = 3)", 1),
501            ("CASE WHEN a.v > 1 THEN true ELSE false END", 1),
502        ] {
503            let p = plan_for(&format!("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE {w}"));
504            assert_eq!(
505                p.pushed_count(), want,
506                "{w} should push {want}: {:?}", p.refusals
507            );
508            assert!(p.refusals.is_empty(), "{w}: {:?}", p.refusals);
509        }
510    }
511
512    #[test]
513    fn nothing_is_pushed_without_a_join_because_there_is_nothing_to_push_below() {
514        let p = plan_for("SELECT 1 FROM a WHERE a.v > 5");
515        assert_eq!(p.pushed_count(), 0);
516        // Not a refusal either — there is simply no join.
517        assert!(p.refusals.is_empty());
518    }
519
520    #[test]
521    fn an_unknown_relation_is_left_to_the_evaluator_to_report() {
522        let p = plan_for("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE zz.v > 5");
523        assert_eq!(p.pushed_count(), 0);
524        assert!(p.refusals[0].contains("unknown relation"), "{:?}", p.refusals);
525    }
526
527    #[test]
528    fn a_binding_is_matched_case_insensitively() {
529        // Binding resolution ignores case, so the planner must too or it would
530        // attribute `A.v` to no relation and refuse a pushable predicate.
531        let p = plan_for("SELECT 1 FROM a JOIN b ON a.x = b.x WHERE A.v > 5");
532        assert_eq!(p.for_binding("a").map(|v| v.len()), Some(1));
533        assert_eq!(p.for_binding("A").map(|v| v.len()), Some(1));
534    }
535}