1mod 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 NoExpression(ProjectedCaseBody),
50 WithExpression(ProjectedCaseBody),
56 InfallibleExprOrNull,
62 ScalarOrScalar,
67 ExpressionOrExpression(ProjectedCaseBody),
76
77 WithExprScalarLookupTable(LiteralLookupTable),
81}
82
83impl Hash for LiteralLookupTable {
90 fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {}
91}
92
93impl PartialEq for LiteralLookupTable {
100 fn eq(&self, _other: &Self) -> bool {
101 true
102 }
103}
104
105impl Eq for LiteralLookupTable {}
106
107#[derive(Debug, Hash, PartialEq, Eq)]
110struct CaseBody {
111 expr: Option<Arc<dyn PhysicalExpr>>,
113 when_then_expr: Vec<WhenThen>,
115 else_expr: Option<Arc<dyn PhysicalExpr>>,
117}
118
119impl CaseBody {
120 fn project(&self) -> Result<ProjectedCaseBody> {
122 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 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 let column_index_map = used_column_indices
159 .iter()
160 .enumerate()
161 .map(|(projected, original)| (*original, projected))
162 .collect::<IndexMap<usize, usize>>();
163
164 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 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#[derive(Debug, Hash, PartialEq, Eq)]
251struct ProjectedCaseBody {
252 projection: Vec<usize>,
253 body: CaseBody,
254 supports_projection: bool,
259}
260
261impl ProjectedCaseBody {
262 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#[derive(Debug)]
293pub struct CaseExpr {
294 body: CaseBody,
296 eval_method: EvalMethod,
298}
299
300impl 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
333fn is_cheap_and_infallible(expr: &Arc<dyn PhysicalExpr>) -> bool {
339 expr.is::<Column>()
340}
341
342fn create_filter(predicate: &BooleanArray, optimize: bool) -> FilterPredicate {
344 let mut filter_builder = FilterBuilder::new(predicate);
345 if optimize {
346 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
363fn 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 unsafe {
380 Ok(RecordBatch::new_unchecked(
381 record_batch.schema(),
382 filtered_columns,
383 filter.count(),
384 ))
385 }
386}
387
388#[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#[derive(Copy, Clone, PartialEq, Eq)]
405struct PartialResultIndex {
406 index: u32,
407}
408
409const NONE_VALUE: u32 = u32::MAX;
410
411impl PartialResultIndex {
412 fn none() -> Self {
414 Self { index: NONE_VALUE }
415 }
416
417 fn zero() -> Self {
418 Self { index: 0 }
419 }
420
421 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 fn is_none(&self) -> bool {
440 self.index == NONE_VALUE
441 }
442}
443
444impl MergeIndex for PartialResultIndex {
445 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 Empty,
468 Partial {
470 arrays: Vec<ArrayRef>,
473 indices: Vec<PartialResultIndex>,
475 },
476 Complete(ColumnarValue),
479}
480
481struct ResultBuilder {
491 data_type: DataType,
492 row_count: usize,
494 state: ResultState,
495}
496
497impl ResultBuilder {
498 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 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 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 #[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 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 fn finish(self) -> Result<ColumnarValue> {
647 match self.state {
648 ResultState::Empty => {
649 Ok(ColumnarValue::Scalar(ScalarValue::try_new_null(
653 &self.data_type,
654 )?))
655 }
656 ResultState::Partial { arrays, indices } => {
657 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 Ok(v)
664 }
665 }
666 }
667}
668
669impl CaseExpr {
670 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 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 pub fn expr(&self) -> Option<&Arc<dyn PhysicalExpr>> {
732 self.body.expr.as_ref()
733 }
734
735 pub fn when_then_expr(&self) -> &[WhenThen] {
737 &self.body.when_then_expr
738 }
739
740 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 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 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 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 let mut remainder_rows: ArrayRef =
777 Arc::new(UInt32Array::from_iter_values(0..batch.num_rows() as u32));
778 let mut remainder_batch = Cow::Borrowed(batch);
780
781 let mut base_values = self
783 .expr
784 .as_ref()
785 .unwrap()
786 .evaluate(batch)?
787 .into_array(batch.num_rows())?;
788
789 let base_null_count = base_values.logical_null_count();
794 if base_null_count > 0 {
795 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 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 let nulls_value = expr.evaluate(&remainder_batch)?;
809 result_builder.add_branch_result(&remainder_rows, nulls_value)?;
810 } else {
811 let nulls_filter = create_filter(¬(&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 if base_all_null {
823 return result_builder.finish();
824 }
825
826 let not_null_filter = create_filter(&base_not_nulls, true);
828 remainder_batch =
829 Cow::Owned(filter_record_batch(&remainder_batch, ¬_null_filter)?);
830 remainder_rows = filter_array(&remainder_rows, ¬_null_filter)?;
831 base_values = filter_array(&base_values, ¬_null_filter)?;
832 }
833
834 let base_value_is_nested = base_values.data_type().is_nested();
837
838 for i in 0..self.when_then_expr.len() {
839 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 !when_value.has_true() {
855 continue;
856 }
857
858 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 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 self.else_expr.is_none() && i == self.when_then_expr.len() - 1 {
882 return result_builder.finish();
883 }
884
885 let next_selection = match when_value.null_count() {
887 0 => not(&when_value),
888 _ => {
889 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 let Some(e) = &self.else_expr {
904 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 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 let mut remainder_rows: ArrayRef =
923 Arc::new(UInt32Array::from_iter(0..batch.num_rows() as u32));
924 let mut remainder_batch = Cow::Borrowed(batch);
926
927 for i in 0..self.when_then_expr.len() {
928 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 !when_value.has_true() {
942 continue;
943 }
944
945 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 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 self.else_expr.is_none() && i == self.when_then_expr.len() - 1 {
969 return result_builder.finish();
970 }
971
972 let next_selection = match when_value.null_count() {
974 0 => not(when_value),
975 _ => {
976 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 let Some(e) = &self.else_expr {
990 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 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 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 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 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 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 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 ColumnarValue::Scalar(ScalarValue::Boolean(Some(true))) => {
1120 then_expr.evaluate(batch)
1121 }
1122 ColumnarValue::Scalar(_) => {
1124 ScalarValue::try_from(self.data_type(&batch.schema())?)
1126 .map(ColumnarValue::Scalar)
1127 }
1128 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 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 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 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 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 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 let when_value = self.body.when_then_expr[0].0.evaluate(batch)?;
1187 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 self.body.when_then_expr[0].1.evaluate(batch)
1201 } else if !when_value.has_true() {
1202 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 let projected_batch = batch.project(&projection)?;
1216 projected.body.expr_or_expr(&projected_batch, when_value)
1217 } else {
1218 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 Err(e) => return Some(Err(e)),
1256 Ok(n) => n,
1257 };
1258
1259 if !is_nullable {
1262 return None;
1263 }
1264
1265 if self.body.expr.is_some() {
1267 return Some(Ok(()));
1268 }
1269
1270 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 nullable_then.map(|_| true)
1299 } else if let Some(e) = &self.body.else_expr {
1300 e.nullable(input_schema)
1303 } else {
1304 Ok(true)
1307 }
1308 }
1309
1310 fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
1311 match &self.eval_method {
1312 EvalMethod::WithExpression(p) => {
1313 self.case_when_with_expr(batch, p)
1316 }
1317 EvalMethod::NoExpression(p) => {
1318 self.case_when_no_expr(batch, p)
1321 }
1322 EvalMethod::InfallibleExprOrNull => {
1323 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 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 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 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
1503fn evaluate_predicate(predicate: &Arc<dyn PhysicalExpr>) -> Result<NullableInterval> {
1505 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 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
1553fn 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
1572pub 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 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 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 #[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 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 #[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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 fn case_test_batch_nulls() -> Result<RecordBatch> {
2389 let load4: Float64Array = vec![
2390 Some(1.77), Some(1.77), Some(1.77), Some(1.78), None, Some(1.77), ]
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 let batch = case_test_batch()?;
2419 let schema = batch.schema();
2420
2421 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 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 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 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 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 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 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 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 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(¬_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 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 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, ¬_predicate, &lit(false))?,
3104 &boolean_schema,
3105 );
3106
3107 let not_not_predicate = expressions::not(Arc::clone(¬_predicate))?;
3109 assert_not_nullable(
3110 when_then_else(&predicate_is_not_null, ¬_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 fn test_case_when_literal_lookup(
3136 values: ArrayRef,
3137 lookup_map: &[(ScalarValue, ScalarValue)],
3138 else_value: Option<ScalarValue>,
3139 expected: ArrayRef,
3140 ) {
3141 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!(
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 test_case_when_literal_lookup(
3237 Arc::clone(&input_values),
3238 lookup_map,
3239 None,
3240 Arc::new(expected.clone()),
3241 );
3242
3243 let else_value = "___fallback___";
3245
3246 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_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), (5, None), (3, Some("three")),
3282 (5, None), ]);
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), (None, None), (Some(2), Some("two")),
3307 (None, None), (None, None), (Some(2), Some("two")),
3310 (Some(5), None), ]);
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), (2, Some("two")),
3343 (3, Some("three")),
3344 (3, Some("three")),
3345 (2, Some("two")),
3346 (3, Some("three")),
3347 (5, None), (5, None), (3, Some("three")),
3350 (5, None), ]);
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 (Some(f32::NAN), Some("should not use this NaN branch")),
3369 (Some(f32::INFINITY), Some("Infinity")),
3370 (Some(0.0), Some("zero")),
3371 (
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), (f32::NEG_INFINITY, None), (3.2, Some("three point two")),
3391 (-0.0, None), ]);
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), (f16::NEG_INFINITY, None), (f16::from_f32(17.4), Some("17 dot 4")),
3428 (f16::NEG_ZERO, None), ]);
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), (f32::NEG_INFINITY, None), (17.4, Some("17 dot 4")),
3459 (-0.0, None), ]);
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), (f64::NEG_INFINITY, None), (17.4, Some("17 dot 4")),
3490 (-0.0, None), ]);
3492
3493 test_lookup_eval_with_and_without_else(
3494 &lookup_map,
3495 Arc::new(input_values),
3496 expected,
3497 );
3498 }
3499
3500 #[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), (5, None), (3, Some("three")),
3521 (5, None), ]);
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]
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), (5, None), (3, Some("three")),
3569 (5, None), ]);
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), (None, None), (Some("what"), Some(22)),
3595 (None, None), (None, None), (Some("what"), Some(22)),
3598 (Some("5"), None), ]);
3600
3601 let input_values = Arc::new(input_values) as ArrayRef;
3602
3603 test_case_when_literal_lookup(
3605 Arc::clone(&input_values),
3606 &lookup_map,
3607 None,
3608 Arc::new(expected.clone()),
3609 );
3610
3611 let else_value = 101;
3613
3614 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_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 #[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 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}