You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2022/10/26 14:41:31 UTC
[GitHub] [arrow-datafusion] mingmwang opened a new pull request, #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
mingmwang opened a new pull request, #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969
# Which issue does this PR close?
<!--
We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
-->
Partially Closes #3854.
# Rationale for this change
<!--
Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
-->
# What changes are included in this PR?
<!--
There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
-->
1. Implement `PartialEq<dyn Any>` for `PhysicalExpr`
2. Add `PhysicalExpr::children()` and `PhysicalExpr::new_with_children()`
3. Add `TreeNodeRewritable` Trait for `PhysicalExpr` rewriting
# Are there any user-facing changes?
<!--
If there are user-facing changes then we may require documentation to be updated before approving the PR.
-->
<!--
If there are any breaking changes to public APIs, please add the `api change` label.
-->
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] mingmwang commented on pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
mingmwang commented on PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#issuecomment-1293727935
@alamb Please help to take a look.
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
mingmwang commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1006956914
##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -52,16 +54,27 @@ use datafusion_expr::ColumnarValue;
static OPTIMIZER_INSET_THRESHOLD: usize = 30;
/// InList
-#[derive(Debug)]
pub struct InListExpr {
expr: Arc<dyn PhysicalExpr>,
list: Vec<Arc<dyn PhysicalExpr>>,
negated: bool,
set: Option<InSet>,
+ input_schema: Schema,
Review Comment:
This is because `InListExpr::new()` method need the schema.
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] Dandandan commented on pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
Dandandan commented on PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#issuecomment-1295304927
No problems merging this in. The overall goal seems great to me, but not much time now to go over the code.
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] isidentical commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
isidentical commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1008265924
##########
datafusion/physical-expr/src/expressions/cast.rs:
##########
@@ -93,6 +94,36 @@ impl PhysicalExpr for CastExpr {
let value = self.expr.evaluate(batch)?;
cast_column(&value, &self.cast_type, &self.cast_options)
}
+
+ fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(CastExpr::new(
+ children[0].clone(),
+ self.cast_type.clone(),
+ CastOptions {
+ safe: self.cast_options.safe,
+ },
+ )))
+ }
+}
+
+impl PartialEq<dyn Any> for CastExpr {
+ fn eq(&self, other: &dyn Any) -> bool {
+ down_cast_any_ref(other)
+ .downcast_ref::<Self>()
+ .map(|x| {
+ self.expr.eq(&x.expr)
+ && self.cast_type == x.cast_type
+ && self.cast_options.safe == x.cast_options.safe
Review Comment:
Nevermind, it seems like we can't change it here. Created a [ticket on arrow-rs](https://github.com/apache/arrow-rs/issues/2966).
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] alamb merged pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
alamb merged PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] alamb commented on pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
alamb commented on PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#issuecomment-1292680129
I plan to review this carefully tomorrow
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
mingmwang commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1007050815
##########
datafusion/physical-expr/src/physical_expr.rs:
##########
@@ -128,6 +137,232 @@ impl PhysicalExprStats for BasicExpressionStats {
}
}
+/// a Trait for marking tree node types that are rewritable
+pub trait TreeNodeRewritable: Clone {
+ /// Transform the tree node using the given [TreeNodeRewriter]
+ /// It performs a depth first walk of an node and its children.
+ ///
+ /// For an node tree such as
+ /// ```text
+ /// ParentNode
+ /// left: ChildNode1
+ /// right: ChildNode2
+ /// ```
+ ///
+ /// The nodes are visited using the following order
+ /// ```text
+ /// pre_visit(ParentNode)
Review Comment:
Can I keep the current naming ? As you had mentioned, they do not match.
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] isidentical commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
isidentical commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1008265924
##########
datafusion/physical-expr/src/expressions/cast.rs:
##########
@@ -93,6 +94,36 @@ impl PhysicalExpr for CastExpr {
let value = self.expr.evaluate(batch)?;
cast_column(&value, &self.cast_type, &self.cast_options)
}
+
+ fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(CastExpr::new(
+ children[0].clone(),
+ self.cast_type.clone(),
+ CastOptions {
+ safe: self.cast_options.safe,
+ },
+ )))
+ }
+}
+
+impl PartialEq<dyn Any> for CastExpr {
+ fn eq(&self, other: &dyn Any) -> bool {
+ down_cast_any_ref(other)
+ .downcast_ref::<Self>()
+ .map(|x| {
+ self.expr.eq(&x.expr)
+ && self.cast_type == x.cast_type
+ && self.cast_options.safe == x.cast_options.safe
Review Comment:
Nevermind, it seems like we can't change it here. Created a ticket on arrow-rs.
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] isidentical commented on pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
isidentical commented on PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#issuecomment-1295249585
Only a minor testing suggestion, but other than that at least a brief overview of the general logic on comparisons and utilities looks great to me.
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] alamb commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
alamb commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1008385320
##########
datafusion/physical-expr/src/expressions/cast.rs:
##########
@@ -93,6 +94,36 @@ impl PhysicalExpr for CastExpr {
let value = self.expr.evaluate(batch)?;
cast_column(&value, &self.cast_type, &self.cast_options)
}
+
+ fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(CastExpr::new(
+ children[0].clone(),
+ self.cast_type.clone(),
+ CastOptions {
+ safe: self.cast_options.safe,
+ },
+ )))
+ }
+}
+
+impl PartialEq<dyn Any> for CastExpr {
+ fn eq(&self, other: &dyn Any) -> bool {
+ down_cast_any_ref(other)
+ .downcast_ref::<Self>()
+ .map(|x| {
+ self.expr.eq(&x.expr)
+ && self.cast_type == x.cast_type
Review Comment:
Added a todo note in https://github.com/apache/arrow-datafusion/pull/4012
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
mingmwang commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1006891316
##########
datafusion/physical-expr/src/expressions/case.rs:
##########
@@ -286,6 +290,89 @@ impl PhysicalExpr for CaseExpr {
self.case_when_no_expr(batch)
}
}
+
+ fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ let mut chileren = vec![];
+ match &self.expr {
+ Some(expr) => chileren.push(expr.clone()),
+ None => chileren.push(Arc::new(NoOp::new())),
+ }
+ self.when_then_expr.iter().for_each(|(cond, value)| {
+ chileren.push(cond.clone());
+ chileren.push(value.clone());
+ });
+
+ match &self.else_expr {
+ Some(expr) => chileren.push(expr.clone()),
+ None => chileren.push(Arc::new(NoOp::new())),
+ }
+ chileren
+ }
+
+ // For physical CaseExpr, we do not allow modifying children size
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ if children.len() != self.children().len() {
+ Err(DataFusionError::Internal(
+ "CaseExpr: Wrong number of children".to_string(),
+ ))
+ } else {
+ assert_eq!(children.len() % 2, 0);
+ let expr = match children[0].clone().as_any().downcast_ref::<NoOp>() {
+ Some(_) => None,
+ _ => Some(children[0].clone()),
+ };
+ let else_expr = match children[children.len() - 1]
+ .clone()
+ .as_any()
+ .downcast_ref::<NoOp>()
+ {
+ Some(_) => None,
+ _ => Some(children[children.len() - 1].clone()),
+ };
+
+ let branches = children[1..children.len() - 1].to_vec();
+ let mut when_then_expr: Vec<WhenThen> = vec![];
+ for (prev, next) in branches.into_iter().tuples() {
+ when_then_expr.push((prev, next));
+ }
+ Ok(Arc::new(CaseExpr::try_new(
+ expr,
+ when_then_expr,
+ else_expr,
+ )?))
+ }
+ }
+}
+
+impl PartialEq<dyn Any> for CaseExpr {
+ fn eq(&self, other: &dyn Any) -> bool {
+ down_cast_any_ref(other)
+ .downcast_ref::<Self>()
+ .map(|x| {
+ let expr_eq = match (&self.expr, &x.expr) {
+ (Some(expr1), Some(expr2)) => expr1.eq(expr2),
+ (None, None) => true,
+ _ => false,
Review Comment:
Sure.
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
mingmwang commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1006881904
##########
datafusion/physical-expr/src/expressions/binary.rs:
##########
@@ -649,6 +650,30 @@ impl PhysicalExpr for BinaryExpr {
right: Arc::clone(self.right()),
})
}
+
+ fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.left.clone(), self.right.clone()]
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(BinaryExpr::new(
Review Comment:
I already add the length check in the method `with_new_children_if_necessary()`, and expr.with_new_children() should not be called directly. This is also aligned with the `ExecutionPlan`.
````
pub fn with_new_children_if_necessary(
expr: Arc<dyn PhysicalExpr>,
children: Vec<Arc<dyn PhysicalExpr>>,
) -> Result<Arc<dyn PhysicalExpr>> {
if children.len() != expr.children().len() {
Err(DataFusionError::Internal(
"PhysicalExpr: Wrong number of children".to_string(),
))
} else if children.is_empty()
|| children
.iter()
.zip(expr.children().iter())
.any(|(c1, c2)| !Arc::ptr_eq(c1, c2))
{
expr.with_new_children(children)
} else {
Ok(expr)
}
}
````
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
mingmwang commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1006962356
##########
datafusion/physical-expr/src/expressions/no_op.rs:
##########
@@ -0,0 +1,87 @@
+// 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.
+
+//! Literal expressions for physical operations
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::{
+ datatypes::{DataType, Schema},
+ record_batch::RecordBatch,
+};
+
+use crate::physical_expr::down_cast_any_ref;
+use crate::PhysicalExpr;
+use datafusion_common::Result;
+use datafusion_expr::ColumnarValue;
+
+/// A place holder expressions, can not be evaluated
+#[derive(Debug, PartialEq, Eq, Default)]
+pub struct NoOp {}
+
+impl NoOp {
+ /// Create a NoOp expression
+ pub fn new() -> Self {
+ Self {}
+ }
+}
+
+impl std::fmt::Display for NoOp {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ write!(f, "NoOp")
+ }
+}
+
+impl PhysicalExpr for NoOp {
+ /// Return a reference to Any that can be used for downcasting
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
+ Ok(DataType::Null)
Review Comment:
The `NoOp` expr type will also be used in other places in the following PR.
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] alamb commented on pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
alamb commented on PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#issuecomment-1295422211
Will plan to merge this in tomorrow unless I hear otherwise -- if @mingmwang hasn't had a chance, we can do the changes as a follow on PR
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] mingmwang commented on pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
mingmwang commented on PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#issuecomment-1295821522
> I am merging this PR in as it has already been around for a while and is blocking work. @mingmwang can you please respond to @isidentical 's comment [#3969 (comment)](https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1008281138) and submit another PR with additional tests, if appropriate?
@alamb @isidentical
Sure, will add one more UT in the following PR.
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] alamb commented on pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
alamb commented on PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#issuecomment-1295812356
I am merging this PR in as it has already been around for a while and is blocking work. @mingmwang can you please respond to @isidentical 's comment https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1008281138 and submit another PR with additional tests, if appropriate?
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] mingmwang commented on pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
mingmwang commented on PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#issuecomment-1292162090
@alamb @tustvold @yahoNanJing
Please help to review.
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] alamb commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
alamb commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1007069014
##########
datafusion/physical-expr/src/physical_expr.rs:
##########
@@ -128,6 +137,232 @@ impl PhysicalExprStats for BasicExpressionStats {
}
}
+/// a Trait for marking tree node types that are rewritable
+pub trait TreeNodeRewritable: Clone {
+ /// Transform the tree node using the given [TreeNodeRewriter]
+ /// It performs a depth first walk of an node and its children.
+ ///
+ /// For an node tree such as
+ /// ```text
+ /// ParentNode
+ /// left: ChildNode1
+ /// right: ChildNode2
+ /// ```
+ ///
+ /// The nodes are visited using the following order
+ /// ```text
+ /// pre_visit(ParentNode)
Review Comment:
I think we need to make sure the doc comments and code match -- the naming of the code is fine with me (for the reasons you mention)
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] mingmwang commented on pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
mingmwang commented on PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#issuecomment-1292801212
@alamb Thanks
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] alamb commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
alamb commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1006725058
##########
datafusion/physical-expr/src/physical_expr.rs:
##########
@@ -66,6 +67,14 @@ pub trait PhysicalExpr: Send + Sync + Display + Debug {
fn expr_stats(&self) -> Arc<dyn PhysicalExprStats> {
Arc::new(BasicExpressionStats {})
}
+ /// Get a list of child PhysicalExpr that provide the input for this expr.
Review Comment:
👍 these are foundational changes needed to do PhysicalExpr rewrites
##########
datafusion/physical-expr/src/expressions/cast.rs:
##########
@@ -93,6 +94,36 @@ impl PhysicalExpr for CastExpr {
let value = self.expr.evaluate(batch)?;
cast_column(&value, &self.cast_type, &self.cast_options)
}
+
+ fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(CastExpr::new(
Review Comment:
recommend assert / error check for children.len() == 1
##########
datafusion/physical-expr/src/expressions/case.rs:
##########
@@ -286,6 +290,89 @@ impl PhysicalExpr for CaseExpr {
self.case_when_no_expr(batch)
}
}
+
+ fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ let mut chileren = vec![];
+ match &self.expr {
+ Some(expr) => chileren.push(expr.clone()),
+ None => chileren.push(Arc::new(NoOp::new())),
+ }
+ self.when_then_expr.iter().for_each(|(cond, value)| {
+ chileren.push(cond.clone());
+ chileren.push(value.clone());
+ });
+
+ match &self.else_expr {
+ Some(expr) => chileren.push(expr.clone()),
+ None => chileren.push(Arc::new(NoOp::new())),
+ }
+ chileren
+ }
+
+ // For physical CaseExpr, we do not allow modifying children size
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ if children.len() != self.children().len() {
+ Err(DataFusionError::Internal(
+ "CaseExpr: Wrong number of children".to_string(),
+ ))
+ } else {
+ assert_eq!(children.len() % 2, 0);
+ let expr = match children[0].clone().as_any().downcast_ref::<NoOp>() {
+ Some(_) => None,
+ _ => Some(children[0].clone()),
+ };
+ let else_expr = match children[children.len() - 1]
+ .clone()
+ .as_any()
+ .downcast_ref::<NoOp>()
+ {
+ Some(_) => None,
+ _ => Some(children[children.len() - 1].clone()),
+ };
+
+ let branches = children[1..children.len() - 1].to_vec();
+ let mut when_then_expr: Vec<WhenThen> = vec![];
+ for (prev, next) in branches.into_iter().tuples() {
+ when_then_expr.push((prev, next));
+ }
+ Ok(Arc::new(CaseExpr::try_new(
+ expr,
+ when_then_expr,
+ else_expr,
+ )?))
+ }
+ }
+}
+
+impl PartialEq<dyn Any> for CaseExpr {
+ fn eq(&self, other: &dyn Any) -> bool {
+ down_cast_any_ref(other)
+ .downcast_ref::<Self>()
+ .map(|x| {
+ let expr_eq = match (&self.expr, &x.expr) {
+ (Some(expr1), Some(expr2)) => expr1.eq(expr2),
+ (None, None) => true,
+ _ => false,
Review Comment:
You could also do `return false` here rather than checking `expr_eq` again later
##########
datafusion/physical-expr/src/expressions/no_op.rs:
##########
@@ -0,0 +1,87 @@
+// 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.
+
+//! Literal expressions for physical operations
Review Comment:
```suggestion
//! NoOp placeholder for physical operations
```
##########
datafusion/physical-expr/src/expressions/no_op.rs:
##########
@@ -0,0 +1,87 @@
+// 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.
+
+//! Literal expressions for physical operations
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::{
+ datatypes::{DataType, Schema},
+ record_batch::RecordBatch,
+};
+
+use crate::physical_expr::down_cast_any_ref;
+use crate::PhysicalExpr;
+use datafusion_common::Result;
+use datafusion_expr::ColumnarValue;
+
+/// A place holder expressions, can not be evaluated
+#[derive(Debug, PartialEq, Eq, Default)]
+pub struct NoOp {}
+
+impl NoOp {
+ /// Create a NoOp expression
+ pub fn new() -> Self {
+ Self {}
+ }
+}
+
+impl std::fmt::Display for NoOp {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ write!(f, "NoOp")
+ }
+}
+
+impl PhysicalExpr for NoOp {
+ /// Return a reference to Any that can be used for downcasting
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
+ Ok(DataType::Null)
+ }
+
+ fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
+ Ok(true)
+ }
+
+ fn evaluate(&self, _batch: &RecordBatch) -> Result<ColumnarValue> {
+ unimplemented!("NoOp::evaluate");
Review Comment:
I recommend returning an error here rather than panic (which is what `unimplemented!` will do)
##########
datafusion/physical-expr/src/scalar_function.rs:
##########
@@ -145,4 +145,26 @@ impl PhysicalExpr for ScalarFunctionExpr {
let fun = self.fun.as_ref();
(fun)(&inputs)
}
+
+ fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ self.args.clone()
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(ScalarFunctionExpr::new(
+ &self.name,
+ self.fun.clone(),
+ children,
+ self.return_type(),
+ )))
+ }
+}
+
+impl PartialEq<dyn Any> for ScalarFunctionExpr {
+ fn eq(&self, _other: &dyn Any) -> bool {
+ false
Review Comment:
This seems incorrect / unfinshed -- shouldn't it be checking the contents of the `other`?
##########
datafusion/physical-expr/src/physical_expr.rs:
##########
@@ -128,6 +137,232 @@ impl PhysicalExprStats for BasicExpressionStats {
}
}
+/// a Trait for marking tree node types that are rewritable
Review Comment:
I recommend putting the rewriting traits into some other module, such as `datafusion/physical-expr/src/rewrite.rs` or example
We can do it as a follow on PR too
##########
datafusion/physical-expr/src/expressions/no_op.rs:
##########
@@ -0,0 +1,87 @@
+// 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.
+
+//! Literal expressions for physical operations
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::{
+ datatypes::{DataType, Schema},
+ record_batch::RecordBatch,
+};
+
+use crate::physical_expr::down_cast_any_ref;
+use crate::PhysicalExpr;
+use datafusion_common::Result;
+use datafusion_expr::ColumnarValue;
+
+/// A place holder expressions, can not be evaluated
Review Comment:
```suggestion
/// A place holder expressions, can not be evaluated.
///
/// Used in some cases where an `Arc<dyn PhysicalExpr>` is needed, such as `children()`
```
##########
datafusion/physical-expr/src/expressions/binary.rs:
##########
@@ -649,6 +650,30 @@ impl PhysicalExpr for BinaryExpr {
right: Arc::clone(self.right()),
})
}
+
+ fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.left.clone(), self.right.clone()]
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(BinaryExpr::new(
Review Comment:
I suggest we should also `assert_eq!(children.len(), 2)` to catch bugs earlier
##########
datafusion/physical-expr/src/expressions/datetime.rs:
##########
@@ -43,6 +44,7 @@ pub struct DateTimeIntervalExpr {
lhs: Arc<dyn PhysicalExpr>,
op: Operator,
rhs: Arc<dyn PhysicalExpr>,
+ input_schema: Schema,
Review Comment:
```suggestion
// TODO: move type checking to the planning phase and not in the physical expr
// so we can remove this
input_schema: Schema,
```
This is unfortunate -- I see you need to do it so you can call `try_new()` -- but really I think DataFusion should have done this type checking in the planning phase rather than at the physical expr stage -- maybe I'll file a ticket to improve that.
##########
datafusion/physical-expr/src/expressions/case.rs:
##########
@@ -286,6 +290,89 @@ impl PhysicalExpr for CaseExpr {
self.case_when_no_expr(batch)
}
}
+
+ fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ let mut chileren = vec![];
Review Comment:
```suggestion
let mut children = vec![];
```
##########
datafusion/physical-expr/src/expressions/case.rs:
##########
@@ -286,6 +290,89 @@ impl PhysicalExpr for CaseExpr {
self.case_when_no_expr(batch)
}
}
+
+ fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ let mut chileren = vec![];
+ match &self.expr {
+ Some(expr) => chileren.push(expr.clone()),
+ None => chileren.push(Arc::new(NoOp::new())),
+ }
+ self.when_then_expr.iter().for_each(|(cond, value)| {
+ chileren.push(cond.clone());
+ chileren.push(value.clone());
+ });
+
+ match &self.else_expr {
+ Some(expr) => chileren.push(expr.clone()),
+ None => chileren.push(Arc::new(NoOp::new())),
+ }
+ chileren
+ }
+
+ // For physical CaseExpr, we do not allow modifying children size
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ if children.len() != self.children().len() {
+ Err(DataFusionError::Internal(
+ "CaseExpr: Wrong number of children".to_string(),
+ ))
+ } else {
+ assert_eq!(children.len() % 2, 0);
+ let expr = match children[0].clone().as_any().downcast_ref::<NoOp>() {
+ Some(_) => None,
+ _ => Some(children[0].clone()),
+ };
+ let else_expr = match children[children.len() - 1]
Review Comment:
i would find it easier to read if the `else_expr` handling was after the `when_then_expr` handling to mirror the `children()` but I think this is fine too
##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -52,16 +54,27 @@ use datafusion_expr::ColumnarValue;
static OPTIMIZER_INSET_THRESHOLD: usize = 30;
/// InList
-#[derive(Debug)]
pub struct InListExpr {
expr: Arc<dyn PhysicalExpr>,
list: Vec<Arc<dyn PhysicalExpr>>,
negated: bool,
set: Option<InSet>,
+ input_schema: Schema,
Review Comment:
Why does this struct need `input_schema`? It seems to me it is not needed
##########
datafusion/physical-expr/src/expressions/case.rs:
##########
@@ -286,6 +290,89 @@ impl PhysicalExpr for CaseExpr {
self.case_when_no_expr(batch)
}
}
+
+ fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ let mut chileren = vec![];
+ match &self.expr {
+ Some(expr) => chileren.push(expr.clone()),
+ None => chileren.push(Arc::new(NoOp::new())),
+ }
+ self.when_then_expr.iter().for_each(|(cond, value)| {
+ chileren.push(cond.clone());
+ chileren.push(value.clone());
+ });
+
+ match &self.else_expr {
+ Some(expr) => chileren.push(expr.clone()),
+ None => chileren.push(Arc::new(NoOp::new())),
+ }
+ chileren
+ }
+
+ // For physical CaseExpr, we do not allow modifying children size
Review Comment:
👍
##########
datafusion/physical-expr/src/expressions/no_op.rs:
##########
@@ -0,0 +1,87 @@
+// 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.
+
+//! Literal expressions for physical operations
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::{
+ datatypes::{DataType, Schema},
+ record_batch::RecordBatch,
+};
+
+use crate::physical_expr::down_cast_any_ref;
+use crate::PhysicalExpr;
+use datafusion_common::Result;
+use datafusion_expr::ColumnarValue;
+
+/// A place holder expressions, can not be evaluated
+#[derive(Debug, PartialEq, Eq, Default)]
+pub struct NoOp {}
+
+impl NoOp {
+ /// Create a NoOp expression
+ pub fn new() -> Self {
+ Self {}
+ }
+}
+
+impl std::fmt::Display for NoOp {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ write!(f, "NoOp")
+ }
+}
+
+impl PhysicalExpr for NoOp {
+ /// Return a reference to Any that can be used for downcasting
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
+ Ok(DataType::Null)
Review Comment:
🤔 since this acts like a `PhysicalExpr::Literal` for `ScalarValue::Null` I wonder if you considered using `PhysicalExpr::Literal` directly instead (for CaseExpr)?
##########
datafusion/physical-expr/src/physical_expr.rs:
##########
@@ -128,6 +137,232 @@ impl PhysicalExprStats for BasicExpressionStats {
}
}
+/// a Trait for marking tree node types that are rewritable
+pub trait TreeNodeRewritable: Clone {
+ /// Transform the tree node using the given [TreeNodeRewriter]
+ /// It performs a depth first walk of an node and its children.
+ ///
+ /// For an node tree such as
+ /// ```text
+ /// ParentNode
+ /// left: ChildNode1
+ /// right: ChildNode2
+ /// ```
+ ///
+ /// The nodes are visited using the following order
+ /// ```text
+ /// pre_visit(ParentNode)
+ /// pre_visit(ChildNode1)
+ /// mutatate(ChildNode1)
+ /// pre_visit(ChildNode2)
+ /// mutate(ChildNode2)
+ /// mutate(ParentNode)
+ /// ```
+ ///
+ /// If an Err result is returned, recursion is stopped immediately
+ ///
+ /// If [`false`] is returned on a call to pre_visit, no
+ /// children of that node are visited, nor is mutate
+ /// called on that node
+ ///
+ fn transform_using<R: TreeNodeRewriter<Self>>(
+ self,
+ rewriter: &mut R,
+ ) -> Result<Self> {
+ let need_mutate = match rewriter.pre_visit(&self)? {
+ RewriteRecursion::Mutate => return rewriter.mutate(self),
+ RewriteRecursion::Stop => return Ok(self),
+ RewriteRecursion::Continue => true,
+ RewriteRecursion::Skip => false,
+ };
+
+ let after_op_children =
+ self.map_children(|node| node.transform_using(rewriter))?;
+
+ // now rewrite this node itself
+ if need_mutate {
+ rewriter.mutate(after_op_children)
+ } else {
+ Ok(after_op_children)
+ }
+ }
+
+ /// Convenience utils for writing optimizers rule: recursively apply the given `op` to the node tree.
+ /// When `op` does not apply to a given node, it is left uncshanged.
Review Comment:
```suggestion
/// When `op` does not apply to a given node, it is left unchanged.
```
##########
datafusion/physical-expr/src/physical_expr.rs:
##########
@@ -128,6 +137,232 @@ impl PhysicalExprStats for BasicExpressionStats {
}
}
+/// a Trait for marking tree node types that are rewritable
+pub trait TreeNodeRewritable: Clone {
+ /// Transform the tree node using the given [TreeNodeRewriter]
+ /// It performs a depth first walk of an node and its children.
+ ///
+ /// For an node tree such as
+ /// ```text
+ /// ParentNode
+ /// left: ChildNode1
+ /// right: ChildNode2
+ /// ```
+ ///
+ /// The nodes are visited using the following order
+ /// ```text
+ /// pre_visit(ParentNode)
Review Comment:
I think these examples need to be change to use the terms `transform_down` and `transform_up` and `transform`
I also think it would be nice to use the same terms here as are used in the rewriter (previsit / postvisit) but I realize they don't quite match up.
##########
datafusion/physical-expr/src/physical_expr.rs:
##########
@@ -128,6 +137,232 @@ impl PhysicalExprStats for BasicExpressionStats {
}
}
+/// a Trait for marking tree node types that are rewritable
+pub trait TreeNodeRewritable: Clone {
+ /// Transform the tree node using the given [TreeNodeRewriter]
+ /// It performs a depth first walk of an node and its children.
+ ///
+ /// For an node tree such as
+ /// ```text
+ /// ParentNode
+ /// left: ChildNode1
+ /// right: ChildNode2
+ /// ```
+ ///
+ /// The nodes are visited using the following order
+ /// ```text
+ /// pre_visit(ParentNode)
+ /// pre_visit(ChildNode1)
+ /// mutatate(ChildNode1)
+ /// pre_visit(ChildNode2)
+ /// mutate(ChildNode2)
+ /// mutate(ParentNode)
+ /// ```
+ ///
+ /// If an Err result is returned, recursion is stopped immediately
+ ///
+ /// If [`false`] is returned on a call to pre_visit, no
+ /// children of that node are visited, nor is mutate
+ /// called on that node
+ ///
+ fn transform_using<R: TreeNodeRewriter<Self>>(
+ self,
+ rewriter: &mut R,
+ ) -> Result<Self> {
+ let need_mutate = match rewriter.pre_visit(&self)? {
+ RewriteRecursion::Mutate => return rewriter.mutate(self),
+ RewriteRecursion::Stop => return Ok(self),
+ RewriteRecursion::Continue => true,
+ RewriteRecursion::Skip => false,
+ };
+
+ let after_op_children =
+ self.map_children(|node| node.transform_using(rewriter))?;
+
+ // now rewrite this node itself
+ if need_mutate {
+ rewriter.mutate(after_op_children)
+ } else {
+ Ok(after_op_children)
+ }
+ }
+
+ /// Convenience utils for writing optimizers rule: recursively apply the given `op` to the node tree.
+ /// When `op` does not apply to a given node, it is left uncshanged.
+ /// The default tree traversal direction is transform_up(Postorder Traversal).
+ fn transform<F>(self, op: &F) -> Result<Self>
+ where
+ F: Fn(Self) -> Option<Self>,
+ {
+ self.transform_up(op)
+ }
+
+ /// Convenience utils for writing optimizers rule: recursively apply the given 'op' to the node and all of its
+ /// children(Preorder Traversal).
+ /// When the `op` does not apply to a given node, it is left unchanged.
+ fn transform_down<F>(self, op: &F) -> Result<Self>
+ where
+ F: Fn(Self) -> Option<Self>,
+ {
+ let node_cloned = self.clone();
+ let after_op = match op(node_cloned) {
+ Some(value) => value,
+ None => self,
+ };
+ after_op.map_children(|node| node.transform_down(op))
+ }
+
+ /// Convenience utils for writing optimizers rule: recursively apply the given 'op' first to all of its
+ /// children and then itself(Postorder Traversal).
+ /// When the `op` does not apply to a given node, it is left unchanged.
+ fn transform_up<F>(self, op: &F) -> Result<Self>
+ where
+ F: Fn(Self) -> Option<Self>,
+ {
+ let after_op_children = self.map_children(|node| node.transform_up(op))?;
+
+ let after_op_children_clone = after_op_children.clone();
+ let new_node = match op(after_op_children) {
+ Some(value) => value,
+ None => after_op_children_clone,
+ };
+ Ok(new_node)
+ }
+
+ /// Apply transform `F` to the node's children, the transform `F` might have a direction(Preorder or Postorder)
+ fn map_children<F>(self, transform: F) -> Result<Self>
+ where
+ F: FnMut(Self) -> Result<Self>;
+}
+
+/// Trait for potentially recursively transform an [`TreeNodeRewritable`] node
+/// tree. When passed to `TreeNodeRewritable::transform_using`, `TreeNodeRewriter::mutate` is
+/// invoked recursively on all nodes of a tree.
+pub trait TreeNodeRewriter<N: TreeNodeRewritable>: Sized {
+ /// Invoked before (Preorder) any children of `node` are rewritten /
+ /// visited. Default implementation returns `Ok(RewriteRecursion::Continue)`
+ fn pre_visit(&mut self, _node: &N) -> Result<RewriteRecursion> {
+ Ok(RewriteRecursion::Continue)
+ }
+
+ /// Invoked after (Postorder) all children of `node` have been mutated and
+ /// returns a potentially modified node.
+ fn mutate(&mut self, node: N) -> Result<N>;
+}
+
+/// Controls how the [TreeNodeRewriter] recursion should proceed.
+#[allow(dead_code)]
+pub enum RewriteRecursion {
+ /// Continue rewrite / visit this node tree.
+ Continue,
+ /// Call 'op' immediately and return.
+ Mutate,
+ /// Do not rewrite / visit the children of this node.
+ Stop,
+ /// Keep recursive but skip apply op on this node
+ Skip,
+}
+
+impl TreeNodeRewritable for Arc<dyn PhysicalExpr> {
+ fn map_children<F>(self, transform: F) -> Result<Self>
+ where
+ F: FnMut(Self) -> Result<Self>,
+ {
+ if !self.children().is_empty() {
+ let new_children: Result<Vec<_>> =
+ self.children().into_iter().map(transform).collect();
+ with_new_children_if_necessary(self, new_children?)
+ } else {
+ Ok(self)
+ }
+ }
+}
+
+/// Returns a copy of this expr if we change any child according to the pointer comparison.
+/// The size of `children` must be equal to the size of `PhysicalExpr::children()`.
+/// Allow the vtable address comparisons for PhysicalExpr Trait Objects,it is harmless even
+/// in the case of 'false-native'.
+#[allow(clippy::vtable_address_comparisons)]
+pub fn with_new_children_if_necessary(
+ expr: Arc<dyn PhysicalExpr>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+) -> Result<Arc<dyn PhysicalExpr>> {
+ if children.len() != expr.children().len() {
+ Err(DataFusionError::Internal(
+ "PhysicalExpr: Wrong number of children".to_string(),
+ ))
+ } else if children.is_empty()
+ || children
+ .iter()
+ .zip(expr.children().iter())
+ .any(|(c1, c2)| !Arc::ptr_eq(c1, c2))
+ {
+ expr.with_new_children(children)
+ } else {
+ Ok(expr)
+ }
+}
+
+/// Compare the two expr lists are equal no matter the order.
+/// For example two InListExpr can be considered to be equals no matter the order:
+///
+/// In('a','b','c') == In('c','b','a')
+pub fn expr_list_eq_any_order(
Review Comment:
This seems like it could be in a utils or some other module
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] isidentical commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
isidentical commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1008265133
##########
datafusion/physical-expr/src/expressions/cast.rs:
##########
@@ -93,6 +94,36 @@ impl PhysicalExpr for CastExpr {
let value = self.expr.evaluate(batch)?;
cast_column(&value, &self.cast_type, &self.cast_options)
}
+
+ fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(CastExpr::new(
+ children[0].clone(),
+ self.cast_type.clone(),
+ CastOptions {
+ safe: self.cast_options.safe,
+ },
+ )))
+ }
+}
+
+impl PartialEq<dyn Any> for CastExpr {
+ fn eq(&self, other: &dyn Any) -> bool {
+ down_cast_any_ref(other)
+ .downcast_ref::<Self>()
+ .map(|x| {
+ self.expr.eq(&x.expr)
+ && self.cast_type == x.cast_type
+ && self.cast_options.safe == x.cast_options.safe
Review Comment:
This seems to be a bit error-prone, considering that `cast_options` might get new members and this part will not count them. Can we consider adding equality comparison support to `CastOptions` directly?
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] ursabot commented on pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
ursabot commented on PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#issuecomment-1295813330
Benchmark runs are scheduled for baseline = 925a96225e2142d8adc53a3323ddf612fffe2007 and contender = 6fae0bd3e2d0bc7f1406546b82a9ad0a2803a733. 6fae0bd3e2d0bc7f1406546b82a9ad0a2803a733 is a master commit associated with this PR. Results will be available as each benchmark for each run completes.
Conbench compare runs links:
[Skipped :warning: Benchmarking of arrow-datafusion-commits is not supported on ec2-t3-xlarge-us-east-2] [ec2-t3-xlarge-us-east-2](https://conbench.ursa.dev/compare/runs/6653b3a1b67a4f4eb8708112f24e3722...318f67aaf86449cb9e070cfc8fd99e70/)
[Skipped :warning: Benchmarking of arrow-datafusion-commits is not supported on test-mac-arm] [test-mac-arm](https://conbench.ursa.dev/compare/runs/179361a526674a4db9094c95f7035710...5733339a7a22413ab82d6cd2b94e8ba0/)
[Skipped :warning: Benchmarking of arrow-datafusion-commits is not supported on ursa-i9-9960x] [ursa-i9-9960x](https://conbench.ursa.dev/compare/runs/bef50d5c47284822ac80fa3d7a456bb2...7cd352eea9184fcf91436be03ae8f44a/)
[Skipped :warning: Benchmarking of arrow-datafusion-commits is not supported on ursa-thinkcentre-m75q] [ursa-thinkcentre-m75q](https://conbench.ursa.dev/compare/runs/b52d32e533e54e1399039b6c77c46c2a...a84bd5fe624a47789a030d958cffd1e7/)
Buildkite builds:
Supported benchmarks:
ec2-t3-xlarge-us-east-2: Supported benchmark langs: Python, R. Runs only benchmarks with cloud = True
test-mac-arm: Supported benchmark langs: C++, Python, R
ursa-i9-9960x: Supported benchmark langs: Python, R, JavaScript
ursa-thinkcentre-m75q: Supported benchmark langs: C++, Java
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] alamb commented on pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
alamb commented on PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#issuecomment-1295051220
Any concerns about merging this in @yahoNanJing @andygrove @liukun4515 @Dandandan @isidentical @avantgardnerio ? Does anyone want longer to review it?
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
mingmwang commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1006885269
##########
datafusion/physical-expr/src/physical_expr.rs:
##########
@@ -128,6 +137,232 @@ impl PhysicalExprStats for BasicExpressionStats {
}
}
+/// a Trait for marking tree node types that are rewritable
Review Comment:
Sure. I can change it in this PR also.
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
mingmwang commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1006993438
##########
datafusion/physical-expr/src/physical_expr.rs:
##########
@@ -128,6 +137,232 @@ impl PhysicalExprStats for BasicExpressionStats {
}
}
+/// a Trait for marking tree node types that are rewritable
+pub trait TreeNodeRewritable: Clone {
+ /// Transform the tree node using the given [TreeNodeRewriter]
+ /// It performs a depth first walk of an node and its children.
+ ///
+ /// For an node tree such as
+ /// ```text
+ /// ParentNode
+ /// left: ChildNode1
+ /// right: ChildNode2
+ /// ```
+ ///
+ /// The nodes are visited using the following order
+ /// ```text
+ /// pre_visit(ParentNode)
+ /// pre_visit(ChildNode1)
+ /// mutatate(ChildNode1)
+ /// pre_visit(ChildNode2)
+ /// mutate(ChildNode2)
+ /// mutate(ParentNode)
+ /// ```
+ ///
+ /// If an Err result is returned, recursion is stopped immediately
+ ///
+ /// If [`false`] is returned on a call to pre_visit, no
+ /// children of that node are visited, nor is mutate
+ /// called on that node
+ ///
+ fn transform_using<R: TreeNodeRewriter<Self>>(
+ self,
+ rewriter: &mut R,
+ ) -> Result<Self> {
+ let need_mutate = match rewriter.pre_visit(&self)? {
+ RewriteRecursion::Mutate => return rewriter.mutate(self),
+ RewriteRecursion::Stop => return Ok(self),
+ RewriteRecursion::Continue => true,
+ RewriteRecursion::Skip => false,
+ };
+
+ let after_op_children =
+ self.map_children(|node| node.transform_using(rewriter))?;
+
+ // now rewrite this node itself
+ if need_mutate {
+ rewriter.mutate(after_op_children)
+ } else {
+ Ok(after_op_children)
+ }
+ }
+
+ /// Convenience utils for writing optimizers rule: recursively apply the given `op` to the node tree.
+ /// When `op` does not apply to a given node, it is left uncshanged.
+ /// The default tree traversal direction is transform_up(Postorder Traversal).
+ fn transform<F>(self, op: &F) -> Result<Self>
+ where
+ F: Fn(Self) -> Option<Self>,
+ {
+ self.transform_up(op)
+ }
+
+ /// Convenience utils for writing optimizers rule: recursively apply the given 'op' to the node and all of its
+ /// children(Preorder Traversal).
+ /// When the `op` does not apply to a given node, it is left unchanged.
+ fn transform_down<F>(self, op: &F) -> Result<Self>
+ where
+ F: Fn(Self) -> Option<Self>,
+ {
+ let node_cloned = self.clone();
+ let after_op = match op(node_cloned) {
+ Some(value) => value,
+ None => self,
+ };
+ after_op.map_children(|node| node.transform_down(op))
+ }
+
+ /// Convenience utils for writing optimizers rule: recursively apply the given 'op' first to all of its
+ /// children and then itself(Postorder Traversal).
+ /// When the `op` does not apply to a given node, it is left unchanged.
+ fn transform_up<F>(self, op: &F) -> Result<Self>
+ where
+ F: Fn(Self) -> Option<Self>,
+ {
+ let after_op_children = self.map_children(|node| node.transform_up(op))?;
+
+ let after_op_children_clone = after_op_children.clone();
+ let new_node = match op(after_op_children) {
+ Some(value) => value,
+ None => after_op_children_clone,
+ };
+ Ok(new_node)
+ }
+
+ /// Apply transform `F` to the node's children, the transform `F` might have a direction(Preorder or Postorder)
+ fn map_children<F>(self, transform: F) -> Result<Self>
+ where
+ F: FnMut(Self) -> Result<Self>;
+}
+
+/// Trait for potentially recursively transform an [`TreeNodeRewritable`] node
+/// tree. When passed to `TreeNodeRewritable::transform_using`, `TreeNodeRewriter::mutate` is
+/// invoked recursively on all nodes of a tree.
+pub trait TreeNodeRewriter<N: TreeNodeRewritable>: Sized {
+ /// Invoked before (Preorder) any children of `node` are rewritten /
+ /// visited. Default implementation returns `Ok(RewriteRecursion::Continue)`
+ fn pre_visit(&mut self, _node: &N) -> Result<RewriteRecursion> {
+ Ok(RewriteRecursion::Continue)
+ }
+
+ /// Invoked after (Postorder) all children of `node` have been mutated and
+ /// returns a potentially modified node.
+ fn mutate(&mut self, node: N) -> Result<N>;
+}
+
+/// Controls how the [TreeNodeRewriter] recursion should proceed.
+#[allow(dead_code)]
+pub enum RewriteRecursion {
+ /// Continue rewrite / visit this node tree.
+ Continue,
+ /// Call 'op' immediately and return.
+ Mutate,
+ /// Do not rewrite / visit the children of this node.
+ Stop,
+ /// Keep recursive but skip apply op on this node
+ Skip,
+}
+
+impl TreeNodeRewritable for Arc<dyn PhysicalExpr> {
+ fn map_children<F>(self, transform: F) -> Result<Self>
+ where
+ F: FnMut(Self) -> Result<Self>,
+ {
+ if !self.children().is_empty() {
+ let new_children: Result<Vec<_>> =
+ self.children().into_iter().map(transform).collect();
+ with_new_children_if_necessary(self, new_children?)
+ } else {
+ Ok(self)
+ }
+ }
+}
+
+/// Returns a copy of this expr if we change any child according to the pointer comparison.
+/// The size of `children` must be equal to the size of `PhysicalExpr::children()`.
+/// Allow the vtable address comparisons for PhysicalExpr Trait Objects,it is harmless even
+/// in the case of 'false-native'.
+#[allow(clippy::vtable_address_comparisons)]
+pub fn with_new_children_if_necessary(
+ expr: Arc<dyn PhysicalExpr>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+) -> Result<Arc<dyn PhysicalExpr>> {
+ if children.len() != expr.children().len() {
+ Err(DataFusionError::Internal(
+ "PhysicalExpr: Wrong number of children".to_string(),
+ ))
+ } else if children.is_empty()
+ || children
+ .iter()
+ .zip(expr.children().iter())
+ .any(|(c1, c2)| !Arc::ptr_eq(c1, c2))
+ {
+ expr.with_new_children(children)
+ } else {
+ Ok(expr)
+ }
+}
+
+/// Compare the two expr lists are equal no matter the order.
+/// For example two InListExpr can be considered to be equals no matter the order:
+///
+/// In('a','b','c') == In('c','b','a')
+pub fn expr_list_eq_any_order(
Review Comment:
Sure, currently there is no utils, I will add one. In the following PRs more util methods will be added.
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] mingmwang commented on pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
mingmwang commented on PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#issuecomment-1294358816
@alamb Could you please approve and merge the PR? Then I can work on the following parts.
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] isidentical commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
isidentical commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1008281138
##########
datafusion/physical-expr/src/utils.rs:
##########
@@ -0,0 +1,205 @@
+// 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 crate::PhysicalExpr;
+use crate::PhysicalSortExpr;
+
+use std::sync::Arc;
+
+/// Compare the two expr lists are equal no matter the order.
+/// For example two InListExpr can be considered to be equals no matter the order:
+///
+/// In('a','b','c') == In('c','b','a')
+pub fn expr_list_eq_any_order(
+ list1: &[Arc<dyn PhysicalExpr>],
+ list2: &[Arc<dyn PhysicalExpr>],
+) -> bool {
+ if list1.len() == list2.len() {
+ let mut expr_vec1 = list1.to_vec();
+ let mut expr_vec2 = list2.to_vec();
+ while let Some(expr1) = expr_vec1.pop() {
+ if let Some(idx) = expr_vec2.iter().position(|expr2| expr1.eq(expr2)) {
+ expr_vec2.swap_remove(idx);
+ } else {
+ break;
+ }
+ }
+ expr_vec1.is_empty() && expr_vec2.is_empty()
+ } else {
+ false
+ }
+}
+
+/// Strictly compare the two expr lists are equal in the given order.
+pub fn expr_list_eq_strict_order(
+ list1: &[Arc<dyn PhysicalExpr>],
+ list2: &[Arc<dyn PhysicalExpr>],
+) -> bool {
+ list1.len() == list2.len() && list1.iter().zip(list2.iter()).all(|(e1, e2)| e1.eq(e2))
+}
+
+/// Strictly compare the two sort expr lists in the given order.
+///
+/// For Physical Sort Exprs, the order matters:
+///
+/// SortExpr('a','b','c') != SortExpr('c','b','a')
+#[allow(dead_code)]
+pub fn sort_expr_list_eq_strict_order(
+ list1: &[PhysicalSortExpr],
+ list2: &[PhysicalSortExpr],
+) -> bool {
+ list1.len() == list2.len() && list1.iter().zip(list2.iter()).all(|(e1, e2)| e1.eq(e2))
+}
+
+#[cfg(test)]
+mod tests {
+
+ use super::*;
+ use crate::expressions::Column;
+ use crate::PhysicalSortExpr;
+ use arrow::compute::SortOptions;
+ use datafusion_common::Result;
+
+ use std::sync::Arc;
+
+ #[test]
+ fn expr_list_eq_any_order_test() -> Result<()> {
+ let list1: Vec<Arc<dyn PhysicalExpr>> = vec![
+ Arc::new(Column::new("a", 0)),
+ Arc::new(Column::new("a", 0)),
+ Arc::new(Column::new("b", 1)),
+ ];
+ let list2: Vec<Arc<dyn PhysicalExpr>> = vec![
+ Arc::new(Column::new("b", 1)),
+ Arc::new(Column::new("b", 1)),
+ Arc::new(Column::new("a", 0)),
+ ];
+ assert!(!expr_list_eq_any_order(list1.as_slice(), list2.as_slice()));
+ assert!(!expr_list_eq_any_order(list2.as_slice(), list1.as_slice()));
+
+ let list3: Vec<Arc<dyn PhysicalExpr>> = vec![
+ Arc::new(Column::new("a", 0)),
+ Arc::new(Column::new("b", 1)),
+ Arc::new(Column::new("c", 2)),
+ Arc::new(Column::new("a", 0)),
+ Arc::new(Column::new("b", 1)),
+ ];
+ let list4: Vec<Arc<dyn PhysicalExpr>> = vec![
+ Arc::new(Column::new("b", 1)),
+ Arc::new(Column::new("b", 1)),
+ Arc::new(Column::new("a", 0)),
+ Arc::new(Column::new("c", 2)),
+ Arc::new(Column::new("a", 0)),
+ ];
+ assert!(expr_list_eq_any_order(list3.as_slice(), list4.as_slice()));
+ assert!(expr_list_eq_any_order(list4.as_slice(), list3.as_slice()));
+ assert!(expr_list_eq_any_order(list3.as_slice(), list3.as_slice()));
+ assert!(expr_list_eq_any_order(list4.as_slice(), list4.as_slice()));
+
Review Comment:
If I didn't miss any, it seems like `expr_list_eq_strict_order` can be also tested with these (it currently seems like missing tests):
```suggestion
assert!(expr_list_eq_strict_order(list1.as_slice(), list1.as_slice());
assert!(expr_list_eq_strict_order(list2.as_slice(), list2.as_slice());
assert!(expr_list_eq_strict_order(list3.as_slice(), list3.as_slice());
assert!(expr_list_eq_strict_order(list4.as_slice(), list4.as_slice());
```
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
mingmwang commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1006881904
##########
datafusion/physical-expr/src/expressions/binary.rs:
##########
@@ -649,6 +650,30 @@ impl PhysicalExpr for BinaryExpr {
right: Arc::clone(self.right()),
})
}
+
+ fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.left.clone(), self.right.clone()]
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(BinaryExpr::new(
Review Comment:
I already add the length check in the method `with_new_children_if_necessary()`, and expr.with_new_children() should not be called directly. This is also aligned with the ExecutionPlan.
````
pub fn with_new_children_if_necessary(
expr: Arc<dyn PhysicalExpr>,
children: Vec<Arc<dyn PhysicalExpr>>,
) -> Result<Arc<dyn PhysicalExpr>> {
if children.len() != expr.children().len() {
Err(DataFusionError::Internal(
"PhysicalExpr: Wrong number of children".to_string(),
))
} else if children.is_empty()
|| children
.iter()
.zip(expr.children().iter())
.any(|(c1, c2)| !Arc::ptr_eq(c1, c2))
{
expr.with_new_children(children)
} else {
Ok(expr)
}
}
````
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
mingmwang commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1006891316
##########
datafusion/physical-expr/src/expressions/case.rs:
##########
@@ -286,6 +290,89 @@ impl PhysicalExpr for CaseExpr {
self.case_when_no_expr(batch)
}
}
+
+ fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ let mut chileren = vec![];
+ match &self.expr {
+ Some(expr) => chileren.push(expr.clone()),
+ None => chileren.push(Arc::new(NoOp::new())),
+ }
+ self.when_then_expr.iter().for_each(|(cond, value)| {
+ chileren.push(cond.clone());
+ chileren.push(value.clone());
+ });
+
+ match &self.else_expr {
+ Some(expr) => chileren.push(expr.clone()),
+ None => chileren.push(Arc::new(NoOp::new())),
+ }
+ chileren
+ }
+
+ // For physical CaseExpr, we do not allow modifying children size
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ if children.len() != self.children().len() {
+ Err(DataFusionError::Internal(
+ "CaseExpr: Wrong number of children".to_string(),
+ ))
+ } else {
+ assert_eq!(children.len() % 2, 0);
+ let expr = match children[0].clone().as_any().downcast_ref::<NoOp>() {
+ Some(_) => None,
+ _ => Some(children[0].clone()),
+ };
+ let else_expr = match children[children.len() - 1]
+ .clone()
+ .as_any()
+ .downcast_ref::<NoOp>()
+ {
+ Some(_) => None,
+ _ => Some(children[children.len() - 1].clone()),
+ };
+
+ let branches = children[1..children.len() - 1].to_vec();
+ let mut when_then_expr: Vec<WhenThen> = vec![];
+ for (prev, next) in branches.into_iter().tuples() {
+ when_then_expr.push((prev, next));
+ }
+ Ok(Arc::new(CaseExpr::try_new(
+ expr,
+ when_then_expr,
+ else_expr,
+ )?))
+ }
+ }
+}
+
+impl PartialEq<dyn Any> for CaseExpr {
+ fn eq(&self, other: &dyn Any) -> bool {
+ down_cast_any_ref(other)
+ .downcast_ref::<Self>()
+ .map(|x| {
+ let expr_eq = match (&self.expr, &x.expr) {
+ (Some(expr1), Some(expr2)) => expr1.eq(expr2),
+ (None, None) => true,
+ _ => false,
Review Comment:
I would prefer the current implementation than returning from the Closure. Returning from the Closure might
confuse people, does it mean return from the Closure or return from the outer method? In Rust it is returned from the Closure but in Scala or Java(I remember) it is returned from the outer method. In my opinion, it is not clear and more lines of code.
````
fn eq(&self, other: &dyn Any) -> bool {
down_cast_any_ref(other)
.downcast_ref::<Self>()
.map(|x| {
match (&self.expr, &x.expr) {
(Some(expr1), Some(expr2)) =>{
if expr1.ne(expr2) {
return false;
}
},
(None, None) => {}
_ => return false,
};
match (&self.else_expr, &x.else_expr) {
(Some(expr1), Some(expr2)) => {
if expr1.ne(expr2) {
return false;
}
},
(None, None) => {}
_ => return false,
};
self.when_then_expr.len() == x.when_then_expr.len()
&& self.when_then_expr.iter().zip(x.when_then_expr.iter()).all(
|((when1, then1), (when2, then2))| {
when1.eq(when2) && then1.eq(then2)
},
)
})
.unwrap_or(false)
}
````
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] alamb commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
alamb commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1006939198
##########
datafusion/physical-expr/src/scalar_function.rs:
##########
@@ -145,4 +145,26 @@ impl PhysicalExpr for ScalarFunctionExpr {
let fun = self.fun.as_ref();
(fun)(&inputs)
}
+
+ fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ self.args.clone()
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(ScalarFunctionExpr::new(
+ &self.name,
+ self.fun.clone(),
+ children,
+ self.return_type(),
+ )))
+ }
+}
+
+impl PartialEq<dyn Any> for ScalarFunctionExpr {
+ fn eq(&self, _other: &dyn Any) -> bool {
+ false
Review Comment:
Comparing name, args and return type seems like a pretty good comparison to me
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
mingmwang commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1006962727
##########
datafusion/physical-expr/src/expressions/no_op.rs:
##########
@@ -0,0 +1,87 @@
+// 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.
+
+//! Literal expressions for physical operations
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::{
+ datatypes::{DataType, Schema},
+ record_batch::RecordBatch,
+};
+
+use crate::physical_expr::down_cast_any_ref;
+use crate::PhysicalExpr;
+use datafusion_common::Result;
+use datafusion_expr::ColumnarValue;
+
+/// A place holder expressions, can not be evaluated
+#[derive(Debug, PartialEq, Eq, Default)]
+pub struct NoOp {}
+
+impl NoOp {
+ /// Create a NoOp expression
+ pub fn new() -> Self {
+ Self {}
+ }
+}
+
+impl std::fmt::Display for NoOp {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ write!(f, "NoOp")
+ }
+}
+
+impl PhysicalExpr for NoOp {
+ /// Return a reference to Any that can be used for downcasting
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
+ Ok(DataType::Null)
+ }
+
+ fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
+ Ok(true)
+ }
+
+ fn evaluate(&self, _batch: &RecordBatch) -> Result<ColumnarValue> {
+ unimplemented!("NoOp::evaluate");
Review Comment:
Sure
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #3969: [Part1] Partition and Sort Enforcement, PhysicalExpr enhancement
Posted by GitBox <gi...@apache.org>.
mingmwang commented on code in PR #3969:
URL: https://github.com/apache/arrow-datafusion/pull/3969#discussion_r1006969514
##########
datafusion/physical-expr/src/scalar_function.rs:
##########
@@ -145,4 +145,26 @@ impl PhysicalExpr for ScalarFunctionExpr {
let fun = self.fun.as_ref();
(fun)(&inputs)
}
+
+ fn children(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ self.args.clone()
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(ScalarFunctionExpr::new(
+ &self.name,
+ self.fun.clone(),
+ children,
+ self.return_type(),
+ )))
+ }
+}
+
+impl PartialEq<dyn Any> for ScalarFunctionExpr {
+ fn eq(&self, _other: &dyn Any) -> bool {
+ false
Review Comment:
Ok
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org