Skip to content

Apache DataFusion SQL Query Engine

ARROW-10679: [Rust] [DataFusion] Implement CASE WHEN physical expression

Andy Grove2c79178b9e0c
diff --git a/rust/datafusion/src/physical_plan/expressions.rs b/rust/datafusion/src/physical_plan/expressions.rs
index 50d554f2c4..4247cf0a75 100644
--- a/rust/datafusion/src/physical_plan/expressions.rs
+++ b/rust/datafusion/src/physical_plan/expressions.rs
@@ -26,7 +26,7 @@ use crate::error::{DataFusionError, Result};
use crate::logical_plan::Operator;
use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr};
use crate::scalar::ScalarValue;
-use arrow::array::LargeStringArray;
+use arrow::array::{self, Array, BooleanBuilder, LargeStringArray};
use arrow::compute;
use arrow::compute::kernels;
use arrow::compute::kernels::arithmetic::{add, divide, multiply, subtract};
@@ -1474,7 +1474,10 @@ impl PhysicalExpr for BinaryExpr {
}
// if both arrays or both literals - extract arrays and continue execution
- let (left, right) = (left_value.into_array(batch), right_value.into_array(batch));
+ let (left, right) = (
+ left_value.into_array(batch.num_rows()),
+ right_value.into_array(batch.num_rows()),
+ );
let result: Result<ArrayRef> = match &self.op {
Operator::Like => binary_string_array_op!(left, right, like),
@@ -1697,6 +1700,409 @@ pub fn is_not_null(arg: Arc<dyn PhysicalExpr>) -> Result<Arc<dyn PhysicalExpr>>
Ok(Arc::new(IsNotNullExpr::new(arg)))
}
+/// The CASE expression is similar to a series of nested if/else and there are two forms that
+/// can be used. The first form consists of a series of boolean "when" expressions with
+/// corresponding "then" expressions, and an optional "else" expression.
+///
+/// CASE WHEN condition THEN result
+/// [WHEN ...]
+/// [ELSE result]
+/// END
+///
+/// The second form uses a base expression and then a series of "when" clauses that match on a
+/// literal value.
+///
+/// CASE expression
+/// WHEN value THEN result
+/// [WHEN ...]
+/// [ELSE result]
+/// END
+#[derive(Debug)]
+struct CaseExpr {
+ /// Optional base expression that can be compared to literal values in the "when" expressions
+ expr: Option<Arc<dyn PhysicalExpr>>,
+ /// One or more when/then expressions
+ when_then_expr: Vec<(Arc<dyn PhysicalExpr>, Arc<dyn PhysicalExpr>)>,
+ /// Optional "else" expression
+ else_expr: Option<Arc<dyn PhysicalExpr>>,
+}
+
+impl fmt::Display for CaseExpr {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "CASE ")?;
+ if let Some(e) = &self.expr {
+ write!(f, "{} ", e)?;
+ }
+ for (w, t) in &self.when_then_expr {
+ write!(f, "WHEN {} THEN {} ", w, t)?;
+ }
+ if let Some(e) = &self.else_expr {
+ write!(f, "ELSE {} ", e)?;
+ }
+ write!(f, "END")
+ }
+}
+
+impl CaseExpr {
+ pub fn try_new(
+ expr: Option<Arc<dyn PhysicalExpr>>,
+ when_then_expr: &[(Arc<dyn PhysicalExpr>, Arc<dyn PhysicalExpr>)],
+ else_expr: Option<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Self> {
+ if when_then_expr.len() == 0 {
+ Err(DataFusionError::Execution(
+ "There must be at least one WHEN clause".to_string(),
+ ))
+ } else {
+ Ok(Self {
+ expr,
+ when_then_expr: when_then_expr.to_vec(),
+ else_expr,
+ })
+ }
+ }
+}
+
+/// Create a CASE expression
+pub fn case(
+ expr: Option<Arc<dyn PhysicalExpr>>,
+ when_thens: &[(Arc<dyn PhysicalExpr>, Arc<dyn PhysicalExpr>)],
+ else_expr: Option<Arc<dyn PhysicalExpr>>,
+) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(CaseExpr::try_new(expr, when_thens, else_expr)?))
+}
+
+macro_rules! if_then_else {
+ ($BUILDER_TYPE:ty, $ARRAY_TYPE:ty, $BOOLS:expr, $TRUE:expr, $FALSE:expr) => {{
+ let true_values = $TRUE
+ .as_ref()
+ .as_any()
+ .downcast_ref::<$ARRAY_TYPE>()
+ .expect("true_values downcast failed");
+
+ let false_values = $FALSE
+ .as_ref()
+ .as_any()
+ .downcast_ref::<$ARRAY_TYPE>()
+ .expect("false_values downcast failed");
+
+ let mut builder = <$BUILDER_TYPE>::new($BOOLS.len());
+ for i in 0..$BOOLS.len() {
+ if $BOOLS.is_null(i) {
+ builder.append_null()?;
+ } else if $BOOLS.value(i) {
+ if true_values.is_null(i) {
+ builder.append_null()?;
+ } else {
+ builder.append_value(true_values.value(i))?;
+ }
+ } else {
+ if false_values.is_null(i) {
+ builder.append_null()?;
+ } else {
+ builder.append_value(false_values.value(i))?;
+ }
+ }
+ }
+ Ok(Arc::new(builder.finish()))
+ }};
+}
+
+fn if_then_else(
+ bools: &BooleanArray,
+ true_values: ArrayRef,
+ false_values: ArrayRef,
+ data_type: &DataType,
+) -> Result<ArrayRef> {
+ match data_type {
+ DataType::UInt8 => if_then_else!(
+ array::UInt8Builder,
+ array::UInt8Array,
+ bools,
+ true_values,
+ false_values
+ ),
+ DataType::UInt16 => if_then_else!(
+ array::UInt16Builder,
+ array::UInt16Array,
+ bools,
+ true_values,
+ false_values
+ ),
+ DataType::UInt32 => if_then_else!(
+ array::UInt32Builder,
+ array::UInt32Array,
+ bools,
+ true_values,
+ false_values
+ ),
+ DataType::UInt64 => if_then_else!(
+ array::UInt64Builder,
+ array::UInt64Array,
+ bools,
+ true_values,
+ false_values
+ ),
+ DataType::Int8 => if_then_else!(
+ array::Int8Builder,
+ array::Int8Array,
+ bools,
+ true_values,
+ false_values
+ ),
+ DataType::Int16 => if_then_else!(
+ array::Int16Builder,
+ array::Int16Array,
+ bools,
+ true_values,
+ false_values
+ ),
+ DataType::Int32 => if_then_else!(
+ array::Int32Builder,
+ array::Int32Array,
+ bools,
+ true_values,
+ false_values
+ ),
+ DataType::Int64 => if_then_else!(
+ array::Int64Builder,
+ array::Int64Array,
+ bools,
+ true_values,
+ false_values
+ ),
+ DataType::Float32 => if_then_else!(
+ array::Float32Builder,
+ array::Float32Array,
+ bools,
+ true_values,
+ false_values
+ ),
+ DataType::Float64 => if_then_else!(
+ array::Float64Builder,
+ array::Float64Array,
+ bools,
+ true_values,
+ false_values
+ ),
+ DataType::Utf8 => if_then_else!(
+ array::StringBuilder,
+ array::StringArray,
+ bools,
+ true_values,
+ false_values
+ ),
+ other => Err(DataFusionError::Execution(format!(
+ "CASE does not support '{:?}'",
+ other
+ ))),
+ }
+}
+
+macro_rules! make_null_array {
+ ($TY:ty, $N:expr) => {{
+ let mut builder = <$TY>::new($N);
+ for _ in 0..$N {
+ builder.append_null()?;
+ }
+ Ok(Arc::new(builder.finish()))
+ }};
+}
+
+fn build_null_array(data_type: &DataType, num_rows: usize) -> Result<ArrayRef> {
+ match data_type {
+ DataType::UInt8 => make_null_array!(array::UInt8Builder, num_rows),
+ DataType::UInt16 => make_null_array!(array::UInt16Builder, num_rows),
+ DataType::UInt32 => make_null_array!(array::UInt32Builder, num_rows),
+ DataType::UInt64 => make_null_array!(array::UInt64Builder, num_rows),
+ DataType::Int8 => make_null_array!(array::Int8Builder, num_rows),
+ DataType::Int16 => make_null_array!(array::Int16Builder, num_rows),
+ DataType::Int32 => make_null_array!(array::Int32Builder, num_rows),
+ DataType::Int64 => make_null_array!(array::Int64Builder, num_rows),
+ DataType::Float32 => make_null_array!(array::Float32Builder, num_rows),
+ DataType::Float64 => make_null_array!(array::Float64Builder, num_rows),
+ DataType::Utf8 => make_null_array!(array::StringBuilder, num_rows),
+ other => Err(DataFusionError::Execution(format!(
+ "CASE does not support '{:?}'",
+ other
+ ))),
+ }
+}
+
+macro_rules! array_equals {
+ ($TY:ty, $L:expr, $R:expr) => {{
+ let when_value = $L
+ .as_ref()
+ .as_any()
+ .downcast_ref::<$TY>()
+ .expect("array_equals downcast failed");
+
+ let base_value = $R
+ .as_ref()
+ .as_any()
+ .downcast_ref::<$TY>()
+ .expect("array_equals downcast failed");
+
+ let mut builder = BooleanBuilder::new(when_value.len());
+ for row in 0..when_value.len() {
+ if when_value.is_valid(row) && base_value.is_valid(row) {
+ builder.append_value(when_value.value(row) == base_value.value(row))?;
+ } else {
+ builder.append_null()?;
+ }
+ }
+ Ok(builder.finish())
+ }};
+}
+
+fn array_equals(
+ data_type: &DataType,
+ when_value: ArrayRef,
+ base_value: ArrayRef,
+) -> Result<BooleanArray> {
+ match data_type {
+ DataType::UInt8 => array_equals!(array::UInt8Array, when_value, base_value),
+ DataType::UInt16 => array_equals!(array::UInt16Array, when_value, base_value),
+ DataType::UInt32 => array_equals!(array::UInt32Array, when_value, base_value),
+ DataType::UInt64 => array_equals!(array::UInt64Array, when_value, base_value),
+ DataType::Int8 => array_equals!(array::Int8Array, when_value, base_value),
+ DataType::Int16 => array_equals!(array::Int16Array, when_value, base_value),
+ DataType::Int32 => array_equals!(array::Int32Array, when_value, base_value),
+ DataType::Int64 => array_equals!(array::Int64Array, when_value, base_value),
+ DataType::Float32 => array_equals!(array::Float32Array, when_value, base_value),
+ DataType::Float64 => array_equals!(array::Float64Array, when_value, base_value),
+ DataType::Utf8 => array_equals!(array::StringArray, when_value, base_value),
+ other => Err(DataFusionError::Execution(format!(
+ "CASE does not support '{:?}'",
+ other
+ ))),
+ }
+}
+
+impl CaseExpr {
+ /// This function evaluates the form of CASE that matches an expression to fixed values.
+ ///
+ /// CASE expression
+ /// WHEN value THEN result
+ /// [WHEN ...]
+ /// [ELSE result]
+ /// END
+ fn case_when_with_expr(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ let return_type = self.when_then_expr[0].1.data_type(&batch.schema())?;
+ let expr = self.expr.as_ref().unwrap();
+ let base_value = expr.evaluate(batch)?;
+ let base_type = expr.data_type(&batch.schema())?;
+ let base_value = base_value.into_array(batch.num_rows());
+
+ // start with the else condition, or nulls
+ let mut current_value: Option<ArrayRef> = if let Some(e) = &self.else_expr {
+ Some(e.evaluate(batch)?.into_array(batch.num_rows()))
+ } else {
+ Some(build_null_array(&return_type, batch.num_rows())?)
+ };
+
+ // walk backwards through the when/then expressions
+ for i in (0..self.when_then_expr.len()).rev() {
+ let i = i as usize;
+
+ let when_value = self.when_then_expr[i].0.evaluate(batch)?;
+ let when_value = when_value.into_array(batch.num_rows());
+
+ let then_value = self.when_then_expr[i].1.evaluate(batch)?;
+ let then_value = then_value.into_array(batch.num_rows());
+
+ // build boolean array representing which rows match the "when" value
+ let when_match = array_equals(&base_type, when_value, base_value.clone())?;
+
+ current_value = Some(if_then_else(
+ &when_match,
+ then_value,
+ current_value.unwrap(),
+ &return_type,
+ )?);
+ }
+
+ Ok(ColumnarValue::Array(current_value.unwrap()))
+ }
+
+ /// This function evaluates the form of CASE where each WHEN expression is a boolean
+ /// expression.
+ ///
+ /// CASE WHEN condition THEN result
+ /// [WHEN ...]
+ /// [ELSE result]
+ /// END
+ fn case_when_no_expr(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ let return_type = self.when_then_expr[0].1.data_type(&batch.schema())?;
+
+ // start with the else condition, or nulls
+ let mut current_value: Option<ArrayRef> = if let Some(e) = &self.else_expr {
+ Some(e.evaluate(batch)?.into_array(batch.num_rows()))
+ } else {
+ Some(build_null_array(&return_type, batch.num_rows())?)
+ };
+
+ // walk backwards through the when/then expressions
+ for i in (0..self.when_then_expr.len()).rev() {
+ let i = i as usize;
+
+ let when_value = self.when_then_expr[i].0.evaluate(batch)?;
+ let when_value = when_value.into_array(batch.num_rows());
+ let when_value = when_value
+ .as_ref()
+ .as_any()
+ .downcast_ref::<BooleanArray>()
+ .expect("WHEN expression did not return a BooleanArray");
+
+ let then_value = self.when_then_expr[i].1.evaluate(batch)?;
+ let then_value = then_value.into_array(batch.num_rows());
+
+ current_value = Some(if_then_else(
+ &when_value,
+ then_value,
+ current_value.unwrap(),
+ &return_type,
+ )?);
+ }
+
+ Ok(ColumnarValue::Array(current_value.unwrap()))
+ }
+}
+
+impl PhysicalExpr for CaseExpr {
+ fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
+ self.when_then_expr[0].1.data_type(input_schema)
+ }
+
+ fn nullable(&self, input_schema: &Schema) -> Result<bool> {
+ // this expression is nullable if any of the input expressions are nullable
+ let then_nullable = self
+ .when_then_expr
+ .iter()
+ .map(|(_, t)| t.nullable(input_schema))
+ .collect::<Result<Vec<_>>>()?;
+ if then_nullable.contains(&true) {
+ Ok(true)
+ } else if let Some(e) = &self.else_expr {
+ e.nullable(input_schema)
+ } else {
+ Ok(false)
+ }
+ }
+
+ fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ if self.expr.is_some() {
+ // this use case evaluates "expr" and then compares the values with the "when"
+ // values
+ self.case_when_with_expr(batch)
+ } else {
+ // The "when" conditions all evaluate to boolean in this use case and can be
+ // arbitrary expressions
+ self.case_when_no_expr(batch)
+ }
+ }
+}
+
/// CAST expression casts an expression to a specific data type
#[derive(Debug)]
pub struct CastExpr {
@@ -1875,7 +2281,7 @@ mod tests {
// expression: "a < b"
let lt = binary_simple(col("a"), Operator::Lt, col("b"));
- let result = lt.evaluate(&batch)?.into_array(&batch);
+ let result = lt.evaluate(&batch)?.into_array(batch.num_rows());
assert_eq!(result.len(), 5);
let expected = vec![false, false, true, true, true];
@@ -1911,7 +2317,7 @@ mod tests {
);
assert_eq!("a < b OR a = b", format!("{}", expr));
- let result = expr.evaluate(&batch)?.into_array(&batch);
+ let result = expr.evaluate(&batch)?.into_array(batch.num_rows());
assert_eq!(result.len(), 5);
let expected = vec![true, true, false, true, false];
@@ -1937,7 +2343,7 @@ mod tests {
let literal_expr = lit(ScalarValue::from(42i32));
assert_eq!("42", format!("{}", literal_expr));
- let literal_array = literal_expr.evaluate(&batch)?.into_array(&batch);
+ let literal_array = literal_expr.evaluate(&batch)?.into_array(batch.num_rows());
let literal_array = literal_array.as_any().downcast_ref::<Int32Array>().unwrap();
// note that the contents of the literal array are unrelated to the batch contents except for the length of the array
@@ -1976,7 +2382,7 @@ mod tests {
assert_eq!(expression.data_type(&schema)?, $C_TYPE);
// compute
- let result = expression.evaluate(&batch)?.into_array(&batch);
+ let result = expression.evaluate(&batch)?.into_array(batch.num_rows());
// verify that the array's data_type is correct
assert_eq!(*result.data_type(), $C_TYPE);
@@ -2127,7 +2533,7 @@ mod tests {
assert_eq!(expression.data_type(&schema)?, DataType::Boolean);
// evaluate and verify the result type matched
- let result = expression.evaluate(&batch)?.into_array(&batch);
+ let result = expression.evaluate(&batch)?.into_array(batch.num_rows());
assert_eq!(result.data_type(), &DataType::Boolean);
// verify that the result itself is correct
@@ -2141,7 +2547,7 @@ mod tests {
assert_eq!(expression.data_type(&schema)?, DataType::Boolean);
// evaluate and verify the result type matched
- let result = expression.evaluate(&batch)?.into_array(&batch);
+ let result = expression.evaluate(&batch)?.into_array(batch.num_rows());
assert_eq!(result.data_type(), &DataType::Boolean);
// verify that the result itself is correct
@@ -2197,7 +2603,7 @@ mod tests {
assert_eq!(expression.data_type(&schema)?, $TYPE);
// compute
- let result = expression.evaluate(&batch)?.into_array(&batch);
+ let result = expression.evaluate(&batch)?.into_array(batch.num_rows());
// verify that the array's data_type is correct
assert_eq!(*result.data_type(), $TYPE);
@@ -2754,7 +3160,7 @@ mod tests {
let values = expr
.iter()
.map(|e| e.evaluate(batch))
- .map(|r| r.map(|v| v.into_array(batch)))
+ .map(|r| r.map(|v| v.into_array(batch.num_rows())))
.collect::<Result<Vec<_>>>()?;
accum.update_batch(&values)?;
accum.evaluate()
@@ -2852,7 +3258,7 @@ mod tests {
) -> Result<()> {
let arithmetic_op = binary_simple(col("a"), op, col("b"));
let batch = RecordBatch::try_new(schema, data)?;
- let result = arithmetic_op.evaluate(&batch)?.into_array(&batch);
+ let result = arithmetic_op.evaluate(&batch)?.into_array(batch.num_rows());
assert_array_eq::<T>(expected, result);
@@ -2887,7 +3293,7 @@ mod tests {
let batch =
RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(input)])?;
- let result = expr.evaluate(&batch)?.into_array(&batch);
+ let result = expr.evaluate(&batch)?.into_array(batch.num_rows());
let result = result
.as_any()
.downcast_ref::<BooleanArray>()
@@ -2916,7 +3322,7 @@ mod tests {
// expression: "a is null"
let expr = is_null(col("a")).unwrap();
- let result = expr.evaluate(&batch)?.into_array(&batch);
+ let result = expr.evaluate(&batch)?.into_array(batch.num_rows());
let result = result
.as_any()
.downcast_ref::<BooleanArray>()
@@ -2937,7 +3343,7 @@ mod tests {
// expression: "a is not null"
let expr = is_not_null(col("a")).unwrap();
- let result = expr.evaluate(&batch)?.into_array(&batch);
+ let result = expr.evaluate(&batch)?.into_array(batch.num_rows());
let result = result
.as_any()
.downcast_ref::<BooleanArray>()
@@ -2949,4 +3355,133 @@ mod tests {
Ok(())
}
+
+ #[test]
+ fn case_with_expr() -> Result<()> {
+ let batch = case_test_batch()?;
+
+ // CASE a WHEN 'foo' THEN 123 WHEN 'bar' THEN 456 END
+ let when1 = lit(ScalarValue::Utf8(Some("foo".to_string())));
+ let then1 = lit(ScalarValue::Int32(Some(123)));
+ let when2 = lit(ScalarValue::Utf8(Some("bar".to_string())));
+ let then2 = lit(ScalarValue::Int32(Some(456)));
+
+ let expr = case(Some(col("a")), &[(when1, then1), (when2, then2)], None)?;
+ let result = expr.evaluate(&batch)?.into_array(batch.num_rows());
+ let result = result
+ .as_any()
+ .downcast_ref::<Int32Array>()
+ .expect("failed to downcast to Int32Array");
+
+ let expected = &Int32Array::from(vec![Some(123), None, None, Some(456)]);
+
+ assert_eq!(expected, result);
+
+ Ok(())
+ }
+
+ #[test]
+ fn case_with_expr_else() -> Result<()> {
+ let batch = case_test_batch()?;
+
+ // CASE a WHEN 'foo' THEN 123 WHEN 'bar' THEN 456 ELSE 999 END
+ let when1 = lit(ScalarValue::Utf8(Some("foo".to_string())));
+ let then1 = lit(ScalarValue::Int32(Some(123)));
+ let when2 = lit(ScalarValue::Utf8(Some("bar".to_string())));
+ let then2 = lit(ScalarValue::Int32(Some(456)));
+ let else_value = lit(ScalarValue::Int32(Some(999)));
+
+ let expr = case(
+ Some(col("a")),
+ &[(when1, then1), (when2, then2)],
+ Some(else_value),
+ )?;
+ let result = expr.evaluate(&batch)?.into_array(batch.num_rows());
+ let result = result
+ .as_any()
+ .downcast_ref::<Int32Array>()
+ .expect("failed to downcast to Int32Array");
+
+ let expected = &Int32Array::from(vec![Some(123), Some(999), None, Some(456)]);
+
+ assert_eq!(expected, result);
+
+ Ok(())
+ }
+
+ #[test]
+ fn case_without_expr() -> Result<()> {
+ let batch = case_test_batch()?;
+
+ // CASE WHEN a = 'foo' THEN 123 WHEN a = 'bar' THEN 456 END
+ let when1 = binary(
+ col("a"),
+ Operator::Eq,
+ lit(ScalarValue::Utf8(Some("foo".to_string()))),
+ &batch.schema(),
+ )?;
+ let then1 = lit(ScalarValue::Int32(Some(123)));
+ let when2 = binary(
+ col("a"),
+ Operator::Eq,
+ lit(ScalarValue::Utf8(Some("bar".to_string()))),
+ &batch.schema(),
+ )?;
+ let then2 = lit(ScalarValue::Int32(Some(456)));
+
+ let expr = case(None, &[(when1, then1), (when2, then2)], None)?;
+ let result = expr.evaluate(&batch)?.into_array(batch.num_rows());
+ let result = result
+ .as_any()
+ .downcast_ref::<Int32Array>()
+ .expect("failed to downcast to Int32Array");
+
+ let expected = &Int32Array::from(vec![Some(123), None, None, Some(456)]);
+
+ assert_eq!(expected, result);
+
+ Ok(())
+ }
+
+ #[test]
+ fn case_without_expr_else() -> Result<()> {
+ let batch = case_test_batch()?;
+
+ // CASE WHEN a = 'foo' THEN 123 WHEN a = 'bar' THEN 456 ELSE 999 END
+ let when1 = binary(
+ col("a"),
+ Operator::Eq,
+ lit(ScalarValue::Utf8(Some("foo".to_string()))),
+ &batch.schema(),
+ )?;
+ let then1 = lit(ScalarValue::Int32(Some(123)));
+ let when2 = binary(
+ col("a"),
+ Operator::Eq,
+ lit(ScalarValue::Utf8(Some("bar".to_string()))),
+ &batch.schema(),
+ )?;
+ let then2 = lit(ScalarValue::Int32(Some(456)));
+ let else_value = lit(ScalarValue::Int32(Some(999)));
+
+ let expr = case(None, &[(when1, then1), (when2, then2)], Some(else_value))?;
+ let result = expr.evaluate(&batch)?.into_array(batch.num_rows());
+ let result = result
+ .as_any()
+ .downcast_ref::<Int32Array>()
+ .expect("failed to downcast to Int32Array");
+
+ let expected = &Int32Array::from(vec![Some(123), Some(999), None, Some(456)]);
+
+ 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.clone()), vec![Arc::new(a)])?;
+ Ok(batch)
+ }
}
diff --git a/rust/datafusion/src/physical_plan/filter.rs b/rust/datafusion/src/physical_plan/filter.rs
index 7c3da888c0..12ba176be5 100644
--- a/rust/datafusion/src/physical_plan/filter.rs
+++ b/rust/datafusion/src/physical_plan/filter.rs
@@ -128,7 +128,7 @@ fn batch_filter(
) -> ArrowResult<RecordBatch> {
predicate
.evaluate(&batch)
- .map(|v| v.into_array(batch))
+ .map(|v| v.into_array(batch.num_rows()))
.map_err(DataFusionError::into_arrow_external_error)
.and_then(|array| {
array
diff --git a/rust/datafusion/src/physical_plan/functions.rs b/rust/datafusion/src/physical_plan/functions.rs
index 12402ec90b..b63c05d64d 100644
--- a/rust/datafusion/src/physical_plan/functions.rs
+++ b/rust/datafusion/src/physical_plan/functions.rs
@@ -348,7 +348,7 @@ impl PhysicalExpr for ScalarFunctionExpr {
let inputs = self
.args
.iter()
- .map(|e| e.evaluate(batch).map(|v| v.into_array(batch)))
+ .map(|e| e.evaluate(batch).map(|v| v.into_array(batch.num_rows())))
.collect::<Result<Vec<_>>>()?;
// evaluate the function
@@ -382,7 +382,7 @@ mod tests {
// evaluate works
let batch = RecordBatch::try_new(Arc::new(schema.clone()), columns)?;
- let result = expr.evaluate(&batch)?.into_array(&batch);
+ let result = expr.evaluate(&batch)?.into_array(batch.num_rows());
// downcast works
let result = result.as_any().downcast_ref::<Float64Array>().unwrap();
@@ -423,7 +423,7 @@ mod tests {
// evaluate works
let batch = RecordBatch::try_new(Arc::new(schema.clone()), columns)?;
- let result = expr.evaluate(&batch)?.into_array(&batch);
+ let result = expr.evaluate(&batch)?.into_array(batch.num_rows());
// downcast works
let result = result.as_any().downcast_ref::<StringArray>().unwrap();
@@ -476,7 +476,7 @@ mod tests {
// evaluate works
let batch = RecordBatch::try_new(Arc::new(schema.clone()), columns)?;
- let result = expr.evaluate(&batch)?.into_array(&batch);
+ let result = expr.evaluate(&batch)?.into_array(batch.num_rows());
// downcast works
let result = result
diff --git a/rust/datafusion/src/physical_plan/hash_aggregate.rs b/rust/datafusion/src/physical_plan/hash_aggregate.rs
index 57a4a01f0f..4dc1f903ff 100644
--- a/rust/datafusion/src/physical_plan/hash_aggregate.rs
+++ b/rust/datafusion/src/physical_plan/hash_aggregate.rs
@@ -433,7 +433,7 @@ fn evaluate(
) -> Result<Vec<ArrayRef>> {
expr.iter()
.map(|expr| expr.evaluate(&batch))
- .map(|r| r.map(|v| v.into_array(batch)))
+ .map(|r| r.map(|v| v.into_array(batch.num_rows())))
.collect::<Result<Vec<_>>>()
}
@@ -562,7 +562,7 @@ fn aggregate_batch(
let values = &expr
.iter()
.map(|e| e.evaluate(batch))
- .map(|r| r.map(|v| v.into_array(batch)))
+ .map(|r| r.map(|v| v.into_array(batch.num_rows())))
.collect::<Result<Vec<_>>>()?;
// 1.3
diff --git a/rust/datafusion/src/physical_plan/hash_join.rs b/rust/datafusion/src/physical_plan/hash_join.rs
index 4933e3370b..8f86df2c68 100644
--- a/rust/datafusion/src/physical_plan/hash_join.rs
+++ b/rust/datafusion/src/physical_plan/hash_join.rs
@@ -202,7 +202,7 @@ fn update_hash(
// evaluate the keys
let keys_values = on
.iter()
- .map(|name| Ok(col(name).evaluate(batch)?.into_array(batch)))
+ .map(|name| Ok(col(name).evaluate(batch)?.into_array(batch.num_rows())))
.collect::<Result<Vec<_>>>()?;
let mut key = Vec::with_capacity(keys_values.len());
diff --git a/rust/datafusion/src/physical_plan/mod.rs b/rust/datafusion/src/physical_plan/mod.rs
index f1d0a344b9..8a5dfd9bbd 100644
--- a/rust/datafusion/src/physical_plan/mod.rs
+++ b/rust/datafusion/src/physical_plan/mod.rs
@@ -126,10 +126,10 @@ impl ColumnarValue {
}
}
- fn into_array(self, batch: &RecordBatch) -> ArrayRef {
+ fn into_array(self, num_rows: usize) -> ArrayRef {
match self {
ColumnarValue::Array(array) => array,
- ColumnarValue::Scalar(scalar) => scalar.to_array_of_size(batch.num_rows()),
+ ColumnarValue::Scalar(scalar) => scalar.to_array_of_size(num_rows),
}
}
}
diff --git a/rust/datafusion/src/physical_plan/projection.rs b/rust/datafusion/src/physical_plan/projection.rs
index a3329041ae..2ef28c81f7 100644
--- a/rust/datafusion/src/physical_plan/projection.rs
+++ b/rust/datafusion/src/physical_plan/projection.rs
@@ -130,7 +130,7 @@ fn batch_project(
expressions
.iter()
.map(|expr| expr.evaluate(&batch))
- .map(|r| r.map(|v| v.into_array(batch)))
+ .map(|r| r.map(|v| v.into_array(batch.num_rows())))
.collect::<Result<Vec<_>>>()
.map_or_else(
|e| Err(DataFusionError::into_arrow_external_error(e)),