Skip to content

Apache DataFusion SQL Query Engine

ARROW-9507: [Rust] [DataFusion] Implement Display for PhysicalExpr

Andy Groved304ada9ee18
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rs
index 989bf9cf51..b9f444a150 100644
--- a/rust/datafusion/src/execution/context.rs
+++ b/rust/datafusion/src/execution/context.rs
@@ -529,6 +529,7 @@ impl ExecutionContext {
physical_args.push(self.create_physical_expr(e, input_schema)?);
}
Ok(Arc::new(ScalarFunctionExpr::new(
+ name,
Box::new(f.fun.clone()),
physical_args,
return_type,
diff --git a/rust/datafusion/src/execution/physical_plan/expressions.rs b/rust/datafusion/src/execution/physical_plan/expressions.rs
index 194f35669f..364cdf58ad 100644
--- a/rust/datafusion/src/execution/physical_plan/expressions.rs
+++ b/rust/datafusion/src/execution/physical_plan/expressions.rs
@@ -18,6 +18,7 @@
//! Defines physical expressions that can evaluated at runtime during query execution
use std::cell::RefCell;
+use std::fmt;
use std::rc::Rc;
use std::sync::Arc;
@@ -61,6 +62,12 @@ impl Column {
}
}
+impl fmt::Display for Column {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "{}", self.name)
+ }
+}
+
impl PhysicalExpr for Column {
/// Get the data type of this expression, given the schema of the input
fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
@@ -965,6 +972,12 @@ impl BinaryExpr {
}
}
+impl fmt::Display for BinaryExpr {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "{} {} {}", self.left, self.op, self.right)
+ }
+}
+
impl PhysicalExpr for BinaryExpr {
fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
self.left.data_type(input_schema)
@@ -1049,6 +1062,11 @@ impl NotExpr {
}
}
+impl fmt::Display for NotExpr {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "NOT {}", self.arg)
+ }
+}
impl PhysicalExpr for NotExpr {
fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
return Ok(DataType::Boolean);
@@ -1126,6 +1144,12 @@ impl CastExpr {
}
}
+impl fmt::Display for CastExpr {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "CAST({} AS {:?})", self.expr, self.cast_type)
+ }
+}
+
impl PhysicalExpr for CastExpr {
fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
Ok(self.cast_type.clone())
@@ -1165,6 +1189,12 @@ macro_rules! build_literal_array {
}};
}
+impl fmt::Display for Literal {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "{}", self.value)
+ }
+}
+
impl PhysicalExpr for Literal {
fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
Ok(self.value.get_datatype())
@@ -1297,6 +1327,8 @@ mod tests {
Operator::Or,
binary(col("a"), Operator::Eq, col("b")),
);
+ assert_eq!("a < b OR a = b", format!("{}", expr));
+
let result = expr.evaluate(&batch)?;
assert_eq!(result.len(), 5);
@@ -1322,6 +1354,8 @@ mod tests {
// create and evaluate a literal expression
let literal_expr = lit(ScalarValue::Int32(42));
+ assert_eq!("42", format!("{}", literal_expr));
+
let literal_array = literal_expr.evaluate(&batch)?;
let literal_array = literal_array.as_any().downcast_ref::<Int32Array>().unwrap();
@@ -1341,6 +1375,7 @@ mod tests {
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
let cast = CastExpr::try_new(col("a"), &schema, DataType::UInt32)?;
+ assert_eq!("CAST(a AS UInt32)", format!("{}", cast));
let result = cast.evaluate(&batch)?;
assert_eq!(result.len(), 5);
diff --git a/rust/datafusion/src/execution/physical_plan/mod.rs b/rust/datafusion/src/execution/physical_plan/mod.rs
index 2e19178467..b3786b8403 100644
--- a/rust/datafusion/src/execution/physical_plan/mod.rs
+++ b/rust/datafusion/src/execution/physical_plan/mod.rs
@@ -18,6 +18,7 @@
//! Traits for physical query plan, supporting parallel execution for partitioned relations.
use std::cell::RefCell;
+use std::fmt::Display;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
@@ -43,7 +44,7 @@ pub trait Partition: Send + Sync {
/// Expression that can be evaluated against a RecordBatch
/// A Physical expression knows its type, nullability and how to evaluate itself.
-pub trait PhysicalExpr: Send + Sync {
+pub trait PhysicalExpr: Send + Sync + Display {
/// Get the data type of this expression, given the schema of the input
fn data_type(&self, input_schema: &Schema) -> Result<DataType>;
/// Decide whehter this expression is nullable, given the schema of the input
diff --git a/rust/datafusion/src/execution/physical_plan/udf.rs b/rust/datafusion/src/execution/physical_plan/udf.rs
index a4480bc0be..a14095869e 100644
--- a/rust/datafusion/src/execution/physical_plan/udf.rs
+++ b/rust/datafusion/src/execution/physical_plan/udf.rs
@@ -17,6 +17,8 @@
//! UDF support
+use std::fmt;
+
use arrow::array::ArrayRef;
use arrow::datatypes::{DataType, Field, Schema};
@@ -62,6 +64,7 @@ impl ScalarFunction {
/// Scalar UDF Physical Expression
pub struct ScalarFunctionExpr {
fun: Box<ScalarUdf>,
+ name: String,
args: Vec<Arc<dyn PhysicalExpr>>,
return_type: DataType,
}
@@ -69,18 +72,35 @@ pub struct ScalarFunctionExpr {
impl ScalarFunctionExpr {
/// Create a new Scalar function
pub fn new(
+ name: &str,
fun: Box<ScalarUdf>,
args: Vec<Arc<dyn PhysicalExpr>>,
return_type: &DataType,
) -> Self {
Self {
fun,
+ name: name.to_owned(),
args,
return_type: return_type.clone(),
}
}
}
+impl fmt::Display for ScalarFunctionExpr {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(
+ f,
+ "{}({})",
+ self.name,
+ self.args
+ .iter()
+ .map(|e| format!("{}", e))
+ .collect::<Vec<String>>()
+ .join(", ")
+ )
+ }
+}
+
impl PhysicalExpr for ScalarFunctionExpr {
fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
Ok(self.return_type.clone())
diff --git a/rust/datafusion/src/logicalplan.rs b/rust/datafusion/src/logicalplan.rs
index 25780f9a12..57571b5a3d 100644
--- a/rust/datafusion/src/logicalplan.rs
+++ b/rust/datafusion/src/logicalplan.rs
@@ -125,6 +125,30 @@ pub enum Operator {
NotLike,
}
+impl fmt::Display for Operator {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ let display = match &self {
+ Operator::Eq => "=",
+ Operator::NotEq => "!=",
+ Operator::Lt => "<",
+ Operator::LtEq => "<=",
+ Operator::Gt => ">",
+ Operator::GtEq => ">=",
+ Operator::Plus => "+",
+ Operator::Minus => "-",
+ Operator::Multiply => "*",
+ Operator::Divide => "/",
+ Operator::Modulus => "%",
+ Operator::And => "AND",
+ Operator::Or => "OR",
+ Operator::Not => "NOT",
+ Operator::Like => "LIKE",
+ Operator::NotLike => "NOT LIKE",
+ };
+ write!(f, "{}", display)
+ }
+}
+
/// ScalarValue enumeration
#[derive(Debug, Clone, PartialEq)]
pub enum ScalarValue {
@@ -179,6 +203,27 @@ impl ScalarValue {
}
}
+impl fmt::Display for ScalarValue {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ match self {
+ ScalarValue::Boolean(value) => write!(f, "{}", value),
+ ScalarValue::UInt8(value) => write!(f, "{}", value),
+ ScalarValue::UInt16(value) => write!(f, "{}", value),
+ ScalarValue::UInt32(value) => write!(f, "{}", value),
+ ScalarValue::UInt64(value) => write!(f, "{}", value),
+ ScalarValue::Int8(value) => write!(f, "{}", value),
+ ScalarValue::Int16(value) => write!(f, "{}", value),
+ ScalarValue::Int32(value) => write!(f, "{}", value),
+ ScalarValue::Int64(value) => write!(f, "{}", value),
+ ScalarValue::Float32(value) => write!(f, "{}", value),
+ ScalarValue::Float64(value) => write!(f, "{}", value),
+ ScalarValue::Utf8(value) => write!(f, "{}", value),
+ ScalarValue::Null => write!(f, "NULL"),
+ ScalarValue::Struct(_) => write!(f, "STRUCT"),
+ }
+ }
+}
+
/// Returns a readable name of an expression based on the input schema.
/// This function recursively transverses the expression for names such as "CAST(a > 2)".
fn create_name(e: &Expr, input_schema: &Schema) -> Result<String> {