Skip to content

Apache DataFusion SQL Query Engine

Add UserDefinedLogicalNodeCore (#5521)

Michał Słapek8c34ca4fa347
diff --git a/datafusion/core/src/physical_plan/planner.rs b/datafusion/core/src/physical_plan/planner.rs
index fc5884ac00..38830c6856 100644
--- a/datafusion/core/src/physical_plan/planner.rs
+++ b/datafusion/core/src/physical_plan/planner.rs
@@ -1878,7 +1878,10 @@ mod tests {
use arrow::record_batch::RecordBatch;
use datafusion_common::assert_contains;
use datafusion_common::{DFField, DFSchema, DFSchemaRef};
- use datafusion_expr::{col, lit, sum, Extension, GroupingSet, LogicalPlanBuilder};
+ use datafusion_expr::{
+ col, lit, sum, Extension, GroupingSet, LogicalPlanBuilder,
+ UserDefinedLogicalNodeCore,
+ };
use fmt::Debug;
use std::collections::HashMap;
use std::convert::TryFrom;
@@ -2400,11 +2403,7 @@ Internal error: Optimizer rule 'type_coercion' failed due to unexpected error: E
}
}
- impl UserDefinedLogicalNode for NoOpExtensionNode {
- fn as_any(&self) -> &dyn Any {
- self
- }
-
+ impl UserDefinedLogicalNodeCore for NoOpExtensionNode {
fn name(&self) -> &str {
"NoOp"
}
@@ -2425,26 +2424,9 @@ Internal error: Optimizer rule 'type_coercion' failed due to unexpected error: E
write!(f, "NoOp")
}
- fn from_template(
- &self,
- _exprs: &[Expr],
- _inputs: &[LogicalPlan],
- ) -> Arc<dyn UserDefinedLogicalNode> {
+ fn from_template(&self, _exprs: &[Expr], _inputs: &[LogicalPlan]) -> Self {
unimplemented!("NoOp");
}
-
- fn dyn_eq(&self, other: &dyn UserDefinedLogicalNode) -> bool {
- match other.as_any().downcast_ref::<Self>() {
- Some(o) => self == o,
- None => false,
- }
- }
-
- fn dyn_hash(&self, state: &mut dyn std::hash::Hasher) {
- use std::hash::Hash;
- let mut s = state;
- self.hash(&mut s);
- }
}
#[derive(Debug)]
diff --git a/datafusion/core/tests/user_defined_plan.rs b/datafusion/core/tests/user_defined_plan.rs
index f1bd8e1ff0..7738a12394 100644
--- a/datafusion/core/tests/user_defined_plan.rs
+++ b/datafusion/core/tests/user_defined_plan.rs
@@ -74,7 +74,10 @@ use datafusion::{
context::{QueryPlanner, SessionState, TaskContext},
runtime_env::RuntimeEnv,
},
- logical_expr::{Expr, Extension, Limit, LogicalPlan, Sort, UserDefinedLogicalNode},
+ logical_expr::{
+ Expr, Extension, Limit, LogicalPlan, Sort, UserDefinedLogicalNode,
+ UserDefinedLogicalNodeCore,
+ },
optimizer::{optimize_children, OptimizerConfig, OptimizerRule},
physical_plan::{
expressions::PhysicalSortExpr,
@@ -337,15 +340,11 @@ impl Debug for TopKPlanNode {
/// For TopK, use explain format for the Debug format. Other types
/// of nodes may
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- self.fmt_for_explain(f)
+ UserDefinedLogicalNodeCore::fmt_for_explain(self, f)
}
}
-impl UserDefinedLogicalNode for TopKPlanNode {
- fn as_any(&self) -> &dyn Any {
- self
- }
-
+impl UserDefinedLogicalNodeCore for TopKPlanNode {
fn name(&self) -> &str {
"TopK"
}
@@ -368,32 +367,15 @@ impl UserDefinedLogicalNode for TopKPlanNode {
write!(f, "TopK: k={}", self.k)
}
- fn from_template(
- &self,
- exprs: &[Expr],
- inputs: &[LogicalPlan],
- ) -> Arc<dyn UserDefinedLogicalNode> {
+ fn from_template(&self, exprs: &[Expr], inputs: &[LogicalPlan]) -> Self {
assert_eq!(inputs.len(), 1, "input size inconsistent");
assert_eq!(exprs.len(), 1, "expression size inconsistent");
- Arc::new(TopKPlanNode {
+ Self {
k: self.k,
input: inputs[0].clone(),
expr: exprs[0].clone(),
- })
- }
-
- fn dyn_eq(&self, other: &dyn UserDefinedLogicalNode) -> bool {
- match other.as_any().downcast_ref::<Self>() {
- Some(o) => self == o,
- None => false,
}
}
-
- fn dyn_hash(&self, state: &mut dyn std::hash::Hasher) {
- use std::hash::Hash;
- let mut s = state;
- self.hash(&mut s);
- }
}
/// Physical planner for TopK nodes
diff --git a/datafusion/expr/src/lib.rs b/datafusion/expr/src/lib.rs
index 9594e74f07..02c51a20e5 100644
--- a/datafusion/expr/src/lib.rs
+++ b/datafusion/expr/src/lib.rs
@@ -76,7 +76,7 @@ pub use logical_plan::{
JoinType, Limit, LogicalPlan, LogicalPlanBuilder, Partitioning, PlanType,
PlanVisitor, Projection, Repartition, SetVariable, Sort, StringifiedPlan, Subquery,
SubqueryAlias, TableScan, ToStringifiedPlan, Union, Unnest, UserDefinedLogicalNode,
- Values, Window, WriteOp,
+ UserDefinedLogicalNodeCore, Values, Window, WriteOp,
};
pub use nullif::SUPPORTED_NULLIF_TYPES;
pub use operator::Operator;
diff --git a/datafusion/expr/src/logical_plan/extension.rs b/datafusion/expr/src/logical_plan/extension.rs
index 1ad328319a..7d03353d9b 100644
--- a/datafusion/expr/src/logical_plan/extension.rs
+++ b/datafusion/expr/src/logical_plan/extension.rs
@@ -17,16 +17,15 @@
//! This module defines the interface for logical nodes
use crate::{Expr, LogicalPlan};
-use datafusion_common::DFSchemaRef;
+use datafusion_common::{DFSchema, DFSchemaRef};
use std::hash::{Hash, Hasher};
use std::{any::Any, cmp::Eq, collections::HashSet, fmt, sync::Arc};
-/// This defines the interface for `LogicalPlan` nodes that can be
+/// This defines the interface for [`LogicalPlan`] nodes that can be
/// used to extend DataFusion with custom relational operators.
///
-/// See the example in
-/// [user_defined_plan.rs](../../tests/user_defined_plan.rs) for an
-/// example of how to use this extension API.
+/// The [`UserDefinedLogicalNodeCore`] trait is *the recommended way to implement*
+/// this trait and avoids having implementing some required boiler plate code.
pub trait UserDefinedLogicalNode: fmt::Debug + Send + Sync {
/// Return a reference to self as Any, to support dynamic downcasting
///
@@ -45,18 +44,18 @@ pub trait UserDefinedLogicalNode: fmt::Debug + Send + Sync {
/// ```
fn as_any(&self) -> &dyn Any;
- /// Return the plan's name
+ /// Return the plan's name.
fn name(&self) -> &str;
- /// Return the logical plan's inputs
+ /// Return the logical plan's inputs.
fn inputs(&self) -> Vec<&LogicalPlan>;
- /// Return the output schema of this logical plan node
+ /// Return the output schema of this logical plan node.
fn schema(&self) -> &DFSchemaRef;
- /// returns all expressions in the current logical plan node. This
+ /// Returns all expressions in the current logical plan node. This
/// should not include expressions of any inputs (aka
- /// non-recursively) These expressions are used for optimizer
+ /// non-recursively). These expressions are used for optimizer
/// passes and rewrites.
fn expressions(&self) -> Vec<Expr>;
@@ -68,14 +67,10 @@ pub trait UserDefinedLogicalNode: fmt::Debug + Send + Sync {
/// predicates from being pushed below this node.
fn prevent_predicate_push_down_columns(&self) -> HashSet<String> {
// default (safe) is all columns in the schema.
- self.schema()
- .fields()
- .iter()
- .map(|f| f.name().clone())
- .collect()
+ get_all_columns_from_schema(self.schema())
}
- /// Write a single line, human readable string to `f` for use in explain plan
+ /// Write a single line, human readable string to `f` for use in explain plan.
///
/// For example: `TopK: k=10`
fn fmt_for_explain(&self, f: &mut fmt::Formatter) -> fmt::Result;
@@ -99,6 +94,9 @@ pub trait UserDefinedLogicalNode: fmt::Debug + Send + Sync {
/// Update the hash `state` with this node requirements from
/// [`Hash`].
///
+ /// Note: consider using [`UserDefinedLogicalNodeCore`] instead of
+ /// [`UserDefinedLogicalNode`] directly.
+ ///
/// This method is required to support hashing [`LogicalPlan`]s. To
/// implement it, typically the type implementing
/// [`UserDefinedLogicalNode`] typically implements [`Hash`] and
@@ -130,6 +128,9 @@ pub trait UserDefinedLogicalNode: fmt::Debug + Send + Sync {
/// Compare `other`, respecting requirements from [std::cmp::Eq].
///
+ /// Note: consider using [`UserDefinedLogicalNodeCore`] instead of
+ /// [`UserDefinedLogicalNode`] directly.
+ ///
/// When `other` has an another type than `self`, then the values
/// are *not* equal.
///
@@ -178,3 +179,111 @@ impl std::cmp::PartialEq for dyn UserDefinedLogicalNode {
}
impl Eq for dyn UserDefinedLogicalNode {}
+
+/// This trait facilitates implementation of the [`UserDefinedLogicalNode`].
+///
+/// See the example in
+/// [user_defined_plan.rs](../../tests/user_defined_plan.rs) for an
+/// example of how to use this extension API.
+pub trait UserDefinedLogicalNodeCore:
+ fmt::Debug + Eq + Hash + Send + Sync + 'static
+{
+ /// Return the plan's name.
+ fn name(&self) -> &str;
+
+ /// Return the logical plan's inputs.
+ fn inputs(&self) -> Vec<&LogicalPlan>;
+
+ /// Return the output schema of this logical plan node.
+ fn schema(&self) -> &DFSchemaRef;
+
+ /// Returns all expressions in the current logical plan node. This
+ /// should not include expressions of any inputs (aka
+ /// non-recursively). These expressions are used for optimizer
+ /// passes and rewrites.
+ fn expressions(&self) -> Vec<Expr>;
+
+ /// A list of output columns (e.g. the names of columns in
+ /// self.schema()) for which predicates can not be pushed below
+ /// this node without changing the output.
+ ///
+ /// By default, this returns all columns and thus prevents any
+ /// predicates from being pushed below this node.
+ fn prevent_predicate_push_down_columns(&self) -> HashSet<String> {
+ // default (safe) is all columns in the schema.
+ get_all_columns_from_schema(self.schema())
+ }
+
+ /// Write a single line, human readable string to `f` for use in explain plan.
+ ///
+ /// For example: `TopK: k=10`
+ fn fmt_for_explain(&self, f: &mut fmt::Formatter) -> fmt::Result;
+
+ /// Create a new `ExtensionPlanNode` with the specified children
+ /// and expressions. This function is used during optimization
+ /// when the plan is being rewritten and a new instance of the
+ /// `ExtensionPlanNode` must be created.
+ ///
+ /// Note that exprs and inputs are in the same order as the result
+ /// of self.inputs and self.exprs.
+ ///
+ /// So, `self.from_template(exprs, ..).expressions() == exprs
+ #[allow(clippy::wrong_self_convention)]
+ fn from_template(&self, exprs: &[Expr], inputs: &[LogicalPlan]) -> Self;
+}
+
+/// Automatically derive UserDefinedLogicalNode to `UserDefinedLogicalNode`
+/// to avoid boiler plate for implementing `as_any`, `Hash` and `PartialEq`
+impl<T: UserDefinedLogicalNodeCore> UserDefinedLogicalNode for T {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ self.name()
+ }
+
+ fn inputs(&self) -> Vec<&LogicalPlan> {
+ self.inputs()
+ }
+
+ fn schema(&self) -> &DFSchemaRef {
+ self.schema()
+ }
+
+ fn expressions(&self) -> Vec<Expr> {
+ self.expressions()
+ }
+
+ fn prevent_predicate_push_down_columns(&self) -> HashSet<String> {
+ self.prevent_predicate_push_down_columns()
+ }
+
+ fn fmt_for_explain(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ self.fmt_for_explain(f)
+ }
+
+ fn from_template(
+ &self,
+ exprs: &[Expr],
+ inputs: &[LogicalPlan],
+ ) -> Arc<dyn UserDefinedLogicalNode> {
+ Arc::new(self.from_template(exprs, inputs))
+ }
+
+ fn dyn_hash(&self, state: &mut dyn Hasher) {
+ let mut s = state;
+ self.hash(&mut s);
+ }
+
+ fn dyn_eq(&self, other: &dyn UserDefinedLogicalNode) -> bool {
+ match other.as_any().downcast_ref::<Self>() {
+ Some(o) => self == o,
+ None => false,
+ }
+ }
+}
+
+fn get_all_columns_from_schema(schema: &DFSchema) -> HashSet<String> {
+ schema.fields().iter().map(|f| f.name().clone()).collect()
+}
diff --git a/datafusion/expr/src/logical_plan/mod.rs b/datafusion/expr/src/logical_plan/mod.rs
index 4ad90dc3c9..0a110148f2 100644
--- a/datafusion/expr/src/logical_plan/mod.rs
+++ b/datafusion/expr/src/logical_plan/mod.rs
@@ -32,4 +32,4 @@ pub use plan::{
pub use display::display_schema;
-pub use extension::UserDefinedLogicalNode;
+pub use extension::{UserDefinedLogicalNode, UserDefinedLogicalNodeCore};
diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs
index fa7090fc8c..3858a7ff58 100644
--- a/datafusion/optimizer/src/push_down_filter.rs
+++ b/datafusion/optimizer/src/push_down_filter.rs
@@ -821,9 +821,8 @@ mod tests {
use datafusion_expr::{
and, col, in_list, in_subquery, lit, logical_plan::JoinType, or, sum, BinaryExpr,
Expr, Extension, LogicalPlanBuilder, Operator, TableSource, TableType,
- UserDefinedLogicalNode,
+ UserDefinedLogicalNodeCore,
};
- use std::any::Any;
use std::fmt::{Debug, Formatter};
use std::sync::Arc;
@@ -1080,11 +1079,7 @@ mod tests {
schema: DFSchemaRef,
}
- impl UserDefinedLogicalNode for NoopPlan {
- fn as_any(&self) -> &dyn Any {
- self
- }
-
+ impl UserDefinedLogicalNodeCore for NoopPlan {
fn name(&self) -> &str {
"NoopPlan"
}
@@ -1112,29 +1107,12 @@ mod tests {
write!(f, "NoopPlan")
}
- fn from_template(
- &self,
- _exprs: &[Expr],
- inputs: &[LogicalPlan],
- ) -> Arc<dyn UserDefinedLogicalNode> {
- Arc::new(Self {
+ fn from_template(&self, _exprs: &[Expr], inputs: &[LogicalPlan]) -> Self {
+ Self {
input: inputs.to_vec(),
schema: self.schema.clone(),
- })
- }
-
- fn dyn_eq(&self, other: &dyn UserDefinedLogicalNode) -> bool {
- match other.as_any().downcast_ref::<Self>() {
- Some(o) => self == o,
- None => false,
}
}
-
- fn dyn_hash(&self, state: &mut dyn std::hash::Hasher) {
- use std::hash::Hash;
- let mut s = state;
- self.hash(&mut s);
- }
}
#[test]
diff --git a/datafusion/optimizer/src/test/user_defined.rs b/datafusion/optimizer/src/test/user_defined.rs
index eb9257edc2..c60342fa00 100644
--- a/datafusion/optimizer/src/test/user_defined.rs
+++ b/datafusion/optimizer/src/test/user_defined.rs
@@ -19,11 +19,10 @@
use datafusion_common::DFSchemaRef;
use datafusion_expr::{
- logical_plan::{Extension, UserDefinedLogicalNode},
+ logical_plan::{Extension, UserDefinedLogicalNodeCore},
Expr, LogicalPlan,
};
use std::{
- any::Any,
fmt::{self, Debug},
sync::Arc,
};
@@ -45,11 +44,7 @@ impl Debug for TestUserDefinedPlanNode {
}
}
-impl UserDefinedLogicalNode for TestUserDefinedPlanNode {
- fn as_any(&self) -> &dyn Any {
- self
- }
-
+impl UserDefinedLogicalNodeCore for TestUserDefinedPlanNode {
fn name(&self) -> &str {
"TestUserDefined"
}
@@ -70,28 +65,11 @@ impl UserDefinedLogicalNode for TestUserDefinedPlanNode {
write!(f, "TestUserDefined")
}
- fn from_template(
- &self,
- exprs: &[Expr],
- inputs: &[LogicalPlan],
- ) -> Arc<dyn UserDefinedLogicalNode> {
+ fn from_template(&self, exprs: &[Expr], inputs: &[LogicalPlan]) -> Self {
assert_eq!(inputs.len(), 1, "input size inconsistent");
assert_eq!(exprs.len(), 0, "expression size inconsistent");
- Arc::new(TestUserDefinedPlanNode {
+ Self {
input: inputs[0].clone(),
- })
- }
-
- fn dyn_eq(&self, other: &dyn UserDefinedLogicalNode) -> bool {
- match other.as_any().downcast_ref::<Self>() {
- Some(o) => self == o,
- None => false,
}
}
-
- fn dyn_hash(&self, state: &mut dyn std::hash::Hasher) {
- use std::hash::Hash;
- let mut s = state;
- self.hash(&mut s);
- }
}
diff --git a/datafusion/proto/src/logical_plan/mod.rs b/datafusion/proto/src/logical_plan/mod.rs
index 802242b3e9..9c9be27328 100644
--- a/datafusion/proto/src/logical_plan/mod.rs
+++ b/datafusion/proto/src/logical_plan/mod.rs
@@ -1387,7 +1387,7 @@ mod roundtrip_tests {
use datafusion_expr::expr::{
self, Between, BinaryExpr, Case, Cast, GroupingSet, Like, Sort,
};
- use datafusion_expr::logical_plan::{Extension, UserDefinedLogicalNode};
+ use datafusion_expr::logical_plan::{Extension, UserDefinedLogicalNodeCore};
use datafusion_expr::{
col, lit, Accumulator, AggregateFunction,
BuiltinScalarFunction::{Sqrt, Substr},
@@ -1397,7 +1397,6 @@ mod roundtrip_tests {
create_udaf, WindowFrame, WindowFrameBound, WindowFrameUnits, WindowFunction,
};
use prost::Message;
- use std::any::Any;
use std::collections::HashMap;
use std::fmt;
use std::fmt::Debug;
@@ -1663,11 +1662,7 @@ mod roundtrip_tests {
}
}
- impl UserDefinedLogicalNode for TopKPlanNode {
- fn as_any(&self) -> &dyn Any {
- self
- }
-
+ impl UserDefinedLogicalNodeCore for TopKPlanNode {
fn name(&self) -> &str {
"TopK"
}
@@ -1690,32 +1685,15 @@ mod roundtrip_tests {
write!(f, "TopK: k={}", self.k)
}
- fn from_template(
- &self,
- exprs: &[Expr],
- inputs: &[LogicalPlan],
- ) -> Arc<dyn UserDefinedLogicalNode> {
+ fn from_template(&self, exprs: &[Expr], inputs: &[LogicalPlan]) -> Self {
assert_eq!(inputs.len(), 1, "input size inconsistent");
assert_eq!(exprs.len(), 1, "expression size inconsistent");
- Arc::new(TopKPlanNode {
+ Self {
k: self.k,
input: inputs[0].clone(),
expr: exprs[0].clone(),
- })
- }
-
- fn dyn_eq(&self, other: &dyn UserDefinedLogicalNode) -> bool {
- match other.as_any().downcast_ref::<Self>() {
- Some(o) => self == o,
- None => false,
}
}
-
- fn dyn_hash(&self, state: &mut dyn std::hash::Hasher) {
- use std::hash::Hash;
- let mut s = state;
- self.hash(&mut s);
- }
}
#[derive(Debug)]