Skip to main content

vortex_expr/transform/
replace.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_array::expr::Expression;
5use vortex_array::expr::traversal::NodeExt;
6use vortex_array::expr::traversal::Transformed;
7use vortex_array::expr::traversal::TraversalOrder;
8use vortex_error::VortexExpect;
9
10/// Replaces all occurrences of `needle` in the expression `expr` with `replacement`.
11pub fn replace(expr: Expression, needle: &Expression, replacement: Expression) -> Expression {
12    expr.transform_down(|node| {
13        if &node == needle {
14            Ok(Transformed {
15                value: replacement.clone(),
16                // If there is a match with a needle there can be no more matches in that subtree.
17                order: TraversalOrder::Skip,
18                changed: true,
19            })
20        } else {
21            Ok(Transformed::no(node))
22        }
23    })
24    .vortex_expect("ReplaceVisitor should not fail")
25    .into_inner()
26}
27
28#[cfg(test)]
29mod test {
30    use vortex_array::dtype::Nullability::NonNullable;
31    use vortex_array::expr::Lambda;
32    use vortex_array::expr::checked_add;
33    use vortex_array::expr::col;
34    use vortex_array::expr::get_item;
35    use vortex_array::expr::list_transform;
36    use vortex_array::expr::lit;
37    use vortex_array::expr::pack;
38    use vortex_array::expr::root;
39    use vortex_array::expr::var;
40    use vortex_error::VortexResult;
41
42    use super::replace;
43
44    #[test]
45    fn test_replace_full_tree() {
46        let e = get_item("b", pack([("a", lit(1)), ("b", lit(2))], NonNullable));
47        let needle = get_item("b", pack([("a", lit(1)), ("b", lit(2))], NonNullable));
48        let replacement = lit(42);
49        let replaced_expr = replace(e, &needle, replacement.clone());
50        assert_eq!(&replaced_expr, &replacement);
51    }
52
53    #[test]
54    fn test_replace_leaf() {
55        let e = pack([("a", lit(1)), ("b", lit(2))], NonNullable);
56        let needle = lit(2);
57        let replacement = lit(42);
58        let replaced_expr = replace(e, &needle, replacement);
59        assert_eq!(replaced_expr.to_string(), "pack(a: 1i32, b: 42i32)");
60    }
61
62    #[test]
63    fn test_replace_leaves_a_lambda_alone() -> VortexResult<()> {
64        // The lambda is in `list_transform`'s options, not among its children.
65        let expr = list_transform(col("l"), Lambda::new(["x"], checked_add(var("x"), lit(1)))?);
66        assert_eq!(replace(expr.clone(), &var("x"), lit(0)), expr);
67        assert_eq!(
68            replace(expr, &root(), col("s")).to_string(),
69            "vortex.list.transform($.s.l, (x) -> (@x + 1i32))"
70        );
71        Ok(())
72    }
73}