Skip to main content

vortex_expr/transform/
match_between.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Rewrites `x >= a AND x < b` into `x BETWEEN a AND b`.
5
6use std::ptr;
7
8use vortex_array::expr::BoundExpression;
9use vortex_array::scalar_fn::ScalarFnVTableExt;
10use vortex_array::scalar_fn::fns::between::Between;
11use vortex_array::scalar_fn::fns::between::BetweenOptions;
12use vortex_array::scalar_fn::fns::between::StrictComparison;
13use vortex_array::scalar_fn::fns::binary::Binary;
14use vortex_array::scalar_fn::fns::get_item::GetItem;
15use vortex_array::scalar_fn::fns::literal::Literal;
16use vortex_array::scalar_fn::fns::operators::Operator;
17use vortex_error::VortexExpect;
18use vortex_error::VortexResult;
19
20/// Merge pairs of range comparisons on the same column within any conjunction of `expr` into a
21/// single [`Between`].
22///
23/// This is not an optimizer rule because it is worth running only once, on a scan's filter.
24/// Subtrees without a match keep their identity, so an expression without any match is returned
25/// unchanged.
26pub fn find_between(expr: BoundExpression) -> VortexResult<BoundExpression> {
27    Ok(try_find_between(&expr)?.unwrap_or(expr))
28}
29
30fn try_find_between(expr: &BoundExpression) -> VortexResult<Option<BoundExpression>> {
31    let children = expr.children();
32    let mut new_children: Option<Vec<BoundExpression>> = None;
33    for (idx, child) in children.iter().enumerate() {
34        if let Some(rewritten) = try_find_between(child)? {
35            new_children
36                .get_or_insert_with(|| children[..idx].to_vec())
37                .push(rewritten);
38        } else if let Some(new_children) = new_children.as_mut() {
39            new_children.push(child.clone());
40        }
41    }
42    let rewritten = new_children
43        .map(|children| expr.clone().with_children(children))
44        .transpose()?;
45
46    let current = rewritten.as_ref().unwrap_or(expr);
47    if is_and(current)
48        && let Some(merged) = merge_straddling_pairs(current)?
49    {
50        return Ok(Some(merged));
51    }
52    Ok(rewritten)
53}
54
55/// Merge pairs of range comparisons that sit on opposite sides of the `AND` node `expr`.
56///
57/// Children are rewritten before their parents, so a pair within one side was already merged at
58/// the `AND` node joining it. Only considering straddling pairs keeps the pass linear in the size
59/// of the conjunction instead of re-pairing every conjunct at every level. The rest of the tree
60/// keeps its shape: the lhs conjunct becomes the between and the rhs conjunct is removed.
61fn merge_straddling_pairs(expr: &BoundExpression) -> VortexResult<Option<BoundExpression>> {
62    let mut current: Option<BoundExpression> = None;
63
64    loop {
65        let expr = current.as_ref().unwrap_or(expr);
66        if !is_and(expr) {
67            break;
68        }
69        let lhs = expr.child(0);
70        let rhs = expr.child(1);
71
72        let Some((lower, upper, between)) = find_conjunct(rhs, &mut |rhs_conjunct| {
73            let rhs_cmp = RangeComparison::try_new(rhs_conjunct)?;
74            find_conjunct(lhs, &mut |lhs_conjunct| {
75                let lhs_cmp = RangeComparison::try_new(lhs_conjunct)?;
76                let between = lhs_cmp.between(&rhs_cmp)?;
77                Some((lhs_conjunct, rhs_conjunct, between))
78            })
79        }) else {
80            break;
81        };
82
83        tracing::debug!(%lower, %upper, "merged range comparisons into {between}");
84
85        let new_lhs = rewrite_conjunct(lhs, lower, Some(&between))?
86            .vortex_expect("matched conjunct is part of the lhs")
87            .vortex_expect("replaced conjunct is never removed");
88        let new_rhs = rewrite_conjunct(rhs, upper, None)?
89            .vortex_expect("matched conjunct is part of the rhs");
90
91        current = Some(match new_rhs {
92            Some(new_rhs) => expr.clone().with_children([new_lhs, new_rhs])?,
93            None => new_lhs,
94        });
95    }
96
97    Ok(current)
98}
99
100fn is_and(expr: &BoundExpression) -> bool {
101    expr.as_opt::<Binary>() == Some(&Operator::And)
102}
103
104/// Return the first `Some` produced by `f` over the conjuncts of the `AND` tree rooted at `expr`.
105fn find_conjunct<'a, T>(
106    expr: &'a BoundExpression,
107    f: &mut impl FnMut(&'a BoundExpression) -> Option<T>,
108) -> Option<T> {
109    if is_and(expr) {
110        find_conjunct(expr.child(0), f).or_else(|| find_conjunct(expr.child(1), f))
111    } else {
112        f(expr)
113    }
114}
115
116/// Replace the conjunct `target`, identified by address, in the `AND` tree rooted at `expr`, or
117/// remove it when `replacement` is `None`.
118///
119/// Returns `None` when `target` is not a conjunct of `expr`, otherwise the rewritten tree, which
120/// is itself `None` when removing `target` leaves nothing behind.
121fn rewrite_conjunct(
122    expr: &BoundExpression,
123    target: &BoundExpression,
124    replacement: Option<&BoundExpression>,
125) -> VortexResult<Option<Option<BoundExpression>>> {
126    if ptr::eq(expr, target) {
127        return Ok(Some(replacement.cloned()));
128    }
129    if !is_and(expr) {
130        return Ok(None);
131    }
132
133    for idx in 0..2 {
134        let Some(new_child) = rewrite_conjunct(expr.child(idx), target, replacement)? else {
135            continue;
136        };
137        let sibling = expr.child(1 - idx).clone();
138        let rewritten = match new_child {
139            Some(new_child) if idx == 0 => expr.clone().with_children([new_child, sibling])?,
140            Some(new_child) => expr.clone().with_children([sibling, new_child])?,
141            None => sibling,
142        };
143        return Ok(Some(Some(rewritten)));
144    }
145
146    Ok(None)
147}
148
149/// A conjunct `column op literal` (in either order) that bounds `column` from one side.
150struct RangeComparison<'a> {
151    column: &'a BoundExpression,
152    literal: &'a BoundExpression,
153    is_lower: bool,
154    strict: StrictComparison,
155}
156
157impl<'a> RangeComparison<'a> {
158    fn try_new(expr: &'a BoundExpression) -> Option<Self> {
159        let operator = *expr.as_opt::<Binary>()?;
160        let lhs = expr.child(0);
161        let rhs = expr.child(1);
162
163        // Normalize the column to the left of the operator.
164        let (column, literal, operator) = if lhs.is::<GetItem>() && rhs.is::<Literal>() {
165            (lhs, rhs, operator)
166        } else if rhs.is::<GetItem>() && lhs.is::<Literal>() {
167            (rhs, lhs, operator.swap()?)
168        } else {
169            return None;
170        };
171
172        let (is_lower, strict) = match operator {
173            Operator::Gt => (true, StrictComparison::Strict),
174            Operator::Gte => (true, StrictComparison::NonStrict),
175            Operator::Lt => (false, StrictComparison::Strict),
176            Operator::Lte => (false, StrictComparison::NonStrict),
177            _ => return None,
178        };
179
180        Some(Self {
181            column,
182            literal,
183            is_lower,
184            strict,
185        })
186    }
187
188    /// Combine two comparisons bounding the same column from opposite sides.
189    fn between(&self, other: &Self) -> Option<BoundExpression> {
190        if self.is_lower == other.is_lower || self.column != other.column {
191            return None;
192        }
193        let (lower, upper) = if self.is_lower {
194            (self, other)
195        } else {
196            (other, self)
197        };
198
199        // A between that fails to type-check leaves the comparisons in place.
200        Between
201            .try_new_bound_expr(
202                BetweenOptions {
203                    lower_strict: lower.strict,
204                    upper_strict: upper.strict,
205                },
206                [
207                    self.column.clone(),
208                    lower.literal.clone(),
209                    upper.literal.clone(),
210                ],
211            )
212            .ok()
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use std::sync::LazyLock;
219
220    use rstest::rstest;
221    use vortex_array::IntoArray;
222    use vortex_array::VortexSessionExecute;
223    use vortex_array::arrays::BoolArray;
224    use vortex_array::arrays::StructArray;
225    use vortex_array::dtype::DType;
226    use vortex_array::dtype::Nullability;
227    use vortex_array::dtype::PType;
228    use vortex_array::dtype::StructFields;
229    use vortex_array::expr::Expression;
230    use vortex_array::expr::and;
231    use vortex_array::expr::between;
232    use vortex_array::expr::col;
233    use vortex_array::expr::gt;
234    use vortex_array::expr::gt_eq;
235    use vortex_array::expr::lit;
236    use vortex_array::expr::lt;
237    use vortex_array::expr::lt_eq;
238    use vortex_array::expr::or;
239    use vortex_array::scalar::Scalar;
240    use vortex_array::scalar_fn::fns::between::BetweenOptions;
241    use vortex_array::scalar_fn::fns::between::StrictComparison;
242    use vortex_buffer::buffer;
243    use vortex_error::VortexResult;
244    use vortex_session::VortexSession;
245
246    use super::find_between;
247
248    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
249
250    fn scope() -> DType {
251        let i32_dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
252        DType::Struct(
253            StructFields::new(
254                ["x", "y", "z"].into(),
255                vec![i32_dtype.clone(), i32_dtype.clone(), i32_dtype],
256            ),
257            Nullability::NonNullable,
258        )
259    }
260
261    fn between_x(lower: i32, upper: i32, lower_strict: bool, upper_strict: bool) -> Expression {
262        let strictness = |strict| {
263            if strict {
264                StrictComparison::Strict
265            } else {
266                StrictComparison::NonStrict
267            }
268        };
269        between(
270            col("x"),
271            lit(lower),
272            lit(upper),
273            BetweenOptions {
274                lower_strict: strictness(lower_strict),
275                upper_strict: strictness(upper_strict),
276            },
277        )
278    }
279
280    #[rstest]
281    // An impossible range is still a between.
282    #[case::bad_match(
283        and(lt_eq(lit(100), col("x")), gt(lit(-100), col("x"))),
284        between_x(100, -100, false, true)
285    )]
286    #[case::literals_on_left(
287        and(lt(lit(2), col("x")), gt_eq(lit(5), col("x"))),
288        between_x(2, 5, true, false)
289    )]
290    #[case::columns_on_left(
291        and(gt_eq(col("x"), lit(2)), lt(col("x"), lit(5))),
292        between_x(2, 5, false, true)
293    )]
294    #[case::mixed_sides(
295        and(gt_eq(col("x"), lit(2)), gt_eq(lit(5), col("x"))),
296        between_x(2, 5, false, false)
297    )]
298    #[case::upper_first(
299        and(gt_eq(lit(5), col("x")), lt(lit(2), col("x"))),
300        between_x(2, 5, true, false)
301    )]
302    #[case::other_conjunct_first(
303        and(
304            and(gt_eq(col("y"), lit(10)), gt_eq(lit(5), col("x"))),
305            lt(lit(2), col("x")),
306        ),
307        and(gt_eq(col("y"), lit(10)), between_x(2, 5, true, false))
308    )]
309    #[case::other_conjunct_last(
310        and(
311            and(gt_eq(lit(5), col("x")), gt_eq(col("y"), lit(10))),
312            lt(lit(2), col("x")),
313        ),
314        and(between_x(2, 5, true, false), gt_eq(col("y"), lit(10)))
315    )]
316    #[case::skips_non_leaf_conjuncts(
317        and(
318            and(gt_eq(col("x"), lit(2)), gt(col("y"), col("z"))),
319            lt(col("x"), lit(5))
320        ),
321        and(between_x(2, 5, false, true), gt(col("y"), col("z")))
322    )]
323    #[case::pair_within_one_side(
324        and(
325            and(gt_eq(col("x"), lit(2)), lt(col("x"), lit(5))),
326            gt(col("y"), col("z"))
327        ),
328        and(between_x(2, 5, false, true), gt(col("y"), col("z")))
329    )]
330    #[case::under_or(
331        or(
332            and(gt_eq(col("x"), lit(2)), lt(col("x"), lit(5))),
333            gt(col("y"), col("z"))
334        ),
335        or(between_x(2, 5, false, true), gt(col("y"), col("z")))
336    )]
337    #[case::no_pair(
338        and(gt_eq(col("x"), lit(2)), lt(col("y"), lit(5))),
339        and(gt_eq(col("x"), lit(2)), lt(col("y"), lit(5)))
340    )]
341    #[case::same_direction(
342        and(gt_eq(col("x"), lit(2)), gt(col("x"), lit(5))),
343        and(gt_eq(col("x"), lit(2)), gt(col("x"), lit(5)))
344    )]
345    fn finds_between(#[case] expr: Expression, #[case] expected: Expression) -> VortexResult<()> {
346        let scope = scope();
347        assert_eq!(find_between(expr.bind(&scope)?)?, expected.bind(&scope)?);
348        Ok(())
349    }
350
351    /// Every pair straddling a single `AND` node is merged.
352    #[test]
353    fn merges_many_pairs() -> VortexResult<()> {
354        let scope = scope();
355        let lowers = ["x", "y", "z"].map(|name| gt_eq(col(name), lit(0)));
356        let uppers = ["x", "y", "z"].map(|name| lt(col(name), lit(10)));
357        let [lx, ly, lz] = lowers;
358        let [ux, uy, uz] = uppers;
359        let expr = and(and(and(lx, ly), lz), and(and(uz, uy), ux));
360
361        let range = |name| {
362            between(
363                col(name),
364                lit(0),
365                lit(10),
366                BetweenOptions {
367                    lower_strict: StrictComparison::NonStrict,
368                    upper_strict: StrictComparison::Strict,
369                },
370            )
371        };
372        let expected = and(and(range("x"), range("y")), range("z"));
373
374        assert_eq!(find_between(expr.bind(&scope)?)?, expected.bind(&scope)?);
375        Ok(())
376    }
377
378    /// A null literal bound must not change the values of the rewritten expression. Kleene `AND`
379    /// keeps a row false when the surviving comparison is false, so the rewrite cannot null it.
380    #[test]
381    fn null_literal_bound_is_value_preserving() -> VortexResult<()> {
382        let ctx = &mut SESSION.create_execution_ctx();
383        let data = StructArray::from_fields(&[("x", buffer![10, 1].into_array())])?.into_array();
384
385        let null_lit = lit(Scalar::null(DType::Primitive(
386            PType::I32,
387            Nullability::Nullable,
388        )));
389        let expr = and(gt_eq(col("x"), null_lit), lt_eq(col("x"), lit(5i32)));
390
391        let before = data
392            .clone()
393            .apply(&expr)?
394            .execute::<BoolArray>(ctx)?
395            .opt_bool_vec(ctx);
396
397        let rewritten = find_between(expr.bind(data.dtype())?)?;
398        let after = data
399            .apply_bound(&rewritten)?
400            .execute::<BoolArray>(ctx)?
401            .opt_bool_vec(ctx);
402
403        // Row 0 is false rather than null because `$.x <= 5` falsifies it on its own.
404        assert_eq!(before, [Some(false), None]);
405        assert_eq!(before, after);
406
407        Ok(())
408    }
409}