Apache DataFusion SQL Query Engine
ARROW-9821: [Rust][DataFusion] Support for User Defined ExtensionNodes in the LogicalPlan
alambab2947102d8f
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex 85d664c018..8fd2531d25 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -291,10 +291,12 @@ impl ExecutionContext {/// Optimize the logical plan by applying optimizer rulespub fn optimize(&self, plan: &LogicalPlan) -> Result<LogicalPlan> {- let plan = ProjectionPushDown::new().optimize(&plan)?;- let plan = FilterPushDown::new().optimize(&plan)?;- let plan = TypeCoercionRule::new().optimize(&plan)?;- Ok(plan)+ // Apply standard rewrites and optimizations+ let mut plan = ProjectionPushDown::new().optimize(&plan)?;+ plan = FilterPushDown::new().optimize(&plan)?;+ plan = TypeCoercionRule::new().optimize(&plan)?;++ self.state.config.query_planner.rewrite_logical_plan(plan)}/// Create a physical plan from a logical plan@@ -302,12 +304,10 @@ impl ExecutionContext {&self,logical_plan: &LogicalPlan,) -> Result<Arc<dyn ExecutionPlan>> {- if let Some(planner) = &self.config().physical_planner {- planner.create_physical_plan(logical_plan, &self.state)- } else {- let planner = DefaultPhysicalPlanner::default();- planner.create_physical_plan(logical_plan, &self.state)- }+ self.state+ .config+ .query_planner+ .create_physical_plan(logical_plan, &self.state)}/// Execute a physical plan and collect the results in memory@@ -383,6 +383,38 @@ impl ScalarFunctionRegistry for ExecutionContext {}}+/// A planner used to add extensions to DataFusion logical and phusical plans.+pub trait QueryPlanner {+ /// Given a `LogicalPlan`, create a new, modified `LogicalPlan`+ /// plan. This method is run after built in `OptimizerRule`s. By+ /// default returns the `plan` unmodified.+ fn rewrite_logical_plan(&self, plan: LogicalPlan) -> Result<LogicalPlan> {+ Ok(plan)+ }++ /// Given a `LogicalPlan`, create an `ExecutionPlan` suitable for execution+ fn create_physical_plan(+ &self,+ logical_plan: &LogicalPlan,+ ctx_state: &ExecutionContextState,+ ) -> Result<Arc<dyn ExecutionPlan>>;+}++/// The query planner used if no user defined planner is provided+struct DefaultQueryPlanner {}++impl QueryPlanner for DefaultQueryPlanner {+ /// Given a `LogicalPlan`, create an `ExecutionPlan` suitable for execution+ fn create_physical_plan(+ &self,+ logical_plan: &LogicalPlan,+ ctx_state: &ExecutionContextState,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ let planner = DefaultPhysicalPlanner::default();+ planner.create_physical_plan(logical_plan, ctx_state)+ }+}+/// Configuration options for execution context#[derive(Clone)]pub struct ExecutionConfig {@@ -390,17 +422,17 @@ pub struct ExecutionConfig {pub concurrency: usize,/// Default batch size when reading data sourcespub batch_size: usize,- /// Optional physical planner to override the default physical planner- physical_planner: Option<Arc<dyn PhysicalPlanner + Send + Sync>>,+ /// Responsible for planning `LogicalPlan`s, and `ExecutionPlan`+ query_planner: Arc<dyn QueryPlanner + Send + Sync>,}impl ExecutionConfig {- /// Create an execution config with default settings+ /// Create an execution config with default settingpub fn new() -> Self {Self {concurrency: num_cpus::get(),batch_size: 4096,- physical_planner: None,+ query_planner: Arc::new(DefaultQueryPlanner {}),}}@@ -420,12 +452,12 @@ impl ExecutionConfig {self}- /// Optional physical planner to override the default physical planner- pub fn with_physical_planner(+ /// Replace the default query planner+ pub fn with_query_planner(mut self,- physical_planner: Arc<dyn PhysicalPlanner + Send + Sync>,+ query_planner: Arc<dyn QueryPlanner + Send + Sync>,) -> Self {- self.physical_planner = Some(physical_planner);+ self.query_planner = query_planner;self}}@@ -1075,10 +1107,11 @@ mod tests {}#[test]- fn custom_physical_planner() -> Result<()> {+ fn custom_query_planner() -> Result<()> {let mut ctx = ExecutionContext::with_config(- ExecutionConfig::new().with_physical_planner(Arc::new(MyPhysicalPlanner {})),+ ExecutionConfig::new().with_query_planner(Arc::new(MyQueryPlanner {})),);+let df = ctx.sql("SELECT 1")?;df.collect().expect_err("query not supported");Ok(())@@ -1098,6 +1131,19 @@ mod tests {}}+ struct MyQueryPlanner {}++ impl QueryPlanner for MyQueryPlanner {+ fn create_physical_plan(+ &self,+ logical_plan: &LogicalPlan,+ ctx_state: &ExecutionContextState,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ let physical_planner = MyPhysicalPlanner {};+ physical_planner.create_physical_plan(logical_plan, ctx_state)+ }+ }+/// Execute SQL and return resultsfn collect(ctx: &mut ExecutionContext, sql: &str) -> Result<Vec<RecordBatch>> {let logical_plan = ctx.create_logical_plan(sql)?;diff --git a/rust/datafusion/src/execution/dataframe_impl.rs b/rust/datafusion/src/execution/dataframe_impl.rsindex a343d2917c..57c4df346b 100644--- a/rust/datafusion/src/execution/dataframe_impl.rs+++ b/rust/datafusion/src/execution/dataframe_impl.rs@@ -115,7 +115,7 @@ impl DataFrame for DataFrameImpl {/// Returns the schema from the logical planfn schema(&self) -> &Schema {- self.plan.schema().as_ref()+ self.plan.schema()}fn explain(&self, verbose: bool) -> Result<Arc<dyn DataFrame>> {diff --git a/rust/datafusion/src/logical_plan/mod.rs b/rust/datafusion/src/logical_plan/mod.rsindex b273625732..c894c833cd 100644--- a/rust/datafusion/src/logical_plan/mod.rs+++ b/rust/datafusion/src/logical_plan/mod.rs@@ -21,7 +21,7 @@//! Logical query plans can then be optimized and executed directly, or translated into//! physical query plans and executed.-use std::{collections::HashSet, fmt, sync::Arc};+use std::{any::Any, collections::HashSet, fmt, sync::Arc};use arrow::datatypes::{DataType, Field, Schema, SchemaRef};@@ -37,6 +37,7 @@ use crate::{sql::parser::FileType,};use arrow::record_batch::RecordBatch;+use fmt::Debug;/// Operators applied to expressions#[derive(Debug, Clone, PartialEq, Eq)]@@ -755,8 +756,72 @@ impl fmt::Debug for Expr {}}-/// The LogicalPlan represents different types of relations (such as Projection,-/// Filter, etc) and can be created by the SQL query planner and the DataFrame API.+/// 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 extenison API+pub trait UserDefinedLogicalNode: Debug {+ /// Return a reference to self as Any, to support dynamic downcasting+ fn as_any(&self) -> &dyn Any;++ /// Return the the logical plan's inputs+ fn inputs(&self) -> Vec<&LogicalPlan>;++ /// Return the output schema of this logical plan node+ fn schema(&self) -> &SchemaRef;++ /// 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.+ self.schema()+ .fields()+ .iter()+ .map(|f| f.name().clone())+ .collect()+ }++ /// 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+ fn from_template(+ &self,+ exprs: &Vec<Expr>,+ inputs: &Vec<LogicalPlan>,+ ) -> Arc<dyn UserDefinedLogicalNode + Send + Sync>;+}++/// A LogicalPlan represents the different types of relational+/// operators (such as Projection, Filter, etc) and can be created by+/// the SQL query planner and the DataFrame API.+///+/// A LogicalPlan represents transforming an input relation (table) to+/// an output relation (table) with a (potentially) different+/// schema. A plan represents a dataflow tree where data flows+/// from leaves up to the root to produce the query result.#[derive(Clone)]pub enum LogicalPlan {/// Evaluates an arbitrary list of expressions (essentially a@@ -890,6 +955,11 @@ pub enum LogicalPlan {/// The output schema of the explain (2 columns of text)schema: SchemaRef,},+ /// Extension operator defined outside of DataFusion+ Extension {+ /// The runtime extension operator+ node: Arc<dyn UserDefinedLogicalNode + Send + Sync>,+ },}impl LogicalPlan {@@ -916,6 +986,7 @@ impl LogicalPlan {LogicalPlan::Limit { input, .. } => input.schema(),LogicalPlan::CreateExternalTable { schema, .. } => &schema,LogicalPlan::Explain { schema, .. } => &schema,+ LogicalPlan::Extension { node } => &node.schema(),}}@@ -1018,6 +1089,13 @@ impl LogicalPlan {write!(f, "Explain")?;plan.fmt_with_indent(f, indent + 1)}+ LogicalPlan::Extension { ref node } => {+ node.fmt_for_explain(f)?;+ node.inputs()+ .iter()+ .map(|input| input.fmt_with_indent(f, indent + 1))+ .collect()+ }}}}@@ -1145,8 +1223,7 @@ impl LogicalPlanBuilder {_ => projected_expr.push(expr[i].clone()),});- let schema =- Schema::new(exprlist_to_fields(&projected_expr, input_schema.as_ref())?);+ let schema = Schema::new(exprlist_to_fields(&projected_expr, input_schema)?);Ok(Self::from(&LogicalPlan::Projection {expr: projected_expr,diff --git a/rust/datafusion/src/optimizer/optimizer.rs b/rust/datafusion/src/optimizer/optimizer.rsindex c41fd78ae3..30015197bc 100644--- a/rust/datafusion/src/optimizer/optimizer.rs+++ b/rust/datafusion/src/optimizer/optimizer.rs@@ -17,6 +17,7 @@//! Query optimizer traits+use super::utils;use crate::error::Result;use crate::logical_plan::LogicalPlan;@@ -27,4 +28,18 @@ pub trait OptimizerRule {fn optimize(&mut self, plan: &LogicalPlan) -> Result<LogicalPlan>;/// Produce a human readable name for this optimizer rulefn name(&self) -> &str;++ /// Convenience rule for writing optimizers: recursively invoke+ /// optimize on plan's children and then return a node of the same+ /// type. Useful for optimizer rules which want to leave the type+ /// of plan unchanged but still apply to the children.+ fn optimize_children(&mut self, plan: &LogicalPlan) -> Result<LogicalPlan> {+ let new_exprs = utils::expressions(&plan);+ let new_inputs = utils::inputs(&plan)+ .into_iter()+ .map(|plan| self.optimize(plan))+ .collect::<Result<Vec<_>>>()?;++ utils::from_plan(plan, &new_exprs, &new_inputs)+ }}diff --git a/rust/datafusion/src/optimizer/projection_push_down.rs b/rust/datafusion/src/optimizer/projection_push_down.rsindex 71034c0bac..8445e8fce6 100644--- a/rust/datafusion/src/optimizer/projection_push_down.rs+++ b/rust/datafusion/src/optimizer/projection_push_down.rs@@ -306,13 +306,14 @@ fn optimize_plan(stringified_plans,schema,} => optimize_explain(optimizer, *verbose, &*plan, stringified_plans, &*schema),- // all other nodes:- // * gather all used columns as required columns+ // all other nodes: Add any additional columns used by+ // expressions in this node to the list of required columnsLogicalPlan::Limit { .. }| LogicalPlan::Filter { .. }| LogicalPlan::EmptyRelation { .. }| LogicalPlan::Sort { .. }- | LogicalPlan::CreateExternalTable { .. } => {+ | LogicalPlan::CreateExternalTable { .. }+ | LogicalPlan::Extension { .. } => {let expr = utils::expressions(plan);// collect all required columns by this planlet mut new_required_columns = required_columns.clone();diff --git a/rust/datafusion/src/optimizer/utils.rs b/rust/datafusion/src/optimizer/utils.rsindex 0e12f00c30..402819e6c3 100644--- a/rust/datafusion/src/optimizer/utils.rs+++ b/rust/datafusion/src/optimizer/utils.rs@@ -114,6 +114,7 @@ pub fn expressions(plan: &LogicalPlan) -> Vec<Expr> {result}LogicalPlan::Sort { expr, .. } => expr.clone(),+ LogicalPlan::Extension { node } => node.expressions(),// plans without expressionsLogicalPlan::TableScan { .. }| LogicalPlan::InMemoryScan { .. }@@ -134,6 +135,7 @@ pub fn inputs(plan: &LogicalPlan) -> Vec<&LogicalPlan> {LogicalPlan::Aggregate { input, .. } => vec![input],LogicalPlan::Sort { input, .. } => vec![input],LogicalPlan::Limit { input, .. } => vec![input],+ LogicalPlan::Extension { node } => node.inputs(),// plans without inputsLogicalPlan::TableScan { .. }| LogicalPlan::InMemoryScan { .. }@@ -177,6 +179,9 @@ pub fn from_plan(n: *n,input: Arc::new(inputs[0].clone()),}),+ LogicalPlan::Extension { node } => Ok(LogicalPlan::Extension {+ node: node.from_template(expr, inputs),+ }),LogicalPlan::EmptyRelation { .. }| LogicalPlan::TableScan { .. }| LogicalPlan::InMemoryScan { .. }diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rsindex d5fd705c6f..5d83db1cf6 100644--- a/rust/datafusion/src/physical_plan/planner.rs+++ b/rust/datafusion/src/physical_plan/planner.rs@@ -22,7 +22,9 @@ use std::sync::Arc;use super::{empty::EmptyExec, expressions::binary, functions};use crate::error::{ExecutionError, Result};use crate::execution::context::ExecutionContextState;-use crate::logical_plan::{Expr, LogicalPlan, PlanType, StringifiedPlan};+use crate::logical_plan::{+ Expr, LogicalPlan, PlanType, StringifiedPlan, UserDefinedLogicalNode,+};use crate::physical_plan::csv::{CsvExec, CsvReadOptions};use crate::physical_plan::explain::ExplainExec;use crate::physical_plan::expressions::{@@ -42,14 +44,30 @@ use crate::physical_plan::{AggregateExpr, ExecutionPlan, PhysicalExpr, PhysicalPuse arrow::compute::SortOptions;use arrow::datatypes::Schema;+/// This trait permits the `DefaultPhysicalPlanner` to create plans for+/// user defined `ExtensionPlanNode`s+pub trait ExtensionPlanner {+ /// Create a physical plan for an extension node+ fn plan_extension(+ &self,+ node: &dyn UserDefinedLogicalNode,+ inputs: Vec<Arc<dyn ExecutionPlan>>,+ ctx_state: &ExecutionContextState,+ ) -> Result<Arc<dyn ExecutionPlan>>;+}+/// Default single node physical query planner that converts a/// `LogicalPlan` to an `ExecutionPlan` suitable for execution.-pub struct DefaultPhysicalPlanner {}+pub struct DefaultPhysicalPlanner {+ extension_planner: Arc<dyn ExtensionPlanner + Send + Sync>,+}impl Default for DefaultPhysicalPlanner {- /// Create an implementation of the physical planner+ /// Create an implementation of the default physical plannerfn default() -> Self {- Self {}+ Self {+ extension_planner: Arc::new(DefaultExtensionPlanner {}),+ }}}@@ -66,6 +84,14 @@ impl PhysicalPlanner for DefaultPhysicalPlanner {}impl DefaultPhysicalPlanner {+ /// Create a physical planner that uses `extension_planner` to+ /// plan extension nodes.+ pub fn with_extension_planner(+ extension_planner: Arc<dyn ExtensionPlanner + Send + Sync>,+ ) -> Self {+ Self { extension_planner }+ }+/// Create a physical plan from a logical planfn optimize_plan(&self,@@ -331,6 +357,32 @@ impl DefaultPhysicalPlanner {let schema_ref = Arc::new(schema.as_ref().clone());Ok(Arc::new(ExplainExec::new(schema_ref, stringified_plans)))}+ LogicalPlan::Extension { node } => {+ let inputs = node+ .inputs()+ .into_iter()+ .map(|input_plan| self.create_physical_plan(input_plan, ctx_state))+ .collect::<Result<Vec<_>>>()?;++ let plan = self.extension_planner.plan_extension(+ node.as_ref(),+ inputs,+ ctx_state,+ )?;++ // Ensure the ExecutionPlan's schema matches the+ // declared logical schema to catch and warn about+ // logic errors when creating user defined plans.+ if plan.schema() != *node.schema() {+ Err(ExecutionError::General(format!(+ "Extension planner for {:?} created an ExecutionPlan with mismatched schema. \+ LogicalPlan schema: {:?}, ExecutionPlan schema: {:?}",+ node, node.schema(), plan.schema()+ )))+ } else {+ Ok(plan)+ }+ }}}@@ -463,23 +515,48 @@ fn tuple_err<T, R>(value: (Result<T>, Result<R>)) -> Result<(T, R)> {}}+struct DefaultExtensionPlanner {}++impl ExtensionPlanner for DefaultExtensionPlanner {+ fn plan_extension(+ &self,+ node: &dyn UserDefinedLogicalNode,+ _inputs: Vec<Arc<dyn ExecutionPlan>>,+ _ctx_state: &ExecutionContextState,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ Err(ExecutionError::NotImplemented(format!(+ "DefaultPhysicalPlanner does not know how to plan {:?}. \+ Provide a custom ExtensionPlanNodePlanner that does",+ node+ )))+ }+}+#[cfg(test)]mod tests {use super::*;use crate::logical_plan::{aggregate_expr, col, lit, LogicalPlanBuilder};- use crate::physical_plan::csv::CsvReadOptions;+ use crate::physical_plan::{csv::CsvReadOptions, Partitioning};use crate::{prelude::ExecutionConfig, test::arrow_testdata_path};- use std::collections::HashMap;-- fn plan(logical_plan: &LogicalPlan) -> Result<Arc<dyn ExecutionPlan>> {- let ctx_state = ExecutionContextState {+ use arrow::{+ datatypes::{DataType, Field, SchemaRef},+ record_batch::RecordBatchReader,+ };+ use fmt::Debug;+ use std::{any::Any, collections::HashMap, fmt, sync::Mutex};++ fn make_ctx_state() -> ExecutionContextState {+ ExecutionContextState {datasources: HashMap::new(),scalar_functions: HashMap::new(),config: ExecutionConfig::new(),- };+ }+ }- let planer = DefaultPhysicalPlanner {};- planer.create_physical_plan(logical_plan, &ctx_state)+ fn plan(logical_plan: &LogicalPlan) -> Result<Arc<dyn ExecutionPlan>> {+ let ctx_state = make_ctx_state();+ let planner = DefaultPhysicalPlanner::default();+ planner.create_physical_plan(logical_plan, &ctx_state)}#[test]@@ -559,4 +636,163 @@ mod tests {}Ok(())}++ #[test]+ fn default_extension_planner() -> Result<()> {+ let ctx_state = make_ctx_state();+ let planner = DefaultPhysicalPlanner::default();+ let logical_plan = LogicalPlan::Extension {+ node: Arc::new(NoOpExtensionNode::default()),+ };+ let plan = planner.create_physical_plan(&logical_plan, &ctx_state);++ let expected_error = "DefaultPhysicalPlanner does not know how to plan NoOp";+ match plan {+ Ok(_) => assert!(false, "Expected planning failure"),+ Err(e) => assert!(+ e.to_string().contains(expected_error),+ "Error '{}' did not contain expected error '{}'",+ e.to_string(),+ expected_error+ ),+ }+ Ok(())+ }++ #[test]+ fn bad_extension_planner() -> Result<()> {+ // Test that creating an execution plan whose schema doesn't+ // match the logical plan's schema generates an error.+ let ctx_state = make_ctx_state();+ let planner = DefaultPhysicalPlanner::with_extension_planner(Arc::new(+ BadExtensionPlanner {},+ ));++ let logical_plan = LogicalPlan::Extension {+ node: Arc::new(NoOpExtensionNode::default()),+ };+ let plan = planner.create_physical_plan(&logical_plan, &ctx_state);++ let expected_error = "Extension planner for NoOp created an ExecutionPlan with mismatched schema. LogicalPlan schema: Schema { fields: [Field { name: \"a\", data_type: Int32, nullable: false, dict_id: 0, dict_is_ordered: false }], metadata: {} }, ExecutionPlan schema: Schema { fields: [Field { name: \"b\", data_type: Int32, nullable: false, dict_id: 0, dict_is_ordered: false }], metadata: {} }";++ match plan {+ Ok(_) => assert!(false, "Expected planning failure"),+ Err(e) => assert!(+ e.to_string().contains(expected_error),+ "Error '{}' did not contain expected error '{}'",+ e.to_string(),+ expected_error+ ),+ }+ Ok(())+ }++ /// An example extension node that doesn't do anything+ struct NoOpExtensionNode {+ schema: SchemaRef,+ }++ impl Default for NoOpExtensionNode {+ fn default() -> Self {+ Self {+ schema: SchemaRef::new(Schema::new(vec![Field::new(+ "a",+ DataType::Int32,+ false,+ )])),+ }+ }+ }++ impl Debug for NoOpExtensionNode {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "NoOp")+ }+ }++ impl UserDefinedLogicalNode for NoOpExtensionNode {+ fn as_any(&self) -> &dyn Any {+ self+ }++ fn inputs(&self) -> Vec<&LogicalPlan> {+ vec![]+ }++ fn schema(&self) -> &SchemaRef {+ &self.schema+ }++ fn expressions(&self) -> Vec<Expr> {+ vec![]+ }++ fn fmt_for_explain(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "NoOp")+ }++ fn from_template(+ &self,+ _exprs: &Vec<Expr>,+ _inputs: &Vec<LogicalPlan>,+ ) -> Arc<dyn UserDefinedLogicalNode + Send + Sync> {+ unimplemented!("NoOp");+ }+ }++ #[derive(Debug)]+ struct NoOpExecutionPlan {+ schema: SchemaRef,+ }++ impl ExecutionPlan for NoOpExecutionPlan {+ fn schema(&self) -> SchemaRef {+ self.schema.clone()+ }++ fn output_partitioning(&self) -> Partitioning {+ Partitioning::UnknownPartitioning(1)+ }++ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {+ vec![]+ }++ fn with_new_children(+ &self,+ _children: Vec<Arc<dyn ExecutionPlan>>,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ unimplemented!("NoOpExecutionPlan::with_new_children");+ }++ /// Execute one partition and return an iterator over RecordBatch+ fn execute(+ &self,+ _partition: usize,+ ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {+ unimplemented!("NoOpExecutionPlan::execute");+ }+ }++ // Produces an execution plan where the schema is mismatched from+ // the logical plan node.+ struct BadExtensionPlanner {}++ impl ExtensionPlanner for BadExtensionPlanner {+ /// Create a physical plan for an extension node+ fn plan_extension(+ &self,+ _node: &dyn UserDefinedLogicalNode,+ _inputs: Vec<Arc<dyn ExecutionPlan>>,+ _ctx_state: &ExecutionContextState,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ Ok(Arc::new(NoOpExecutionPlan {+ schema: SchemaRef::new(Schema::new(vec![Field::new(+ "b",+ DataType::Int32,+ false,+ )])),+ }))+ }+ }}diff --git a/rust/datafusion/tests/customer.csv b/rust/datafusion/tests/customer.csvnew file mode 100644index 0000000000..2abcd65904--- /dev/null+++ b/rust/datafusion/tests/customer.csv@@ -0,0 +1,4 @@+andrew,100+jorge,200+andy,150+paul,300diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rsindex 852a060f1f..c0172adc54 100644--- a/rust/datafusion/tests/sql.rs+++ b/rust/datafusion/tests/sql.rs@@ -583,11 +583,11 @@ fn register_alltypes_parquet(ctx: &mut ExecutionContext) {/// Execute query and return result set as tab delimited stringfn execute(ctx: &mut ExecutionContext, sql: &str) -> Vec<String> {let plan = ctx.create_logical_plan(&sql).unwrap();- let logical_schema = plan.schema().clone();+ let logical_schema = plan.schema();let plan = ctx.optimize(&plan).unwrap();- let optimized_logical_schema = plan.schema().clone();+ let optimized_logical_schema = plan.schema();let plan = ctx.create_physical_plan(&plan).unwrap();- let physical_schema = plan.schema().clone();+ let physical_schema = plan.schema();let results = ctx.collect(plan).unwrap();assert_eq!(logical_schema.as_ref(), optimized_logical_schema.as_ref());diff --git a/rust/datafusion/tests/user_defined_plan.rs b/rust/datafusion/tests/user_defined_plan.rsnew file mode 100644index 0000000000..98d2e01c6f--- /dev/null+++ b/rust/datafusion/tests/user_defined_plan.rs@@ -0,0 +1,510 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++//! This module contains an end to end demonstration of creating+//! a user defined operator in DataFusion.+//!+//! Specifically, it shows how to define a `TopKNode` that implements+//! `ExtensionPlanNode`, add an OptimizerRule to rewrite a+//! `LogicalPlan` to use that node a `LogicalPlan`, create an+//! `ExecutionPlan` and finally produce results.+//!+//! # TopK Background:+//!+//! A "Top K" node is a common query optimization which is used for+//! queries such as "find the top 3 customers by revenue". The+//! (simplified) SQL for such a query might be:+//!+//! ```sql+//! CREATE EXTERNAL TABLE sales(customer_id VARCHAR, revenue BIGINT)+//! STORED AS CSV location 'tests/customer.csv';+//!+//! SELECT customer_id, revenue FROM sales ORDER BY revenue DESC limit 3;+//! ```+//!+//! And a naive plan would be:+//!+//! ```+//! > explain SELECT customer_id, revenue FROM sales ORDER BY revenue DESC limit 3;+//! +--------------+----------------------------------------++//! | plan_type | plan |+//! +--------------+----------------------------------------++//! | logical_plan | Limit: 3 |+//! | | Sort: #revenue DESC NULLS FIRST |+//! | | Projection: #customer_id, #revenue |+//! | | TableScan: sales projection=None |+//! +--------------+----------------------------------------++//! ```+//!+//! While this plan produces the correct answer, the careful reader+//! will note it fully sorts the input before discarding everything+//! other than the top 3 elements.+//!+//! The same answer can be produced by simply keeping track of the top+//! N elements, reducing the total amount of required buffer memory.+//!++use arrow::{+ array::{Int64Array, StringArray},+ datatypes::SchemaRef,+ error::ArrowError,+ record_batch::{RecordBatch, RecordBatchReader},+ util::pretty::pretty_format_batches,+};+use datafusion::{+ error::{ExecutionError, Result},+ execution::context::ExecutionContextState,+ execution::context::QueryPlanner,+ logical_plan::{Expr, LogicalPlan, UserDefinedLogicalNode},+ optimizer::{optimizer::OptimizerRule, utils::optimize_explain},+ physical_plan::{+ planner::{DefaultPhysicalPlanner, ExtensionPlanner},+ Distribution, ExecutionPlan, Partitioning, PhysicalPlanner,+ },+ prelude::{ExecutionConfig, ExecutionContext},+};+use fmt::Debug;+use std::{+ any::Any,+ collections::BTreeMap,+ fmt,+ sync::{Arc, Mutex},+};++/// Execute the specified sql and return the resulting record batches+/// pretty printed as a String.+fn exec_sql(ctx: &mut ExecutionContext, sql: &str) -> Result<String> {+ let df = ctx.sql(sql)?;+ let batches = df.collect()?;+ pretty_format_batches(&batches).map_err(|e| ExecutionError::ArrowError(e))+}++/// Create a test table.+fn setup_table(mut ctx: ExecutionContext) -> Result<ExecutionContext> {+ let sql = "CREATE EXTERNAL TABLE sales(customer_id VARCHAR, revenue BIGINT) STORED AS CSV location 'tests/customer.csv'";++ let expected = vec!["++", "++"];++ let s = exec_sql(&mut ctx, sql)?;+ let actual = s.lines().collect::<Vec<_>>();++ assert_eq!(expected, actual, "Creating table");+ Ok(ctx)+}++const QUERY: &str =+ "SELECT customer_id, revenue FROM sales ORDER BY revenue DESC limit 3";++// Run the query using the specified execution context and compare it+// to the known result+fn run_and_compare_query(mut ctx: ExecutionContext, description: &str) -> Result<()> {+ let expected = vec![+ "+-------------+---------+",+ "| customer_id | revenue |",+ "+-------------+---------+",+ "| paul | 300 |",+ "| jorge | 200 |",+ "| andy | 150 |",+ "+-------------+---------+",+ ];++ let s = exec_sql(&mut ctx, QUERY)?;+ let actual = s.lines().collect::<Vec<_>>();++ assert_eq!(+ expected,+ actual,+ "output mismatch for {}. Expectedn\n{}Actual:\n{}",+ description,+ expected.join("\n"),+ s+ );+ Ok(())+}++#[test]+// Run the query using default planners and optimizer+fn normal_query() -> Result<()> {+ let ctx = setup_table(ExecutionContext::new())?;+ run_and_compare_query(ctx, "Default context")+}++#[test]+// Run the query using topk optimization+fn topk_query() -> Result<()> {+ // Note the only difference is that the top+ let ctx = setup_table(make_topk_context())?;+ run_and_compare_query(ctx, "Topk context")+}++#[test]+// Run EXPLAIN PLAN and show the plan was in fact rewritten+fn topk_plan() -> Result<()> {+ let mut ctx = setup_table(make_topk_context())?;++ let expected = vec![+ "| logical_plan after topk | TopK: k=3 |",+ "| | Projection: #customer_id, #revenue |",+ "| | TableScan: sales projection=Some([0, 1]) |",+ ].join("\n");++ let explain_query = format!("EXPLAIN VERBOSE {}", QUERY);+ let actual_output = exec_sql(&mut ctx, &explain_query)?;++ // normalize newlines (output on windows uses \r\n)+ let actual_output = actual_output.replace("\r\n", "\n");++ assert!(actual_output.contains(&expected) , "Expected output not present in actual output\nExpected:\n---------\n{}\nActual:\n--------\n{}", expected, actual_output);+ Ok(())+}++fn make_topk_context() -> ExecutionContext {+ let config = ExecutionConfig::new().with_query_planner(Arc::new(TopKQueryPlanner {}));++ ExecutionContext::with_config(config)+}++// ------ The implementation of the TopK code follows -----++struct TopKQueryPlanner {}++impl QueryPlanner for TopKQueryPlanner {+ fn rewrite_logical_plan(&self, plan: LogicalPlan) -> Result<LogicalPlan> {+ TopKOptimizerRule {}.optimize(&plan)+ }++ /// Given a `LogicalPlan` created from above, create an+ /// `ExecutionPlan` suitable for execution+ fn create_physical_plan(+ &self,+ logical_plan: &LogicalPlan,+ ctx_state: &ExecutionContextState,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ // Teach the default physical planner how to plan TopK nodes.+ let physical_planner =+ DefaultPhysicalPlanner::with_extension_planner(Arc::new(TopKPlanner {}));+ // Delegate most work of physical planning to the default physical planner+ physical_planner.create_physical_plan(logical_plan, ctx_state)+ }+}++struct TopKOptimizerRule {}+impl OptimizerRule for TopKOptimizerRule {+ // Example rewrite pass to insert a user defined LogicalPlanNode+ fn optimize(&mut self, plan: &LogicalPlan) -> Result<LogicalPlan> {+ match plan {+ // Note: this code simply looks for the pattern of a Limit followed by a+ // Sort and replaces it by a TopK node. It does not handle many+ // edge cases (e.g multiple sort columns, sort ASC / DESC), etc.+ LogicalPlan::Limit { ref n, ref input } => {+ if let LogicalPlan::Sort {+ ref expr,+ ref input,+ } = **input+ {+ if expr.len() == 1 {+ // we found a sort with a single sort expr, replace with a a TopK+ return Ok(LogicalPlan::Extension {+ node: Arc::new(TopKPlanNode {+ k: *n,+ input: self.optimize(input.as_ref())?,+ expr: expr[0].clone(),+ }),+ });+ }+ }+ }+ // Due to the way explain is implemented, in order to get+ // explain functionality we need to explicitly handle it+ // here.+ LogicalPlan::Explain {+ verbose,+ plan,+ stringified_plans,+ schema,+ } => {+ return optimize_explain(+ self,+ *verbose,+ &*plan,+ stringified_plans,+ &*schema,+ )+ }+ _ => {}+ }++ // If we didn't find the Limit/Sort combination, recurse as+ // normal and build the result.+ self.optimize_children(plan)+ }++ fn name(&self) -> &str {+ "topk"+ }+}++struct TopKPlanNode {+ k: usize,+ input: LogicalPlan,+ /// The sort expression (this example only supports a single sort+ /// expr)+ expr: Expr,+}++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)+ }+}++impl UserDefinedLogicalNode for TopKPlanNode {+ fn as_any(&self) -> &dyn Any {+ self+ }++ fn inputs(&self) -> Vec<&LogicalPlan> {+ vec![&self.input]+ }++ /// Schema for TopK is the same as the input+ fn schema(&self) -> &SchemaRef {+ self.input.schema()+ }++ fn expressions(&self) -> Vec<Expr> {+ vec![self.expr.clone()]+ }++ /// For example: `TopK: k=10`+ fn fmt_for_explain(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "TopK: k={}", self.k)+ }++ fn from_template(+ &self,+ exprs: &Vec<Expr>,+ inputs: &Vec<LogicalPlan>,+ ) -> Arc<dyn UserDefinedLogicalNode + Send + Sync> {+ assert_eq!(inputs.len(), 1, "input size inconistent");+ assert_eq!(exprs.len(), 1, "expression size inconistent");+ Arc::new(TopKPlanNode {+ k: self.k,+ input: inputs[0].clone(),+ expr: exprs[0].clone(),+ })+ }+}++/// Physical planner for TopK nodes+struct TopKPlanner {}++impl ExtensionPlanner for TopKPlanner {+ /// Create a physical plan for an extension node+ fn plan_extension(+ &self,+ node: &dyn UserDefinedLogicalNode,+ inputs: Vec<Arc<dyn ExecutionPlan>>,+ _ctx_state: &ExecutionContextState,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ if let Some(topk_node) = node.as_any().downcast_ref::<TopKPlanNode>() {+ assert_eq!(inputs.len(), 1, "Inconsistent number of inputs");+ // figure out input name+ Ok(Arc::new(TopKExec {+ input: inputs[0].clone(),+ k: topk_node.k,+ }))+ } else {+ Err(ExecutionError::General(format!(+ "Unknown extension node type {:?}",+ node+ )))+ }+ }+}++/// Physical operator that implements TopK for u64 data types. This+/// code is not general and is meant as an illustration only+struct TopKExec {+ input: Arc<dyn ExecutionPlan>,+ /// The maxium number of values+ k: usize,+}++impl Debug for TopKExec {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "TopKExec")+ }+}++impl ExecutionPlan for TopKExec {+ fn schema(&self) -> SchemaRef {+ self.input.schema()+ }++ fn output_partitioning(&self) -> Partitioning {+ Partitioning::UnknownPartitioning(1)+ }++ fn required_child_distribution(&self) -> Distribution {+ Distribution::UnspecifiedDistribution+ }++ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {+ vec![self.input.clone()]+ }++ fn with_new_children(+ &self,+ children: Vec<Arc<dyn ExecutionPlan>>,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ match children.len() {+ 1 => Ok(Arc::new(TopKExec {+ input: children[0].clone(),+ k: self.k,+ })),+ _ => Err(ExecutionError::General(+ "TopKExec wrong number of children".to_string(),+ )),+ }+ }++ /// Execute one partition and return an iterator over RecordBatch+ fn execute(+ &self,+ partition: usize,+ ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {+ if 0 != partition {+ return Err(ExecutionError::General(format!(+ "TopKExec invalid partition {}",+ partition+ )));+ }++ Ok(Arc::new(Mutex::new(TopKReader {+ input: self.input.execute(partition)?,+ k: self.k,+ top_values: BTreeMap::new(),+ done: false,+ })))+ }+}++// A very specialized TopK implementation+struct TopKReader {+ /// The input to read data from+ input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,+ /// Maximum number of output values+ k: usize,+ /// Hard coded implementation for sales / customer_id example+ top_values: BTreeMap<i64, String>,+ /// Have we produced the output yet?+ done: bool,+}++impl TopKReader {+ /// Keeps track of the revenue from customer_id and stores if it+ /// is the top values we have seen so far.+ fn add_row(&mut self, customer_id: &str, revenue: i64) {+ self.top_values.insert(revenue, customer_id.into());+ // only keep top k+ while self.top_values.len() > self.k {+ self.remove_lowest_value()+ }+ }++ fn remove_lowest_value(&mut self) {+ if !self.top_values.is_empty() {+ let smallest_revenue = {+ let (revenue, _) = self.top_values.iter().next().unwrap();+ *revenue+ };+ self.top_values.remove(&smallest_revenue);+ }+ }+}++impl RecordBatchReader for TopKReader {+ fn schema(&self) -> SchemaRef {+ self.input.lock().expect("locked input reader").schema()+ }++ /// Reads the next `RecordBatch`.+ fn next_batch(&mut self) -> std::result::Result<Option<RecordBatch>, ArrowError> {+ if self.done {+ return Ok(None);+ }++ // use a loop so that we release the mutex once we have read each input_batch+ loop {+ let input_batch = self+ .input+ .lock()+ .expect("locked input mutex")+ .next_batch()?;++ match input_batch {+ Some(input_batch) => {+ println!("Got an input batch");+ let num_rows = input_batch.num_rows();++ // Assuming the input columns are+ // column[0]: customer_id / UTF8+ // column[1]: revenue: Int64+ let customer_id = input_batch+ .column(0)+ .as_any()+ .downcast_ref::<StringArray>()+ .expect("Column 0 is not customer_id");++ let revenue = input_batch+ .column(1)+ .as_any()+ .downcast_ref::<Int64Array>()+ .expect("Column 1 is not revenue");++ for row in 0..num_rows {+ self.add_row(customer_id.value(row), revenue.value(row));+ }+ }+ None => break,+ }+ }++ let mut revenue_builder = Int64Array::builder(self.top_values.len());+ let mut customer_id_builder = StringArray::builder(self.top_values.len());++ // make output by walking over the map backwards (so values are descending)+ for (revenue, customer_id) in self.top_values.iter().rev() {+ revenue_builder.append_value(*revenue)?;+ customer_id_builder.append_value(customer_id)?;+ }++ let record_batch = RecordBatch::try_new(+ self.schema().clone(),+ vec![+ Arc::new(customer_id_builder.finish()),+ Arc::new(revenue_builder.finish()),+ ],+ )?;++ self.done = true;+ Ok(Some(record_batch))+ }+}