Apache DataFusion SQL Query Engine
ARROW-10016: [Rust] Implement is null / is not null kernels
Jörn Horstmanne68e721ba03d
diff --git a/rust/datafusion/src/logical_plan/mod.rs b/rust/datafusion/src/logical_plan/mod.rsindex 30759ffced..bbf403e358 100644--- a/rust/datafusion/src/logical_plan/mod.rs+++ b/rust/datafusion/src/logical_plan/mod.rs@@ -79,6 +79,14 @@ fn create_name(e: &Expr, input_schema: &Schema) -> Result<String> {let expr = create_name(expr, input_schema)?;Ok(format!("NOT {}", expr))}+ Expr::IsNull(expr) => {+ let expr = create_name(expr, input_schema)?;+ Ok(format!("{} IS NULL", expr))+ }+ Expr::IsNotNull(expr) => {+ let expr = create_name(expr, input_schema)?;+ Ok(format!("{} IS NOT NULL", expr))+ }Expr::ScalarFunction { fun, args, .. } => {create_function_name(&fun.to_string(), args, input_schema)}diff --git a/rust/datafusion/src/physical_plan/expressions.rs b/rust/datafusion/src/physical_plan/expressions.rsindex 8b62079711..e1eb111319 100644--- a/rust/datafusion/src/physical_plan/expressions.rs+++ b/rust/datafusion/src/physical_plan/expressions.rs@@ -1420,6 +1420,82 @@ pub fn not(}}+/// IS NULL expression+#[derive(Debug)]+pub struct IsNullExpr {+ arg: Arc<dyn PhysicalExpr>,+}++impl IsNullExpr {+ /// Create new not expression+ pub fn new(arg: Arc<dyn PhysicalExpr>) -> Self {+ Self { arg }+ }+}++impl fmt::Display for IsNullExpr {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "{} IS NULL", self.arg)+ }+}+impl PhysicalExpr for IsNullExpr {+ fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {+ return Ok(DataType::Boolean);+ }++ fn nullable(&self, _input_schema: &Schema) -> Result<bool> {+ Ok(false)+ }++ fn evaluate(&self, batch: &RecordBatch) -> Result<ArrayRef> {+ let arg = self.arg.evaluate(batch)?;+ return Ok(Arc::new(arrow::compute::is_null(&arg)?));+ }+}++/// Create an IS NULL expression+pub fn is_null(arg: Arc<dyn PhysicalExpr>) -> Result<Arc<dyn PhysicalExpr>> {+ Ok(Arc::new(IsNullExpr::new(arg)))+}++/// IS NULL expression+#[derive(Debug)]+pub struct IsNotNullExpr {+ arg: Arc<dyn PhysicalExpr>,+}++impl IsNotNullExpr {+ /// Create new not expression+ pub fn new(arg: Arc<dyn PhysicalExpr>) -> Self {+ Self { arg }+ }+}++impl fmt::Display for IsNotNullExpr {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "{} IS NOT NULL", self.arg)+ }+}+impl PhysicalExpr for IsNotNullExpr {+ fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {+ return Ok(DataType::Boolean);+ }++ fn nullable(&self, _input_schema: &Schema) -> Result<bool> {+ Ok(false)+ }++ fn evaluate(&self, batch: &RecordBatch) -> Result<ArrayRef> {+ let arg = self.arg.evaluate(batch)?;+ return Ok(Arc::new(arrow::compute::is_not_null(&arg)?));+ }+}++/// Create an IS NOT NULL expression+pub fn is_not_null(arg: Arc<dyn PhysicalExpr>) -> Result<Arc<dyn PhysicalExpr>> {+ Ok(Arc::new(IsNotNullExpr::new(arg)))+}+/// CAST expression casts an expression to a specific data type#[derive(Debug)]pub struct CastExpr {@@ -1679,7 +1755,6 @@ mod tests {.downcast_ref::<BooleanArray>().expect("failed to downcast to BooleanArray");for i in 0..5 {- print!("{}", i);assert_eq!(result.value(i), expected[i]);}@@ -2599,4 +2674,46 @@ mod tests {Ok(())}++ #[test]+ fn is_null_op() -> Result<()> {+ let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);+ let a = StringArray::from(vec![Some("foo"), None]);+ let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;++ // expression: "a is null"+ let expr = is_null(col("a")).unwrap();+ let result = expr.evaluate(&batch)?;+ let result = result+ .as_any()+ .downcast_ref::<BooleanArray>()+ .expect("failed to downcast to BooleanArray");++ let expected = &BooleanArray::from(vec![false, true]);++ assert_eq!(expected, result);++ Ok(())+ }++ #[test]+ fn is_not_null_op() -> Result<()> {+ let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);+ let a = StringArray::from(vec![Some("foo"), None]);+ let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;++ // expression: "a is not null"+ let expr = is_not_null(col("a")).unwrap();+ let result = expr.evaluate(&batch)?;+ let result = result+ .as_any()+ .downcast_ref::<BooleanArray>()+ .expect("failed to downcast to BooleanArray");++ let expected = &BooleanArray::from(vec![true, false]);++ assert_eq!(expected, result);++ Ok(())+ }}diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rsindex c7e035cb1e..87da7b7ac9 100644--- a/rust/datafusion/src/physical_plan/planner.rs+++ b/rust/datafusion/src/physical_plan/planner.rs@@ -424,6 +424,14 @@ impl DefaultPhysicalPlanner {self.create_physical_expr(expr, input_schema, ctx_state)?,input_schema,),+ Expr::IsNull(expr) => expressions::is_null(self.create_physical_expr(+ expr,+ input_schema,+ ctx_state,+ )?),+ Expr::IsNotNull(expr) => expressions::is_not_null(+ self.create_physical_expr(expr, input_schema, ctx_state)?,+ ),Expr::ScalarFunction { fun, args } => {let physical_args = args.iter()diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rsindex a87dc79ea3..c3f31822df 100644--- a/rust/datafusion/tests/sql.rs+++ b/rust/datafusion/tests/sql.rs@@ -139,6 +139,39 @@ fn csv_query_with_predicate() -> Result<()> {Ok(())}+#[test]+fn csv_query_with_negated_predicate() -> Result<()> {+ let mut ctx = ExecutionContext::new();+ register_aggregate_csv(&mut ctx)?;+ let sql = "SELECT COUNT(1) FROM aggregate_test_100 WHERE NOT(c1 != 'a')";+ let actual = execute(&mut ctx, sql).join("\n");+ let expected = "21".to_string();+ assert_eq!(expected, actual);+ Ok(())+}++#[test]+fn csv_query_with_is_not_null_predicate() -> Result<()> {+ let mut ctx = ExecutionContext::new();+ register_aggregate_csv(&mut ctx)?;+ let sql = "SELECT COUNT(1) FROM aggregate_test_100 WHERE c1 IS NOT NULL";+ let actual = execute(&mut ctx, sql).join("\n");+ let expected = "100".to_string();+ assert_eq!(expected, actual);+ Ok(())+}++#[test]+fn csv_query_with_is_null_predicate() -> Result<()> {+ let mut ctx = ExecutionContext::new();+ register_aggregate_csv(&mut ctx)?;+ let sql = "SELECT COUNT(1) FROM aggregate_test_100 WHERE c1 IS NULL";+ let actual = execute(&mut ctx, sql).join("\n");+ let expected = "0".to_string();+ assert_eq!(expected, actual);+ Ok(())+}+#[test]fn csv_query_group_by_int_min_max() -> Result<()> {let mut ctx = ExecutionContext::new();@@ -858,3 +891,51 @@ fn to_timstamp() -> Result<()> {assert_eq!(expected, actual);Ok(())}++#[test]+fn query_is_null() -> Result<()> {+ let schema = Arc::new(Schema::new(vec![Field::new("c1", DataType::Float64, true)]));++ let data = RecordBatch::try_new(+ schema.clone(),+ vec![Arc::new(Float64Array::from(vec![+ Some(1.0),+ None,+ Some(f64::NAN),+ ]))],+ )?;++ let table = MemTable::new(schema, vec![vec![data]])?;++ let mut ctx = ExecutionContext::new();+ ctx.register_table("test", Box::new(table));+ let sql = "SELECT c1 IS NULL FROM test";+ let actual = execute(&mut ctx, sql).join("\n");+ let expected = "false\ntrue\nfalse".to_string();+ assert_eq!(expected, actual);+ Ok(())+}++#[test]+fn query_is_not_null() -> Result<()> {+ let schema = Arc::new(Schema::new(vec![Field::new("c1", DataType::Float64, true)]));++ let data = RecordBatch::try_new(+ schema.clone(),+ vec![Arc::new(Float64Array::from(vec![+ Some(1.0),+ None,+ Some(f64::NAN),+ ]))],+ )?;++ let table = MemTable::new(schema, vec![vec![data]])?;++ let mut ctx = ExecutionContext::new();+ ctx.register_table("test", Box::new(table));+ let sql = "SELECT c1 IS NOT NULL FROM test";+ let actual = execute(&mut ctx, sql).join("\n");+ let expected = "true\nfalse\ntrue".to_string();+ assert_eq!(expected, actual);+ Ok(())+}