Apache DataFusion SQL Query Engine
Fix case evaluation with NULLs (#2118)
Andrew Lamb9e3bec811549
diff --git a/datafusion/physical-expr/src/expressions/case.rs b/datafusion/physical-expr/src/expressions/case.rsindex fa37c826c3..02f1d3c384 100644--- a/datafusion/physical-expr/src/expressions/case.rs+++ b/datafusion/physical-expr/src/expressions/case.rs@@ -407,6 +407,7 @@ mod tests {use crate::expressions::lit;use crate::expressions::{binary, cast};use arrow::array::StringArray;+ use arrow::buffer::Buffer;use arrow::datatypes::DataType::Float64;use arrow::datatypes::*;use datafusion_common::ScalarValue;@@ -647,10 +648,94 @@ mod tests {Ok(())}++ #[test]+ fn case_with_matches_and_nulls() -> Result<()> {+ let batch = case_test_batch_nulls()?;+ let schema = batch.schema();++ // SELECT CASE WHEN load4 = 1.77 THEN load4 END+ let when = binary(+ col("load4", &schema)?,+ Operator::Eq,+ lit(ScalarValue::Float64(Some(1.77))),+ &batch.schema(),+ )?;+ let then = col("load4", &schema)?;++ let expr = case(None, &[(when, then)], None)?;+ let result = expr.evaluate(&batch)?.into_array(batch.num_rows());+ let result = result+ .as_any()+ .downcast_ref::<Float64Array>()+ .expect("failed to downcast to Float64Array");++ let expected =+ &Float64Array::from(vec![Some(1.77), None, None, None, None, Some(1.77)]);++ assert_eq!(expected, result);++ Ok(())+ }++ #[test]+ fn case_expr_matches_and_nulls() -> Result<()> {+ let batch = case_test_batch_nulls()?;+ let schema = batch.schema();++ // SELECT CASE load4 WHEN 1.77 THEN load4 END+ let expr = col("load4", &schema)?;+ let when = lit(ScalarValue::Float64(Some(1.77)));+ let then = col("load4", &schema)?;++ let expr = case(Some(expr), &[(when, then)], None)?;+ let result = expr.evaluate(&batch)?.into_array(batch.num_rows());+ let result = result+ .as_any()+ .downcast_ref::<Float64Array>()+ .expect("failed to downcast to Float64Array");++ let expected =+ &Float64Array::from(vec![Some(1.77), None, None, None, None, Some(1.77)]);++ assert_eq!(expected, result);++ Ok(())+ }+fn case_test_batch() -> Result<RecordBatch> {let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);let a = StringArray::from(vec![Some("foo"), Some("baz"), None, Some("bar")]);let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)])?;Ok(batch)}++ // Construct an array that has several NULL values whose+ // underlying buffer actually matches the where expr predicate+ fn case_test_batch_nulls() -> Result<RecordBatch> {+ let load4: Float64Array = vec![+ Some(1.77), // 1.77+ Some(1.77), // null <-- same value, but will be set to null+ Some(1.77), // null <-- same value, but will be set to null+ Some(1.78), // 1.78+ None, // null+ Some(1.77), // 1.77+ ]+ .into_iter()+ .collect();++ //let valid_array = vec![true, false, false, true, false, tru+ let null_buffer = Buffer::from_slice_ref(&[0b00101001u8]);+ let load4 = ArrayDataBuilder::new(load4.data_type().clone())+ .len(load4.len())+ .null_bit_buffer(null_buffer)+ .buffers(load4.data().buffers().to_vec())+ .build()+ .unwrap();+ let load4: Float64Array = load4.into();++ let batch =+ RecordBatch::try_from_iter(vec![("load4", Arc::new(load4) as ArrayRef)])?;+ Ok(batch)+ }}diff --git a/datafusion/physical-expr/src/physical_expr.rs b/datafusion/physical-expr/src/physical_expr.rsindex 79c2269f8a..1f1da388d9 100644--- a/datafusion/physical-expr/src/physical_expr.rs+++ b/datafusion/physical-expr/src/physical_expr.rs@@ -28,7 +28,7 @@ use std::fmt::{Debug, Display};use arrow::array::{make_array, Array, ArrayRef, BooleanArray, MutableArrayData, UInt64Array,};-use arrow::compute::{take, SlicesIterator};+use arrow::compute::{and_kleene, is_not_null, take, SlicesIterator};use std::any::Any;use std::sync::Arc;@@ -87,6 +87,10 @@ pub trait PhysicalExpr: Send + Sync + Display + Debug {fn scatter(mask: &BooleanArray, truthy: &dyn Array) -> Result<ArrayRef> {let truthy = truthy.data();+ // update the mask so that any null values become false+ // (SlicesIterator doesn't respect nulls)+ let mask = and_kleene(mask, &is_not_null(mask)?)?;+let mut mutable = MutableArrayData::new(vec![&*truthy], true, mask.len());// the SlicesIterator slices only the true values. So the gaps left by this iterator we need to@@ -97,7 +101,7 @@ fn scatter(mask: &BooleanArray, truthy: &dyn Array) -> Result<ArrayRef> {// keep track of current position we have in truthy arraylet mut true_pos = 0;- SlicesIterator::new(mask).for_each(|(start, end)| {+ SlicesIterator::new(&mask).for_each(|(start, end)| {// the gap needs to be filled with nullsif start > filled {mutable.extend_nulls(start - filled);@@ -109,8 +113,8 @@ fn scatter(mask: &BooleanArray, truthy: &dyn Array) -> Result<ArrayRef> {filled = end;});// the remaining part is falsy- if filled < truthy.len() {- mutable.extend_nulls(truthy.len() - filled);+ if filled < mask.len() {+ mutable.extend_nulls(mask.len() - filled);}let data = mutable.freeze();@@ -138,6 +142,37 @@ mod tests {Ok(())}+ #[test]+ fn scatter_int_end_with_false() -> Result<()> {+ let truthy = Arc::new(Int32Array::from(vec![1, 10, 11, 100]));+ let mask = BooleanArray::from(vec![true, false, true, false, false, false]);++ // output should be same length as mask+ let expected =+ Int32Array::from_iter(vec![Some(1), None, Some(10), None, None, None]);+ let result = scatter(&mask, truthy.as_ref())?;+ let result = result.as_any().downcast_ref::<Int32Array>().unwrap();++ assert_eq!(&expected, result);+ Ok(())+ }++ #[test]+ fn scatter_with_null_mask() -> Result<()> {+ let truthy = Arc::new(Int32Array::from(vec![1, 10, 11]));+ let mask: BooleanArray = vec![Some(false), None, Some(true), Some(true), None]+ .into_iter()+ .collect();++ // output should treat nulls as though they are false+ let expected = Int32Array::from_iter(vec![None, None, Some(1), Some(10), None]);+ let result = scatter(&mask, truthy.as_ref())?;+ let result = result.as_any().downcast_ref::<Int32Array>().unwrap();++ assert_eq!(&expected, result);+ Ok(())+ }+#[test]fn scatter_boolean() -> Result<()> {let truthy = Arc::new(BooleanArray::from(vec![false, false, false, true]));