Skip to content

Apache DataFusion SQL Query Engine

ARROW-10839: [Rust] [Data Fusion] Implement BETWEEN operator

Mike Seddonaa6138432fbb
diff --git a/rust/benchmarks/src/bin/tpch.rs b/rust/benchmarks/src/bin/tpch.rs
index fd7102223a..2ed9ab0d8a 100644
--- a/rust/benchmarks/src/bin/tpch.rs
+++ b/rust/benchmarks/src/bin/tpch.rs
@@ -365,7 +365,7 @@ fn create_logical_plan(ctx: &mut ExecutionContext, query: usize) -> Result<Logic
where
l_shipdate >= '1994-01-01'
and l_shipdate < '1995-01-01'
- and l_discount > 0.06 - 0.01 and l_discount < 0.06 + 0.01
+ and l_discount between 0.06 - 0.01 and 0.06 + 0.01
and l_quantity < 24;"
),
diff --git a/rust/datafusion/src/logical_plan/expr.rs b/rust/datafusion/src/logical_plan/expr.rs
index ae2ea25c75..ca72948f1a 100644
--- a/rust/datafusion/src/logical_plan/expr.rs
+++ b/rust/datafusion/src/logical_plan/expr.rs
@@ -76,6 +76,17 @@ pub enum Expr {
IsNull(Box<Expr>),
/// arithmetic negation of an expression, the operand must be of a signed numeric data type
Negative(Box<Expr>),
+ /// Whether an expression is between a given range.
+ Between {
+ /// The value to compare
+ expr: Box<Expr>,
+ /// Whether the expression is negated
+ negated: bool,
+ /// The low end of the range
+ low: Box<Expr>,
+ /// The high end of the range
+ high: Box<Expr>,
+ },
/// 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.
@@ -212,6 +223,7 @@ impl Expr {
&right.get_type(schema)?,
),
Expr::Sort { ref expr, .. } => expr.get_type(schema),
+ Expr::Between { .. } => Ok(DataType::Boolean),
Expr::Wildcard => Err(DataFusionError::Internal(
"Wildcard expressions are not valid in a logical query plan".to_owned(),
)),
@@ -265,6 +277,7 @@ impl Expr {
..
} => Ok(left.nullable(input_schema)? || right.nullable(input_schema)?),
Expr::Sort { ref expr, .. } => expr.nullable(input_schema),
+ Expr::Between { ref expr, .. } => expr.nullable(input_schema),
Expr::Wildcard => Err(DataFusionError::Internal(
"Wildcard expressions are not valid in a logical query plan".to_owned(),
)),
@@ -774,6 +787,18 @@ impl fmt::Debug for Expr {
Expr::AggregateUDF { fun, ref args, .. } => {
fmt_function(f, &fun.name, false, args)
}
+ Expr::Between {
+ expr,
+ negated,
+ low,
+ high,
+ } => {
+ if *negated {
+ write!(f, "{:?} NOT BETWEEN {:?} AND {:?}", expr, low, high)
+ } else {
+ write!(f, "{:?} BETWEEN {:?} AND {:?}", expr, low, high)
+ }
+ }
Expr::Wildcard => write!(f, "*"),
}
}
diff --git a/rust/datafusion/src/optimizer/utils.rs b/rust/datafusion/src/optimizer/utils.rs
index aebb791591..436f8fb599 100644
--- a/rust/datafusion/src/optimizer/utils.rs
+++ b/rust/datafusion/src/optimizer/utils.rs
@@ -24,7 +24,7 @@ use arrow::datatypes::Schema;
use super::optimizer::OptimizerRule;
use crate::error::{DataFusionError, Result};
use crate::logical_plan::{
- DFSchema, DFSchemaRef, Expr, LogicalPlan, PlanType, StringifiedPlan,
+ DFSchema, DFSchemaRef, Expr, LogicalPlan, Operator, PlanType, StringifiedPlan,
};
use crate::prelude::{col, lit};
use crate::scalar::ScalarValue;
@@ -94,6 +94,14 @@ pub fn expr_to_column_names(expr: &Expr, accum: &mut HashSet<String>) -> Result<
Expr::AggregateUDF { args, .. } => exprlist_to_column_names(args, accum),
Expr::ScalarFunction { args, .. } => exprlist_to_column_names(args, accum),
Expr::ScalarUDF { args, .. } => exprlist_to_column_names(args, accum),
+ Expr::Between {
+ expr, low, high, ..
+ } => {
+ expr_to_column_names(expr, accum)?;
+ expr_to_column_names(low, accum)?;
+ expr_to_column_names(high, accum)?;
+ Ok(())
+ }
Expr::Wildcard => Err(DataFusionError::Internal(
"Wildcard expressions are not valid in a logical query plan".to_owned(),
)),
@@ -280,6 +288,13 @@ pub fn expr_sub_expressions(expr: &Expr) -> Result<Vec<Expr>> {
Expr::Not(expr) => Ok(vec![expr.as_ref().to_owned()]),
Expr::Negative(expr) => Ok(vec![expr.as_ref().to_owned()]),
Expr::Sort { expr, .. } => Ok(vec![expr.as_ref().to_owned()]),
+ Expr::Between {
+ expr, low, high, ..
+ } => Ok(vec![
+ expr.as_ref().to_owned(),
+ low.as_ref().to_owned(),
+ high.as_ref().to_owned(),
+ ]),
Expr::Wildcard { .. } => Err(DataFusionError::Internal(
"Wildcard expressions are not valid in a logical query plan".to_owned(),
)),
@@ -370,6 +385,27 @@ pub fn rewrite_expression(expr: &Expr, expressions: &Vec<Expr>) -> Result<Expr>
asc: asc.clone(),
nulls_first: nulls_first.clone(),
}),
+ Expr::Between { negated, .. } => {
+ let expr = Expr::BinaryExpr {
+ left: Box::new(Expr::BinaryExpr {
+ left: Box::new(expressions[0].clone()),
+ op: Operator::GtEq,
+ right: Box::new(expressions[1].clone()),
+ }),
+ op: Operator::And,
+ right: Box::new(Expr::BinaryExpr {
+ left: Box::new(expressions[0].clone()),
+ op: Operator::LtEq,
+ right: Box::new(expressions[2].clone()),
+ }),
+ };
+
+ if *negated {
+ Ok(Expr::Not(Box::new(expr)))
+ } else {
+ Ok(expr)
+ }
+ }
Expr::Wildcard { .. } => Err(DataFusionError::Internal(
"Wildcard expressions are not valid in a logical query plan".to_owned(),
)),
diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rs
index a296885bda..118e277833 100644
--- a/rust/datafusion/src/physical_plan/planner.rs
+++ b/rust/datafusion/src/physical_plan/planner.rs
@@ -23,7 +23,7 @@ use super::{aggregates, empty::EmptyExec, expressions::binary, functions, udaf};
use crate::error::{DataFusionError, Result};
use crate::execution::context::ExecutionContextState;
use crate::logical_plan::{
- DFSchema, Expr, LogicalPlan, PlanType, StringifiedPlan, TableSource,
+ DFSchema, Expr, LogicalPlan, Operator, PlanType, StringifiedPlan, TableSource,
UserDefinedLogicalNode,
};
use crate::physical_plan::csv::{CsvExec, CsvReadOptions};
@@ -558,6 +558,32 @@ impl DefaultPhysicalPlanner {
input_schema,
)
}
+ Expr::Between {
+ expr,
+ negated,
+ low,
+ high,
+ } => {
+ let value_expr =
+ self.create_physical_expr(expr, input_schema, ctx_state)?;
+ let low_expr = self.create_physical_expr(low, input_schema, ctx_state)?;
+ let high_expr =
+ self.create_physical_expr(high, input_schema, ctx_state)?;
+
+ // rewrite the between into the two binary operators
+ let binary_expr = binary(
+ binary(value_expr.clone(), Operator::GtEq, low_expr, input_schema)?,
+ Operator::And,
+ binary(value_expr.clone(), Operator::LtEq, high_expr, input_schema)?,
+ input_schema,
+ );
+
+ if *negated {
+ expressions::not(binary_expr?, input_schema)
+ } else {
+ binary_expr
+ }
+ }
other => Err(DataFusionError::NotImplemented(format!(
"Physical plan does not support logical expression {:?}",
other
diff --git a/rust/datafusion/src/sql/planner.rs b/rust/datafusion/src/sql/planner.rs
index b18e1f3944..c4c42632f1 100644
--- a/rust/datafusion/src/sql/planner.rs
+++ b/rust/datafusion/src/sql/planner.rs
@@ -662,6 +662,18 @@ impl<'a, S: SchemaProvider> SqlToRel<'a, S> {
}
},
+ SQLExpr::Between {
+ ref expr,
+ ref negated,
+ ref low,
+ ref high,
+ } => Ok(Expr::Between {
+ expr: Box::new(self.sql_to_rex(&expr, &schema)?),
+ negated: *negated,
+ low: Box::new(self.sql_to_rex(&low, &schema)?),
+ high: Box::new(self.sql_to_rex(&high, &schema)?),
+ }),
+
SQLExpr::BinaryOp {
ref left,
ref op,
@@ -995,6 +1007,26 @@ mod tests {
quick_test(sql, expected);
}
+ #[test]
+ fn select_between() {
+ let sql = "SELECT state FROM person WHERE age BETWEEN 21 AND 65";
+ let expected = "Projection: #state\
+ \n Filter: #age BETWEEN Int64(21) AND Int64(65)\
+ \n TableScan: person projection=None";
+
+ quick_test(sql, expected);
+ }
+
+ #[test]
+ fn select_between_negated() {
+ let sql = "SELECT state FROM person WHERE age NOT BETWEEN 21 AND 65";
+ let expected = "Projection: #state\
+ \n Filter: #age NOT BETWEEN Int64(21) AND Int64(65)\
+ \n TableScan: person projection=None";
+
+ quick_test(sql, expected);
+ }
+
#[test]
fn select_nested() {
let sql = "SELECT fn2, last_name
diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rs
index b92f2777ae..072ad25d11 100644
--- a/rust/datafusion/tests/sql.rs
+++ b/rust/datafusion/tests/sql.rs
@@ -1799,3 +1799,27 @@ where
assert!((l - r).abs() <= 2.0 * f64::EPSILON);
});
}
+
+#[tokio::test]
+async fn csv_between_expr() -> Result<()> {
+ let mut ctx = ExecutionContext::new();
+ register_aggregate_csv(&mut ctx)?;
+ let sql = "SELECT c4 FROM aggregate_test_100 WHERE c12 BETWEEN 0.995 AND 1.0";
+ let mut actual = execute(&mut ctx, sql).await;
+ actual.sort();
+ let expected = vec![vec!["10837"]];
+ assert_eq!(expected, actual);
+ Ok(())
+}
+
+#[tokio::test]
+async fn csv_between_expr_negated() -> Result<()> {
+ let mut ctx = ExecutionContext::new();
+ register_aggregate_csv(&mut ctx)?;
+ let sql = "SELECT c4 FROM aggregate_test_100 WHERE c12 NOT BETWEEN 0 AND 0.995";
+ let mut actual = execute(&mut ctx, sql).await;
+ actual.sort();
+ let expected = vec![vec!["10837"]];
+ assert_eq!(expected, actual);
+ Ok(())
+}