Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1399,6 +1399,18 @@ impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> {
// Rules for Case
//

// CASE WHEN true THEN A ... END --> A
Expr::Case(Case {
expr: None,
when_then_expr,
else_expr: _,
}) if !when_then_expr.is_empty()
&& matches!(when_then_expr[0].0.as_ref(),
Expr::Literal(ScalarValue::Boolean(Some(true)), _)) =>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we please use is_true to follow the pattern in the rest of this method?

pub fn is_true(expr: &Expr) -> bool {
match expr {
Expr::Literal(ScalarValue::Boolean(Some(v)), _) => *v,
_ => false,
}
}

{
Transformed::yes((*when_then_expr[0].1).clone())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be good to avoid this clone too,

How about something like this:

Suggested change
Transformed::yes((*when_then_expr[0].1).clone())
let (when, then_) = when_then_expr.swap_remove(0);
Transformed::yes(*when)

}

// CASE
// WHEN X THEN A
// WHEN Y THEN B
Expand Down Expand Up @@ -3552,6 +3564,61 @@ mod tests {
);
}

#[test]
fn simplify_expr_case_when_true() {
// CASE WHEN true THEN 1 ELSE x END --> 1
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we please add some negative tests too -- like CASE WHEN a THEN 1 ELSE 2 END?

assert_eq!(
simplify(Expr::Case(Case::new(
None,
vec![(
Box::new(lit(true)),
Box::new(lit(1)),
)],
Some(Box::new(col("x"))),
))),
lit(1)
);

// CASE WHEN true THEN col("a") ELSE col("b") END --> col("a")
assert_eq!(
simplify(Expr::Case(Case::new(
None,
vec![(
Box::new(lit(true)),
Box::new(col("a")),
)],
Some(Box::new(col("b"))),
))),
col("a")
);

// CASE WHEN true THEN col("a") WHEN col("x") > 5 THEN col("b") ELSE col("c") END --> col("a")
assert_eq!(
simplify(Expr::Case(Case::new(
None,
vec![
(Box::new(lit(true)), Box::new(col("a"))),
(Box::new(col("x").gt(lit(5))), Box::new(col("b"))),
],
Some(Box::new(col("c"))),
))),
col("a")
);

// CASE WHEN true THEN col("a") END --> col("a") (no else clause)
assert_eq!(
simplify(Expr::Case(Case::new(
None,
vec![(
Box::new(lit(true)),
Box::new(col("a")),
)],
None,
))),
col("a")
);
}

fn distinct_from(left: impl Into<Expr>, right: impl Into<Expr>) -> Expr {
Expr::BinaryExpr(BinaryExpr {
left: Box::new(left.into()),
Expand Down
Loading