Skip to content

Apache DataFusion SQL Query Engine

ARROW-10330: [Rust][DataFusion] Implement NULLIF() SQL function

Evan Chan4d5f06b23329
diff --git a/rust/datafusion/README.md b/rust/datafusion/README.md
index 69517d6c1f..78b0a3172b 100644
--- a/rust/datafusion/README.md
+++ b/rust/datafusion/README.md
@@ -58,6 +58,8 @@ DataFusion includes a simple command-line interactive SQL utility. See the [CLI
- String functions
- [x] Length
- [x] Concatenate
+- Miscellaneous/Boolean functions
+ - [x] nullif
- Common date/time functions
- [ ] Basic date functions
- [ ] Basic time functions
diff --git a/rust/datafusion/src/physical_plan/expressions.rs b/rust/datafusion/src/physical_plan/expressions.rs
index 4456b67771..4c45900cf5 100644
--- a/rust/datafusion/src/physical_plan/expressions.rs
+++ b/rust/datafusion/src/physical_plan/expressions.rs
@@ -30,7 +30,7 @@ use arrow::array::{self, Array, BooleanBuilder, LargeStringArray};
use arrow::compute;
use arrow::compute::kernels;
use arrow::compute::kernels::arithmetic::{add, divide, multiply, subtract};
-use arrow::compute::kernels::boolean::{and, or};
+use arrow::compute::kernels::boolean::{and, nullif, or};
use arrow::compute::kernels::comparison::{eq, gt, gt_eq, lt, lt_eq, neq};
use arrow::compute::kernels::comparison::{
eq_scalar, gt_eq_scalar, gt_scalar, lt_eq_scalar, lt_scalar, neq_scalar,
@@ -1534,6 +1534,80 @@ pub fn binary(
Ok(Arc::new(BinaryExpr::new(l, op, r)))
}
+/// Invoke a compute kernel on a primitive array and a Boolean Array
+macro_rules! compute_bool_array_op {
+ ($LEFT:expr, $RIGHT:expr, $OP:ident, $DT:ident) => {{
+ let ll = $LEFT
+ .as_any()
+ .downcast_ref::<$DT>()
+ .expect("compute_op failed to downcast array");
+ let rr = $RIGHT
+ .as_any()
+ .downcast_ref::<BooleanArray>()
+ .expect("compute_op failed to downcast array");
+ Ok(Arc::new($OP(&ll, &rr)?))
+ }};
+}
+
+/// Binary op between primitive and boolean arrays
+macro_rules! primitive_bool_array_op {
+ ($LEFT:expr, $RIGHT:expr, $OP:ident) => {{
+ match $LEFT.data_type() {
+ DataType::Int8 => compute_bool_array_op!($LEFT, $RIGHT, $OP, Int8Array),
+ DataType::Int16 => compute_bool_array_op!($LEFT, $RIGHT, $OP, Int16Array),
+ DataType::Int32 => compute_bool_array_op!($LEFT, $RIGHT, $OP, Int32Array),
+ DataType::Int64 => compute_bool_array_op!($LEFT, $RIGHT, $OP, Int64Array),
+ DataType::UInt8 => compute_bool_array_op!($LEFT, $RIGHT, $OP, UInt8Array),
+ DataType::UInt16 => compute_bool_array_op!($LEFT, $RIGHT, $OP, UInt16Array),
+ DataType::UInt32 => compute_bool_array_op!($LEFT, $RIGHT, $OP, UInt32Array),
+ DataType::UInt64 => compute_bool_array_op!($LEFT, $RIGHT, $OP, UInt64Array),
+ DataType::Float32 => compute_bool_array_op!($LEFT, $RIGHT, $OP, Float32Array),
+ DataType::Float64 => compute_bool_array_op!($LEFT, $RIGHT, $OP, Float64Array),
+ other => Err(DataFusionError::Internal(format!(
+ "Unsupported data type {:?} for NULLIF/primitive/boolean operator",
+ other
+ ))),
+ }
+ }};
+}
+
+///
+/// Implements NULLIF(expr1, expr2)
+/// Args: 0 - left expr is any array
+/// 1 - if the left is equal to this expr2, then the result is NULL, otherwise left value is passed.
+///
+pub fn nullif_func(args: &[ArrayRef]) -> Result<ArrayRef> {
+ if args.len() != 2 {
+ return Err(DataFusionError::Internal(format!(
+ "{:?} args were supplied but NULLIF takes exactly two args",
+ args.len(),
+ )));
+ }
+
+ // Get args0 == args1 evaluated and produce a boolean array
+ let cond_array = binary_array_op!(args[0], args[1], eq)?;
+
+ // Now, invoke nullif on the result
+ primitive_bool_array_op!(args[0], *cond_array, nullif)
+}
+
+/// Currently supported types by the nullif function.
+/// The order of these types correspond to the order on which coercion applies
+/// This should thus be from least informative to most informative
+pub static SUPPORTED_NULLIF_TYPES: &'static [DataType] = &[
+ DataType::Boolean,
+ DataType::UInt8,
+ DataType::UInt16,
+ DataType::UInt32,
+ DataType::UInt64,
+ DataType::Int8,
+ DataType::Int16,
+ DataType::Int32,
+ DataType::Int64,
+ DataType::Float32,
+ DataType::Float64,
+];
+
/// Not expression
#[derive(Debug)]
pub struct NotExpr {
@@ -3150,6 +3224,70 @@ mod tests {
)
}
+ #[test]
+ fn nullif_int32() -> Result<()> {
+ let a = Int32Array::from(vec![
+ Some(1),
+ Some(2),
+ None,
+ None,
+ Some(3),
+ None,
+ None,
+ Some(4),
+ Some(5),
+ ]);
+ let a = Arc::new(a);
+ let a_len = a.len();
+
+ let lit_array = Arc::new(Int32Array::from(vec![2; a.len()]));
+
+ let result = nullif_func(&[a.clone(), lit_array])?;
+
+ assert_eq!(result.len(), a_len);
+
+ let expected = Int32Array::from(vec![
+ Some(1),
+ None,
+ None,
+ None,
+ Some(3),
+ None,
+ None,
+ Some(4),
+ Some(5),
+ ]);
+ assert_array_eq::<Int32Type>(expected, result);
+ Ok(())
+ }
+
+ #[test]
+ // Ensure that arrays with no nulls can also invoke NULLIF() correctly
+ fn nullif_int32_nonulls() -> Result<()> {
+ let a = Int32Array::from(vec![1, 3, 10, 7, 8, 1, 2, 4, 5]);
+ let a = Arc::new(a);
+ let a_len = a.len();
+
+ let lit_array = Arc::new(Int32Array::from(vec![1; a.len()]));
+
+ let result = nullif_func(&[a.clone(), lit_array])?;
+ assert_eq!(result.len(), a_len);
+
+ let expected = Int32Array::from(vec![
+ None,
+ Some(3),
+ Some(10),
+ Some(7),
+ Some(8),
+ None,
+ Some(2),
+ Some(4),
+ Some(5),
+ ]);
+ assert_array_eq::<Int32Type>(expected, result);
+ Ok(())
+ }
+
fn aggregate(
batch: &RecordBatch,
agg: Arc<dyn AggregateExpr>,
@@ -3274,7 +3412,11 @@ mod tests {
.expect("Actual array should unwrap to type of expected array");
for i in 0..expected.len() {
- assert_eq!(expected.value(i), actual.value(i));
+ if expected.is_null(i) {
+ assert!(actual.is_null(i));
+ } else {
+ assert_eq!(expected.value(i), actual.value(i));
+ }
}
}
diff --git a/rust/datafusion/src/physical_plan/functions.rs b/rust/datafusion/src/physical_plan/functions.rs
index 6bcff8a6bf..b954f479d9 100644
--- a/rust/datafusion/src/physical_plan/functions.rs
+++ b/rust/datafusion/src/physical_plan/functions.rs
@@ -36,6 +36,7 @@ use super::{
use crate::error::{DataFusionError, Result};
use crate::physical_plan::array_expressions;
use crate::physical_plan::datetime_expressions;
+use crate::physical_plan::expressions::{nullif_func, SUPPORTED_NULLIF_TYPES};
use crate::physical_plan::math_expressions;
use crate::physical_plan::string_expressions;
use arrow::{
@@ -121,6 +122,8 @@ pub enum BuiltinScalarFunction {
ToTimestamp,
/// construct an array from columns
Array,
+ /// SQL NULLIF()
+ NullIf,
}
impl fmt::Display for BuiltinScalarFunction {
@@ -155,6 +158,7 @@ impl FromStr for BuiltinScalarFunction {
"concat" => BuiltinScalarFunction::Concat,
"to_timestamp" => BuiltinScalarFunction::ToTimestamp,
"array" => BuiltinScalarFunction::Array,
+ "nullif" => BuiltinScalarFunction::NullIf,
_ => {
return Err(DataFusionError::Plan(format!(
"There is no built-in function named {}",
@@ -185,9 +189,8 @@ pub fn return_type(
)));
}
- // the return type of the built in function. Eventually there
- // will be built-in functions whose return type depends on the
- // incoming type.
+ // the return type of the built in function.
+ // Some built-in functions' return type depends on the incoming type.
match fun {
BuiltinScalarFunction::Length => Ok(match arg_types[0] {
DataType::LargeUtf8 => DataType::Int64,
@@ -207,6 +210,11 @@ pub fn return_type(
Box::new(Field::new("item", arg_types[0].clone(), true)),
arg_types.len() as i32,
)),
+ BuiltinScalarFunction::NullIf => {
+ // NULLIF has two args and they might get coerced, get a preview of this
+ let coerced_types = data_types(arg_types, &signature(fun));
+ coerced_types.map(|typs| typs[0].clone())
+ }
_ => Ok(DataType::Float64),
}
}
@@ -236,6 +244,7 @@ pub fn create_physical_expr(
BuiltinScalarFunction::Trunc => math_expressions::trunc,
BuiltinScalarFunction::Abs => math_expressions::abs,
BuiltinScalarFunction::Signum => math_expressions::signum,
+ BuiltinScalarFunction::NullIf => nullif_func,
BuiltinScalarFunction::Length => |args| Ok(length(args[0].as_ref())?),
BuiltinScalarFunction::Concat => {
|args| Ok(Arc::new(string_expressions::concatenate(args)?))
@@ -275,6 +284,9 @@ fn signature(fun: &BuiltinScalarFunction) -> Signature {
BuiltinScalarFunction::Array => {
Signature::Variadic(array_expressions::SUPPORTED_ARRAY_TYPES.to_vec())
}
+ BuiltinScalarFunction::NullIf => {
+ Signature::Uniform(2, SUPPORTED_NULLIF_TYPES.to_vec())
+ }
// math expressions expect 1 argument of type f64 or f32
// priority is given to f64 because e.g. `sqrt(1i32)` is in IR (real numbers) and thus we
// return the best approximation for it (in f64).
diff --git a/rust/datafusion/src/sql/planner.rs b/rust/datafusion/src/sql/planner.rs
index 700260ca70..3bcee30a8a 100644
--- a/rust/datafusion/src/sql/planner.rs
+++ b/rust/datafusion/src/sql/planner.rs
@@ -974,6 +974,16 @@ mod tests {
quick_test(sql, expected);
}
+ #[test]
+ fn select_where_nullif_division() {
+ let sql = "SELECT c3/(c4+c5) \
+ FROM aggregate_test_100 WHERE c3/nullif(c4+c5, 0) > 0.1";
+ let expected = "Projection: #c3 Divide #c4 Plus #c5\
+ \n Filter: #c3 Divide nullif(#c4 Plus #c5, Int64(0)) Gt Float64(0.1)\
+ \n TableScan: aggregate_test_100 projection=None";
+ quick_test(sql, expected);
+ }
+
#[test]
fn select_order_by() {
let sql = "SELECT id FROM person ORDER BY id";
diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rs
index e236f692df..7327487d3b 100644
--- a/rust/datafusion/tests/sql.rs
+++ b/rust/datafusion/tests/sql.rs
@@ -536,6 +536,29 @@ async fn csv_query_avg_multi_batch() -> Result<()> {
Ok(())
}
+#[tokio::test]
+async fn csv_query_nullif_divide_by_0() -> Result<()> {
+ let mut ctx = ExecutionContext::new();
+ register_aggregate_csv(&mut ctx)?;
+ let sql = "SELECT c8/nullif(c7, 0) FROM aggregate_test_100";
+ let actual = execute(&mut ctx, sql).await;
+ let actual = &actual[80..90]; // We just want to compare rows 80-89
+ let expected = vec![
+ vec!["258"],
+ vec!["664"],
+ vec!["NULL"],
+ vec!["22"],
+ vec!["164"],
+ vec!["448"],
+ vec!["365"],
+ vec!["1640"],
+ vec!["671"],
+ vec!["203"],
+ ];
+ assert_eq!(expected, actual);
+ Ok(())
+}
+
#[tokio::test]
async fn csv_query_count() -> Result<()> {
let mut ctx = ExecutionContext::new();