Skip to main content

datafusion_physical_expr/expressions/
case.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5mod literal_lookup_table;
6
7use super::{Column, Literal};
8use crate::expressions::{
9    BinaryExpr, CastExpr, LambdaVariable, NegativeExpr, NotExpr, lit, try_cast,
10};
11use crate::{PhysicalExpr, ScalarFunctionExpr};
12use arrow::array::*;
13use arrow::compute::kernels::zip::zip;
14use arrow::compute::{
15    FilterBuilder, FilterPredicate, is_not_null, not, nullif, prep_null_mask_filter,
16};
17use arrow::datatypes::{DataType, Schema, UInt32Type, UnionMode};
18use arrow::error::ArrowError;
19use datafusion_common::cast::as_boolean_array;
20use datafusion_common::{
21    DataFusionError, Result, ScalarValue, assert_or_internal_err, exec_err,
22    internal_datafusion_err, internal_err,
23};
24use datafusion_expr::ColumnarValue;
25use datafusion_expr_common::interval_arithmetic::NullableInterval;
26use datafusion_expr_common::operator::Operator;
27use indexmap::IndexMap;
28use std::borrow::Cow;
29use std::collections::BTreeSet;
30use std::hash::Hash;
31use std::sync::Arc;
32
33use crate::expressions::case::literal_lookup_table::LiteralLookupTable;
34use arrow::compute::kernels::merge::{MergeIndex, merge, merge_n};
35use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
36use datafusion_physical_expr_common::datum::compare_with_eq;
37use datafusion_physical_expr_common::utils::scatter;
38use itertools::Itertools;
39use std::fmt::{Debug, Formatter};
40
41pub(super) type WhenThen = (Arc<dyn PhysicalExpr>, Arc<dyn PhysicalExpr>);
42
43#[derive(Debug, Hash, PartialEq, Eq)]
44enum EvalMethod {
45    /// CASE WHEN condition THEN result
46    ///      [WHEN ...]
47    ///      [ELSE result]
48    /// END
49    NoExpression(ProjectedCaseBody),
50    /// CASE expression
51    ///     WHEN value THEN result
52    ///     [WHEN ...]
53    ///     [ELSE result]
54    /// END
55    WithExpression(ProjectedCaseBody),
56    /// This is a specialization for a specific use case where we can take a fast path
57    /// for expressions that are infallible and can be cheaply computed for the entire
58    /// record batch rather than just for the rows where the predicate is true.
59    ///
60    /// CASE WHEN condition THEN infallible_expression [ELSE NULL] END
61    InfallibleExprOrNull,
62    /// This is a specialization for a specific use case where we can take a fast path
63    /// if there is just one when/then pair and both the `then` and `else` expressions
64    /// are literal values
65    /// CASE WHEN condition THEN literal ELSE literal END
66    ScalarOrScalar,
67    /// This is a specialization for a specific use case where we can take a fast path
68    /// if there is just one when/then pair, the `then` is an expression, and `else` is either
69    /// an expression, literal NULL or absent.
70    ///
71    /// In contrast to [`EvalMethod::InfallibleExprOrNull`], this specialization can handle fallible
72    /// `then` expressions.
73    ///
74    /// CASE WHEN condition THEN expression [ELSE expression] END
75    ExpressionOrExpression(ProjectedCaseBody),
76
77    /// This is a specialization for [`EvalMethod::WithExpression`] when the value and results are literals
78    ///
79    /// See [`LiteralLookupTable`] for more details
80    WithExprScalarLookupTable(LiteralLookupTable),
81}
82
83/// Implementing hash so we can use `derive` on [`EvalMethod`].
84///
85/// not implementing actual [`Hash`] as it is not dyn compatible so we cannot implement it for
86/// `dyn` [`literal_lookup_table::WhenLiteralIndexMap`].
87///
88/// So implementing empty hash is still valid as the data is derived from `PhysicalExpr` s which are already hashed
89impl Hash for LiteralLookupTable {
90    fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {}
91}
92
93/// Implementing Equal so we can use `derive` on [`EvalMethod`].
94///
95/// not implementing actual [`PartialEq`] as it is not dyn compatible so we cannot implement it for
96/// `dyn` [`literal_lookup_table::WhenLiteralIndexMap`].
97///
98/// So we always return true as the data is derived from `PhysicalExpr` s which are already compared
99impl PartialEq for LiteralLookupTable {
100    fn eq(&self, _other: &Self) -> bool {
101        true
102    }
103}
104
105impl Eq for LiteralLookupTable {}
106
107/// The body of a CASE expression which consists of an optional base expression, the "when/then"
108/// branches and an optional "else" branch.
109#[derive(Debug, Hash, PartialEq, Eq)]
110struct CaseBody {
111    /// Optional base expression that can be compared to literal values in the "when" expressions
112    expr: Option<Arc<dyn PhysicalExpr>>,
113    /// One or more when/then expressions
114    when_then_expr: Vec<WhenThen>,
115    /// Optional "else" expression
116    else_expr: Option<Arc<dyn PhysicalExpr>>,
117}
118
119impl CaseBody {
120    /// Derives a [ProjectedCaseBody] from this [CaseBody].
121    fn project(&self) -> Result<ProjectedCaseBody> {
122        // Determine the set of columns that are used in all the expressions of the case body.
123        // Use an ordered set so lambda variables continue to be positioned after columns
124        let mut used_column_indices = BTreeSet::<usize>::new();
125        let mut supports_projection = true;
126        let mut collect_column_indices = |expr: &Arc<dyn PhysicalExpr>| {
127            expr.apply(|expr| {
128                if let Some(column) = expr.downcast_ref::<Column>() {
129                    used_column_indices.insert(column.index());
130                } else if let Some(lambda_variable) =
131                    expr.downcast_ref::<LambdaVariable>()
132                {
133                    used_column_indices.insert(lambda_variable.index());
134                } else if expr.downcast_ref::<Literal>().is_none()
135                    && expr.downcast_ref::<ScalarFunctionExpr>().is_none()
136                    && expr.children().is_empty()
137                {
138                    // Unknown leaves may read input columns without exposing a Column child.
139                    supports_projection = false;
140                }
141                Ok(TreeNodeRecursion::Continue)
142            })
143            .expect("Closure cannot fail");
144        };
145
146        if let Some(e) = &self.expr {
147            collect_column_indices(e);
148        }
149        self.when_then_expr.iter().for_each(|(w, t)| {
150            collect_column_indices(w);
151            collect_column_indices(t);
152        });
153        if let Some(e) = &self.else_expr {
154            collect_column_indices(e);
155        }
156
157        // Construct a mapping from the original column index to the projected column index.
158        let column_index_map = used_column_indices
159            .iter()
160            .enumerate()
161            .map(|(projected, original)| (*original, projected))
162            .collect::<IndexMap<usize, usize>>();
163
164        // Construct the projected body by rewriting each expression from the original body
165        // using the column index mapping.
166        let project = |expr: &Arc<dyn PhysicalExpr>| -> Result<Arc<dyn PhysicalExpr>> {
167            Arc::clone(expr)
168                .transform_down(|e| {
169                    if let Some(column) = e.downcast_ref::<Column>() {
170                        let original = column.index();
171                        let projected = *column_index_map.get(&original).unwrap();
172                        if projected != original {
173                            return Ok(Transformed::yes(Arc::new(Column::new(
174                                column.name(),
175                                projected,
176                            ))));
177                        }
178                    } else if let Some(lambda_variable) =
179                        e.downcast_ref::<LambdaVariable>()
180                    {
181                        let original = lambda_variable.index();
182                        let projected = *column_index_map.get(&original).unwrap();
183                        if projected != original {
184                            return Ok(Transformed::yes(Arc::new(LambdaVariable::new(
185                                projected,
186                                Arc::clone(lambda_variable.field()),
187                            ))));
188                        }
189                    }
190                    Ok(Transformed::no(e))
191                })
192                .map(|t| t.data)
193        };
194
195        let projected_body = CaseBody {
196            expr: self.expr.as_ref().map(project).transpose()?,
197            when_then_expr: self
198                .when_then_expr
199                .iter()
200                .map(|(e, t)| Ok((project(e)?, project(t)?)))
201                .collect::<Result<Vec<_>>>()?,
202            else_expr: self.else_expr.as_ref().map(project).transpose()?,
203        };
204
205        // Construct the projection vector
206        let projection = column_index_map
207            .iter()
208            .sorted_by_key(|(_, v)| **v)
209            .map(|(k, _)| *k)
210            .collect::<Vec<_>>();
211
212        Ok(ProjectedCaseBody {
213            projection,
214            body: projected_body,
215            supports_projection,
216        })
217    }
218}
219
220/// A derived case body that can be used to evaluate a case expression after projecting
221/// record batches using a projection vector.
222///
223/// This is used to avoid filtering columns that are not used in the
224/// input `RecordBatch` when progressively evaluating a `CASE` expression's
225/// remainder batches. Filtering these columns is wasteful since for a record
226/// batch of `n` rows, filtering requires at worst a copy of `n - 1` values
227/// per array. If these filtered values will never be accessed, the time spent
228/// producing them is better avoided.
229///
230/// For example, if we are evaluating the following case expression that
231/// only references columns B and D:
232///
233/// ```sql
234/// SELECT CASE WHEN B > 10 THEN D ELSE NULL END FROM (VALUES (...)) T(A, B, C, D)
235/// ```
236///
237/// Of the 4 input columns `[A, B, C, D]`, the `CASE` expression only access `B` and `D`.
238/// Filtering `A` and `C` would be unnecessary and wasteful.
239///
240/// If we only retain columns `B` and `D` using `RecordBatch::project` and the projection vector
241/// `[1, 3]`, the indices of these two columns will change to `[0, 1]`. To evaluate the
242/// case expression, it will need to be rewritten from `CASE WHEN B@1 > 10 THEN D@3 ELSE NULL END`
243/// to `CASE WHEN B@0 > 10 THEN D@1 ELSE NULL END`.
244///
245/// The projection vector and the rewritten expression (which only differs from the original in
246/// column reference indices) are held in a `ProjectedCaseBody`.
247///
248/// When `supports_projection` is false, evaluation uses the original body and full batch because
249/// the expression may depend on input columns that are not visible in its children.
250#[derive(Debug, Hash, PartialEq, Eq)]
251struct ProjectedCaseBody {
252    projection: Vec<usize>,
253    body: CaseBody,
254    /// Whether `body` is safe to evaluate against a projected batch.
255    ///
256    /// When false, `projection` and the rewritten `body` must not be used because an
257    /// expression may read input columns without exposing them through its children.
258    supports_projection: bool,
259}
260
261impl ProjectedCaseBody {
262    /// Returns a projection when evaluating the derived body can avoid unused input columns.
263    fn projection_for(&self, batch: &RecordBatch) -> Option<Vec<usize>> {
264        let projection = self
265            .projection
266            .iter()
267            .copied()
268            .filter(|index| *index < batch.num_columns())
269            .collect::<Vec<_>>();
270        (self.supports_projection && projection.len() < batch.num_columns())
271            .then_some(projection)
272    }
273}
274
275/// The CASE expression is similar to a series of nested if/else and there are two forms that
276/// can be used. The first form consists of a series of boolean "when" expressions with
277/// corresponding "then" expressions, and an optional "else" expression.
278///
279/// CASE WHEN condition THEN result
280///      [WHEN ...]
281///      [ELSE result]
282/// END
283///
284/// The second form uses a base expression and then a series of "when" clauses that match on a
285/// literal value.
286///
287/// CASE expression
288///     WHEN value THEN result
289///     [WHEN ...]
290///     [ELSE result]
291/// END
292#[derive(Debug)]
293pub struct CaseExpr {
294    /// The case expression body
295    body: CaseBody,
296    /// Evaluation method to use
297    eval_method: EvalMethod,
298}
299
300// eval_method is functionally derived from body, so excluding it from
301// Hash/Eq avoids redundantly hashing the expression tree twice. For
302// nested CASE chains this prevents exponential blowup (see #22173).
303impl Hash for CaseExpr {
304    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
305        self.body.hash(state);
306    }
307}
308
309impl PartialEq for CaseExpr {
310    fn eq(&self, other: &Self) -> bool {
311        self.body == other.body
312    }
313}
314
315impl Eq for CaseExpr {}
316
317impl std::fmt::Display for CaseExpr {
318    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
319        write!(f, "CASE ")?;
320        if let Some(e) = &self.body.expr {
321            write!(f, "{e} ")?;
322        }
323        for (w, t) in &self.body.when_then_expr {
324            write!(f, "WHEN {w} THEN {t} ")?;
325        }
326        if let Some(e) = &self.body.else_expr {
327            write!(f, "ELSE {e} ")?;
328        }
329        write!(f, "END")
330    }
331}
332
333/// This is a specialization for a specific use case where we can take a fast path
334/// for expressions that are infallible and can be cheaply computed for the entire
335/// record batch rather than just for the rows where the predicate is true. For now,
336/// this is limited to use with Column expressions but could potentially be used for other
337/// expressions in the future
338fn is_cheap_and_infallible(expr: &Arc<dyn PhysicalExpr>) -> bool {
339    expr.is::<Column>()
340}
341
342/// Creates a [FilterPredicate] from a boolean array.
343fn create_filter(predicate: &BooleanArray, optimize: bool) -> FilterPredicate {
344    let mut filter_builder = FilterBuilder::new(predicate);
345    if optimize {
346        // Always optimize the filter since we use them multiple times.
347        filter_builder = filter_builder.optimize();
348    }
349    filter_builder.build()
350}
351
352fn multiple_arrays(data_type: &DataType) -> bool {
353    match data_type {
354        DataType::Struct(fields) => {
355            fields.len() > 1
356                || fields.len() == 1 && multiple_arrays(fields[0].data_type())
357        }
358        DataType::Union(fields, UnionMode::Sparse) => !fields.is_empty(),
359        _ => false,
360    }
361}
362
363// This should be removed when https://github.com/apache/arrow-rs/pull/8693
364// is merged and becomes available.
365fn filter_record_batch(
366    record_batch: &RecordBatch,
367    filter: &FilterPredicate,
368) -> std::result::Result<RecordBatch, ArrowError> {
369    let filtered_columns = record_batch
370        .columns()
371        .iter()
372        .map(|a| filter_array(a, filter))
373        .collect::<std::result::Result<Vec<_>, _>>()?;
374    // SAFETY: since we start from a valid RecordBatch, there's no need to revalidate the schema
375    // since the set of columns has not changed.
376    // The input column arrays all had the same length (since they're coming from a valid RecordBatch)
377    // and the filtering them with the same filter will produces a new set of arrays with identical
378    // lengths.
379    unsafe {
380        Ok(RecordBatch::new_unchecked(
381            record_batch.schema(),
382            filtered_columns,
383            filter.count(),
384        ))
385    }
386}
387
388// This function exists purely to be able to use the same call style
389// for `filter_record_batch` and `filter_array` at the point of use.
390// When https://github.com/apache/arrow-rs/pull/8693 is available, replace
391// both with method calls on `FilterPredicate`.
392#[inline(always)]
393fn filter_array(
394    array: &dyn Array,
395    filter: &FilterPredicate,
396) -> std::result::Result<ArrayRef, ArrowError> {
397    filter.filter(array)
398}
399
400/// An index into the partial results array that's more compact than `usize`.
401///
402/// `u32::MAX` is reserved as a special 'none' value. This is used instead of
403/// `Option` to keep the array of indices as compact as possible.
404#[derive(Copy, Clone, PartialEq, Eq)]
405struct PartialResultIndex {
406    index: u32,
407}
408
409const NONE_VALUE: u32 = u32::MAX;
410
411impl PartialResultIndex {
412    /// Returns the 'none' placeholder value.
413    fn none() -> Self {
414        Self { index: NONE_VALUE }
415    }
416
417    fn zero() -> Self {
418        Self { index: 0 }
419    }
420
421    /// Creates a new partial result index.
422    ///
423    /// If the provided value is greater than or equal to `u32::MAX`
424    /// an error will be returned.
425    fn try_new(index: usize) -> Result<Self> {
426        let Ok(index) = u32::try_from(index) else {
427            return internal_err!("Partial result index exceeds limit");
428        };
429
430        assert_or_internal_err!(
431            index != NONE_VALUE,
432            "Partial result index exceeds limit"
433        );
434
435        Ok(Self { index })
436    }
437
438    /// Determines if this index is the 'none' placeholder value or not.
439    fn is_none(&self) -> bool {
440        self.index == NONE_VALUE
441    }
442}
443
444impl MergeIndex for PartialResultIndex {
445    /// Returns `Some(index)` if this value is not the 'none' placeholder, `None` otherwise.
446    fn index(&self) -> Option<usize> {
447        if self.is_none() {
448            None
449        } else {
450            Some(self.index as usize)
451        }
452    }
453}
454
455impl Debug for PartialResultIndex {
456    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
457        if self.is_none() {
458            write!(f, "null")
459        } else {
460            write!(f, "{}", self.index)
461        }
462    }
463}
464
465enum ResultState {
466    /// The final result is an array containing only null values.
467    Empty,
468    /// The final result needs to be computed by merging the data in `arrays`.
469    Partial {
470        // A `Vec` of partial results that should be merged.
471        // `partial_result_indices` contains indexes into this vec.
472        arrays: Vec<ArrayRef>,
473        // Indicates per result row from which array in `partial_results` a value should be taken.
474        indices: Vec<PartialResultIndex>,
475    },
476    /// A single branch matched all input rows. When creating the final result, no further merging
477    /// of partial results is necessary.
478    Complete(ColumnarValue),
479}
480
481/// A builder for constructing result arrays for CASE expressions.
482///
483/// Rather than building a monolithic array containing all results, it maintains a set of
484/// partial result arrays and a mapping that indicates for each row which partial array
485/// contains the result value for that row.
486///
487/// On finish(), the builder will merge all partial results into a single array if necessary.
488/// If all rows evaluated to the same array, that array can be returned directly without
489/// any merging overhead.
490struct ResultBuilder {
491    data_type: DataType,
492    /// The number of rows in the final result.
493    row_count: usize,
494    state: ResultState,
495}
496
497impl ResultBuilder {
498    /// Creates a new ResultBuilder that will produce arrays of the given data type.
499    ///
500    /// The `row_count` parameter indicates the number of rows in the final result.
501    fn new(data_type: &DataType, row_count: usize) -> Self {
502        Self {
503            data_type: data_type.clone(),
504            row_count,
505            state: ResultState::Empty,
506        }
507    }
508
509    /// Adds a result for one branch of the case expression.
510    ///
511    /// `row_indices` should be a [UInt32Array] containing [RecordBatch] relative row indices
512    /// for which `value` contains result values.
513    ///
514    /// If `value` is a scalar, the scalar value will be used as the value for each row in `row_indices`.
515    ///
516    /// If `value` is an array, the values from the array and the indices from `row_indices` will be
517    /// processed pairwise. The lengths of `value` and `row_indices` must match.
518    ///
519    /// The diagram below shows a situation where a when expression matched rows 1 and 4 of the
520    /// record batch. The then expression produced the value array `[A, D]`.
521    /// After adding this result, the result array will have been added to `partial arrays` and
522    /// `partial indices` will have been updated at indexes `1` and `4`.
523    ///
524    /// ```text
525    ///  ┌─────────┐     ┌─────────┐┌───────────┐                            ┌─────────┐┌───────────┐
526    ///  │    C    │     │ 0: None ││┌ 0 ──────┐│                            │ 0: None ││┌ 0 ──────┐│
527    ///  ├─────────┤     ├─────────┤││    A    ││                            ├─────────┤││    A    ││
528    ///  │    D    │     │ 1: None ││└─────────┘│                            │ 1:  2   ││└─────────┘│
529    ///  └─────────┘     ├─────────┤│┌ 1 ──────┐│   add_branch_result(       ├─────────┤│┌ 1 ──────┐│
530    ///   matching       │ 2:  0   │││    B    ││     row indices,           │ 2:  0   │││    B    ││
531    /// 'then' values    ├─────────┤│└─────────┘│     value                  ├─────────┤│└─────────┘│
532    ///                  │ 3: None ││           │   )                        │ 3: None ││┌ 2 ──────┐│
533    ///  ┌─────────┐     ├─────────┤│           │ ─────────────────────────▶ ├─────────┤││    C    ││
534    ///  │    1    │     │ 4: None ││           │                            │ 4:  2   ││├─────────┤│
535    ///  ├─────────┤     ├─────────┤│           │                            ├─────────┤││    D    ││
536    ///  │    4    │     │ 5:  1   ││           │                            │ 5:  1   ││└─────────┘│
537    ///  └─────────┘     └─────────┘└───────────┘                            └─────────┘└───────────┘
538    /// row indices        partial     partial                                 partial     partial
539    ///                    indices     arrays                                  indices     arrays
540    /// ```
541    fn add_branch_result(
542        &mut self,
543        row_indices: &ArrayRef,
544        value: ColumnarValue,
545    ) -> Result<()> {
546        match value {
547            ColumnarValue::Array(a) => {
548                if a.len() != row_indices.len() {
549                    internal_err!("Array length must match row indices length")
550                } else if row_indices.len() == self.row_count {
551                    self.set_complete_result(ColumnarValue::Array(a))
552                } else {
553                    self.add_partial_result(row_indices, a)
554                }
555            }
556            ColumnarValue::Scalar(s) => {
557                if row_indices.len() == self.row_count {
558                    self.set_complete_result(ColumnarValue::Scalar(s))
559                } else {
560                    self.add_partial_result(
561                        row_indices,
562                        s.to_array_of_size(row_indices.len())?,
563                    )
564                }
565            }
566        }
567    }
568
569    /// Adds a partial result array.
570    ///
571    /// This method adds the given array data as a partial result and updates the index mapping
572    /// to indicate that the specified rows should take their values from this array.
573    /// The partial results will be merged into a single array when finish() is called.
574    fn add_partial_result(
575        &mut self,
576        row_indices: &ArrayRef,
577        row_values: ArrayRef,
578    ) -> Result<()> {
579        assert_or_internal_err!(
580            row_indices.null_count() == 0,
581            "Row indices must not contain nulls"
582        );
583
584        match &mut self.state {
585            ResultState::Empty => {
586                let array_index = PartialResultIndex::zero();
587                let mut indices = vec![PartialResultIndex::none(); self.row_count];
588                for row_ix in row_indices.as_primitive::<UInt32Type>().values().iter() {
589                    indices[*row_ix as usize] = array_index;
590                }
591
592                self.state = ResultState::Partial {
593                    arrays: vec![row_values],
594                    indices,
595                };
596
597                Ok(())
598            }
599            ResultState::Partial { arrays, indices } => {
600                let array_index = PartialResultIndex::try_new(arrays.len())?;
601
602                arrays.push(row_values);
603
604                for row_ix in row_indices.as_primitive::<UInt32Type>().values().iter() {
605                    // This is check is only active for debug config because the callers of this method,
606                    // `case_when_with_expr` and `case_when_no_expr`, already ensure that
607                    // they only calculate a value for each row at most once.
608                    #[cfg(debug_assertions)]
609                    assert_or_internal_err!(
610                        indices[*row_ix as usize].is_none(),
611                        "Duplicate value for row {}",
612                        *row_ix
613                    );
614
615                    indices[*row_ix as usize] = array_index;
616                }
617                Ok(())
618            }
619            ResultState::Complete(_) => internal_err!(
620                "Cannot add a partial result when complete result is already set"
621            ),
622        }
623    }
624
625    /// Sets a result that applies to all rows.
626    ///
627    /// This is an optimization for cases where all rows evaluate to the same result.
628    /// When a complete result is set, the builder will return it directly from finish()
629    /// without any merging overhead.
630    fn set_complete_result(&mut self, value: ColumnarValue) -> Result<()> {
631        match &self.state {
632            ResultState::Empty => {
633                self.state = ResultState::Complete(value);
634                Ok(())
635            }
636            ResultState::Partial { .. } => {
637                internal_err!(
638                    "Cannot set a complete result when there are already partial results"
639                )
640            }
641            ResultState::Complete(_) => internal_err!("Complete result already set"),
642        }
643    }
644
645    /// Finishes building the result and returns the final array.
646    fn finish(self) -> Result<ColumnarValue> {
647        match self.state {
648            ResultState::Empty => {
649                // No complete result and no partial results.
650                // This can happen for case expressions with no else branch where no rows
651                // matched.
652                Ok(ColumnarValue::Scalar(ScalarValue::try_new_null(
653                    &self.data_type,
654                )?))
655            }
656            ResultState::Partial { arrays, indices } => {
657                // Merge partial results into a single array.
658                let array_refs = arrays.iter().map(|a| a.as_ref()).collect::<Vec<_>>();
659                Ok(ColumnarValue::Array(merge_n(&array_refs, &indices)?))
660            }
661            ResultState::Complete(v) => {
662                // If we have a complete result, we can just return it.
663                Ok(v)
664            }
665        }
666    }
667}
668
669impl CaseExpr {
670    /// Create a new CASE WHEN expression
671    pub fn try_new(
672        expr: Option<Arc<dyn PhysicalExpr>>,
673        when_then_expr: Vec<WhenThen>,
674        else_expr: Option<Arc<dyn PhysicalExpr>>,
675    ) -> Result<Self> {
676        // normalize null literals to None in the else_expr (this already happens
677        // during SQL planning, but not necessarily for other use cases)
678        let else_expr = match &else_expr {
679            Some(e) => match e.downcast_ref::<Literal>() {
680                Some(lit) if lit.value().is_null() => None,
681                _ => else_expr,
682            },
683            _ => else_expr,
684        };
685
686        if when_then_expr.is_empty() {
687            return exec_err!("There must be at least one WHEN clause");
688        }
689
690        let body = CaseBody {
691            expr,
692            when_then_expr,
693            else_expr,
694        };
695
696        let eval_method = Self::find_best_eval_method(&body)?;
697
698        Ok(Self { body, eval_method })
699    }
700
701    fn find_best_eval_method(body: &CaseBody) -> Result<EvalMethod> {
702        if body.expr.is_some() {
703            if let Some(mapping) = LiteralLookupTable::maybe_new(body) {
704                return Ok(EvalMethod::WithExprScalarLookupTable(mapping));
705            }
706
707            return Ok(EvalMethod::WithExpression(body.project()?));
708        }
709
710        Ok(
711            if body.when_then_expr.len() == 1
712                && is_cheap_and_infallible(&(body.when_then_expr[0].1))
713                && body.else_expr.is_none()
714            {
715                EvalMethod::InfallibleExprOrNull
716            } else if body.when_then_expr.len() == 1
717                && body.when_then_expr[0].1.is::<Literal>()
718                && body.else_expr.is_some()
719                && body.else_expr.as_ref().unwrap().is::<Literal>()
720            {
721                EvalMethod::ScalarOrScalar
722            } else if body.when_then_expr.len() == 1 {
723                EvalMethod::ExpressionOrExpression(body.project()?)
724            } else {
725                EvalMethod::NoExpression(body.project()?)
726            },
727        )
728    }
729
730    /// Optional base expression that can be compared to literal values in the "when" expressions
731    pub fn expr(&self) -> Option<&Arc<dyn PhysicalExpr>> {
732        self.body.expr.as_ref()
733    }
734
735    /// One or more when/then expressions
736    pub fn when_then_expr(&self) -> &[WhenThen] {
737        &self.body.when_then_expr
738    }
739
740    /// Optional "else" expression
741    pub fn else_expr(&self) -> Option<&Arc<dyn PhysicalExpr>> {
742        self.body.else_expr.as_ref()
743    }
744}
745
746impl CaseBody {
747    fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
748        // since all then results have the same data type, we can choose any one as the
749        // return data type except for the null.
750        let mut data_type = DataType::Null;
751        for i in 0..self.when_then_expr.len() {
752            data_type = self.when_then_expr[i].1.data_type(input_schema)?;
753            if !data_type.equals_datatype(&DataType::Null) {
754                break;
755            }
756        }
757        // if all then results are null, we use data type of else expr instead if possible.
758        if data_type.equals_datatype(&DataType::Null)
759            && let Some(e) = &self.else_expr
760        {
761            data_type = e.data_type(input_schema)?;
762        }
763
764        Ok(data_type)
765    }
766
767    /// See [CaseExpr::case_when_with_expr].
768    fn case_when_with_expr(
769        &self,
770        batch: &RecordBatch,
771        return_type: &DataType,
772    ) -> Result<ColumnarValue> {
773        let mut result_builder = ResultBuilder::new(return_type, batch.num_rows());
774
775        // `remainder_rows` contains the indices of the rows that need to be evaluated
776        let mut remainder_rows: ArrayRef =
777            Arc::new(UInt32Array::from_iter_values(0..batch.num_rows() as u32));
778        // `remainder_batch` contains the rows themselves that need to be evaluated
779        let mut remainder_batch = Cow::Borrowed(batch);
780
781        // evaluate the base expression
782        let mut base_values = self
783            .expr
784            .as_ref()
785            .unwrap()
786            .evaluate(batch)?
787            .into_array(batch.num_rows())?;
788
789        // Fill in a result value already for rows where the base expression value is null
790        // Since each when expression is tested against the base expression using the equality
791        // operator, null base values can never match any when expression. `x = NULL` is falsy,
792        // for all possible values of `x`.
793        let base_null_count = base_values.logical_null_count();
794        if base_null_count > 0 {
795            // Use `is_not_null` since this is a cheap clone of the null buffer from 'base_value'.
796            // We already checked there are nulls, so we can be sure a new buffer will not be
797            // created.
798            let base_not_nulls = is_not_null(base_values.as_ref())?;
799            let base_all_null = base_null_count == remainder_batch.num_rows();
800
801            // If there is an else expression, use that as the default value for the null rows
802            // Otherwise the default `null` value from the result builder will be used.
803            if let Some(e) = &self.else_expr {
804                let expr = try_cast(Arc::clone(e), &batch.schema(), return_type.clone())?;
805
806                if base_all_null {
807                    // All base values were null, so no need to filter
808                    let nulls_value = expr.evaluate(&remainder_batch)?;
809                    result_builder.add_branch_result(&remainder_rows, nulls_value)?;
810                } else {
811                    // Filter out the null rows and evaluate the else expression for those
812                    let nulls_filter = create_filter(&not(&base_not_nulls)?, true);
813                    let nulls_batch =
814                        filter_record_batch(&remainder_batch, &nulls_filter)?;
815                    let nulls_rows = filter_array(&remainder_rows, &nulls_filter)?;
816                    let nulls_value = expr.evaluate(&nulls_batch)?;
817                    result_builder.add_branch_result(&nulls_rows, nulls_value)?;
818                }
819            }
820
821            // All base values are null, so we can return early
822            if base_all_null {
823                return result_builder.finish();
824            }
825
826            // Remove the null rows from the remainder batch
827            let not_null_filter = create_filter(&base_not_nulls, true);
828            remainder_batch =
829                Cow::Owned(filter_record_batch(&remainder_batch, &not_null_filter)?);
830            remainder_rows = filter_array(&remainder_rows, &not_null_filter)?;
831            base_values = filter_array(&base_values, &not_null_filter)?;
832        }
833
834        // The types of case and when expressions will be coerced to match.
835        // We only need to check if the base_value is nested.
836        let base_value_is_nested = base_values.data_type().is_nested();
837
838        for i in 0..self.when_then_expr.len() {
839            // Evaluate the 'when' predicate for the remainder batch
840            // This results in a boolean array with the same length as the remaining number of rows
841            let when_expr = &self.when_then_expr[i].0;
842            let when_value = match when_expr.evaluate(&remainder_batch)? {
843                ColumnarValue::Array(a) => {
844                    compare_with_eq(&a, &base_values, base_value_is_nested)
845                }
846                ColumnarValue::Scalar(s) => {
847                    compare_with_eq(&s.to_scalar()?, &base_values, base_value_is_nested)
848                }
849            }?;
850
851            // If the 'when' predicate did not match any rows, continue to the next branch immediately.
852            // Only counts valid slots that are true (masked-null predicate slots are ignored),
853            // so no `prep_null_mask_filter` needed here.
854            if !when_value.has_true() {
855                continue;
856            }
857
858            // If the 'when' predicate matched all remaining rows, there is no need to filter
859            if when_value.null_count() == 0 && !when_value.has_false() {
860                let then_expression = &self.when_then_expr[i].1;
861                let then_value = then_expression.evaluate(&remainder_batch)?;
862                result_builder.add_branch_result(&remainder_rows, then_value)?;
863                return result_builder.finish();
864            }
865
866            // Filter the remainder batch based on the 'when' value
867            // This results in a batch containing only the rows that need to be evaluated
868            // for the current branch
869            // Still no need to call `prep_null_mask_filter` since `create_filter` will already do
870            // this unconditionally.
871            let then_filter = create_filter(&when_value, true);
872            let then_batch = filter_record_batch(&remainder_batch, &then_filter)?;
873            let then_rows = filter_array(&remainder_rows, &then_filter)?;
874
875            let then_expression = &self.when_then_expr[i].1;
876            let then_value = then_expression.evaluate(&then_batch)?;
877            result_builder.add_branch_result(&then_rows, then_value)?;
878
879            // If this is the last 'when' branch and there is no 'else' expression, there's no
880            // point in calculating the remaining rows.
881            if self.else_expr.is_none() && i == self.when_then_expr.len() - 1 {
882                return result_builder.finish();
883            }
884
885            // Prepare the next when branch (or the else branch)
886            let next_selection = match when_value.null_count() {
887                0 => not(&when_value),
888                _ => {
889                    // `prep_null_mask_filter` is required to ensure the not operation treats nulls
890                    // as false
891                    not(&prep_null_mask_filter(&when_value))
892                }
893            }?;
894            let next_filter = create_filter(&next_selection, true);
895            remainder_batch =
896                Cow::Owned(filter_record_batch(&remainder_batch, &next_filter)?);
897            remainder_rows = filter_array(&remainder_rows, &next_filter)?;
898            base_values = filter_array(&base_values, &next_filter)?;
899        }
900
901        // If we reached this point, some rows were left unmatched.
902        // Check if those need to be evaluated using the 'else' expression.
903        if let Some(e) = &self.else_expr {
904            // keep `else_expr`'s data type and return type consistent
905            let expr = try_cast(Arc::clone(e), &batch.schema(), return_type.clone())?;
906            let else_value = expr.evaluate(&remainder_batch)?;
907            result_builder.add_branch_result(&remainder_rows, else_value)?;
908        }
909
910        result_builder.finish()
911    }
912
913    /// See [CaseExpr::case_when_no_expr].
914    fn case_when_no_expr(
915        &self,
916        batch: &RecordBatch,
917        return_type: &DataType,
918    ) -> Result<ColumnarValue> {
919        let mut result_builder = ResultBuilder::new(return_type, batch.num_rows());
920
921        // `remainder_rows` contains the indices of the rows that need to be evaluated
922        let mut remainder_rows: ArrayRef =
923            Arc::new(UInt32Array::from_iter(0..batch.num_rows() as u32));
924        // `remainder_batch` contains the rows themselves that need to be evaluated
925        let mut remainder_batch = Cow::Borrowed(batch);
926
927        for i in 0..self.when_then_expr.len() {
928            // Evaluate the 'when' predicate for the remainder batch
929            // This results in a boolean array with the same length as the remaining number of rows
930            let when_predicate = &self.when_then_expr[i].0;
931            let when_value = when_predicate
932                .evaluate(&remainder_batch)?
933                .into_array(remainder_batch.num_rows())?;
934            let when_value = as_boolean_array(&when_value).map_err(|_| {
935                internal_datafusion_err!("WHEN expression did not return a BooleanArray")
936            })?;
937
938            // If the 'when' predicate did not match any rows, continue to the next branch immediately.
939            // Only counts valid slots that are true (masked-null predicate slots are ignored)
940            // so no `prep_null_mask_filter` needed here.
941            if !when_value.has_true() {
942                continue;
943            }
944
945            // If the 'when' predicate matched all remaining rows, there is no need to filter
946            if when_value.null_count() == 0 && !when_value.has_false() {
947                let then_expression = &self.when_then_expr[i].1;
948                let then_value = then_expression.evaluate(&remainder_batch)?;
949                result_builder.add_branch_result(&remainder_rows, then_value)?;
950                return result_builder.finish();
951            }
952
953            // Filter the remainder batch based on the 'when' value
954            // This results in a batch containing only the rows that need to be evaluated
955            // for the current branch
956            // Still no need to call `prep_null_mask_filter` since `create_filter` will already do
957            // this unconditionally.
958            let then_filter = create_filter(when_value, true);
959            let then_batch = filter_record_batch(&remainder_batch, &then_filter)?;
960            let then_rows = filter_array(&remainder_rows, &then_filter)?;
961
962            let then_expression = &self.when_then_expr[i].1;
963            let then_value = then_expression.evaluate(&then_batch)?;
964            result_builder.add_branch_result(&then_rows, then_value)?;
965
966            // If this is the last 'when' branch and there is no 'else' expression, there's no
967            // point in calculating the remaining rows.
968            if self.else_expr.is_none() && i == self.when_then_expr.len() - 1 {
969                return result_builder.finish();
970            }
971
972            // Prepare the next when branch (or the else branch)
973            let next_selection = match when_value.null_count() {
974                0 => not(when_value),
975                _ => {
976                    // `prep_null_mask_filter` is required to ensure the not operation treats nulls
977                    // as false
978                    not(&prep_null_mask_filter(when_value))
979                }
980            }?;
981            let next_filter = create_filter(&next_selection, true);
982            remainder_batch =
983                Cow::Owned(filter_record_batch(&remainder_batch, &next_filter)?);
984            remainder_rows = filter_array(&remainder_rows, &next_filter)?;
985        }
986
987        // If we reached this point, some rows were left unmatched.
988        // Check if those need to be evaluated using the 'else' expression.
989        if let Some(e) = &self.else_expr {
990            // keep `else_expr`'s data type and return type consistent
991            let expr = try_cast(Arc::clone(e), &batch.schema(), return_type.clone())?;
992            let else_value = expr.evaluate(&remainder_batch)?;
993            result_builder.add_branch_result(&remainder_rows, else_value)?;
994        }
995
996        result_builder.finish()
997    }
998
999    /// See [CaseExpr::expr_or_expr].
1000    fn expr_or_expr(
1001        &self,
1002        batch: &RecordBatch,
1003        when_value: &BooleanArray,
1004    ) -> Result<ColumnarValue> {
1005        let when_value = match when_value.null_count() {
1006            0 => Cow::Borrowed(when_value),
1007            _ => {
1008                // `prep_null_mask_filter` is required to ensure null is treated as false
1009                Cow::Owned(prep_null_mask_filter(when_value))
1010            }
1011        };
1012
1013        let optimize_filter = batch.num_columns() > 1
1014            || (batch.num_columns() == 1 && multiple_arrays(batch.column(0).data_type()));
1015
1016        let when_filter = create_filter(&when_value, optimize_filter);
1017        let then_batch = filter_record_batch(batch, &when_filter)?;
1018        let then_value = self.when_then_expr[0].1.evaluate(&then_batch)?;
1019
1020        match &self.else_expr {
1021            None => {
1022                let then_array = then_value.to_array(when_value.true_count())?;
1023                scatter(&when_value, then_array.as_ref()).map(ColumnarValue::Array)
1024            }
1025            Some(else_expr) => {
1026                let else_selection = not(&when_value)?;
1027                let else_filter = create_filter(&else_selection, optimize_filter);
1028                let else_batch = filter_record_batch(batch, &else_filter)?;
1029
1030                // keep `else_expr`'s data type and return type consistent
1031                let return_type = self.data_type(&batch.schema())?;
1032                let else_expr =
1033                    try_cast(Arc::clone(else_expr), &batch.schema(), return_type.clone())
1034                        .unwrap_or_else(|_| Arc::clone(else_expr));
1035
1036                let else_value = else_expr.evaluate(&else_batch)?;
1037
1038                Ok(ColumnarValue::Array(match (then_value, else_value) {
1039                    (ColumnarValue::Array(t), ColumnarValue::Array(e)) => {
1040                        merge(&when_value, &t, &e)
1041                    }
1042                    (ColumnarValue::Scalar(t), ColumnarValue::Array(e)) => {
1043                        merge(&when_value, &t.to_scalar()?, &e)
1044                    }
1045                    (ColumnarValue::Array(t), ColumnarValue::Scalar(e)) => {
1046                        merge(&when_value, &t, &e.to_scalar()?)
1047                    }
1048                    (ColumnarValue::Scalar(t), ColumnarValue::Scalar(e)) => {
1049                        merge(&when_value, &t.to_scalar()?, &e.to_scalar()?)
1050                    }
1051                }?))
1052            }
1053        }
1054    }
1055}
1056
1057impl CaseExpr {
1058    /// This function evaluates the form of CASE that matches an expression to fixed values.
1059    ///
1060    /// CASE expression
1061    ///     WHEN value THEN result
1062    ///     [WHEN ...]
1063    ///     [ELSE result]
1064    /// END
1065    fn case_when_with_expr(
1066        &self,
1067        batch: &RecordBatch,
1068        projected: &ProjectedCaseBody,
1069    ) -> Result<ColumnarValue> {
1070        let return_type = self.data_type(&batch.schema())?;
1071        if let Some(projection) = projected.projection_for(batch) {
1072            let projected_batch = batch.project(&projection)?;
1073            projected
1074                .body
1075                .case_when_with_expr(&projected_batch, &return_type)
1076        } else {
1077            self.body.case_when_with_expr(batch, &return_type)
1078        }
1079    }
1080
1081    /// This function evaluates the form of CASE where each WHEN expression is a boolean
1082    /// expression.
1083    ///
1084    /// CASE WHEN condition THEN result
1085    ///      [WHEN ...]
1086    ///      [ELSE result]
1087    /// END
1088    fn case_when_no_expr(
1089        &self,
1090        batch: &RecordBatch,
1091        projected: &ProjectedCaseBody,
1092    ) -> Result<ColumnarValue> {
1093        let return_type = self.data_type(&batch.schema())?;
1094        if let Some(projection) = projected.projection_for(batch) {
1095            let projected_batch = batch.project(&projection)?;
1096            projected
1097                .body
1098                .case_when_no_expr(&projected_batch, &return_type)
1099        } else {
1100            self.body.case_when_no_expr(batch, &return_type)
1101        }
1102    }
1103
1104    /// This function evaluates the specialized case of:
1105    ///
1106    /// CASE WHEN condition THEN column
1107    ///      [ELSE NULL]
1108    /// END
1109    ///
1110    /// Note that this function is only safe to use for "then" expressions
1111    /// that are infallible because the expression will be evaluated for all
1112    /// rows in the input batch.
1113    fn case_column_or_null(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
1114        let when_expr = &self.body.when_then_expr[0].0;
1115        let then_expr = &self.body.when_then_expr[0].1;
1116
1117        match when_expr.evaluate(batch)? {
1118            // WHEN true --> column
1119            ColumnarValue::Scalar(ScalarValue::Boolean(Some(true))) => {
1120                then_expr.evaluate(batch)
1121            }
1122            // WHEN [false | null] --> NULL
1123            ColumnarValue::Scalar(_) => {
1124                // return scalar NULL value
1125                ScalarValue::try_from(self.data_type(&batch.schema())?)
1126                    .map(ColumnarValue::Scalar)
1127            }
1128            // WHEN column --> column
1129            ColumnarValue::Array(bit_mask) => {
1130                let bit_mask = bit_mask
1131                    .as_any()
1132                    .downcast_ref::<BooleanArray>()
1133                    .expect("predicate should evaluate to a boolean array");
1134                // invert the bitmask
1135                let bit_mask = match bit_mask.null_count() {
1136                    0 => not(bit_mask)?,
1137                    _ => not(&prep_null_mask_filter(bit_mask))?,
1138                };
1139                match then_expr.evaluate(batch)? {
1140                    ColumnarValue::Array(array) => {
1141                        Ok(ColumnarValue::Array(nullif(&array, &bit_mask)?))
1142                    }
1143                    ColumnarValue::Scalar(_) => {
1144                        internal_err!("expression did not evaluate to an array")
1145                    }
1146                }
1147            }
1148        }
1149    }
1150
1151    fn scalar_or_scalar(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
1152        let return_type = self.data_type(&batch.schema())?;
1153
1154        // evaluate when expression
1155        let when_value = self.body.when_then_expr[0].0.evaluate(batch)?;
1156        let when_value = when_value.into_array(batch.num_rows())?;
1157        let when_value = as_boolean_array(&when_value).map_err(|_| {
1158            internal_datafusion_err!("WHEN expression did not return a BooleanArray")
1159        })?;
1160
1161        // Treat 'NULL' as false value
1162        let when_value = match when_value.null_count() {
1163            0 => Cow::Borrowed(when_value),
1164            _ => Cow::Owned(prep_null_mask_filter(when_value)),
1165        };
1166
1167        // evaluate then_value
1168        let then_value = self.body.when_then_expr[0].1.evaluate(batch)?;
1169        let then_value = Scalar::new(then_value.into_array(1)?);
1170
1171        let Some(e) = &self.body.else_expr else {
1172            return internal_err!("expression did not evaluate to an array");
1173        };
1174        // keep `else_expr`'s data type and return type consistent
1175        let expr = try_cast(Arc::clone(e), &batch.schema(), return_type)?;
1176        let else_ = Scalar::new(expr.evaluate(batch)?.into_array(1)?);
1177        Ok(ColumnarValue::Array(zip(&when_value, &then_value, &else_)?))
1178    }
1179
1180    fn expr_or_expr(
1181        &self,
1182        batch: &RecordBatch,
1183        projected: &ProjectedCaseBody,
1184    ) -> Result<ColumnarValue> {
1185        // evaluate when condition on batch
1186        let when_value = self.body.when_then_expr[0].0.evaluate(batch)?;
1187        // `num_rows == 1` is intentional to avoid expanding scalars.
1188        // If the `when_value` is effectively a scalar, the 'all true' and 'all false' checks
1189        // below will avoid incorrectly using the scalar as a merge/zip mask.
1190        let when_value = when_value.into_array(1)?;
1191        let when_value = as_boolean_array(&when_value).map_err(|e| {
1192            DataFusionError::Context(
1193                "WHEN expression did not return a BooleanArray".to_string(),
1194                Box::new(e),
1195            )
1196        })?;
1197
1198        if when_value.null_count() == 0 && !when_value.has_false() {
1199            // All input rows are true, just call the 'then' expression
1200            self.body.when_then_expr[0].1.evaluate(batch)
1201        } else if !when_value.has_true() {
1202            // All input rows are false/null, just call the 'else' expression
1203            match &self.body.else_expr {
1204                Some(else_expr) => else_expr.evaluate(batch),
1205                None => {
1206                    let return_type = self.data_type(&batch.schema())?;
1207                    Ok(ColumnarValue::Scalar(ScalarValue::try_new_null(
1208                        &return_type,
1209                    )?))
1210                }
1211            }
1212        } else if let Some(projection) = projected.projection_for(batch) {
1213            // The case expressions do not use all the columns of the input batch.
1214            // Project first to reduce time spent filtering.
1215            let projected_batch = batch.project(&projection)?;
1216            projected.body.expr_or_expr(&projected_batch, when_value)
1217        } else {
1218            // All columns are used in the case expressions, so there is no need to project.
1219            self.body.expr_or_expr(batch, when_value)
1220        }
1221    }
1222
1223    fn with_lookup_table(
1224        &self,
1225        batch: &RecordBatch,
1226        lookup_table: &LiteralLookupTable,
1227    ) -> Result<ColumnarValue> {
1228        let expr = self.body.expr.as_ref().unwrap();
1229        let evaluated_expression = expr.evaluate(batch)?;
1230
1231        let is_scalar = matches!(evaluated_expression, ColumnarValue::Scalar(_));
1232        let evaluated_expression = evaluated_expression.to_array(1)?;
1233
1234        let values = lookup_table.map_keys_to_values(&evaluated_expression)?;
1235
1236        let result = if is_scalar {
1237            ColumnarValue::Scalar(ScalarValue::try_from_array(values.as_ref(), 0)?)
1238        } else {
1239            ColumnarValue::Array(values)
1240        };
1241
1242        Ok(result)
1243    }
1244}
1245
1246impl PhysicalExpr for CaseExpr {
1247    fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
1248        self.body.data_type(input_schema)
1249    }
1250
1251    fn nullable(&self, input_schema: &Schema) -> Result<bool> {
1252        let nullable_then = self.body.when_then_expr.iter().find_map(|(w, t)| {
1253            let is_nullable = match t.nullable(input_schema) {
1254                // Pass on error determining nullability verbatim
1255                Err(e) => return Some(Err(e)),
1256                Ok(n) => n,
1257            };
1258
1259            // Branches with a then expression that is not nullable do not impact the
1260            // nullability of the case expression.
1261            if !is_nullable {
1262                return None;
1263            }
1264
1265            // For case-with-expression assume all 'then' expressions are reachable
1266            if self.body.expr.is_some() {
1267                return Some(Ok(()));
1268            }
1269
1270            // For branches with a nullable 'then' expression, try to determine
1271            // if the 'then' expression is ever reachable in the situation where
1272            // it would evaluate to null.
1273
1274            // Replace the `then` expression with `NULL` in the `when` expression
1275            let with_null = match replace_with_null(
1276                w,
1277                unwrap_certainly_null_expr(t.as_ref()),
1278                input_schema,
1279            ) {
1280                Err(e) => return Some(Err(e)),
1281                Ok(e) => e,
1282            };
1283
1284            let can_be_true = match evaluate_predicate(&with_null).and_then(|bounds| {
1285                bounds.contains_value(ScalarValue::Boolean(Some(true)))
1286            }) {
1287                Err(e) => return Some(Err(e)),
1288                Ok(b) => b,
1289            };
1290
1291            if can_be_true { Some(Ok(())) } else { None }
1292        });
1293
1294        if let Some(nullable_then) = nullable_then {
1295            // There is at least one reachable nullable 'then' expression, so the case
1296            // expression itself is nullable.
1297            // Use `Result::map` to propagate the error from `nullable_then` if there is one.
1298            nullable_then.map(|_| true)
1299        } else if let Some(e) = &self.body.else_expr {
1300            // There are no reachable nullable 'then' expressions, so all we still need to
1301            // check is the 'else' expression's nullability.
1302            e.nullable(input_schema)
1303        } else {
1304            // CASE produces NULL if there is no `else` expr
1305            // (aka when none of the `when_then_exprs` match)
1306            Ok(true)
1307        }
1308    }
1309
1310    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
1311        match &self.eval_method {
1312            EvalMethod::WithExpression(p) => {
1313                // this use case evaluates "expr" and then compares the values with the "when"
1314                // values
1315                self.case_when_with_expr(batch, p)
1316            }
1317            EvalMethod::NoExpression(p) => {
1318                // The "when" conditions all evaluate to boolean in this use case and can be
1319                // arbitrary expressions
1320                self.case_when_no_expr(batch, p)
1321            }
1322            EvalMethod::InfallibleExprOrNull => {
1323                // Specialization for CASE WHEN expr THEN column [ELSE NULL] END
1324                self.case_column_or_null(batch)
1325            }
1326            EvalMethod::ScalarOrScalar => self.scalar_or_scalar(batch),
1327            EvalMethod::ExpressionOrExpression(p) => self.expr_or_expr(batch, p),
1328            EvalMethod::WithExprScalarLookupTable(lookup_table) => {
1329                self.with_lookup_table(batch, lookup_table)
1330            }
1331        }
1332    }
1333
1334    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
1335        let mut children = Vec::with_capacity(self.body.when_then_expr.len() * 2 + 2);
1336        if let Some(expr) = &self.body.expr {
1337            children.push(expr)
1338        }
1339        self.body.when_then_expr.iter().for_each(|(cond, value)| {
1340            children.push(cond);
1341            children.push(value);
1342        });
1343
1344        if let Some(else_expr) = &self.body.else_expr {
1345            children.push(else_expr)
1346        }
1347        children
1348    }
1349
1350    // For physical CaseExpr, we do not allow modifying children size
1351    fn with_new_children(
1352        self: Arc<Self>,
1353        children: Vec<Arc<dyn PhysicalExpr>>,
1354    ) -> Result<Arc<dyn PhysicalExpr>> {
1355        if children.len() != self.children().len() {
1356            internal_err!("CaseExpr: Wrong number of children")
1357        } else {
1358            let (expr, when_then_expr, else_expr) =
1359                match (self.expr().is_some(), self.body.else_expr.is_some()) {
1360                    (true, true) => (
1361                        Some(&children[0]),
1362                        &children[1..children.len() - 1],
1363                        Some(&children[children.len() - 1]),
1364                    ),
1365                    (true, false) => {
1366                        (Some(&children[0]), &children[1..children.len()], None)
1367                    }
1368                    (false, true) => (
1369                        None,
1370                        &children[0..children.len() - 1],
1371                        Some(&children[children.len() - 1]),
1372                    ),
1373                    (false, false) => (None, &children[0..children.len()], None),
1374                };
1375            Ok(Arc::new(CaseExpr::try_new(
1376                expr.cloned(),
1377                when_then_expr.iter().cloned().tuples().collect(),
1378                else_expr.cloned(),
1379            )?))
1380        }
1381    }
1382
1383    fn fmt_sql(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1384        write!(f, "CASE ")?;
1385        if let Some(e) = &self.body.expr {
1386            e.fmt_sql(f)?;
1387            write!(f, " ")?;
1388        }
1389
1390        for (w, t) in &self.body.when_then_expr {
1391            write!(f, "WHEN ")?;
1392            w.fmt_sql(f)?;
1393            write!(f, " THEN ")?;
1394            t.fmt_sql(f)?;
1395            write!(f, " ")?;
1396        }
1397
1398        if let Some(e) = &self.body.else_expr {
1399            write!(f, "ELSE ")?;
1400            e.fmt_sql(f)?;
1401            write!(f, " ")?;
1402        }
1403        write!(f, "END")
1404    }
1405
1406    #[cfg(feature = "proto")]
1407    fn try_to_proto(
1408        &self,
1409        ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
1410    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
1411        use datafusion_proto_models::protobuf;
1412
1413        let Self {
1414            body,
1415            // Derived from `body` by `try_new` on decode.
1416            eval_method: _,
1417        } = self;
1418        let CaseBody {
1419            expr,
1420            when_then_expr,
1421            else_expr,
1422        } = body;
1423
1424        Ok(Some(protobuf::PhysicalExprNode {
1425            expr_id: None,
1426            expr_type: Some(protobuf::physical_expr_node::ExprType::Case(Box::new(
1427                protobuf::PhysicalCaseNode {
1428                    expr: expr
1429                        .as_ref()
1430                        .map(|expr| ctx.encode_child(expr).map(Box::new))
1431                        .transpose()?,
1432                    when_then_expr: when_then_expr
1433                        .iter()
1434                        .map(|(when_expr, then_expr)| {
1435                            Ok(protobuf::PhysicalWhenThen {
1436                                when_expr: Some(ctx.encode_child(when_expr)?),
1437                                then_expr: Some(ctx.encode_child(then_expr)?),
1438                            })
1439                        })
1440                        .collect::<Result<Vec<_>>>()?,
1441                    else_expr: else_expr
1442                        .as_ref()
1443                        .map(|expr| ctx.encode_child(expr).map(Box::new))
1444                        .transpose()?,
1445                },
1446            ))),
1447        }))
1448    }
1449}
1450
1451#[cfg(feature = "proto")]
1452impl CaseExpr {
1453    /// Reconstruct a [`CaseExpr`] from its protobuf representation.
1454    pub fn try_from_proto(
1455        node: &datafusion_proto_models::protobuf::PhysicalExprNode,
1456        ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
1457    ) -> Result<Arc<dyn PhysicalExpr>> {
1458        use datafusion_physical_expr_common::expect_expr_variant;
1459        use datafusion_proto_models::protobuf;
1460
1461        let case = expect_expr_variant!(
1462            node,
1463            protobuf::physical_expr_node::ExprType::Case,
1464            "CaseExpr",
1465        );
1466        let protobuf::PhysicalCaseNode {
1467            expr,
1468            when_then_expr,
1469            else_expr,
1470        } = &**case;
1471
1472        Ok(Arc::new(CaseExpr::try_new(
1473            expr.as_deref().map(|expr| ctx.decode(expr)).transpose()?,
1474            when_then_expr
1475                .iter()
1476                .map(|when_then| {
1477                    let protobuf::PhysicalWhenThen {
1478                        when_expr,
1479                        then_expr,
1480                    } = when_then;
1481                    Ok((
1482                        ctx.decode_required_expression(
1483                            when_expr.as_ref(),
1484                            "CaseExpr",
1485                            "when_expr",
1486                        )?,
1487                        ctx.decode_required_expression(
1488                            then_expr.as_ref(),
1489                            "CaseExpr",
1490                            "then_expr",
1491                        )?,
1492                    ))
1493                })
1494                .collect::<Result<Vec<_>>>()?,
1495            else_expr
1496                .as_deref()
1497                .map(|expr| ctx.decode(expr))
1498                .transpose()?,
1499        )?))
1500    }
1501}
1502
1503/// Uses three-valued bounds when input columns prevent constant evaluation.
1504fn evaluate_predicate(predicate: &Arc<dyn PhysicalExpr>) -> Result<NullableInterval> {
1505    // Create a dummy record with no columns and one row
1506    let batch = RecordBatch::try_new_with_options(
1507        Arc::new(Schema::empty()),
1508        vec![],
1509        &RecordBatchOptions::new().with_row_count(Some(1)),
1510    )?;
1511
1512    // Evaluate the predicate and interpret the result as a boolean
1513    let result = match predicate.evaluate(&batch) {
1514        Err(_) => {
1515            if let Some(expr) = predicate.downcast_ref::<BinaryExpr>()
1516                && matches!(expr.op(), Operator::And | Operator::Or)
1517            {
1518                return evaluate_predicate(expr.left())?
1519                    .apply_operator(expr.op(), &evaluate_predicate(expr.right())?);
1520            }
1521            if let Some(expr) = predicate.downcast_ref::<NotExpr>() {
1522                return evaluate_predicate(expr.arg())?.not();
1523            }
1524            return Ok(NullableInterval::ANY_TRUTH_VALUE);
1525        }
1526        Ok(ColumnarValue::Array(array)) => {
1527            ScalarValue::try_from_array(array.as_ref(), 0)?
1528        }
1529        Ok(ColumnarValue::Scalar(scalar)) => scalar,
1530    };
1531    Ok(result.cast_to(&DataType::Boolean)?.into())
1532}
1533
1534fn replace_with_null(
1535    expr: &Arc<dyn PhysicalExpr>,
1536    expr_to_replace: &dyn PhysicalExpr,
1537    input_schema: &Schema,
1538) -> Result<Arc<dyn PhysicalExpr>, DataFusionError> {
1539    let with_null = Arc::clone(expr)
1540        .transform_down(|e| {
1541            if e.as_ref().dyn_eq(expr_to_replace) {
1542                let data_type = e.data_type(input_schema)?;
1543                let null_literal = lit(ScalarValue::try_new_null(&data_type)?);
1544                Ok(Transformed::yes(null_literal))
1545            } else {
1546                Ok(Transformed::no(e))
1547            }
1548        })?
1549        .data;
1550    Ok(with_null)
1551}
1552
1553/// Returns the innermost [`PhysicalExpr`] that is provably null if `expr` is null.
1554///
1555/// Keep this in sync with the logical-plan equivalent, `unwrap_certainly_null_expr`
1556/// in `datafusion/expr/src/expr_schema.rs`. If the two disagree on which wrappers
1557/// are null-preserving, `CASE` nullability computed by the logical and physical
1558/// planners can diverge and cause a schema mismatch during planning.
1559/// See <https://github.com/apache/datafusion/pull/23844> for rationale.
1560fn unwrap_certainly_null_expr(expr: &dyn PhysicalExpr) -> &dyn PhysicalExpr {
1561    if let Some(expr) = expr.downcast_ref::<NotExpr>() {
1562        unwrap_certainly_null_expr(expr.arg().as_ref())
1563    } else if let Some(expr) = expr.downcast_ref::<NegativeExpr>() {
1564        unwrap_certainly_null_expr(expr.arg().as_ref())
1565    } else if let Some(expr) = expr.downcast_ref::<CastExpr>() {
1566        unwrap_certainly_null_expr(expr.expr.as_ref())
1567    } else {
1568        expr
1569    }
1570}
1571
1572/// Create a CASE expression
1573pub fn case(
1574    expr: Option<Arc<dyn PhysicalExpr>>,
1575    when_thens: Vec<WhenThen>,
1576    else_expr: Option<Arc<dyn PhysicalExpr>>,
1577) -> Result<Arc<dyn PhysicalExpr>> {
1578    Ok(Arc::new(CaseExpr::try_new(expr, when_thens, else_expr)?))
1579}
1580
1581#[cfg(test)]
1582mod tests {
1583    use super::*;
1584
1585    use crate::expressions;
1586    use crate::expressions::{binary, cast, col, is_not_null};
1587    use arrow::buffer::Buffer;
1588    use arrow::datatypes::DataType::Float64;
1589    use arrow::datatypes::Field;
1590    use datafusion_common::cast::{as_float64_array, as_int32_array};
1591    use datafusion_common::config::ConfigOptions;
1592    use datafusion_common::plan_err;
1593    use datafusion_common::tree_node::{Transformed, TransformedResult, TreeNode};
1594    use datafusion_expr::type_coercion::binary::type_union_coercion;
1595    use datafusion_physical_expr_common::physical_expr::fmt_sql;
1596    use half::f16;
1597
1598    #[derive(Debug, Hash, PartialEq, Eq)]
1599    struct CustomColumn {
1600        inner: Column,
1601    }
1602
1603    impl CustomColumn {
1604        fn new(name: &str, index: usize) -> Self {
1605            Self {
1606                inner: Column::new(name, index),
1607            }
1608        }
1609    }
1610
1611    impl std::fmt::Display for CustomColumn {
1612        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1613            std::fmt::Display::fmt(&self.inner, f)
1614        }
1615    }
1616
1617    impl PhysicalExpr for CustomColumn {
1618        fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
1619            self.inner.data_type(input_schema)
1620        }
1621
1622        fn nullable(&self, input_schema: &Schema) -> Result<bool> {
1623            self.inner.nullable(input_schema)
1624        }
1625
1626        fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
1627            self.inner.evaluate(batch)
1628        }
1629
1630        fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
1631            vec![]
1632        }
1633
1634        fn with_new_children(
1635            self: Arc<Self>,
1636            children: Vec<Arc<dyn PhysicalExpr>>,
1637        ) -> Result<Arc<dyn PhysicalExpr>> {
1638            assert!(children.is_empty());
1639            Ok(self)
1640        }
1641
1642        fn fmt_sql(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1643            self.inner.fmt_sql(f)
1644        }
1645    }
1646
1647    #[test]
1648    fn case_with_expr() -> Result<()> {
1649        let batch = case_test_batch()?;
1650        let schema = batch.schema();
1651
1652        // CASE a WHEN 'foo' THEN 123 WHEN 'bar' THEN 456 END
1653        let when1 = lit("foo");
1654        let then1 = lit(123i32);
1655        let when2 = lit("bar");
1656        let then2 = lit(456i32);
1657
1658        let expr = generate_case_when_with_type_coercion(
1659            Some(col("a", &schema)?),
1660            vec![(when1, then1), (when2, then2)],
1661            None,
1662            schema.as_ref(),
1663        )?;
1664        let result = expr
1665            .evaluate(&batch)?
1666            .into_array(batch.num_rows())
1667            .expect("Failed to convert to array");
1668        let result = as_int32_array(&result)?;
1669
1670        let expected = &Int32Array::from(vec![Some(123), None, None, Some(456)]);
1671
1672        assert_eq!(expected, result);
1673
1674        Ok(())
1675    }
1676
1677    #[test]
1678    fn case_with_expr_dictionary() -> Result<()> {
1679        let schema = Schema::new(vec![Field::new(
1680            "a",
1681            DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::Utf8)),
1682            true,
1683        )]);
1684        let keys = UInt8Array::from(vec![0u8, 1u8, 2u8, 3u8]);
1685        let values = StringArray::from(vec![Some("foo"), Some("baz"), None, Some("bar")]);
1686        let dictionary = DictionaryArray::new(keys, Arc::new(values));
1687        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(dictionary)])?;
1688
1689        let schema = batch.schema();
1690
1691        // CASE a WHEN 'foo' THEN 123 WHEN 'bar' THEN 456 END
1692        let when1 = lit("foo");
1693        let then1 = lit(123i32);
1694        let when2 = lit("bar");
1695        let then2 = lit(456i32);
1696
1697        let expr = generate_case_when_with_type_coercion(
1698            Some(col("a", &schema)?),
1699            vec![(when1, then1), (when2, then2)],
1700            None,
1701            schema.as_ref(),
1702        )?;
1703        let result = expr
1704            .evaluate(&batch)?
1705            .into_array(batch.num_rows())
1706            .expect("Failed to convert to array");
1707        let result = as_int32_array(&result)?;
1708
1709        let expected = &Int32Array::from(vec![Some(123), None, None, Some(456)]);
1710
1711        assert_eq!(expected, result);
1712
1713        Ok(())
1714    }
1715
1716    // Make sure we are not failing when got literal in case when but input is dictionary encoded
1717    #[test]
1718    fn case_with_expr_primitive_dictionary() -> Result<()> {
1719        let schema = Schema::new(vec![Field::new(
1720            "a",
1721            DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::UInt64)),
1722            true,
1723        )]);
1724        let keys = UInt8Array::from(vec![0u8, 1u8, 2u8, 3u8]);
1725        let values = UInt64Array::from(vec![Some(10), Some(20), None, Some(30)]);
1726        let dictionary = DictionaryArray::new(keys, Arc::new(values));
1727        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(dictionary)])?;
1728
1729        let schema = batch.schema();
1730
1731        // CASE a WHEN 10 THEN 123 WHEN 30 THEN 456 END
1732        let when1 = lit(10_u64);
1733        let then1 = lit(123_i32);
1734        let when2 = lit(30_u64);
1735        let then2 = lit(456_i32);
1736
1737        let expr = generate_case_when_with_type_coercion(
1738            Some(col("a", &schema)?),
1739            vec![(when1, then1), (when2, then2)],
1740            None,
1741            schema.as_ref(),
1742        )?;
1743        let result = expr
1744            .evaluate(&batch)?
1745            .into_array(batch.num_rows())
1746            .expect("Failed to convert to array");
1747        let result = as_int32_array(&result)?;
1748
1749        let expected = &Int32Array::from(vec![Some(123), None, None, Some(456)]);
1750
1751        assert_eq!(expected, result);
1752
1753        Ok(())
1754    }
1755
1756    // Make sure we are not failing when got literal in case when but input is dictionary encoded
1757    #[test]
1758    fn case_with_expr_boolean_dictionary() -> Result<()> {
1759        let schema = Schema::new(vec![Field::new(
1760            "a",
1761            DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::Boolean)),
1762            true,
1763        )]);
1764        let keys = UInt8Array::from(vec![0u8, 1u8, 2u8, 3u8]);
1765        let values = BooleanArray::from(vec![Some(true), Some(false), None, Some(true)]);
1766        let dictionary = DictionaryArray::new(keys, Arc::new(values));
1767        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(dictionary)])?;
1768
1769        let schema = batch.schema();
1770
1771        // CASE a WHEN true THEN 123 WHEN false THEN 456 END
1772        let when1 = lit(true);
1773        let then1 = lit(123i32);
1774        let when2 = lit(false);
1775        let then2 = lit(456i32);
1776
1777        let expr = generate_case_when_with_type_coercion(
1778            Some(col("a", &schema)?),
1779            vec![(when1, then1), (when2, then2)],
1780            None,
1781            schema.as_ref(),
1782        )?;
1783        let result = expr
1784            .evaluate(&batch)?
1785            .into_array(batch.num_rows())
1786            .expect("Failed to convert to array");
1787        let result = as_int32_array(&result)?;
1788
1789        let expected = &Int32Array::from(vec![Some(123), Some(456), None, Some(123)]);
1790
1791        assert_eq!(expected, result);
1792
1793        Ok(())
1794    }
1795
1796    #[test]
1797    fn case_with_expr_all_null_dictionary() -> Result<()> {
1798        let schema = Schema::new(vec![Field::new(
1799            "a",
1800            DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::Utf8)),
1801            true,
1802        )]);
1803        let keys = UInt8Array::from(vec![2u8, 2u8, 2u8, 2u8]);
1804        let values = StringArray::from(vec![Some("foo"), Some("baz"), None, Some("bar")]);
1805        let dictionary = DictionaryArray::new(keys, Arc::new(values));
1806        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(dictionary)])?;
1807
1808        let schema = batch.schema();
1809
1810        // CASE a WHEN 'foo' THEN 123 WHEN 'bar' THEN 456 END
1811        let when1 = lit("foo");
1812        let then1 = lit(123i32);
1813        let when2 = lit("bar");
1814        let then2 = lit(456i32);
1815
1816        let expr = generate_case_when_with_type_coercion(
1817            Some(col("a", &schema)?),
1818            vec![(when1, then1), (when2, then2)],
1819            None,
1820            schema.as_ref(),
1821        )?;
1822        let result = expr
1823            .evaluate(&batch)?
1824            .into_array(batch.num_rows())
1825            .expect("Failed to convert to array");
1826        let result = as_int32_array(&result)?;
1827
1828        let expected = &Int32Array::from(vec![None, None, None, None]);
1829
1830        assert_eq!(expected, result);
1831
1832        Ok(())
1833    }
1834
1835    #[test]
1836    fn case_with_expr_else() -> Result<()> {
1837        let batch = case_test_batch()?;
1838        let schema = batch.schema();
1839
1840        // CASE a WHEN 'foo' THEN 123 WHEN 'bar' THEN 456 ELSE 999 END
1841        let when1 = lit("foo");
1842        let then1 = lit(123i32);
1843        let when2 = lit("bar");
1844        let then2 = lit(456i32);
1845        let else_value = lit(999i32);
1846
1847        let expr = generate_case_when_with_type_coercion(
1848            Some(col("a", &schema)?),
1849            vec![(when1, then1), (when2, then2)],
1850            Some(else_value),
1851            schema.as_ref(),
1852        )?;
1853        let result = expr
1854            .evaluate(&batch)?
1855            .into_array(batch.num_rows())
1856            .expect("Failed to convert to array");
1857        let result = as_int32_array(&result)?;
1858
1859        let expected =
1860            &Int32Array::from(vec![Some(123), Some(999), Some(999), Some(456)]);
1861
1862        assert_eq!(expected, result);
1863
1864        Ok(())
1865    }
1866
1867    #[test]
1868    fn case_with_expr_divide_by_zero() -> Result<()> {
1869        let batch = case_test_batch1()?;
1870        let schema = batch.schema();
1871
1872        // CASE a when 0 THEN float64(null) ELSE 25.0 / cast(a, float64)  END
1873        let when1 = lit(0i32);
1874        let then1 = lit(ScalarValue::Float64(None));
1875        let else_value = binary(
1876            lit(25.0f64),
1877            Operator::Divide,
1878            cast(col("a", &schema)?, &batch.schema(), Float64)?,
1879            &batch.schema(),
1880        )?;
1881
1882        let expr = generate_case_when_with_type_coercion(
1883            Some(col("a", &schema)?),
1884            vec![(when1, then1)],
1885            Some(else_value),
1886            schema.as_ref(),
1887        )?;
1888        let result = expr
1889            .evaluate(&batch)?
1890            .into_array(batch.num_rows())
1891            .expect("Failed to convert to array");
1892        let result =
1893            as_float64_array(&result).expect("failed to downcast to Float64Array");
1894
1895        let expected = &Float64Array::from(vec![Some(25.0), None, None, Some(5.0)]);
1896
1897        assert_eq!(expected, result);
1898
1899        Ok(())
1900    }
1901
1902    #[test]
1903    fn case_without_expr() -> Result<()> {
1904        let batch = case_test_batch()?;
1905        let schema = batch.schema();
1906
1907        // CASE WHEN a = 'foo' THEN 123 WHEN a = 'bar' THEN 456 END
1908        let when1 = binary(
1909            col("a", &schema)?,
1910            Operator::Eq,
1911            lit("foo"),
1912            &batch.schema(),
1913        )?;
1914        let then1 = lit(123i32);
1915        let when2 = binary(
1916            col("a", &schema)?,
1917            Operator::Eq,
1918            lit("bar"),
1919            &batch.schema(),
1920        )?;
1921        let then2 = lit(456i32);
1922
1923        let expr = generate_case_when_with_type_coercion(
1924            None,
1925            vec![(when1, then1), (when2, then2)],
1926            None,
1927            schema.as_ref(),
1928        )?;
1929        let result = expr
1930            .evaluate(&batch)?
1931            .into_array(batch.num_rows())
1932            .expect("Failed to convert to array");
1933        let result = as_int32_array(&result)?;
1934
1935        let expected = &Int32Array::from(vec![Some(123), None, None, Some(456)]);
1936
1937        assert_eq!(expected, result);
1938
1939        Ok(())
1940    }
1941
1942    #[test]
1943    fn case_without_expr_with_custom_column() -> Result<()> {
1944        let batch = case_test_batch()?;
1945        let schema = batch.schema();
1946
1947        let when1 = binary(
1948            Arc::new(CustomColumn::new("a", 0)),
1949            Operator::Eq,
1950            lit("foo"),
1951            &schema,
1952        )?;
1953        let when2 = binary(
1954            Arc::new(CustomColumn::new("a", 0)),
1955            Operator::Eq,
1956            lit("bar"),
1957            &schema,
1958        )?;
1959        let expr = generate_case_when_with_type_coercion(
1960            None,
1961            vec![(when1, lit(123i32)), (when2, lit(456i32))],
1962            None,
1963            schema.as_ref(),
1964        )?;
1965
1966        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
1967        let result = as_int32_array(&result)?;
1968        let expected = Int32Array::from(vec![Some(123), None, None, Some(456)]);
1969
1970        assert_eq!(&expected, result);
1971        Ok(())
1972    }
1973
1974    #[test]
1975    fn case_with_expr_with_custom_column() -> Result<()> {
1976        let batch = case_test_batch_with_extra_columns()?;
1977        let schema = batch.schema();
1978
1979        let expr = CaseExpr::try_new(
1980            Some(Arc::new(CustomColumn::new("a", 0))),
1981            vec![(lit("foo"), col("b", &schema)?)],
1982            Some(col("c", &schema)?),
1983        )?;
1984
1985        match &expr.eval_method {
1986            EvalMethod::WithExpression(projected) => {
1987                assert!(!projected.supports_projection);
1988            }
1989            method => panic!("expected WithExpression, got {method:?}"),
1990        }
1991
1992        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
1993        let result = as_int32_array(&result)?;
1994        let expected = Int32Array::from(vec![Some(1), Some(20), Some(30), Some(40)]);
1995
1996        assert_eq!(&expected, result);
1997        Ok(())
1998    }
1999
2000    #[test]
2001    fn case_expr_or_expr_with_custom_column() -> Result<()> {
2002        let batch = case_test_batch_with_extra_columns()?;
2003        let schema = batch.schema();
2004        let when = binary(
2005            Arc::new(CustomColumn::new("a", 0)),
2006            Operator::Eq,
2007            lit("foo"),
2008            &schema,
2009        )?;
2010
2011        let expr = CaseExpr::try_new(
2012            None,
2013            vec![(when, col("b", &schema)?)],
2014            Some(col("c", &schema)?),
2015        )?;
2016
2017        match &expr.eval_method {
2018            EvalMethod::ExpressionOrExpression(projected) => {
2019                assert!(!projected.supports_projection);
2020            }
2021            method => panic!("expected ExpressionOrExpression, got {method:?}"),
2022        }
2023
2024        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
2025        let result = as_int32_array(&result)?;
2026        let expected = Int32Array::from(vec![Some(1), Some(20), Some(30), Some(40)]);
2027
2028        assert_eq!(&expected, result);
2029        Ok(())
2030    }
2031
2032    #[test]
2033    fn case_expr_or_expr_keeps_nullary_scalar_functions_projectable() -> Result<()> {
2034        let batch = case_test_batch1()?;
2035        let schema = batch.schema();
2036        let random: Arc<dyn PhysicalExpr> = Arc::new(ScalarFunctionExpr::try_new(
2037            datafusion_functions::math::random(),
2038            vec![],
2039            &schema,
2040            Arc::new(ConfigOptions::default()),
2041        )?);
2042        let when = binary(random, Operator::Gt, lit(0.5f64), &schema)?;
2043
2044        let expr = CaseExpr::try_new(
2045            None,
2046            vec![(when, col("b", &schema)?)],
2047            Some(col("c", &schema)?),
2048        )?;
2049
2050        match &expr.eval_method {
2051            EvalMethod::ExpressionOrExpression(projected) => {
2052                assert!(projected.supports_projection);
2053                assert_eq!(projected.projection, vec![1, 2]);
2054            }
2055            method => panic!("expected ExpressionOrExpression, got {method:?}"),
2056        }
2057
2058        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
2059        assert_eq!(result.len(), batch.num_rows());
2060        Ok(())
2061    }
2062
2063    #[test]
2064    fn case_with_expr_when_null() -> Result<()> {
2065        let batch = case_test_batch()?;
2066        let schema = batch.schema();
2067
2068        // CASE a WHEN NULL THEN 0 WHEN a THEN 123 ELSE 999 END
2069        let when1 = lit(ScalarValue::Utf8(None));
2070        let then1 = lit(0i32);
2071        let when2 = col("a", &schema)?;
2072        let then2 = lit(123i32);
2073        let else_value = lit(999i32);
2074
2075        let expr = generate_case_when_with_type_coercion(
2076            Some(col("a", &schema)?),
2077            vec![(when1, then1), (when2, then2)],
2078            Some(else_value),
2079            schema.as_ref(),
2080        )?;
2081        let result = expr
2082            .evaluate(&batch)?
2083            .into_array(batch.num_rows())
2084            .expect("Failed to convert to array");
2085        let result = as_int32_array(&result)?;
2086
2087        let expected =
2088            &Int32Array::from(vec![Some(123), Some(123), Some(999), Some(123)]);
2089
2090        assert_eq!(expected, result);
2091
2092        Ok(())
2093    }
2094
2095    #[test]
2096    fn case_without_expr_divide_by_zero() -> Result<()> {
2097        let batch = case_test_batch1()?;
2098        let schema = batch.schema();
2099
2100        // CASE WHEN a > 0 THEN 25.0 / cast(a, float64) ELSE float64(null) END
2101        let when1 = binary(col("a", &schema)?, Operator::Gt, lit(0i32), &batch.schema())?;
2102        let then1 = binary(
2103            lit(25.0f64),
2104            Operator::Divide,
2105            cast(col("a", &schema)?, &batch.schema(), Float64)?,
2106            &batch.schema(),
2107        )?;
2108        let x = lit(ScalarValue::Float64(None));
2109
2110        let expr = generate_case_when_with_type_coercion(
2111            None,
2112            vec![(when1, then1)],
2113            Some(x),
2114            schema.as_ref(),
2115        )?;
2116        let result = expr
2117            .evaluate(&batch)?
2118            .into_array(batch.num_rows())
2119            .expect("Failed to convert to array");
2120        let result =
2121            as_float64_array(&result).expect("failed to downcast to Float64Array");
2122
2123        let expected = &Float64Array::from(vec![Some(25.0), None, None, Some(5.0)]);
2124
2125        assert_eq!(expected, result);
2126
2127        Ok(())
2128    }
2129
2130    fn case_test_batch_with_extra_columns() -> Result<RecordBatch> {
2131        let schema = Schema::new(vec![
2132            Field::new("a", DataType::Utf8, true),
2133            Field::new("b", DataType::Int32, true),
2134            Field::new("c", DataType::Int32, true),
2135        ]);
2136        let a = StringArray::from(vec![Some("foo"), Some("baz"), None, Some("bar")]);
2137        let b = Int32Array::from(vec![Some(1), Some(2), Some(3), Some(4)]);
2138        let c = Int32Array::from(vec![Some(10), Some(20), Some(30), Some(40)]);
2139        RecordBatch::try_new(
2140            Arc::new(schema),
2141            vec![Arc::new(a), Arc::new(b), Arc::new(c)],
2142        )
2143        .map_err(Into::into)
2144    }
2145
2146    fn case_test_batch1() -> Result<RecordBatch> {
2147        let schema = Schema::new(vec![
2148            Field::new("a", DataType::Int32, true),
2149            Field::new("b", DataType::Int32, true),
2150            Field::new("c", DataType::Int32, true),
2151        ]);
2152        let a = Int32Array::from(vec![Some(1), Some(0), None, Some(5)]);
2153        let b = Int32Array::from(vec![Some(3), None, Some(14), Some(7)]);
2154        let c = Int32Array::from(vec![Some(0), Some(-3), Some(777), None]);
2155        let batch = RecordBatch::try_new(
2156            Arc::new(schema),
2157            vec![Arc::new(a), Arc::new(b), Arc::new(c)],
2158        )?;
2159        Ok(batch)
2160    }
2161
2162    #[test]
2163    fn case_without_expr_else() -> Result<()> {
2164        let batch = case_test_batch()?;
2165        let schema = batch.schema();
2166
2167        // CASE WHEN a = 'foo' THEN 123 WHEN a = 'bar' THEN 456 ELSE 999 END
2168        let when1 = binary(
2169            col("a", &schema)?,
2170            Operator::Eq,
2171            lit("foo"),
2172            &batch.schema(),
2173        )?;
2174        let then1 = lit(123i32);
2175        let when2 = binary(
2176            col("a", &schema)?,
2177            Operator::Eq,
2178            lit("bar"),
2179            &batch.schema(),
2180        )?;
2181        let then2 = lit(456i32);
2182        let else_value = lit(999i32);
2183
2184        let expr = generate_case_when_with_type_coercion(
2185            None,
2186            vec![(when1, then1), (when2, then2)],
2187            Some(else_value),
2188            schema.as_ref(),
2189        )?;
2190        let result = expr
2191            .evaluate(&batch)?
2192            .into_array(batch.num_rows())
2193            .expect("Failed to convert to array");
2194        let result = as_int32_array(&result)?;
2195
2196        let expected =
2197            &Int32Array::from(vec![Some(123), Some(999), Some(999), Some(456)]);
2198
2199        assert_eq!(expected, result);
2200
2201        Ok(())
2202    }
2203
2204    #[test]
2205    fn case_with_type_cast() -> Result<()> {
2206        let batch = case_test_batch()?;
2207        let schema = batch.schema();
2208
2209        // CASE WHEN a = 'foo' THEN 123.3 ELSE 999 END
2210        let when = binary(
2211            col("a", &schema)?,
2212            Operator::Eq,
2213            lit("foo"),
2214            &batch.schema(),
2215        )?;
2216        let then = lit(123.3f64);
2217        let else_value = lit(999i32);
2218
2219        let expr = generate_case_when_with_type_coercion(
2220            None,
2221            vec![(when, then)],
2222            Some(else_value),
2223            schema.as_ref(),
2224        )?;
2225        let result = expr
2226            .evaluate(&batch)?
2227            .into_array(batch.num_rows())
2228            .expect("Failed to convert to array");
2229        let result =
2230            as_float64_array(&result).expect("failed to downcast to Float64Array");
2231
2232        let expected =
2233            &Float64Array::from(vec![Some(123.3), Some(999.0), Some(999.0), Some(999.0)]);
2234
2235        assert_eq!(expected, result);
2236
2237        Ok(())
2238    }
2239
2240    #[test]
2241    fn case_with_matches_and_nulls() -> Result<()> {
2242        let batch = case_test_batch_nulls()?;
2243        let schema = batch.schema();
2244
2245        // SELECT CASE WHEN load4 = 1.77 THEN load4 END
2246        let when = binary(
2247            col("load4", &schema)?,
2248            Operator::Eq,
2249            lit(1.77f64),
2250            &batch.schema(),
2251        )?;
2252        let then = col("load4", &schema)?;
2253
2254        let expr = generate_case_when_with_type_coercion(
2255            None,
2256            vec![(when, then)],
2257            None,
2258            schema.as_ref(),
2259        )?;
2260        let result = expr
2261            .evaluate(&batch)?
2262            .into_array(batch.num_rows())
2263            .expect("Failed to convert to array");
2264        let result =
2265            as_float64_array(&result).expect("failed to downcast to Float64Array");
2266
2267        let expected =
2268            &Float64Array::from(vec![Some(1.77), None, None, None, None, Some(1.77)]);
2269
2270        assert_eq!(expected, result);
2271
2272        Ok(())
2273    }
2274
2275    #[test]
2276    fn case_with_scalar_predicate() -> Result<()> {
2277        let batch = case_test_batch_nulls()?;
2278        let schema = batch.schema();
2279
2280        // SELECT CASE WHEN TRUE THEN load4 END
2281        let when = lit(true);
2282        let then = col("load4", &schema)?;
2283        let expr = generate_case_when_with_type_coercion(
2284            None,
2285            vec![(when, then)],
2286            None,
2287            schema.as_ref(),
2288        )?;
2289
2290        // many rows
2291        let result = expr
2292            .evaluate(&batch)?
2293            .into_array(batch.num_rows())
2294            .expect("Failed to convert to array");
2295        let result =
2296            as_float64_array(&result).expect("failed to downcast to Float64Array");
2297        let expected = &Float64Array::from(vec![
2298            Some(1.77),
2299            None,
2300            None,
2301            Some(1.78),
2302            None,
2303            Some(1.77),
2304        ]);
2305        assert_eq!(expected, result);
2306
2307        // one row
2308        let expected = Float64Array::from(vec![Some(1.1)]);
2309        let batch =
2310            RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(expected.clone())])?;
2311        let result = expr
2312            .evaluate(&batch)?
2313            .into_array(batch.num_rows())
2314            .expect("Failed to convert to array");
2315        let result =
2316            as_float64_array(&result).expect("failed to downcast to Float64Array");
2317        assert_eq!(&expected, result);
2318
2319        Ok(())
2320    }
2321
2322    #[test]
2323    fn case_expr_matches_and_nulls() -> Result<()> {
2324        let batch = case_test_batch_nulls()?;
2325        let schema = batch.schema();
2326
2327        // SELECT CASE load4 WHEN 1.77 THEN load4 END
2328        let expr = col("load4", &schema)?;
2329        let when = lit(1.77f64);
2330        let then = col("load4", &schema)?;
2331
2332        let expr = generate_case_when_with_type_coercion(
2333            Some(expr),
2334            vec![(when, then)],
2335            None,
2336            schema.as_ref(),
2337        )?;
2338        let result = expr
2339            .evaluate(&batch)?
2340            .into_array(batch.num_rows())
2341            .expect("Failed to convert to array");
2342        let result =
2343            as_float64_array(&result).expect("failed to downcast to Float64Array");
2344
2345        let expected =
2346            &Float64Array::from(vec![Some(1.77), None, None, None, None, Some(1.77)]);
2347
2348        assert_eq!(expected, result);
2349
2350        Ok(())
2351    }
2352
2353    #[test]
2354    fn test_when_null_and_some_cond_else_null() -> Result<()> {
2355        let batch = case_test_batch()?;
2356        let schema = batch.schema();
2357
2358        let when = binary(
2359            Arc::new(Literal::new(ScalarValue::Boolean(None))),
2360            Operator::And,
2361            binary(col("a", &schema)?, Operator::Eq, lit("foo"), &schema)?,
2362            &schema,
2363        )?;
2364        let then = col("a", &schema)?;
2365
2366        // SELECT CASE WHEN (NULL AND a = 'foo') THEN a ELSE NULL END
2367        let expr = Arc::new(CaseExpr::try_new(None, vec![(when, then)], None)?);
2368        let result = expr
2369            .evaluate(&batch)?
2370            .into_array(batch.num_rows())
2371            .expect("Failed to convert to array");
2372        let result = as_string_array(&result);
2373
2374        // all result values should be null
2375        assert_eq!(result.logical_null_count(), batch.num_rows());
2376        Ok(())
2377    }
2378
2379    fn case_test_batch() -> Result<RecordBatch> {
2380        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
2381        let a = StringArray::from(vec![Some("foo"), Some("baz"), None, Some("bar")]);
2382        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)])?;
2383        Ok(batch)
2384    }
2385
2386    // Construct an array that has several NULL values whose
2387    // underlying buffer actually matches the where expr predicate
2388    fn case_test_batch_nulls() -> Result<RecordBatch> {
2389        let load4: Float64Array = vec![
2390            Some(1.77), // 1.77
2391            Some(1.77), // null <-- same value, but will be set to null
2392            Some(1.77), // null <-- same value, but will be set to null
2393            Some(1.78), // 1.78
2394            None,       // null
2395            Some(1.77), // 1.77
2396        ]
2397        .into_iter()
2398        .collect();
2399
2400        let null_buffer = Buffer::from([0b00101001u8]);
2401        let load4 = load4
2402            .into_data()
2403            .into_builder()
2404            .null_bit_buffer(Some(null_buffer))
2405            .build()
2406            .unwrap();
2407        let load4: Float64Array = load4.into();
2408
2409        let batch =
2410            RecordBatch::try_from_iter(vec![("load4", Arc::new(load4) as ArrayRef)])?;
2411        Ok(batch)
2412    }
2413
2414    #[test]
2415    fn case_test_incompatible() -> Result<()> {
2416        // 1 then is int64
2417        // 2 then is boolean
2418        let batch = case_test_batch()?;
2419        let schema = batch.schema();
2420
2421        // CASE WHEN a = 'foo' THEN 123 WHEN a = 'bar' THEN true END
2422        let when1 = binary(
2423            col("a", &schema)?,
2424            Operator::Eq,
2425            lit("foo"),
2426            &batch.schema(),
2427        )?;
2428        let then1 = lit(123i32);
2429        let when2 = binary(
2430            col("a", &schema)?,
2431            Operator::Eq,
2432            lit("bar"),
2433            &batch.schema(),
2434        )?;
2435        let then2 = lit(true);
2436
2437        let expr = generate_case_when_with_type_coercion(
2438            None,
2439            vec![(when1, then1), (when2, then2)],
2440            None,
2441            schema.as_ref(),
2442        );
2443        assert!(expr.is_err());
2444
2445        // then 1 is int32
2446        // then 2 is int64
2447        // else is float
2448        // CASE WHEN a = 'foo' THEN 123 WHEN a = 'bar' THEN 456 ELSE 1.23 END
2449        let when1 = binary(
2450            col("a", &schema)?,
2451            Operator::Eq,
2452            lit("foo"),
2453            &batch.schema(),
2454        )?;
2455        let then1 = lit(123i32);
2456        let when2 = binary(
2457            col("a", &schema)?,
2458            Operator::Eq,
2459            lit("bar"),
2460            &batch.schema(),
2461        )?;
2462        let then2 = lit(456i64);
2463        let else_expr = lit(1.23f64);
2464
2465        let expr = generate_case_when_with_type_coercion(
2466            None,
2467            vec![(when1, then1), (when2, then2)],
2468            Some(else_expr),
2469            schema.as_ref(),
2470        );
2471        assert!(expr.is_ok());
2472        let result_type = expr.unwrap().data_type(schema.as_ref())?;
2473        assert_eq!(Float64, result_type);
2474        Ok(())
2475    }
2476
2477    #[test]
2478    fn case_eq() -> Result<()> {
2479        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
2480
2481        let when1 = lit("foo");
2482        let then1 = lit(123i32);
2483        let when2 = lit("bar");
2484        let then2 = lit(456i32);
2485        let else_value = lit(999i32);
2486
2487        let expr1 = generate_case_when_with_type_coercion(
2488            Some(col("a", &schema)?),
2489            vec![
2490                (Arc::clone(&when1), Arc::clone(&then1)),
2491                (Arc::clone(&when2), Arc::clone(&then2)),
2492            ],
2493            Some(Arc::clone(&else_value)),
2494            &schema,
2495        )?;
2496
2497        let expr2 = generate_case_when_with_type_coercion(
2498            Some(col("a", &schema)?),
2499            vec![
2500                (Arc::clone(&when1), Arc::clone(&then1)),
2501                (Arc::clone(&when2), Arc::clone(&then2)),
2502            ],
2503            Some(Arc::clone(&else_value)),
2504            &schema,
2505        )?;
2506
2507        let expr3 = generate_case_when_with_type_coercion(
2508            Some(col("a", &schema)?),
2509            vec![(Arc::clone(&when1), Arc::clone(&then1)), (when2, then2)],
2510            None,
2511            &schema,
2512        )?;
2513
2514        let expr4 = generate_case_when_with_type_coercion(
2515            Some(col("a", &schema)?),
2516            vec![(when1, then1)],
2517            Some(else_value),
2518            &schema,
2519        )?;
2520
2521        assert!(expr1.eq(&expr2));
2522        assert!(expr2.eq(&expr1));
2523
2524        assert!(expr2.ne(&expr3));
2525        assert!(expr3.ne(&expr2));
2526
2527        assert!(expr1.ne(&expr4));
2528        assert!(expr4.ne(&expr1));
2529
2530        Ok(())
2531    }
2532
2533    #[test]
2534    fn case_transform() -> Result<()> {
2535        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
2536
2537        let when1 = lit("foo");
2538        let then1 = lit(123i32);
2539        let when2 = lit("bar");
2540        let then2 = lit(456i32);
2541        let else_value = lit(999i32);
2542
2543        let expr = generate_case_when_with_type_coercion(
2544            Some(col("a", &schema)?),
2545            vec![
2546                (Arc::clone(&when1), Arc::clone(&then1)),
2547                (Arc::clone(&when2), Arc::clone(&then2)),
2548            ],
2549            Some(Arc::clone(&else_value)),
2550            &schema,
2551        )?;
2552
2553        let expr2 = Arc::clone(&expr)
2554            .transform(|e| {
2555                let transformed = match e.downcast_ref::<Literal>() {
2556                    Some(lit_value) => match lit_value.value() {
2557                        ScalarValue::Utf8(Some(str_value)) => {
2558                            Some(lit(str_value.to_uppercase()))
2559                        }
2560                        _ => None,
2561                    },
2562                    _ => None,
2563                };
2564                Ok(if let Some(transformed) = transformed {
2565                    Transformed::yes(transformed)
2566                } else {
2567                    Transformed::no(e)
2568                })
2569            })
2570            .data()
2571            .unwrap();
2572
2573        let expr3 = Arc::clone(&expr)
2574            .transform_down(|e| {
2575                let transformed = match e.downcast_ref::<Literal>() {
2576                    Some(lit_value) => match lit_value.value() {
2577                        ScalarValue::Utf8(Some(str_value)) => {
2578                            Some(lit(str_value.to_uppercase()))
2579                        }
2580                        _ => None,
2581                    },
2582                    _ => None,
2583                };
2584                Ok(if let Some(transformed) = transformed {
2585                    Transformed::yes(transformed)
2586                } else {
2587                    Transformed::no(e)
2588                })
2589            })
2590            .data()
2591            .unwrap();
2592
2593        assert!(expr.ne(&expr2));
2594        assert!(expr2.eq(&expr3));
2595
2596        Ok(())
2597    }
2598
2599    #[test]
2600    fn test_column_or_null_specialization() -> Result<()> {
2601        // create input data
2602        let mut c1 = Int32Builder::new();
2603        let mut c2 = StringBuilder::new();
2604        for i in 0..1000 {
2605            c1.append_value(i);
2606            if i % 7 == 0 {
2607                c2.append_null();
2608            } else {
2609                c2.append_value(format!("string {i}"));
2610            }
2611        }
2612        let c1 = Arc::new(c1.finish());
2613        let c2 = Arc::new(c2.finish());
2614        let schema = Schema::new(vec![
2615            Field::new("c1", DataType::Int32, true),
2616            Field::new("c2", DataType::Utf8, true),
2617        ]);
2618        let batch = RecordBatch::try_new(Arc::new(schema), vec![c1, c2]).unwrap();
2619
2620        // CaseWhenExprOrNull should produce same results as CaseExpr
2621        let predicate = Arc::new(BinaryExpr::new(
2622            make_col("c1", 0),
2623            Operator::LtEq,
2624            make_lit_i32(250),
2625        ));
2626        let expr = CaseExpr::try_new(None, vec![(predicate, make_col("c2", 1))], None)?;
2627        assert_eq!(expr.eval_method, EvalMethod::InfallibleExprOrNull);
2628        match expr.evaluate(&batch)? {
2629            ColumnarValue::Array(array) => {
2630                assert_eq!(1000, array.len());
2631                assert_eq!(785, array.null_count());
2632            }
2633            _ => unreachable!(),
2634        }
2635        Ok(())
2636    }
2637
2638    #[test]
2639    fn test_expr_or_expr_specialization() -> Result<()> {
2640        let batch = case_test_batch1()?;
2641        let schema = batch.schema();
2642        let when = binary(
2643            col("a", &schema)?,
2644            Operator::LtEq,
2645            lit(2i32),
2646            &batch.schema(),
2647        )?;
2648        let then = col("b", &schema)?;
2649        let else_expr = col("c", &schema)?;
2650        let expr = CaseExpr::try_new(None, vec![(when, then)], Some(else_expr))?;
2651        assert!(matches!(
2652            expr.eval_method,
2653            EvalMethod::ExpressionOrExpression(_)
2654        ));
2655        let result = expr
2656            .evaluate(&batch)?
2657            .into_array(batch.num_rows())
2658            .expect("Failed to convert to array");
2659        let result = as_int32_array(&result).expect("failed to downcast to Int32Array");
2660
2661        let expected = &Int32Array::from(vec![Some(3), None, Some(777), None]);
2662
2663        assert_eq!(expected, result);
2664        Ok(())
2665    }
2666
2667    fn make_col(name: &str, index: usize) -> Arc<dyn PhysicalExpr> {
2668        Arc::new(Column::new(name, index))
2669    }
2670
2671    fn make_lit_i32(n: i32) -> Arc<dyn PhysicalExpr> {
2672        Arc::new(Literal::new(ScalarValue::Int32(Some(n))))
2673    }
2674
2675    fn generate_case_when_with_type_coercion(
2676        expr: Option<Arc<dyn PhysicalExpr>>,
2677        when_thens: Vec<WhenThen>,
2678        else_expr: Option<Arc<dyn PhysicalExpr>>,
2679        input_schema: &Schema,
2680    ) -> Result<Arc<dyn PhysicalExpr>> {
2681        let coerce_type =
2682            get_case_common_type(&when_thens, else_expr.clone(), input_schema);
2683        let (when_thens, else_expr) = match coerce_type {
2684            None => plan_err!(
2685                "Can't get a common type for then {when_thens:?} and else {else_expr:?} expression"
2686            ),
2687            Some(data_type) => {
2688                // cast then expr
2689                let left = when_thens
2690                    .into_iter()
2691                    .map(|(when, then)| {
2692                        let then = try_cast(then, input_schema, data_type.clone())?;
2693                        Ok((when, then))
2694                    })
2695                    .collect::<Result<Vec<_>>>()?;
2696                let right = match else_expr {
2697                    None => None,
2698                    Some(expr) => Some(try_cast(expr, input_schema, data_type.clone())?),
2699                };
2700
2701                Ok((left, right))
2702            }
2703        }?;
2704        case(expr, when_thens, else_expr)
2705    }
2706
2707    fn get_case_common_type(
2708        when_thens: &[WhenThen],
2709        else_expr: Option<Arc<dyn PhysicalExpr>>,
2710        input_schema: &Schema,
2711    ) -> Option<DataType> {
2712        let thens_type = when_thens
2713            .iter()
2714            .map(|when_then| {
2715                let data_type = &when_then.1.data_type(input_schema).unwrap();
2716                data_type.clone()
2717            })
2718            .collect::<Vec<_>>();
2719        let else_type = match else_expr {
2720            None => {
2721                // case when then exprs must have one then value
2722                thens_type[0].clone()
2723            }
2724            Some(else_phy_expr) => else_phy_expr.data_type(input_schema).unwrap(),
2725        };
2726        thens_type
2727            .iter()
2728            .try_fold(else_type, |left_type, right_type| {
2729                type_union_coercion(&left_type, right_type)
2730            })
2731    }
2732
2733    #[test]
2734    fn test_fmt_sql() -> Result<()> {
2735        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
2736
2737        // CASE WHEN a = 'foo' THEN 123.3 ELSE 999 END
2738        let when = binary(col("a", &schema)?, Operator::Eq, lit("foo"), &schema)?;
2739        let then = lit(123.3f64);
2740        let else_value = lit(999i32);
2741
2742        let expr = generate_case_when_with_type_coercion(
2743            None,
2744            vec![(when, then)],
2745            Some(else_value),
2746            &schema,
2747        )?;
2748
2749        let display_string = expr.to_string();
2750        assert_eq!(
2751            display_string,
2752            "CASE WHEN a@0 = foo THEN 123.3 ELSE TRY_CAST(999 AS Float64) END"
2753        );
2754
2755        let sql_string = fmt_sql(expr.as_ref()).to_string();
2756        assert_eq!(
2757            sql_string,
2758            "CASE WHEN a = foo THEN 123.3 ELSE TRY_CAST(999 AS Float64) END"
2759        );
2760
2761        Ok(())
2762    }
2763
2764    fn when_then_else(
2765        when: &Arc<dyn PhysicalExpr>,
2766        then: &Arc<dyn PhysicalExpr>,
2767        els: &Arc<dyn PhysicalExpr>,
2768    ) -> Result<Arc<dyn PhysicalExpr>> {
2769        let case = CaseExpr::try_new(
2770            None,
2771            vec![(Arc::clone(when), Arc::clone(then))],
2772            Some(Arc::clone(els)),
2773        )?;
2774        Ok(Arc::new(case))
2775    }
2776
2777    #[test]
2778    fn test_case_expression_nullability_with_nullable_column() -> Result<()> {
2779        case_expression_nullability(true)
2780    }
2781
2782    #[test]
2783    fn test_case_expression_nullability_with_not_nullable_column() -> Result<()> {
2784        case_expression_nullability(false)
2785    }
2786
2787    #[rstest::rstest]
2788    #[case::and(Operator::And, false, false)]
2789    #[case::or(Operator::Or, false, true)]
2790    #[case::not_and(Operator::And, true, true)]
2791    #[case::not_or(Operator::Or, true, false)]
2792    fn test_case_expression_nullability_with_independent_columns(
2793        #[case] op: Operator,
2794        #[case] negated: bool,
2795        #[case] nullable: bool,
2796        #[values(false, true)] reverse: bool,
2797    ) -> Result<()> {
2798        let schema = Schema::new(vec![
2799            Field::new("a", DataType::Int32, true),
2800            Field::new("b", DataType::Int32, true),
2801        ]);
2802        let a: Arc<dyn PhysicalExpr> = col("a", &schema)?;
2803        let left: Arc<dyn PhysicalExpr> =
2804            binary(Arc::clone(&a), Operator::Gt, lit(1), &schema)?;
2805        let right: Arc<dyn PhysicalExpr> =
2806            binary(col("b", &schema)?, Operator::Lt, lit(3), &schema)?;
2807        let predicate: Arc<dyn PhysicalExpr> = if reverse {
2808            binary(right, op, left, &schema)?
2809        } else {
2810            binary(left, op, right, &schema)?
2811        };
2812        let predicate: Arc<dyn PhysicalExpr> = if negated {
2813            expressions::not(predicate)?
2814        } else {
2815            predicate
2816        };
2817
2818        assert_nullability(when_then_else(&predicate, &a, &lit(0))?, &schema, nullable);
2819        Ok(())
2820    }
2821
2822    #[rstest::rstest]
2823    #[case::and_over_or(false, false)]
2824    #[case::not_and_over_or(true, true)]
2825    fn test_case_expression_nullability_with_nested_predicates(
2826        #[case] negated: bool,
2827        #[case] nullable: bool,
2828        #[values(false, true)] reverse: bool,
2829    ) -> Result<()> {
2830        let schema = Arc::new(Schema::new(vec![
2831            Field::new("a", DataType::Int32, true),
2832            Field::new("b", DataType::Int32, true),
2833        ]));
2834        let a: Arc<dyn PhysicalExpr> = col("a", &schema)?;
2835        let b: Arc<dyn PhysicalExpr> = col("b", &schema)?;
2836
2837        // a > 1 AND (b < 3 OR b IS NULL)
2838        let a_gt_1: Arc<dyn PhysicalExpr> =
2839            binary(Arc::clone(&a), Operator::Gt, lit(1), &schema)?;
2840        let b_lt_3_or_null: Arc<dyn PhysicalExpr> = binary(
2841            binary(Arc::clone(&b), Operator::Lt, lit(3), &schema)?,
2842            Operator::Or,
2843            expressions::is_null(b)?,
2844            &schema,
2845        )?;
2846        let predicate: Arc<dyn PhysicalExpr> = if reverse {
2847            binary(b_lt_3_or_null, Operator::And, a_gt_1, &schema)?
2848        } else {
2849            binary(a_gt_1, Operator::And, b_lt_3_or_null, &schema)?
2850        };
2851        let predicate: Arc<dyn PhysicalExpr> = if negated {
2852            expressions::not(predicate)?
2853        } else {
2854            predicate
2855        };
2856        let expr = when_then_else(&predicate, &a, &lit(0))?;
2857
2858        assert_nullability(Arc::clone(&expr), &schema, nullable);
2859
2860        // Cross-check the inferred nullability against evaluation on every combination
2861        // of NULL and non-NULL inputs. With a = NULL and b = 3 the negated predicate is
2862        // TRUE, so the THEN branch yields NULL.
2863        let rows: Vec<(Option<i32>, Option<i32>)> = [None, Some(1), Some(2)]
2864            .into_iter()
2865            .flat_map(|a| [None, Some(2), Some(3)].into_iter().map(move |b| (a, b)))
2866            .collect();
2867        let batch = RecordBatch::try_new(
2868            Arc::clone(&schema),
2869            vec![
2870                Arc::new(Int32Array::from_iter(rows.iter().map(|(a, _)| *a))),
2871                Arc::new(Int32Array::from_iter(rows.iter().map(|(_, b)| *b))),
2872            ],
2873        )?;
2874        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
2875        assert_eq!(result.null_count() > 0, nullable);
2876        Ok(())
2877    }
2878
2879    #[rstest::rstest]
2880    #[case::literal(lit("invalid"))]
2881    #[case::and_left(Arc::new(BinaryExpr::new(
2882        lit("invalid"),
2883        Operator::And,
2884        make_col("flag", 0)
2885    )))]
2886    #[case::and_right(Arc::new(BinaryExpr::new(
2887        make_col("flag", 0),
2888        Operator::And,
2889        lit("invalid")
2890    )))]
2891    #[case::or_left(Arc::new(BinaryExpr::new(
2892        lit("invalid"),
2893        Operator::Or,
2894        make_col("flag", 0)
2895    )))]
2896    #[case::or_right(Arc::new(BinaryExpr::new(
2897        make_col("flag", 0),
2898        Operator::Or,
2899        lit("invalid")
2900    )))]
2901    #[case::not(Arc::new(NotExpr::new(lit("invalid"))))]
2902    fn test_case_expression_nullability_with_invalid_predicate(
2903        #[case] predicate: Arc<dyn PhysicalExpr>,
2904    ) -> Result<()> {
2905        let batch = RecordBatch::try_from_iter(vec![
2906            (
2907                "flag",
2908                Arc::new(BooleanArray::from(vec![Some(true), Some(false), None]))
2909                    as ArrayRef,
2910            ),
2911            (
2912                "value",
2913                Arc::new(Int32Array::from(vec![Some(1), None, Some(3)])) as ArrayRef,
2914            ),
2915        ])?;
2916        let schema = batch.schema();
2917        let expr = when_then_else(&predicate, &col("value", &schema)?, &lit(0))?;
2918        let error = expr
2919            .nullable(&schema)
2920            .expect_err("invalid predicates must fail nullability inference");
2921        assert!(error.to_string().contains("invalid"), "{error}");
2922        assert!(expr.evaluate(&batch).is_err());
2923        Ok(())
2924    }
2925
2926    fn case_expression_nullability(col_is_nullable: bool) -> Result<()> {
2927        let schema =
2928            Schema::new(vec![Field::new("foo", DataType::Int32, col_is_nullable)]);
2929
2930        let foo = col("foo", &schema)?;
2931        let foo_is_not_null = is_not_null(Arc::clone(&foo))?;
2932        let foo_is_null = expressions::is_null(Arc::clone(&foo))?;
2933        let not_foo_is_null = expressions::not(Arc::clone(&foo_is_null))?;
2934        let zero = lit(0);
2935        let foo_eq_zero =
2936            binary(Arc::clone(&foo), Operator::Eq, Arc::clone(&zero), &schema)?;
2937        let cast_foo = cast(Arc::clone(&foo), &schema, DataType::Int64)?;
2938        let negative_foo = expressions::negative(Arc::clone(&foo), &schema)?;
2939
2940        assert_not_nullable(when_then_else(&foo_is_not_null, &foo, &zero)?, &schema);
2941        assert_not_nullable(when_then_else(&not_foo_is_null, &foo, &zero)?, &schema);
2942        assert_not_nullable(when_then_else(&foo_eq_zero, &foo, &zero)?, &schema);
2943        assert_not_nullable(
2944            when_then_else(&foo_is_not_null, &cast_foo, &lit(0i64))?,
2945            &schema,
2946        );
2947        assert_not_nullable(
2948            when_then_else(&foo_is_not_null, &negative_foo, &zero)?,
2949            &schema,
2950        );
2951
2952        // Nested null-preserving wrappers must be unwrapped recursively. `CAST(-foo)`
2953        // still collapses `foo IS NOT NULL` to `false`, so the branch is
2954        // unreachable-as-null and the `CASE` is not nullable.
2955        let cast_negative_foo = cast(
2956            expressions::negative(Arc::clone(&foo), &schema)?,
2957            &schema,
2958            DataType::Int64,
2959        )?;
2960        assert_not_nullable(
2961            when_then_else(&foo_is_not_null, &cast_negative_foo, &lit(0i64))?,
2962            &schema,
2963        );
2964
2965        // `TRY_CAST` is intentionally NOT treated as null-preserving: it yields
2966        // NULL on a failed cast even for a non-null input, so a guarded `TRY_CAST`
2967        // branch is still reachable-as-null and the `CASE` stays nullable. This must
2968        // stay consistent with the logical planner (`unwrap_certainly_null_expr` in
2969        // `datafusion/expr/src/expr_schema.rs`); unwrapping it on only one side would
2970        // reintroduce a logical/physical schema mismatch.
2971        let try_cast_foo = try_cast(Arc::clone(&foo), &schema, DataType::Int64)?;
2972        assert_nullable(
2973            when_then_else(&foo_is_not_null, &try_cast_foo, &lit(0i64))?,
2974            &schema,
2975        );
2976
2977        assert_not_nullable(
2978            when_then_else(
2979                &binary(
2980                    Arc::clone(&foo_is_not_null),
2981                    Operator::And,
2982                    Arc::clone(&foo_eq_zero),
2983                    &schema,
2984                )?,
2985                &foo,
2986                &zero,
2987            )?,
2988            &schema,
2989        );
2990
2991        assert_not_nullable(
2992            when_then_else(
2993                &binary(
2994                    Arc::clone(&foo_eq_zero),
2995                    Operator::And,
2996                    Arc::clone(&foo_is_not_null),
2997                    &schema,
2998                )?,
2999                &foo,
3000                &zero,
3001            )?,
3002            &schema,
3003        );
3004
3005        assert_not_nullable(
3006            when_then_else(
3007                &binary(
3008                    Arc::clone(&foo_is_not_null),
3009                    Operator::Or,
3010                    Arc::clone(&foo_eq_zero),
3011                    &schema,
3012                )?,
3013                &foo,
3014                &zero,
3015            )?,
3016            &schema,
3017        );
3018
3019        assert_not_nullable(
3020            when_then_else(
3021                &binary(
3022                    Arc::clone(&foo_eq_zero),
3023                    Operator::Or,
3024                    Arc::clone(&foo_is_not_null),
3025                    &schema,
3026                )?,
3027                &foo,
3028                &zero,
3029            )?,
3030            &schema,
3031        );
3032
3033        assert_nullability(
3034            when_then_else(
3035                &binary(
3036                    Arc::clone(&foo_is_null),
3037                    Operator::Or,
3038                    Arc::clone(&foo_eq_zero),
3039                    &schema,
3040                )?,
3041                &foo,
3042                &zero,
3043            )?,
3044            &schema,
3045            col_is_nullable,
3046        );
3047
3048        assert_nullability(
3049            when_then_else(
3050                &binary(
3051                    binary(Arc::clone(&foo), Operator::Eq, Arc::clone(&zero), &schema)?,
3052                    Operator::Or,
3053                    Arc::clone(&foo_is_null),
3054                    &schema,
3055                )?,
3056                &foo,
3057                &zero,
3058            )?,
3059            &schema,
3060            col_is_nullable,
3061        );
3062
3063        assert_not_nullable(
3064            when_then_else(
3065                &binary(
3066                    binary(
3067                        binary(
3068                            Arc::clone(&foo),
3069                            Operator::Eq,
3070                            Arc::clone(&zero),
3071                            &schema,
3072                        )?,
3073                        Operator::And,
3074                        Arc::clone(&foo_is_not_null),
3075                        &schema,
3076                    )?,
3077                    Operator::Or,
3078                    binary(
3079                        binary(
3080                            Arc::clone(&foo),
3081                            Operator::Eq,
3082                            Arc::clone(&foo),
3083                            &schema,
3084                        )?,
3085                        Operator::And,
3086                        Arc::clone(&foo_is_not_null),
3087                        &schema,
3088                    )?,
3089                    &schema,
3090                )?,
3091                &foo,
3092                &zero,
3093            )?,
3094            &schema,
3095        );
3096
3097        let boolean_schema =
3098            Schema::new(vec![Field::new("predicate", DataType::Boolean, true)]);
3099        let predicate = col("predicate", &boolean_schema)?;
3100        let predicate_is_not_null = is_not_null(Arc::clone(&predicate))?;
3101        let not_predicate = expressions::not(Arc::clone(&predicate))?;
3102        assert_not_nullable(
3103            when_then_else(&predicate_is_not_null, &not_predicate, &lit(false))?,
3104            &boolean_schema,
3105        );
3106
3107        // Nested `NOT` is likewise unwrapped recursively.
3108        let not_not_predicate = expressions::not(Arc::clone(&not_predicate))?;
3109        assert_not_nullable(
3110            when_then_else(&predicate_is_not_null, &not_not_predicate, &lit(false))?,
3111            &boolean_schema,
3112        );
3113
3114        Ok(())
3115    }
3116
3117    fn assert_not_nullable(expr: Arc<dyn PhysicalExpr>, schema: &Schema) {
3118        assert!(!expr.nullable(schema).unwrap());
3119    }
3120
3121    fn assert_nullable(expr: Arc<dyn PhysicalExpr>, schema: &Schema) {
3122        assert!(expr.nullable(schema).unwrap());
3123    }
3124
3125    fn assert_nullability(expr: Arc<dyn PhysicalExpr>, schema: &Schema, nullable: bool) {
3126        if nullable {
3127            assert_nullable(expr, schema);
3128        } else {
3129            assert_not_nullable(expr, schema);
3130        }
3131    }
3132
3133    // Test Lookup evaluation
3134
3135    fn test_case_when_literal_lookup(
3136        values: ArrayRef,
3137        lookup_map: &[(ScalarValue, ScalarValue)],
3138        else_value: Option<ScalarValue>,
3139        expected: ArrayRef,
3140    ) {
3141        // Create lookup
3142        // CASE <expr>
3143        // WHEN <when_constant_1> THEN <then_constant_1>
3144        // WHEN <when_constant_2> THEN <then_constant_2>
3145        // [ ELSE <else_constant> ]
3146
3147        let schema = Schema::new(vec![Field::new(
3148            "a",
3149            values.data_type().clone(),
3150            values.is_nullable(),
3151        )]);
3152        let schema = Arc::new(schema);
3153
3154        let batch = RecordBatch::try_new(schema, vec![values])
3155            .expect("failed to create RecordBatch");
3156
3157        let schema = batch.schema_ref();
3158        let case = col("a", schema).expect("failed to create col");
3159
3160        let when_then = lookup_map
3161            .iter()
3162            .map(|(when, then)| {
3163                (
3164                    Arc::new(Literal::new(when.clone())) as _,
3165                    Arc::new(Literal::new(then.clone())) as _,
3166                )
3167            })
3168            .collect::<Vec<WhenThen>>();
3169
3170        let else_expr = else_value.map(|else_value| {
3171            Arc::new(Literal::new(else_value)) as Arc<dyn PhysicalExpr>
3172        });
3173        let expr = CaseExpr::try_new(Some(case), when_then, else_expr)
3174            .expect("failed to create case");
3175
3176        // Assert that we are testing what we intend to assert
3177        assert!(
3178            matches!(
3179                expr.eval_method,
3180                EvalMethod::WithExprScalarLookupTable { .. }
3181            ),
3182            "we should use the expected eval method"
3183        );
3184
3185        let actual = expr
3186            .evaluate(&batch)
3187            .expect("failed to evaluate case")
3188            .into_array(batch.num_rows())
3189            .expect("Failed to convert to array");
3190
3191        assert_eq!(
3192            actual.data_type(),
3193            expected.data_type(),
3194            "Data type mismatch"
3195        );
3196
3197        assert_eq!(
3198            actual.as_ref(),
3199            expected.as_ref(),
3200            "actual (left) does not match expected (right)"
3201        );
3202    }
3203
3204    fn create_lookup<When, Then>(
3205        when_then_pairs: impl IntoIterator<Item = (When, Then)>,
3206    ) -> Vec<(ScalarValue, ScalarValue)>
3207    where
3208        ScalarValue: From<When>,
3209        ScalarValue: From<Then>,
3210    {
3211        when_then_pairs
3212            .into_iter()
3213            .map(|(when, then)| (ScalarValue::from(when), ScalarValue::from(then)))
3214            .collect()
3215    }
3216
3217    fn create_input_and_expected<Input, Expected, InputFromItem, ExpectedFromItem>(
3218        input_and_expected_pairs: impl IntoIterator<Item = (InputFromItem, ExpectedFromItem)>,
3219    ) -> (Input, Expected)
3220    where
3221        Input: Array + From<Vec<InputFromItem>>,
3222        Expected: Array + From<Vec<ExpectedFromItem>>,
3223    {
3224        let (input_items, expected_items): (Vec<InputFromItem>, Vec<ExpectedFromItem>) =
3225            input_and_expected_pairs.into_iter().unzip();
3226
3227        (Input::from(input_items), Expected::from(expected_items))
3228    }
3229
3230    fn test_lookup_eval_with_and_without_else(
3231        lookup_map: &[(ScalarValue, ScalarValue)],
3232        input_values: ArrayRef,
3233        expected: StringArray,
3234    ) {
3235        // Testing without ELSE should fallback to None
3236        test_case_when_literal_lookup(
3237            Arc::clone(&input_values),
3238            lookup_map,
3239            None,
3240            Arc::new(expected.clone()),
3241        );
3242
3243        // Testing with Else
3244        let else_value = "___fallback___";
3245
3246        // Changing each expected None to be fallback
3247        let expected_with_else = expected
3248            .iter()
3249            .map(|item| item.unwrap_or(else_value))
3250            .map(Some)
3251            .collect::<StringArray>();
3252
3253        // Test case
3254        test_case_when_literal_lookup(
3255            input_values,
3256            lookup_map,
3257            Some(ScalarValue::Utf8(Some(else_value.to_string()))),
3258            Arc::new(expected_with_else),
3259        );
3260    }
3261
3262    #[test]
3263    fn test_case_when_literal_lookup_int32_to_string() {
3264        let lookup_map = create_lookup([
3265            (Some(4), Some("four")),
3266            (Some(2), Some("two")),
3267            (Some(3), Some("three")),
3268            (Some(1), Some("one")),
3269        ]);
3270
3271        let (input_values, expected) =
3272            create_input_and_expected::<Int32Array, StringArray, _, _>([
3273                (1, Some("one")),
3274                (2, Some("two")),
3275                (3, Some("three")),
3276                (3, Some("three")),
3277                (2, Some("two")),
3278                (3, Some("three")),
3279                (5, None), // No match in WHEN
3280                (5, None), // No match in WHEN
3281                (3, Some("three")),
3282                (5, None), // No match in WHEN
3283            ]);
3284
3285        test_lookup_eval_with_and_without_else(
3286            &lookup_map,
3287            Arc::new(input_values),
3288            expected,
3289        );
3290    }
3291
3292    #[test]
3293    fn test_case_when_literal_lookup_none_case_should_never_match() {
3294        let lookup_map = create_lookup([
3295            (Some(4), Some("four")),
3296            (None, Some("none")),
3297            (Some(2), Some("two")),
3298            (Some(1), Some("one")),
3299        ]);
3300
3301        let (input_values, expected) =
3302            create_input_and_expected::<Int32Array, StringArray, _, _>([
3303                (Some(1), Some("one")),
3304                (Some(5), None), // No match in WHEN
3305                (None, None), // None cases are never match in CASE <expr> WHEN <value> syntax
3306                (Some(2), Some("two")),
3307                (None, None), // None cases are never match in CASE <expr> WHEN <value> syntax
3308                (None, None), // None cases are never match in CASE <expr> WHEN <value> syntax
3309                (Some(2), Some("two")),
3310                (Some(5), None), // No match in WHEN
3311            ]);
3312
3313        test_lookup_eval_with_and_without_else(
3314            &lookup_map,
3315            Arc::new(input_values),
3316            expected,
3317        );
3318    }
3319
3320    #[test]
3321    fn test_case_when_literal_lookup_int32_to_string_with_duplicate_cases() {
3322        let lookup_map = create_lookup([
3323            (Some(4), Some("four")),
3324            (Some(4), Some("no 4")),
3325            (Some(2), Some("two")),
3326            (Some(2), Some("no 2")),
3327            (Some(3), Some("three")),
3328            (Some(3), Some("no 3")),
3329            (Some(2), Some("no 2")),
3330            (Some(4), Some("no 4")),
3331            (Some(2), Some("no 2")),
3332            (Some(3), Some("no 3")),
3333            (Some(4), Some("no 4")),
3334            (Some(2), Some("no 2")),
3335            (Some(3), Some("no 3")),
3336            (Some(3), Some("no 3")),
3337        ]);
3338
3339        let (input_values, expected) =
3340            create_input_and_expected::<Int32Array, StringArray, _, _>([
3341                (1, None), // No match in WHEN
3342                (2, Some("two")),
3343                (3, Some("three")),
3344                (3, Some("three")),
3345                (2, Some("two")),
3346                (3, Some("three")),
3347                (5, None), // No match in WHEN
3348                (5, None), // No match in WHEN
3349                (3, Some("three")),
3350                (5, None), // No match in WHEN
3351            ]);
3352
3353        test_lookup_eval_with_and_without_else(
3354            &lookup_map,
3355            Arc::new(input_values),
3356            expected,
3357        );
3358    }
3359
3360    #[test]
3361    fn test_case_when_literal_lookup_f32_to_string_with_special_values_and_duplicate_cases()
3362     {
3363        let lookup_map = create_lookup([
3364            (Some(4.0), Some("four point zero")),
3365            (Some(f32::NAN), Some("NaN")),
3366            (Some(3.2), Some("three point two")),
3367            // Duplicate case to make sure it is not used
3368            (Some(f32::NAN), Some("should not use this NaN branch")),
3369            (Some(f32::INFINITY), Some("Infinity")),
3370            (Some(0.0), Some("zero")),
3371            // Duplicate case to make sure it is not used
3372            (
3373                Some(f32::INFINITY),
3374                Some("should not use this Infinity branch"),
3375            ),
3376            (Some(1.1), Some("one point one")),
3377        ]);
3378
3379        let (input_values, expected) =
3380            create_input_and_expected::<Float32Array, StringArray, _, _>([
3381                (1.1, Some("one point one")),
3382                (f32::NAN, Some("NaN")),
3383                (3.2, Some("three point two")),
3384                (3.2, Some("three point two")),
3385                (0.0, Some("zero")),
3386                (f32::INFINITY, Some("Infinity")),
3387                (3.2, Some("three point two")),
3388                (f32::NEG_INFINITY, None), // No match in WHEN
3389                (f32::NEG_INFINITY, None), // No match in WHEN
3390                (3.2, Some("three point two")),
3391                (-0.0, None), // No match in WHEN
3392            ]);
3393
3394        test_lookup_eval_with_and_without_else(
3395            &lookup_map,
3396            Arc::new(input_values),
3397            expected,
3398        );
3399    }
3400
3401    #[test]
3402    fn test_case_when_literal_lookup_f16_to_string_with_special_values() {
3403        let lookup_map = create_lookup([
3404            (
3405                ScalarValue::Float16(Some(f16::from_f32(3.2))),
3406                Some("3 dot 2"),
3407            ),
3408            (ScalarValue::Float16(Some(f16::NAN)), Some("NaN")),
3409            (
3410                ScalarValue::Float16(Some(f16::from_f32(17.4))),
3411                Some("17 dot 4"),
3412            ),
3413            (ScalarValue::Float16(Some(f16::INFINITY)), Some("Infinity")),
3414            (ScalarValue::Float16(Some(f16::ZERO)), Some("zero")),
3415        ]);
3416
3417        let (input_values, expected) =
3418            create_input_and_expected::<Float16Array, StringArray, _, _>([
3419                (f16::from_f32(3.2), Some("3 dot 2")),
3420                (f16::NAN, Some("NaN")),
3421                (f16::from_f32(17.4), Some("17 dot 4")),
3422                (f16::from_f32(17.4), Some("17 dot 4")),
3423                (f16::INFINITY, Some("Infinity")),
3424                (f16::from_f32(17.4), Some("17 dot 4")),
3425                (f16::NEG_INFINITY, None), // No match in WHEN
3426                (f16::NEG_INFINITY, None), // No match in WHEN
3427                (f16::from_f32(17.4), Some("17 dot 4")),
3428                (f16::NEG_ZERO, None), // No match in WHEN
3429            ]);
3430
3431        test_lookup_eval_with_and_without_else(
3432            &lookup_map,
3433            Arc::new(input_values),
3434            expected,
3435        );
3436    }
3437
3438    #[test]
3439    fn test_case_when_literal_lookup_f32_to_string_with_special_values() {
3440        let lookup_map = create_lookup([
3441            (3.2, Some("3 dot 2")),
3442            (f32::NAN, Some("NaN")),
3443            (17.4, Some("17 dot 4")),
3444            (f32::INFINITY, Some("Infinity")),
3445            (f32::ZERO, Some("zero")),
3446        ]);
3447
3448        let (input_values, expected) =
3449            create_input_and_expected::<Float32Array, StringArray, _, _>([
3450                (3.2, Some("3 dot 2")),
3451                (f32::NAN, Some("NaN")),
3452                (17.4, Some("17 dot 4")),
3453                (17.4, Some("17 dot 4")),
3454                (f32::INFINITY, Some("Infinity")),
3455                (17.4, Some("17 dot 4")),
3456                (f32::NEG_INFINITY, None), // No match in WHEN
3457                (f32::NEG_INFINITY, None), // No match in WHEN
3458                (17.4, Some("17 dot 4")),
3459                (-0.0, None), // No match in WHEN
3460            ]);
3461
3462        test_lookup_eval_with_and_without_else(
3463            &lookup_map,
3464            Arc::new(input_values),
3465            expected,
3466        );
3467    }
3468
3469    #[test]
3470    fn test_case_when_literal_lookup_f64_to_string_with_special_values() {
3471        let lookup_map = create_lookup([
3472            (3.2, Some("3 dot 2")),
3473            (f64::NAN, Some("NaN")),
3474            (17.4, Some("17 dot 4")),
3475            (f64::INFINITY, Some("Infinity")),
3476            (f64::ZERO, Some("zero")),
3477        ]);
3478
3479        let (input_values, expected) =
3480            create_input_and_expected::<Float64Array, StringArray, _, _>([
3481                (3.2, Some("3 dot 2")),
3482                (f64::NAN, Some("NaN")),
3483                (17.4, Some("17 dot 4")),
3484                (17.4, Some("17 dot 4")),
3485                (f64::INFINITY, Some("Infinity")),
3486                (17.4, Some("17 dot 4")),
3487                (f64::NEG_INFINITY, None), // No match in WHEN
3488                (f64::NEG_INFINITY, None), // No match in WHEN
3489                (17.4, Some("17 dot 4")),
3490                (-0.0, None), // No match in WHEN
3491            ]);
3492
3493        test_lookup_eval_with_and_without_else(
3494            &lookup_map,
3495            Arc::new(input_values),
3496            expected,
3497        );
3498    }
3499
3500    // Test that we don't lose the decimal precision and scale info
3501    #[test]
3502    fn test_decimal_with_non_default_precision_and_scale() {
3503        let lookup_map = create_lookup([
3504            (ScalarValue::Decimal32(Some(4), 3, 2), Some("four")),
3505            (ScalarValue::Decimal32(Some(2), 3, 2), Some("two")),
3506            (ScalarValue::Decimal32(Some(3), 3, 2), Some("three")),
3507            (ScalarValue::Decimal32(Some(1), 3, 2), Some("one")),
3508        ]);
3509
3510        let (input_values, expected) =
3511            create_input_and_expected::<Decimal32Array, StringArray, _, _>([
3512                (1, Some("one")),
3513                (2, Some("two")),
3514                (3, Some("three")),
3515                (3, Some("three")),
3516                (2, Some("two")),
3517                (3, Some("three")),
3518                (5, None), // No match in WHEN
3519                (5, None), // No match in WHEN
3520                (3, Some("three")),
3521                (5, None), // No match in WHEN
3522            ]);
3523
3524        let input_values = input_values
3525            .with_precision_and_scale(3, 2)
3526            .expect("must be able to set precision and scale");
3527
3528        test_lookup_eval_with_and_without_else(
3529            &lookup_map,
3530            Arc::new(input_values),
3531            expected,
3532        );
3533    }
3534
3535    // Test that we don't lose the timezone info
3536    #[test]
3537    fn test_timestamp_with_non_default_timezone() {
3538        let timezone: Option<Arc<str>> = Some("-10:00".into());
3539        let lookup_map = create_lookup([
3540            (
3541                ScalarValue::TimestampMillisecond(Some(4), timezone.clone()),
3542                Some("four"),
3543            ),
3544            (
3545                ScalarValue::TimestampMillisecond(Some(2), timezone.clone()),
3546                Some("two"),
3547            ),
3548            (
3549                ScalarValue::TimestampMillisecond(Some(3), timezone.clone()),
3550                Some("three"),
3551            ),
3552            (
3553                ScalarValue::TimestampMillisecond(Some(1), timezone.clone()),
3554                Some("one"),
3555            ),
3556        ]);
3557
3558        let (input_values, expected) =
3559            create_input_and_expected::<TimestampMillisecondArray, StringArray, _, _>([
3560                (1, Some("one")),
3561                (2, Some("two")),
3562                (3, Some("three")),
3563                (3, Some("three")),
3564                (2, Some("two")),
3565                (3, Some("three")),
3566                (5, None), // No match in WHEN
3567                (5, None), // No match in WHEN
3568                (3, Some("three")),
3569                (5, None), // No match in WHEN
3570            ]);
3571
3572        let input_values = input_values.with_timezone_opt(timezone);
3573
3574        test_lookup_eval_with_and_without_else(
3575            &lookup_map,
3576            Arc::new(input_values),
3577            expected,
3578        );
3579    }
3580
3581    #[test]
3582    fn test_with_strings_to_int32() {
3583        let lookup_map = create_lookup([
3584            (Some("why"), Some(42)),
3585            (Some("what"), Some(22)),
3586            (Some("when"), Some(17)),
3587        ]);
3588
3589        let (input_values, expected) =
3590            create_input_and_expected::<StringArray, Int32Array, _, _>([
3591                (Some("why"), Some(42)),
3592                (Some("5"), None), // No match in WHEN
3593                (None, None), // None cases are never match in CASE <expr> WHEN <value> syntax
3594                (Some("what"), Some(22)),
3595                (None, None), // None cases are never match in CASE <expr> WHEN <value> syntax
3596                (None, None), // None cases are never match in CASE <expr> WHEN <value> syntax
3597                (Some("what"), Some(22)),
3598                (Some("5"), None), // No match in WHEN
3599            ]);
3600
3601        let input_values = Arc::new(input_values) as ArrayRef;
3602
3603        // Testing without ELSE should fallback to None
3604        test_case_when_literal_lookup(
3605            Arc::clone(&input_values),
3606            &lookup_map,
3607            None,
3608            Arc::new(expected.clone()),
3609        );
3610
3611        // Testing with Else
3612        let else_value = 101;
3613
3614        // Changing each expected None to be fallback
3615        let expected_with_else = expected
3616            .iter()
3617            .map(|item| item.unwrap_or(else_value))
3618            .map(Some)
3619            .collect::<Int32Array>();
3620
3621        // Test case
3622        test_case_when_literal_lookup(
3623            input_values,
3624            &lookup_map,
3625            Some(ScalarValue::Int32(Some(else_value))),
3626            Arc::new(expected_with_else),
3627        );
3628    }
3629
3630    #[test]
3631    fn test_case_when_literal_lookup_fixed_size_binary_to_int32() {
3632        let lookup_map = vec![
3633            (
3634                ScalarValue::FixedSizeBinary(1, Some(vec![1])),
3635                ScalarValue::Int32(Some(10)),
3636            ),
3637            (
3638                ScalarValue::FixedSizeBinary(1, Some(vec![2])),
3639                ScalarValue::Int32(Some(20)),
3640            ),
3641        ];
3642
3643        let input_values = ScalarValue::iter_to_array(vec![
3644            ScalarValue::FixedSizeBinary(1, Some(vec![1])),
3645            ScalarValue::FixedSizeBinary(1, Some(vec![2])),
3646            ScalarValue::FixedSizeBinary(1, Some(vec![3])),
3647            ScalarValue::FixedSizeBinary(1, None),
3648        ])
3649        .expect("valid fixed size binary array");
3650
3651        let expected_no_else =
3652            Arc::new(Int32Array::from(vec![Some(10), Some(20), None, None])) as ArrayRef;
3653
3654        test_case_when_literal_lookup(
3655            Arc::clone(&input_values),
3656            &lookup_map,
3657            None,
3658            expected_no_else,
3659        );
3660
3661        let expected_with_else = Arc::new(Int32Array::from(vec![
3662            Some(10),
3663            Some(20),
3664            Some(99),
3665            Some(99),
3666        ])) as ArrayRef;
3667
3668        test_case_when_literal_lookup(
3669            input_values,
3670            &lookup_map,
3671            Some(ScalarValue::Int32(Some(99))),
3672            expected_with_else,
3673        );
3674    }
3675
3676    /// Reproduces https://github.com/apache/datafusion/issues/22173
3677    ///
3678    /// Nested self-referential CASE chains (common in rewrite-style projections)
3679    /// should not cause exponential hashing work during physical planning.
3680    #[test]
3681    fn nested_self_referential_case_hash_stays_bounded() -> Result<()> {
3682        use std::hash::Hasher;
3683
3684        #[derive(Default)]
3685        struct CountingHasher {
3686            write_calls: usize,
3687            bytes_written: usize,
3688        }
3689
3690        impl Hasher for CountingHasher {
3691            fn finish(&self) -> u64 {
3692                0
3693            }
3694
3695            fn write(&mut self, bytes: &[u8]) {
3696                self.write_calls += 1;
3697                self.bytes_written += bytes.len();
3698            }
3699        }
3700
3701        let schema =
3702            Arc::new(Schema::new(vec![Field::new("kind", DataType::Utf8, true)]));
3703
3704        let kind = col("kind", &schema)?;
3705        let mut label = Arc::clone(&kind);
3706
3707        let num_levels = 18;
3708        for idx in 0..num_levels {
3709            let predicate = Arc::new(BinaryExpr::new(
3710                Arc::clone(&kind),
3711                Operator::Eq,
3712                lit(idx.to_string()),
3713            )) as Arc<dyn PhysicalExpr>;
3714
3715            label = case(None, vec![(predicate, lit("label"))], Some(label))?;
3716        }
3717
3718        let mut hasher = CountingHasher::default();
3719        label.hash(&mut hasher);
3720
3721        assert!(
3722            hasher.write_calls < 50_000,
3723            "hashing nested CASE expression took {} hasher writes and {} bytes",
3724            hasher.write_calls,
3725            hasher.bytes_written
3726        );
3727
3728        Ok(())
3729    }
3730}
3731
3732#[cfg(all(test, feature = "proto"))]
3733mod proto_tests {
3734    use super::*;
3735    use crate::expressions::col;
3736    use crate::proto_test_util::{
3737        StubDecoder, StubEncoder, UnreachableDecoder, column_node,
3738    };
3739    use arrow::datatypes::Field;
3740    use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
3741    use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
3742    use datafusion_proto_models::protobuf;
3743    use datafusion_proto_models::protobuf::{PhysicalExprNode, PhysicalWhenThen};
3744
3745    fn proto_case_fixture() -> CaseExpr {
3746        let schema = Schema::new(vec![Field::new("a", DataType::Boolean, true)]);
3747        CaseExpr::try_new(
3748            Some(col("a", &schema).unwrap()),
3749            vec![(lit(true), lit(1_i32))],
3750            Some(lit(0_i32)),
3751        )
3752        .unwrap()
3753    }
3754
3755    fn proto_when_then(
3756        when_expr: Option<PhysicalExprNode>,
3757        then_expr: Option<PhysicalExprNode>,
3758    ) -> PhysicalWhenThen {
3759        PhysicalWhenThen {
3760            when_expr,
3761            then_expr,
3762        }
3763    }
3764
3765    fn proto_case_node(
3766        expr: Option<Box<PhysicalExprNode>>,
3767        when_then_expr: Vec<PhysicalWhenThen>,
3768        else_expr: Option<Box<PhysicalExprNode>>,
3769    ) -> PhysicalExprNode {
3770        PhysicalExprNode {
3771            expr_id: None,
3772            expr_type: Some(protobuf::physical_expr_node::ExprType::Case(Box::new(
3773                protobuf::PhysicalCaseNode {
3774                    expr,
3775                    when_then_expr,
3776                    else_expr,
3777                },
3778            ))),
3779        }
3780    }
3781
3782    #[test]
3783    fn try_to_proto_encodes_case_expr() {
3784        let case = proto_case_fixture();
3785        let encoder = StubEncoder::ok();
3786        let ctx = PhysicalExprEncodeCtx::new(&encoder);
3787
3788        let node = case
3789            .try_to_proto(&ctx)
3790            .unwrap()
3791            .expect("CaseExpr should encode to Some(node)");
3792
3793        assert!(node.expr_id.is_none());
3794        let case_node = match node.expr_type {
3795            Some(protobuf::physical_expr_node::ExprType::Case(boxed)) => *boxed,
3796            other => panic!("expected a CaseExpr node, got {other:?}"),
3797        };
3798        assert!(case_node.expr.is_some());
3799        assert_eq!(case_node.when_then_expr.len(), 1);
3800        assert!(case_node.when_then_expr[0].when_expr.is_some());
3801        assert!(case_node.when_then_expr[0].then_expr.is_some());
3802        assert!(case_node.else_expr.is_some());
3803    }
3804
3805    #[test]
3806    fn try_to_proto_distinguishes_optional_case_exprs() {
3807        let encoder = StubEncoder::ok();
3808        let ctx = PhysicalExprEncodeCtx::new(&encoder);
3809
3810        for (expr, else_expr) in [(None, Some(lit(0_i32))), (Some(lit(true)), None)] {
3811            let case = CaseExpr::try_new(expr, vec![(lit(true), lit(1_i32))], else_expr)
3812                .unwrap();
3813            let node = case.try_to_proto(&ctx).unwrap().unwrap();
3814            let Some(protobuf::physical_expr_node::ExprType::Case(case_node)) =
3815                node.expr_type
3816            else {
3817                panic!("expected a CaseExpr node");
3818            };
3819
3820            assert_eq!(case_node.expr.is_some(), case.expr().is_some());
3821            assert_eq!(case_node.else_expr.is_some(), case.else_expr().is_some());
3822        }
3823    }
3824
3825    #[test]
3826    fn try_to_proto_propagates_child_encode_error() {
3827        let case = proto_case_fixture();
3828        // Call 1 is the optional CASE expr, call 2 is the WHEN expr.
3829        let encoder = StubEncoder::failing_on(2);
3830        let ctx = PhysicalExprEncodeCtx::new(&encoder);
3831
3832        let err = case.try_to_proto(&ctx).unwrap_err();
3833        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 2")));
3834    }
3835
3836    #[test]
3837    fn try_from_proto_decodes_case_expr() {
3838        let node = proto_case_node(
3839            Some(Box::new(column_node("case"))),
3840            vec![proto_when_then(
3841                Some(column_node("when")),
3842                Some(column_node("then")),
3843            )],
3844            Some(Box::new(column_node("else"))),
3845        );
3846        let schema = Schema::empty();
3847        let decoder = StubDecoder::ok();
3848        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
3849
3850        let decoded = CaseExpr::try_from_proto(&node, &ctx).unwrap();
3851        let case = decoded
3852            .downcast_ref::<CaseExpr>()
3853            .expect("decoded expr should be a CaseExpr");
3854
3855        assert!(case.expr().is_some());
3856        assert_eq!(case.when_then_expr().len(), 1);
3857        assert!(case.else_expr().is_some());
3858    }
3859
3860    #[test]
3861    fn try_from_proto_rejects_non_case_node() {
3862        let node = column_node("a");
3863        let schema = Schema::empty();
3864        let decoder = UnreachableDecoder;
3865        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
3866
3867        let err = CaseExpr::try_from_proto(&node, &ctx).unwrap_err();
3868        assert!(
3869            matches!(err, DataFusionError::Internal(msg) if msg.contains("PhysicalExprNode is not a CaseExpr"))
3870        );
3871    }
3872
3873    #[test]
3874    fn try_from_proto_rejects_missing_when_expr() {
3875        let node = proto_case_node(
3876            None,
3877            vec![proto_when_then(None, Some(column_node("then")))],
3878            None,
3879        );
3880        let schema = Schema::empty();
3881        let decoder = UnreachableDecoder;
3882        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
3883
3884        let err = CaseExpr::try_from_proto(&node, &ctx).unwrap_err();
3885        assert!(
3886            matches!(err, DataFusionError::Internal(msg) if msg.contains("CaseExpr is missing required field 'when_expr'"))
3887        );
3888    }
3889
3890    #[test]
3891    fn try_from_proto_rejects_missing_then_expr() {
3892        let node = proto_case_node(
3893            None,
3894            vec![proto_when_then(Some(column_node("when")), None)],
3895            None,
3896        );
3897        let schema = Schema::empty();
3898        let decoder = StubDecoder::ok();
3899        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
3900
3901        let err = CaseExpr::try_from_proto(&node, &ctx).unwrap_err();
3902        assert!(
3903            matches!(err, DataFusionError::Internal(msg) if msg.contains("CaseExpr is missing required field 'then_expr'"))
3904        );
3905    }
3906
3907    #[test]
3908    fn try_from_proto_propagates_child_decode_error() {
3909        let node = proto_case_node(
3910            Some(Box::new(column_node("case"))),
3911            vec![proto_when_then(
3912                Some(column_node("when")),
3913                Some(column_node("then")),
3914            )],
3915            Some(Box::new(column_node("else"))),
3916        );
3917        let schema = Schema::empty();
3918        let decoder = StubDecoder::failing_on(2);
3919        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
3920
3921        let err = CaseExpr::try_from_proto(&node, &ctx).unwrap_err();
3922        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 2")));
3923    }
3924}