Skip to content

Apache DataFusion SQL Query Engine

ARROW-9990: [Rust] [DataFusion] Fixed the NOT operator

Jorge C. Leitaod1f7ee19bd14
diff --git a/rust/datafusion/src/logical_plan/mod.rs b/rust/datafusion/src/logical_plan/mod.rs
index 9c11d2397a..99ad06ebe8 100644
--- a/rust/datafusion/src/logical_plan/mod.rs
+++ b/rust/datafusion/src/logical_plan/mod.rs
@@ -150,6 +150,10 @@ fn create_name(e: &Expr, input_schema: &Schema) -> Result<String> {
let expr = create_name(expr, input_schema)?;
Ok(format!("CAST({} as {:?})", expr, data_type))
}
+ Expr::Not(expr) => {
+ let expr = create_name(expr, input_schema)?;
+ Ok(format!("NOT {}", expr))
+ }
Expr::ScalarFunction { fun, args, .. } => {
create_function_name(&fun.to_string(), args, input_schema)
}
diff --git a/rust/datafusion/src/logical_plan/operators.rs b/rust/datafusion/src/logical_plan/operators.rs
index e17c7cce58..f002d01314 100644
--- a/rust/datafusion/src/logical_plan/operators.rs
+++ b/rust/datafusion/src/logical_plan/operators.rs
@@ -48,8 +48,6 @@ pub enum Operator {
And,
/// Logical OR, like `||`
Or,
- /// Logical NOT, like `!`
- Not,
/// Matches a wildcard pattern
Like,
/// Does not match a wildcard pattern
@@ -72,7 +70,6 @@ impl fmt::Display for Operator {
Operator::Modulus => "%",
Operator::And => "AND",
Operator::Or => "OR",
- Operator::Not => "NOT",
Operator::Like => "LIKE",
Operator::NotLike => "NOT LIKE",
};
diff --git a/rust/datafusion/src/physical_plan/expressions.rs b/rust/datafusion/src/physical_plan/expressions.rs
index 5bb1ff110d..ceb9dd1be3 100644
--- a/rust/datafusion/src/physical_plan/expressions.rs
+++ b/rust/datafusion/src/physical_plan/expressions.rs
@@ -1121,11 +1121,6 @@ fn common_binary_type(
"Modulus operator is still not supported".to_string(),
))
}
- Operator::Not => {
- return Err(ExecutionError::InternalError(
- "Trying to coerce a unary operator".to_string(),
- ))
- }
};
// re-write the error message of failed coercions to include the operator's information
@@ -1173,9 +1168,6 @@ pub fn binary_operator_data_type(
Operator::Modulus => Err(ExecutionError::NotImplemented(
"Modulus operator is still not supported".to_string(),
)),
- Operator::Not => Err(ExecutionError::InternalError(
- "Trying to coerce a unary operator".to_string(),
- )),
}
}
@@ -1262,9 +1254,6 @@ impl PhysicalExpr for BinaryExpr {
Operator::Modulus => Err(ExecutionError::NotImplemented(
"Modulus operator is still not supported".to_string(),
)),
- Operator::Not => {
- Err(ExecutionError::General("Unsupported operator".to_string()))
- }
}
}
}
@@ -1305,19 +1294,12 @@ impl PhysicalExpr for NotExpr {
return Ok(DataType::Boolean);
}
- fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
- // !Null == true
- Ok(false)
+ fn nullable(&self, input_schema: &Schema) -> Result<bool> {
+ self.arg.nullable(input_schema)
}
fn evaluate(&self, batch: &RecordBatch) -> Result<ArrayRef> {
let arg = self.arg.evaluate(batch)?;
- if arg.data_type() != &DataType::Boolean {
- return Err(ExecutionError::General(format!(
- "Cannot evaluate \"not\" expression with type {:?}",
- arg.data_type(),
- )));
- }
let arg = arg
.as_any()
.downcast_ref::<BooleanArray>()
@@ -1326,9 +1308,27 @@ impl PhysicalExpr for NotExpr {
}
}
-/// Create a unary expression
-pub fn not(arg: Arc<dyn PhysicalExpr>) -> Arc<dyn PhysicalExpr> {
- Arc::new(NotExpr::new(arg))
+/// Creates a unary expression NOT
+///
+/// # Errors
+///
+/// This function errors when the argument's type is not boolean
+pub fn not(
+ arg: Arc<dyn PhysicalExpr>,
+ input_schema: &Schema,
+) -> Result<Arc<dyn PhysicalExpr>> {
+ let data_type = arg.data_type(input_schema)?;
+ if data_type != DataType::Boolean {
+ Err(ExecutionError::General(
+ format!(
+ "NOT '{:?}' can't be evaluated because the expression's type is {:?}, not boolean",
+ arg, data_type,
+ )
+ .to_string(),
+ ))
+ } else {
+ Ok(Arc::new(NotExpr::new(arg)))
+ }
}
/// CAST expression casts an expression to a specific data type
@@ -1736,20 +1736,6 @@ mod tests {
}
}
- #[test]
- fn test_coersion_invalid() -> Result<()> {
- let expr =
- common_binary_type(&DataType::Float32, &Operator::Not, &DataType::Utf8);
- if let Err(ExecutionError::InternalError(_)) = expr {
- Ok(())
- } else {
- Err(ExecutionError::General(
- "Coercion should have returned an ExecutionError::InternalError"
- .to_string(),
- ))
- }
- }
-
// runs an end-to-end test of physical type cast
// 1. construct a record batch with a column "a" of type A
// 2. construct a physical expression of CAST(a AS B)
@@ -2481,22 +2467,34 @@ mod tests {
#[test]
fn neg_op() -> Result<()> {
let schema = Schema::new(vec![Field::new("a", DataType::Boolean, true)]);
- let a = BooleanArray::from(vec![true, false]);
- let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
- // expression: "!a"
- let lt = not(col("a"));
- let result = lt.evaluate(&batch)?;
- assert_eq!(result.len(), 2);
+ let expr = not(col("a"), &schema)?;
+ assert_eq!(expr.data_type(&schema)?, DataType::Boolean);
+ assert_eq!(expr.nullable(&schema)?, true);
+
+ let input = BooleanArray::from(vec![Some(true), None, Some(false)]);
+ let expected = &BooleanArray::from(vec![Some(false), None, Some(true)]);
- let expected = vec![false, true];
+ let batch =
+ RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(input)])?;
+
+ let result = expr.evaluate(&batch)?;
let result = result
.as_any()
.downcast_ref::<BooleanArray>()
.expect("failed to downcast to BooleanArray");
- for i in 0..2 {
- assert_eq!(result.value(i), expected[i]);
- }
+ assert_eq!(result, expected);
+
+ Ok(())
+ }
+
+ /// verify that expression errors when the input expression is not a boolean.
+ #[test]
+ fn neg_op_not_null() -> Result<()> {
+ let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
+
+ let expr = not(col("a"), &schema);
+ assert!(expr.is_err());
Ok(())
}
diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rs
index 8230ba883d..c2e5826fbb 100644
--- a/rust/datafusion/src/physical_plan/planner.rs
+++ b/rust/datafusion/src/physical_plan/planner.rs
@@ -437,6 +437,10 @@ impl DefaultPhysicalPlanner {
input_schema,
data_type.clone(),
),
+ Expr::Not(expr) => expressions::not(
+ self.create_physical_expr(expr, input_schema, ctx_state)?,
+ input_schema,
+ ),
Expr::ScalarFunction { fun, args } => {
let physical_args = args
.iter()
@@ -534,7 +538,7 @@ impl ExtensionPlanner for DefaultExtensionPlanner {
mod tests {
use super::*;
use crate::logical_plan::{col, lit, sum, LogicalPlanBuilder};
- use crate::physical_plan::{csv::CsvReadOptions, Partitioning};
+ use crate::physical_plan::{csv::CsvReadOptions, expressions, Partitioning};
use crate::{prelude::ExecutionConfig, test::arrow_testdata_path};
use arrow::{
datatypes::{DataType, Field, SchemaRef},
@@ -582,6 +586,21 @@ mod tests {
Ok(())
}
+ #[test]
+ fn test_create_not() -> Result<()> {
+ let schema = Schema::new(vec![Field::new("a", DataType::Boolean, true)]);
+
+ let planner = DefaultPhysicalPlanner::default();
+
+ let expr =
+ planner.create_physical_expr(&col("a").not(), &schema, &make_ctx_state())?;
+ let expected = expressions::not(expressions::col("a"), &schema)?;
+
+ assert_eq!(format!("{:?}", expr), format!("{:?}", expected));
+
+ Ok(())
+ }
+
#[test]
fn test_with_csv_plan() -> Result<()> {
let testdata = arrow_testdata_path();
diff --git a/rust/datafusion/src/sql/planner.rs b/rust/datafusion/src/sql/planner.rs
index d08e57a385..40e6dbf7e6 100644
--- a/rust/datafusion/src/sql/planner.rs
+++ b/rust/datafusion/src/sql/planner.rs
@@ -493,16 +493,11 @@ impl<'a, S: SchemaProvider> SqlToRel<'a, S> {
))),
}?;
- match operator {
- Operator::Not => Err(ExecutionError::InternalError(format!(
- "SQL unary operator \"NOT\" cannot be interpreted as a binary operator"
- ))),
- _ => Ok(Expr::BinaryExpr {
- left: Box::new(self.sql_to_rex(&left, &schema)?),
- op: operator,
- right: Box::new(self.sql_to_rex(&right, &schema)?),
- })
- }
+ Ok(Expr::BinaryExpr {
+ left: Box::new(self.sql_to_rex(&left, &schema)?),
+ op: operator,
+ right: Box::new(self.sql_to_rex(&right, &schema)?),
+ })
}
SQLExpr::Function(function) => {
diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rs
index 33385d53be..9de59fbd40 100644
--- a/rust/datafusion/tests/sql.rs
+++ b/rust/datafusion/tests/sql.rs
@@ -680,9 +680,13 @@ fn result_str(results: &[RecordBatch]) -> Vec<String> {
DataType::Boolean => {
let array =
column.as_any().downcast_ref::<BooleanArray>().unwrap();
- let s = array.value(row_index);
+ let s = if array.is_null(row_index) {
+ "NULL".to_string()
+ } else {
+ format!("{:?}", array.value(row_index))
+ };
- str.push_str(&format!("{:?}", s));
+ str.push_str(&s);
}
_ => str.push_str("???"),
}
@@ -713,6 +717,30 @@ fn query_length() -> Result<()> {
Ok(())
}
+#[test]
+fn query_not() -> Result<()> {
+ let schema = Arc::new(Schema::new(vec![Field::new("c1", DataType::Boolean, true)]));
+
+ let data = RecordBatch::try_new(
+ schema.clone(),
+ vec![Arc::new(BooleanArray::from(vec![
+ Some(false),
+ None,
+ Some(true),
+ ]))],
+ )?;
+
+ let table = MemTable::new(schema, vec![vec![data]])?;
+
+ let mut ctx = ExecutionContext::new();
+ ctx.register_table("test", Box::new(table));
+ let sql = "SELECT NOT c1 FROM test";
+ let actual = execute(&mut ctx, sql).join("\n");
+ let expected = "true\nNULL\nfalse".to_string();
+ assert_eq!(expected, actual);
+ Ok(())
+}
+
#[test]
fn query_concat() -> Result<()> {
let schema = Arc::new(Schema::new(vec![