Skip to content

Commit

Permalink
Keep output as scalar for scalar function if all inputs are scalar
Browse files Browse the repository at this point in the history
  • Loading branch information
viirya committed Oct 29, 2023
1 parent 9ee055a commit f4683d8
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
11 changes: 10 additions & 1 deletion datafusion/physical-expr/src/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,8 @@ where
ColumnarValue::Array(a) => Some(a.len()),
});

let is_scalar = len.is_none();

let inferred_length = len.unwrap_or(1);
let args = args
.iter()
Expand All @@ -373,7 +375,14 @@ where
.collect::<Vec<ArrayRef>>();

let result = (inner)(&args);
result.map(ColumnarValue::Array)

if is_scalar {
// If all inputs are scalar, keeps output as scalar
let result = result.and_then(|arr| ScalarValue::try_from_array(&arr, 0));
result.map(ColumnarValue::Scalar)
} else {
result.map(ColumnarValue::Array)
}
})
}

Expand Down
34 changes: 34 additions & 0 deletions datafusion/physical-expr/src/planner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -448,3 +448,37 @@ pub fn create_physical_expr(
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use arrow_array::{ArrayRef, BooleanArray, RecordBatch, StringArray};
use arrow_schema::{DataType, Field, Schema};
use datafusion_common::{DFSchema, Result};
use datafusion_expr::{col, left, Literal};

#[test]
fn test_create_physical_expr_scalar_input_output() -> Result<()> {
let expr = col("letter").eq(left("APACHE".lit(), 1i64.lit()));

let schema = Schema::new(vec![Field::new("letter", DataType::Utf8, false)]);
let df_schema = DFSchema::try_from_qualified_schema("data", &schema)?;
let p = create_physical_expr(&expr, &df_schema, &schema, &ExecutionProps::new())?;

let batch = RecordBatch::try_new(
Arc::new(schema),
vec![Arc::new(StringArray::from_iter_values(vec![
"A", "B", "C", "D",
]))],
)?;
let result = p.evaluate(&batch)?;
let result = result.into_array(4);

assert_eq!(
&result,
&(Arc::new(BooleanArray::from(vec![true, false, false, false,])) as ArrayRef)
);

Ok(())
}
}

0 comments on commit f4683d8

Please sign in to comment.