alamb commented on code in PR #11082:
URL: https://github.com/apache/datafusion/pull/11082#discussion_r1650278660


##########
datafusion/sql/src/unparser/rewrite.rs:
##########
@@ -0,0 +1,96 @@
+// 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.
+
+use std::sync::Arc;
+
+use datafusion_common::{
+    tree_node::{Transformed, TransformedResult, TreeNode, TreeNodeRewriter},
+    Result,
+};
+use datafusion_expr::{Expr, LogicalPlan, Sort};
+
+/// Normalize the schema of a union plan to remove qualifiers from the schema 
fields.
+pub(super) struct NormalizeUnionSchema {}
+
+impl NormalizeUnionSchema {
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl TreeNodeRewriter for NormalizeUnionSchema {
+    type Node = LogicalPlan;
+
+    /// Invoked while traversing down the tree before any children are 
rewritten.
+    /// Default implementation returns the node as is and continues recursion.
+    fn f_down(&mut self, plan: LogicalPlan) -> 
Result<Transformed<LogicalPlan>> {
+        match plan {
+            LogicalPlan::Union(mut union) => {
+                let schema = match Arc::try_unwrap(union.schema) {
+                    Ok(inner) => inner,
+                    Err(schema) => (*schema).clone(),
+                };
+                let schema = schema.strip_qualifiers();
+
+                union.schema = Arc::new(schema);
+                Ok(Transformed::yes(LogicalPlan::Union(union)))
+            }
+            LogicalPlan::Sort(sort) => {
+                if !matches!(&*sort.input, LogicalPlan::Union(_)) {
+                    return Ok(Transformed::no(LogicalPlan::Sort(sort)));
+                }
+
+                let mut sort_expr_rewriter = NormalizeSortExprForUnion::new();
+                let sort_exprs: Vec<Expr> = sort
+                    .expr
+                    .into_iter()
+                    .map(|expr| expr.rewrite(&mut sort_expr_rewriter).data())
+                    .collect::<Result<Vec<_>>>()?;

Review Comment:
   You actually might be able to use `LogicalPlan::map_exprs` here instead of 
having to manually rewrite the sort_exprs too 🤔 
   
   
https://github.com/apache/datafusion/blob/c7ac8b8221229b307bba434390ce1d19b7fb9358/datafusion/expr/src/logical_plan/tree_node.rs#L538C12-L538C27



##########
datafusion/sql/src/unparser/rewrite.rs:
##########
@@ -0,0 +1,96 @@
+// 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.
+
+use std::sync::Arc;
+
+use datafusion_common::{
+    tree_node::{Transformed, TransformedResult, TreeNode, TreeNodeRewriter},
+    Result,
+};
+use datafusion_expr::{Expr, LogicalPlan, Sort};
+
+/// Normalize the schema of a union plan to remove qualifiers from the schema 
fields.
+pub(super) struct NormalizeUnionSchema {}
+
+impl NormalizeUnionSchema {
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl TreeNodeRewriter for NormalizeUnionSchema {

Review Comment:
   FYI because these two rewriters don't have state, you could also implement 
them using transform_up -- like
   
   ```rust
   let plan = plan.transform_up(|plan| {
       match plan {
               LogicalPlan::Union(mut union) => {
                   let schema = match Arc::try_unwrap(union.schema) {
                       Ok(inner) => inner,
                       Err(schema) => (*schema).clone(),
                   };
   ...
   })?.data
   ```



##########
datafusion/sql/src/unparser/rewrite.rs:
##########
@@ -0,0 +1,96 @@
+// 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.
+
+use std::sync::Arc;
+
+use datafusion_common::{
+    tree_node::{Transformed, TransformedResult, TreeNode, TreeNodeRewriter},
+    Result,
+};
+use datafusion_expr::{Expr, LogicalPlan, Sort};
+
+/// Normalize the schema of a union plan to remove qualifiers from the schema 
fields.
+pub(super) struct NormalizeUnionSchema {}
+
+impl NormalizeUnionSchema {
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl TreeNodeRewriter for NormalizeUnionSchema {
+    type Node = LogicalPlan;
+
+    /// Invoked while traversing down the tree before any children are 
rewritten.
+    /// Default implementation returns the node as is and continues recursion.
+    fn f_down(&mut self, plan: LogicalPlan) -> 
Result<Transformed<LogicalPlan>> {
+        match plan {
+            LogicalPlan::Union(mut union) => {
+                let schema = match Arc::try_unwrap(union.schema) {
+                    Ok(inner) => inner,
+                    Err(schema) => (*schema).clone(),
+                };
+                let schema = schema.strip_qualifiers();
+
+                union.schema = Arc::new(schema);
+                Ok(Transformed::yes(LogicalPlan::Union(union)))
+            }
+            LogicalPlan::Sort(sort) => {
+                if !matches!(&*sort.input, LogicalPlan::Union(_)) {
+                    return Ok(Transformed::no(LogicalPlan::Sort(sort)));
+                }
+
+                let mut sort_expr_rewriter = NormalizeSortExprForUnion::new();
+                let sort_exprs: Vec<Expr> = sort
+                    .expr
+                    .into_iter()
+                    .map(|expr| expr.rewrite(&mut sort_expr_rewriter).data())
+                    .collect::<Result<Vec<_>>>()?;

Review Comment:
   If you want, you could avoid the rewriter here too via 
   
   ```rust
    let sort_exprs: Vec<Expr> = sort
                       .expr
                       .into_iter()
                       .map_until_stop_and_collect(|expr| {
                           expr.transform_up(|expr| {
                               if let Expr::Column(mut col) = expr {
                                   col.relation = None;
                                   Ok(Transformed::yes(Expr::Column(col)))
                               } else {
                                   Ok(Transformed::no(expr))
                               }
                           })
                       })?.data;
   ```
   
   
   However, I will admit the rewriter keeps the logic nicely separated which is 
nice



##########
datafusion/sql/src/unparser/rewrite.rs:
##########
@@ -0,0 +1,96 @@
+// 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.
+
+use std::sync::Arc;
+
+use datafusion_common::{
+    tree_node::{Transformed, TransformedResult, TreeNode, TreeNodeRewriter},
+    Result,
+};
+use datafusion_expr::{Expr, LogicalPlan, Sort};
+
+/// Normalize the schema of a union plan to remove qualifiers from the schema 
fields.
+pub(super) struct NormalizeUnionSchema {}
+
+impl NormalizeUnionSchema {
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl TreeNodeRewriter for NormalizeUnionSchema {
+    type Node = LogicalPlan;
+
+    /// Invoked while traversing down the tree before any children are 
rewritten.
+    /// Default implementation returns the node as is and continues recursion.
+    fn f_down(&mut self, plan: LogicalPlan) -> 
Result<Transformed<LogicalPlan>> {
+        match plan {
+            LogicalPlan::Union(mut union) => {
+                let schema = match Arc::try_unwrap(union.schema) {
+                    Ok(inner) => inner,
+                    Err(schema) => (*schema).clone(),
+                };
+                let schema = schema.strip_qualifiers();
+
+                union.schema = Arc::new(schema);
+                Ok(Transformed::yes(LogicalPlan::Union(union)))
+            }
+            LogicalPlan::Sort(sort) => {

Review Comment:
   It might be worth documenting here why this very special pattern is verified 
-- specifically for the unparser



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to