Apache DataFusion SQL Query Engine
Add `FunctionRewrite` API, Move Array specific rewrites to `datafusion_functions_array` (#9583)
Andrew Lamba43938d3e3c4
diff --git a/datafusion/core/src/execution/context/mod.rs b/datafusion/core/src/execution/context/mod.rsindex 8bc65a0ca2..32c1c60ec5 100644--- a/datafusion/core/src/execution/context/mod.rs+++ b/datafusion/core/src/execution/context/mod.rs@@ -90,6 +90,7 @@ use uuid::Uuid;pub use datafusion_execution::config::SessionConfig;pub use datafusion_execution::TaskContext;pub use datafusion_expr::execution_props::ExecutionProps;+use datafusion_expr::expr_rewriter::FunctionRewrite;mod avro;mod csv;@@ -1285,6 +1286,13 @@ impl FunctionRegistry for SessionContext {fn register_udwf(&mut self, udwf: Arc<WindowUDF>) -> Result<Option<Arc<WindowUDF>>> {self.state.write().register_udwf(udwf)}++ fn register_function_rewrite(+ &mut self,+ rewrite: Arc<dyn FunctionRewrite + Send + Sync>,+ ) -> Result<()> {+ self.state.write().register_function_rewrite(rewrite)+ }}/// A planner used to add extensions to DataFusion logical and physical plans.@@ -2209,6 +2217,14 @@ impl FunctionRegistry for SessionState {}Ok(udwf)}++ fn register_function_rewrite(+ &mut self,+ rewrite: Arc<dyn FunctionRewrite + Send + Sync>,+ ) -> Result<()> {+ self.analyzer.add_function_rewrite(rewrite);+ Ok(())+ }}impl OptimizerConfig for SessionState {diff --git a/datafusion/execution/src/registry.rs b/datafusion/execution/src/registry.rsindex 5bc9a7a07b..f3714a11c2 100644--- a/datafusion/execution/src/registry.rs+++ b/datafusion/execution/src/registry.rs@@ -18,6 +18,7 @@//! FunctionRegistry traituse datafusion_common::{not_impl_err, plan_datafusion_err, Result};+use datafusion_expr::expr_rewriter::FunctionRewrite;use datafusion_expr::{AggregateUDF, ScalarUDF, UserDefinedLogicalNode, WindowUDF};use std::collections::HashMap;use std::{collections::HashSet, sync::Arc};@@ -93,6 +94,20 @@ pub trait FunctionRegistry {fn deregister_udwf(&mut self, _name: &str) -> Result<Option<Arc<WindowUDF>>> {not_impl_err!("Deregistering WindowUDF")}++ /// Registers a new [`FunctionRewrite`] with the registry.+ ///+ /// `FunctionRewrite` rules are used to rewrite certain / operators in the+ /// logical plan to function calls. For example `a || b` might be written to+ /// `array_concat(a, b)`.+ ///+ /// This allows the behavior of operators to be customized by the user.+ fn register_function_rewrite(+ &mut self,+ _rewrite: Arc<dyn FunctionRewrite + Send + Sync>,+ ) -> Result<()> {+ not_impl_err!("Registering FunctionRewrite")+ }}/// Serializer and deserializer registry for extensions like [UserDefinedLogicalNode].diff --git a/datafusion/expr/src/expr_rewriter/mod.rs b/datafusion/expr/src/expr_rewriter/mod.rsindex cd9a8344de..357b1aed7d 100644--- a/datafusion/expr/src/expr_rewriter/mod.rs+++ b/datafusion/expr/src/expr_rewriter/mod.rs@@ -25,6 +25,7 @@ use crate::expr::{Alias, Unnest};use crate::logical_plan::Projection;use crate::{Expr, ExprSchemable, LogicalPlan, LogicalPlanBuilder};+use datafusion_common::config::ConfigOptions;use datafusion_common::tree_node::{Transformed, TransformedResult, TreeNode, TreeNodeRewriter,};@@ -33,6 +34,30 @@ use datafusion_common::{Column, DFSchema, Result};mod order_by;pub use order_by::rewrite_sort_cols_by_aggs;+/// Trait for rewriting [`Expr`]s into function calls.+///+/// This trait is used with `FunctionRegistry::register_function_rewrite` to+/// to evaluating `Expr`s using functions that may not be built in to DataFusion+///+/// For example, concatenating arrays `a || b` is represented as+/// `Operator::ArrowAt`, but can be implemented by calling a function+/// `array_concat` from the `functions-array` crate.+pub trait FunctionRewrite {+ /// Return a human readable name for this rewrite+ fn name(&self) -> &str;++ /// Potentially rewrite `expr` to some other expression+ ///+ /// Note that recursion is handled by the caller -- this method should only+ /// handle `expr`, not recurse to its children.+ fn rewrite(+ &self,+ expr: Expr,+ schema: &DFSchema,+ config: &ConfigOptions,+ ) -> Result<Transformed<Expr>>;+}+/// Recursively call [`Column::normalize_with_schemas`] on all [`Column`] expressions/// in the `expr` expression tree.pub fn normalize_col(expr: Expr, plan: &LogicalPlan) -> Result<Expr> {diff --git a/datafusion/functions-array/src/lib.rs b/datafusion/functions-array/src/lib.rsindex 31b971a422..a932e7d7a5 100644--- a/datafusion/functions-array/src/lib.rs+++ b/datafusion/functions-array/src/lib.rs@@ -32,6 +32,7 @@ mod array_has;mod concat;mod kernels;mod make_array;+mod rewrite;mod udf;mod utils;@@ -96,5 +97,7 @@ pub fn register_all(registry: &mut dyn FunctionRegistry) -> Result<()> {}Ok(()) as Result<()>})?;+ registry.register_function_rewrite(Arc::new(rewrite::ArrayFunctionRewriter {}))?;+Ok(())}diff --git a/datafusion/functions-array/src/rewrite.rs b/datafusion/functions-array/src/rewrite.rsnew file mode 100644index 0000000000..368fad41af--- /dev/null+++ b/datafusion/functions-array/src/rewrite.rs@@ -0,0 +1,211 @@+// 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.++//! Rewrites for using Array Functions++use crate::concat::{array_append, array_concat};+use crate::expr_fn::{array_has_all, array_prepend};+use datafusion_common::config::ConfigOptions;+use datafusion_common::tree_node::Transformed;+use datafusion_common::utils::list_ndims;+use datafusion_common::{Column, DFSchema};+use datafusion_expr::expr::ScalarFunction;+use datafusion_expr::expr_rewriter::FunctionRewrite;+use datafusion_expr::{+ BinaryExpr, BuiltinScalarFunction, Expr, GetFieldAccess, GetIndexedField, Operator,+};++/// Rewrites expressions into function calls to array functions+pub(crate) struct ArrayFunctionRewriter {}++impl FunctionRewrite for ArrayFunctionRewriter {+ fn name(&self) -> &str {+ "FunctionRewrite"+ }++ fn rewrite(+ &self,+ expr: Expr,+ schema: &DFSchema,+ _config: &ConfigOptions,+ ) -> datafusion_common::Result<Transformed<Expr>> {+ let transformed = match expr {+ // array1 @> array2 -> array_has_all(array1, array2)+ Expr::BinaryExpr(BinaryExpr { left, op, right })+ if op == Operator::AtArrow+ && is_func(&left, "make_array")+ && is_func(&right, "make_array") =>+ {+ Transformed::yes(array_has_all(*left, *right))+ }++ // array1 <@ array2 -> array_has_all(array2, array1)+ Expr::BinaryExpr(BinaryExpr { left, op, right })+ if op == Operator::ArrowAt+ && is_func(&left, "make_array")+ && is_func(&right, "make_array") =>+ {+ Transformed::yes(array_has_all(*right, *left))+ }++ // Column cases:+ // 1) array_prepend/append/concat || column+ Expr::BinaryExpr(BinaryExpr { left, op, right })+ if op == Operator::StringConcat+ && is_one_of_func(+ &left,+ &["array_append", "array_prepend", "array_concat"],+ )+ && as_col(&right).is_some() =>+ {+ let c = as_col(&right).unwrap();+ let d = schema.field_from_column(c)?.data_type();+ let ndim = list_ndims(d);+ match ndim {+ 0 => Transformed::yes(array_append(*left, *right)),+ _ => Transformed::yes(array_concat(vec![*left, *right])),+ }+ }+ // 2) select column1 || column2+ Expr::BinaryExpr(BinaryExpr { left, op, right })+ if op == Operator::StringConcat+ && as_col(&left).is_some()+ && as_col(&right).is_some() =>+ {+ let c1 = as_col(&left).unwrap();+ let c2 = as_col(&right).unwrap();+ let d1 = schema.field_from_column(c1)?.data_type();+ let d2 = schema.field_from_column(c2)?.data_type();+ let ndim1 = list_ndims(d1);+ let ndim2 = list_ndims(d2);+ match (ndim1, ndim2) {+ (0, _) => Transformed::yes(array_prepend(*left, *right)),+ (_, 0) => Transformed::yes(array_append(*left, *right)),+ _ => Transformed::yes(array_concat(vec![*left, *right])),+ }+ }++ // Chain concat operator (a || b) || array,+ // (array_concat, array_append, array_prepend) || array -> array concat+ Expr::BinaryExpr(BinaryExpr { left, op, right })+ if op == Operator::StringConcat+ && is_one_of_func(+ &left,+ &["array_append", "array_prepend", "array_concat"],+ )+ && is_func(&right, "make_array") =>+ {+ Transformed::yes(array_concat(vec![*left, *right]))+ }++ // Chain concat operator (a || b) || scalar,+ // (array_concat, array_append, array_prepend) || scalar -> array append+ Expr::BinaryExpr(BinaryExpr { left, op, right })+ if op == Operator::StringConcat+ && is_one_of_func(+ &left,+ &["array_append", "array_prepend", "array_concat"],+ ) =>+ {+ Transformed::yes(array_append(*left, *right))+ }++ // array || array -> array concat+ Expr::BinaryExpr(BinaryExpr { left, op, right })+ if op == Operator::StringConcat+ && is_func(&left, "make_array")+ && is_func(&right, "make_array") =>+ {+ Transformed::yes(array_concat(vec![*left, *right]))+ }++ // array || scalar -> array append+ Expr::BinaryExpr(BinaryExpr { left, op, right })+ if op == Operator::StringConcat && is_func(&left, "make_array") =>+ {+ Transformed::yes(array_append(*left, *right))+ }++ // scalar || array -> array prepend+ Expr::BinaryExpr(BinaryExpr { left, op, right })+ if op == Operator::StringConcat && is_func(&right, "make_array") =>+ {+ Transformed::yes(array_prepend(*left, *right))+ }++ // expr[idx] ==> array_element(expr, idx)+ Expr::GetIndexedField(GetIndexedField {+ expr,+ field: GetFieldAccess::ListIndex { key },+ }) => {+ let args = vec![*expr, *key];+ Transformed::yes(Expr::ScalarFunction(ScalarFunction::new(+ BuiltinScalarFunction::ArrayElement,+ args,+ )))+ }++ // expr[start, stop, stride] ==> array_slice(expr, start, stop, stride)+ Expr::GetIndexedField(GetIndexedField {+ expr,+ field:+ GetFieldAccess::ListRange {+ start,+ stop,+ stride,+ },+ }) => {+ let args = vec![*expr, *start, *stop, *stride];+ Transformed::yes(Expr::ScalarFunction(ScalarFunction::new(+ BuiltinScalarFunction::ArraySlice,+ args,+ )))+ }++ _ => Transformed::no(expr),+ };+ Ok(transformed)+ }+}++/// Returns true if expr is a function call to the specified named function.+/// Returns false otherwise.+fn is_func(expr: &Expr, func_name: &str) -> bool {+ let Expr::ScalarFunction(ScalarFunction { func_def, args: _ }) = expr else {+ return false;+ };++ func_def.name() == func_name+}++/// Returns true if expr is a function call with one of the specified names+fn is_one_of_func(expr: &Expr, func_names: &[&str]) -> bool {+ let Expr::ScalarFunction(ScalarFunction { func_def, args: _ }) = expr else {+ return false;+ };++ func_names.contains(&func_def.name())+}++/// returns Some(col) if this is Expr::Column+fn as_col(expr: &Expr) -> Option<&Column> {+ if let Expr::Column(c) = expr {+ Some(c)+ } else {+ None+ }+}diff --git a/datafusion/optimizer/src/analyzer/function_rewrite.rs b/datafusion/optimizer/src/analyzer/function_rewrite.rsnew file mode 100644index 0000000000..15b5265df9--- /dev/null+++ b/datafusion/optimizer/src/analyzer/function_rewrite.rs@@ -0,0 +1,120 @@+// 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.++//! [`ApplyFunctionRewrites`] to replace `Expr`s with function calls (e.g `||` to array_concat`)++use super::AnalyzerRule;+use datafusion_common::config::ConfigOptions;+use datafusion_common::tree_node::{Transformed, TreeNodeRewriter};+use datafusion_common::{DFSchema, Result};+use datafusion_expr::expr_rewriter::{rewrite_preserving_name, FunctionRewrite};+use datafusion_expr::utils::merge_schema;+use datafusion_expr::{Expr, LogicalPlan};+use std::sync::Arc;++/// Analyzer rule that invokes [`FunctionRewrite`]s on expressions+#[derive(Default)]+pub struct ApplyFunctionRewrites {+ /// Expr --> Function writes to apply+ function_rewrites: Vec<Arc<dyn FunctionRewrite + Send + Sync>>,+}++impl ApplyFunctionRewrites {+ pub fn new(function_rewrites: Vec<Arc<dyn FunctionRewrite + Send + Sync>>) -> Self {+ Self { function_rewrites }+ }+}++impl AnalyzerRule for ApplyFunctionRewrites {+ fn name(&self) -> &str {+ "apply_function_rewrites"+ }++ fn analyze(&self, plan: LogicalPlan, options: &ConfigOptions) -> Result<LogicalPlan> {+ self.analyze_internal(&plan, options)+ }+}++impl ApplyFunctionRewrites {+ fn analyze_internal(+ &self,+ plan: &LogicalPlan,+ options: &ConfigOptions,+ ) -> Result<LogicalPlan> {+ // optimize child plans first+ let new_inputs = plan+ .inputs()+ .iter()+ .map(|p| self.analyze_internal(p, options))+ .collect::<Result<Vec<_>>>()?;++ // get schema representing all available input fields. This is used for data type+ // resolution only, so order does not matter here+ let mut schema = merge_schema(new_inputs.iter().collect());++ if let LogicalPlan::TableScan(ts) = plan {+ let source_schema =+ DFSchema::try_from_qualified_schema(&ts.table_name, &ts.source.schema())?;+ schema.merge(&source_schema);+ }++ let mut expr_rewrite = OperatorToFunctionRewriter {+ function_rewrites: &self.function_rewrites,+ options,+ schema: &schema,+ };++ let new_expr = plan+ .expressions()+ .into_iter()+ .map(|expr| {+ // ensure names don't change:+ // https://github.com/apache/arrow-datafusion/issues/3555+ rewrite_preserving_name(expr, &mut expr_rewrite)+ })+ .collect::<Result<Vec<_>>>()?;++ plan.with_new_exprs(new_expr, new_inputs)+ }+}+struct OperatorToFunctionRewriter<'a> {+ function_rewrites: &'a [Arc<dyn FunctionRewrite + Send + Sync>],+ options: &'a ConfigOptions,+ schema: &'a DFSchema,+}++impl<'a> TreeNodeRewriter for OperatorToFunctionRewriter<'a> {+ type Node = Expr;++ fn f_up(&mut self, mut expr: Expr) -> Result<Transformed<Expr>> {+ // apply transforms one by one+ let mut transformed = false;+ for rewriter in self.function_rewrites.iter() {+ let result = rewriter.rewrite(expr, self.schema, self.options)?;+ if result.transformed {+ transformed = true;+ }+ expr = result.data+ }++ Ok(if transformed {+ Transformed::yes(expr)+ } else {+ Transformed::no(expr)+ })+ }+}diff --git a/datafusion/optimizer/src/analyzer/mod.rs b/datafusion/optimizer/src/analyzer/mod.rsindex d685212841..ae61aea997 100644--- a/datafusion/optimizer/src/analyzer/mod.rs+++ b/datafusion/optimizer/src/analyzer/mod.rs@@ -15,33 +15,33 @@// specific language governing permissions and limitations// under the License.-pub mod count_wildcard_rule;-pub mod inline_table_scan;-pub mod rewrite_expr;-pub mod subquery;-pub mod type_coercion;+use std::sync::Arc;-use crate::analyzer::count_wildcard_rule::CountWildcardRule;-use crate::analyzer::inline_table_scan::InlineTableScan;+use log::debug;-use crate::analyzer::subquery::check_subquery_expr;-use crate::analyzer::type_coercion::TypeCoercion;-use crate::utils::log_plan;use datafusion_common::config::ConfigOptions;use datafusion_common::instant::Instant;use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};use datafusion_common::{DataFusionError, Result};use datafusion_expr::expr::Exists;use datafusion_expr::expr::InSubquery;+use datafusion_expr::expr_rewriter::FunctionRewrite;use datafusion_expr::utils::inspect_expr_pre;use datafusion_expr::{Expr, LogicalPlan};-use log::debug;-use std::sync::Arc;-#[cfg(feature = "array_expressions")]-use datafusion_functions_array::expr_fn::array_has_all;+use crate::analyzer::count_wildcard_rule::CountWildcardRule;+use crate::analyzer::inline_table_scan::InlineTableScan;+use crate::analyzer::subquery::check_subquery_expr;+use crate::analyzer::type_coercion::TypeCoercion;+use crate::utils::log_plan;++use self::function_rewrite::ApplyFunctionRewrites;-use self::rewrite_expr::OperatorToFunction;+pub mod count_wildcard_rule;+pub mod function_rewrite;+pub mod inline_table_scan;+pub mod subquery;+pub mod type_coercion;/// [`AnalyzerRule`]s transform [`LogicalPlan`]s in some way to make/// the plan valid prior to the rest of the DataFusion optimization process.@@ -65,9 +65,15 @@ pub trait AnalyzerRule {/// A human readable name for this analyzer rulefn name(&self) -> &str;}+/// A rule-based Analyzer.+///+/// An `Analyzer` transforms a `LogicalPlan`+/// prior to the rest of the DataFusion optimization process.#[derive(Clone)]pub struct Analyzer {+ /// Expr --> Function writes to apply prior to analysis passes+ pub function_rewrites: Vec<Arc<dyn FunctionRewrite + Send + Sync>>,/// All rules to applypub rules: Vec<Arc<dyn AnalyzerRule + Send + Sync>>,}@@ -83,9 +89,6 @@ impl Analyzer {pub fn new() -> Self {let rules: Vec<Arc<dyn AnalyzerRule + Send + Sync>> = vec![Arc::new(InlineTableScan::new()),- // OperatorToFunction should be run before TypeCoercion, since it rewrite based on the argument types (List or Scalar),- // and TypeCoercion may cast the argument types from Scalar to List.- Arc::new(OperatorToFunction::new()),Arc::new(TypeCoercion::new()),Arc::new(CountWildcardRule::new()),];@@ -94,7 +97,18 @@ impl Analyzer {/// Create a new analyzer with the given rulespub fn with_rules(rules: Vec<Arc<dyn AnalyzerRule + Send + Sync>>) -> Self {- Self { rules }+ Self {+ function_rewrites: vec![],+ rules,+ }+ }++ /// Add a function rewrite rule+ pub fn add_function_rewrite(+ &mut self,+ rewrite: Arc<dyn FunctionRewrite + Send + Sync>,+ ) {+ self.function_rewrites.push(rewrite);}/// Analyze the logical plan by applying analyzer rules, and@@ -111,8 +125,18 @@ impl Analyzer {let start_time = Instant::now();let mut new_plan = plan.clone();+ // Create an analyzer pass that rewrites `Expr`s to function_calls, as+ // appropriate.+ //+ // Note this is run before all other rules since it rewrites based on+ // the argument types (List or Scalar), and TypeCoercion may cast the+ // argument types from Scalar to List.+ let expr_to_function: Arc<dyn AnalyzerRule + Send + Sync> =+ Arc::new(ApplyFunctionRewrites::new(self.function_rewrites.clone()));+ let rules = std::iter::once(&expr_to_function).chain(self.rules.iter());+// TODO add common rule executor for Analyzer and Optimizer- for rule in &self.rules {+ for rule in rules {new_plan = rule.analyze(new_plan, config).map_err(|e| {DataFusionError::Context(rule.name().to_string(), Box::new(e))})?;diff --git a/datafusion/optimizer/src/analyzer/rewrite_expr.rs b/datafusion/optimizer/src/analyzer/rewrite_expr.rsdeleted file mode 100644index 99578e9118..0000000000--- a/datafusion/optimizer/src/analyzer/rewrite_expr.rs+++ /dev/null@@ -1,353 +0,0 @@-// 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.--//! Analyzer rule for to replace operators with function calls (e.g `||` to array_concat`)--#[cfg(feature = "array_expressions")]-use std::sync::Arc;--use super::AnalyzerRule;--use datafusion_common::config::ConfigOptions;-use datafusion_common::tree_node::{Transformed, TreeNodeRewriter};-#[cfg(feature = "array_expressions")]-use datafusion_common::{utils::list_ndims, DFSchemaRef};-use datafusion_common::{DFSchema, Result};-use datafusion_expr::expr::ScalarFunction;-use datafusion_expr::expr_rewriter::rewrite_preserving_name;-use datafusion_expr::utils::merge_schema;-use datafusion_expr::BuiltinScalarFunction;-use datafusion_expr::GetFieldAccess;-use datafusion_expr::GetIndexedField;-#[cfg(feature = "array_expressions")]-use datafusion_expr::{BinaryExpr, Operator, ScalarFunctionDefinition};-use datafusion_expr::{Expr, LogicalPlan};-#[cfg(feature = "array_expressions")]-use datafusion_functions_array::expr_fn::{array_append, array_concat, array_prepend};--#[derive(Default)]-pub struct OperatorToFunction {}--impl OperatorToFunction {- pub fn new() -> Self {- Self {}- }-}--impl AnalyzerRule for OperatorToFunction {- fn name(&self) -> &str {- "operator_to_function"- }-- fn analyze(&self, plan: LogicalPlan, _: &ConfigOptions) -> Result<LogicalPlan> {- analyze_internal(&plan)- }-}--fn analyze_internal(plan: &LogicalPlan) -> Result<LogicalPlan> {- // optimize child plans first- let new_inputs = plan- .inputs()- .iter()- .map(|p| analyze_internal(p))- .collect::<Result<Vec<_>>>()?;-- // get schema representing all available input fields. This is used for data type- // resolution only, so order does not matter here- let mut schema = merge_schema(new_inputs.iter().collect());-- if let LogicalPlan::TableScan(ts) = plan {- let source_schema =- DFSchema::try_from_qualified_schema(&ts.table_name, &ts.source.schema())?;- schema.merge(&source_schema);- }-- let mut expr_rewrite = OperatorToFunctionRewriter {- #[cfg(feature = "array_expressions")]- schema: Arc::new(schema),- };-- let new_expr = plan- .expressions()- .into_iter()- .map(|expr| {- // ensure names don't change:- // https://github.com/apache/arrow-datafusion/issues/3555- rewrite_preserving_name(expr, &mut expr_rewrite)- })- .collect::<Result<Vec<_>>>()?;-- plan.with_new_exprs(new_expr, new_inputs)-}--pub(crate) struct OperatorToFunctionRewriter {- #[cfg(feature = "array_expressions")]- pub(crate) schema: DFSchemaRef,-}--impl TreeNodeRewriter for OperatorToFunctionRewriter {- type Node = Expr;-- fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {- #[cfg(feature = "array_expressions")]- if let Expr::BinaryExpr(BinaryExpr {- ref left,- op,- ref right,- }) = expr- {- if let Some(expr) = rewrite_array_concat_operator_to_func_for_column(- left.as_ref(),- op,- right.as_ref(),- self.schema.as_ref(),- )?- .or_else(|| {- rewrite_array_concat_operator_to_func(left.as_ref(), op, right.as_ref())- }) {- // Convert &Box<Expr> -> Expr- return Ok(Transformed::yes(expr));- }-- // TODO: change OperatorToFunction to OperatoToArrayFunction and configure it with array_expressions feature- // after other array functions are udf-based- #[cfg(feature = "array_expressions")]- if let Some(expr) = rewrite_array_has_all_operator_to_func(left, op, right) {- return Ok(Transformed::yes(expr));- }- }-- if let Expr::GetIndexedField(GetIndexedField {- ref expr,- ref field,- }) = expr- {- match field {- GetFieldAccess::ListIndex { ref key } => {- let expr = *expr.clone();- let key = *key.clone();- let args = vec![expr, key];- return Ok(Transformed::yes(Expr::ScalarFunction(- ScalarFunction::new(BuiltinScalarFunction::ArrayElement, args),- )));- }- GetFieldAccess::ListRange {- start,- stop,- stride,- } => {- let expr = *expr.clone();- let start = *start.clone();- let stop = *stop.clone();- let stride = *stride.clone();- let args = vec![expr, start, stop, stride];- return Ok(Transformed::yes(Expr::ScalarFunction(- ScalarFunction::new(BuiltinScalarFunction::ArraySlice, args),- )));- }- _ => {}- }- }-- Ok(Transformed::no(expr))- }-}--// Note This rewrite is only done if the built in DataFusion `array_expressions` feature is enabled.-// Even if users implement their own array functions, those functions are not equal to the DataFusion-// udf based array functions, so this rewrite is not corrrect-#[cfg(feature = "array_expressions")]-fn rewrite_array_has_all_operator_to_func(- left: &Expr,- op: Operator,- right: &Expr,-) -> Option<Expr> {- use super::array_has_all;-- if op != Operator::AtArrow && op != Operator::ArrowAt {- return None;- }-- match (left, right) {- // array1 @> array2 -> array_has_all(array1, array2)- // array1 <@ array2 -> array_has_all(array2, array1)- (- Expr::ScalarFunction(ScalarFunction {- func_def: ScalarFunctionDefinition::UDF(left_fun),- args: _left_args,- }),- Expr::ScalarFunction(ScalarFunction {- func_def: ScalarFunctionDefinition::UDF(right_fun),- args: _right_args,- }),- ) if left_fun.name() == "make_array" && right_fun.name() == "make_array" => {- let left = left.clone();- let right = right.clone();-- let expr = if let Operator::ArrowAt = op {- array_has_all(right, left)- } else {- array_has_all(left, right)- };- Some(expr)- }- _ => None,- }-}--/// Summary of the logic below:-///-/// 1) array || array -> array concat-///-/// 2) array || scalar -> array append-///-/// 3) scalar || array -> array prepend-///-/// 4) (arry concat, array append, array prepend) || array -> array concat-///-/// 5) (arry concat, array append, array prepend) || scalar -> array append-#[cfg(feature = "array_expressions")]-fn rewrite_array_concat_operator_to_func(- left: &Expr,- op: Operator,- right: &Expr,-) -> Option<Expr> {- // Convert `Array StringConcat Array` to ScalarFunction::ArrayConcat-- if op != Operator::StringConcat {- return None;- }-- match (left, right) {- // Chain concat operator (a || b) || array,- // (arry concat, array append, array prepend) || array -> array concat- (- Expr::ScalarFunction(ScalarFunction {- func_def: ScalarFunctionDefinition::UDF(left_fun),- args: _left_args,- }),- Expr::ScalarFunction(ScalarFunction {- func_def: ScalarFunctionDefinition::UDF(right_fun),- args: _right_args,- }),- ) if ["array_append", "array_prepend", "array_concat"]- .contains(&left_fun.name())- && right_fun.name() == "make_array" =>- {- Some(array_concat(vec![left.clone(), right.clone()]))- }- // Chain concat operator (a || b) || scalar,- // (arry concat, array append, array prepend) || scalar -> array append- (- Expr::ScalarFunction(ScalarFunction {- func_def: ScalarFunctionDefinition::UDF(left_fun),- args: _left_args,- }),- _scalar,- ) if ["array_append", "array_prepend", "array_concat"]- .contains(&left_fun.name()) =>- {- Some(array_append(left.clone(), right.clone()))- }- // array || array -> array concat- (- Expr::ScalarFunction(ScalarFunction {- func_def: ScalarFunctionDefinition::UDF(left_fun),- args: _left_args,- }),- Expr::ScalarFunction(ScalarFunction {- func_def: ScalarFunctionDefinition::UDF(right_fun),- args: _right_args,- }),- ) if left_fun.name() == "make_array" && right_fun.name() == "make_array" => {- Some(array_concat(vec![left.clone(), right.clone()]))- }- // array || scalar -> array append- (- Expr::ScalarFunction(ScalarFunction {- func_def: ScalarFunctionDefinition::UDF(left_fun),- args: _left_args,- }),- _right_scalar,- ) if left_fun.name() == "make_array" => {- Some(array_append(left.clone(), right.clone()))- }- // scalar || array -> array prepend- (- _left_scalar,- Expr::ScalarFunction(ScalarFunction {- func_def: ScalarFunctionDefinition::UDF(right_fun),- args: _right_args,- }),- ) if right_fun.name() == "make_array" => {- Some(array_prepend(left.clone(), right.clone()))- }-- _ => None,- }-}--/// Summary of the logic below:-///-/// 1) (arry concat, array append, array prepend) || column -> (array append, array concat)-///-/// 2) column1 || column2 -> (array prepend, array append, array concat)-#[cfg(feature = "array_expressions")]-fn rewrite_array_concat_operator_to_func_for_column(- left: &Expr,- op: Operator,- right: &Expr,- schema: &DFSchema,-) -> Result<Option<Expr>> {- if op != Operator::StringConcat {- return Ok(None);- }-- match (left, right) {- // Column cases:- // 1) array_prepend/append/concat || column- (- Expr::ScalarFunction(ScalarFunction {- func_def: ScalarFunctionDefinition::UDF(left_fun),- args: _left_args,- }),- Expr::Column(c),- ) if ["array_append", "array_prepend", "array_concat"]- .contains(&left_fun.name()) =>- {- let d = schema.field_from_column(c)?.data_type();- let ndim = list_ndims(d);- match ndim {- 0 => Ok(Some(array_append(left.clone(), right.clone()))),- _ => Ok(Some(array_concat(vec![left.clone(), right.clone()]))),- }- }- // 2) select column1 || column2- (Expr::Column(c1), Expr::Column(c2)) => {- let d1 = schema.field_from_column(c1)?.data_type();- let d2 = schema.field_from_column(c2)?.data_type();- let ndim1 = list_ndims(d1);- let ndim2 = list_ndims(d2);- match (ndim1, ndim2) {- (0, _) => Ok(Some(array_prepend(left.clone(), right.clone()))),- (_, 0) => Ok(Some(array_append(left.clone(), right.clone()))),- _ => Ok(Some(array_concat(vec![left.clone(), right.clone()]))),- }- }- _ => Ok(None),- }-}diff --git a/datafusion/sqllogictest/test_files/explain.slt b/datafusion/sqllogictest/test_files/explain.sltindex 64152f0302..b7ad36dace 100644--- a/datafusion/sqllogictest/test_files/explain.slt+++ b/datafusion/sqllogictest/test_files/explain.slt@@ -179,8 +179,8 @@ EXPLAIN VERBOSE SELECT a, b, c FROM simple_explain_testinitial_logical_planProjection: simple_explain_test.a, simple_explain_test.b, simple_explain_test.c--TableScan: simple_explain_test+logical_plan after apply_function_rewrites SAME TEXT AS ABOVElogical_plan after inline_table_scan SAME TEXT AS ABOVE-logical_plan after operator_to_function SAME TEXT AS ABOVElogical_plan after type_coercion SAME TEXT AS ABOVElogical_plan after count_wildcard_rule SAME TEXT AS ABOVEanalyzed_logical_plan SAME TEXT AS ABOVE