EeshanBembi commented on code in PR #17602:
URL: https://github.com/apache/datafusion/pull/17602#discussion_r2353529356


##########
datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs:
##########
@@ -1400,13 +1400,40 @@ impl<S: SimplifyInfo> TreeNodeRewriter for 
Simplifier<'_, S> {
             //
 
             // CASE WHEN true THEN A ... END --> A
+            // CASE WHEN X THEN A WHEN TRUE THEN B ... END --> CASE WHEN X 
THEN A ELSE B END
             Expr::Case(Case {
                 expr: None,
                 mut when_then_expr,
-                else_expr: _,
-            }) if !when_then_expr.is_empty() && 
is_true(when_then_expr[0].0.as_ref()) => {
-                let (_, then_) = when_then_expr.swap_remove(0);
-                Transformed::yes(*then_)
+                else_expr,
+                // if let guard is not stabilized so we can't use it yet: 
https://github.com/rust-lang/rust/issues/51114
+                // Once it's supported we can avoid searching through 
when_then_expr twice in the below .any() and .position() calls
+                // }) if let Some(i) = when_then_expr.iter().position(|(when, 
_)| is_true(when.as_ref())) => {
+            }) if when_then_expr
+                .iter()
+                .any(|(when, _)| is_true(when.as_ref())) =>
+            {
+                if let Some(i) = when_then_expr
+                    .iter()
+                    .position(|(when, _)| is_true(when.as_ref()))
+                {
+                    let (_, then_) = when_then_expr.swap_remove(i);
+                    // CASE WHEN true THEN A ... END --> A
+                    if i == 0 {
+                        return Ok(Transformed::yes(*then_));
+                    }
+                    // CASE WHEN X THEN A WHEN TRUE THEN B ... END --> CASE 
WHEN X THEN A ELSE B END
+                    let truncated_when_then_expr = 
when_then_expr[..i].to_vec();

Review Comment:
   Performance / allocation nit (optional)
   
   You currently build `truncated_when_then_expr` via a slice clone:
   ```rust
   let truncated_when_then_expr = when_then_expr[..i].to_vec();
   ```
   Since when_then_expr is already mut, you can avoid an allocation and extra 
copies by truncating in place:
   ```
   when_then_expr.truncate(i);
   let truncated_when_then_expr = when_then_expr;
   ```
   This eliminates the to_vec() allocation and is more efficient, especially 
for larger CASE expressions.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org
For additional commands, e-mail: github-h...@datafusion.apache.org

Reply via email to