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/11 12:43:26 UTC

[GitHub] [arrow-datafusion] andygrove opened a new pull request, #3796: WIP: Add `Filter::try_new` with validation

andygrove opened a new pull request, #3796:
URL: https://github.com/apache/arrow-datafusion/pull/3796

   # 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.
   -->
   
   Closes https://github.com/apache/arrow-datafusion/issues/3795
   
    # 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.  
   -->
   
   Filters should not use aliased expressions
   
   # 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.
   -->
   
   - Implement `Filter::try_new` and make `Filter` attributes private to force the use of the constructor
   - Update all call sites
   
   # 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] alamb commented on a diff in pull request #3796: Add `Filter::try_new` with validation

Posted by GitBox <gi...@apache.org>.
alamb commented on code in PR #3796:
URL: https://github.com/apache/arrow-datafusion/pull/3796#discussion_r993467473


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1148,18 +1150,72 @@ pub struct SubqueryAlias {
 #[derive(Clone)]
 pub struct Filter {
     /// The predicate expression, which must have Boolean type.
-    pub predicate: Expr,
+    predicate: Expr,
     /// The incoming logical plan
-    pub input: Arc<LogicalPlan>,
+    input: Arc<LogicalPlan>,
 }
 
 impl Filter {
+    /// Create a new filter operator.
+    pub fn try_new(
+        predicate: Expr,
+        input: Arc<LogicalPlan>,
+    ) -> datafusion_common::Result<Self> {
+        // Filter predicates must return a boolean value so we try and validate that here.
+        // Note that it is not always possible to resolve the predicate expression during plan
+        // construction (such as with correlated subqueries) so we make a best effort here and
+        // ignore errors resolving the expression against the schema.
+        if let Ok(predicate_type) = predicate.get_type(input.schema()) {
+            if predicate_type != DataType::Boolean {
+                return Err(DataFusionError::Plan(format!(
+                    "Cannot create filter with non-boolean predicate '{}' returning {}",
+                    predicate, predicate_type
+                )));
+            }
+        }
+
+        // filter predicates should not contain aliased expressions so we remove any aliases here
+        // but perhaps we should be failing here instead?
+        struct RemoveAliases {}

Review Comment:
   I think you could reuse `unalias` here: https://docs.rs/datafusion/13.0.0/datafusion/logical_plan/fn.unalias.html



-- 
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 #3796: Add `Filter::try_new` with validation

Posted by GitBox <gi...@apache.org>.
alamb commented on PR #3796:
URL: https://github.com/apache/arrow-datafusion/pull/3796#issuecomment-1275143069

   The CI test is unrelated: https://github.com/apache/arrow-datafusion/issues/3798


-- 
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 #3796: Add `Filter::try_new` with validation

Posted by GitBox <gi...@apache.org>.
alamb merged PR #3796:
URL: https://github.com/apache/arrow-datafusion/pull/3796


-- 
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] andygrove commented on a diff in pull request #3796: WIP: Add `Filter::try_new` with validation

Posted by GitBox <gi...@apache.org>.
andygrove commented on code in PR #3796:
URL: https://github.com/apache/arrow-datafusion/pull/3796#discussion_r992387526


##########
datafusion/optimizer/src/projection_push_down.rs:
##########
@@ -580,12 +580,12 @@ mod tests {
         let table_scan = test_table_scan()?;
 
         let plan = LogicalPlanBuilder::from(table_scan)
-            .filter(col("c"))?
+            .filter(col("c").gt(lit(1)))?

Review Comment:
   This test was invalid and the new validation checks caught this.



-- 
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 #3796: Add `Filter::try_new` with validation

Posted by GitBox <gi...@apache.org>.
alamb commented on code in PR #3796:
URL: https://github.com/apache/arrow-datafusion/pull/3796#discussion_r992627413


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1148,18 +1150,72 @@ pub struct SubqueryAlias {
 #[derive(Clone)]
 pub struct Filter {
     /// The predicate expression, which must have Boolean type.
-    pub predicate: Expr,
+    predicate: Expr,
     /// The incoming logical plan
-    pub input: Arc<LogicalPlan>,
+    input: Arc<LogicalPlan>,
 }
 
 impl Filter {
+    /// Create a new filter operator.
+    pub fn try_new(
+        predicate: Expr,
+        input: Arc<LogicalPlan>,
+    ) -> datafusion_common::Result<Self> {
+        // Filter predicates must return a boolean value so we try and validate that here.
+        // Note that it is not always possible to resolve the predicate expression during plan
+        // construction (such as with correlated subqueries) so we make a best effort here and
+        // ignore errors resolving the expression against the schema.
+        if let Ok(predicate_type) = predicate.get_type(input.schema()) {
+            if predicate_type != DataType::Boolean {
+                return Err(DataFusionError::Plan(format!(
+                    "Cannot create filter with non-boolean predicate '{}' returning {}",
+                    predicate, predicate_type
+                )));
+            }
+        }
+
+        // filter predicates should not contain aliased expressions so we remove any aliases here

Review Comment:
   Is the rationale here that the the output of a `FilterExpr` has the same schema as its input -- since the Filter never changes its input if we find an alias on the FilterExpr then something is likely wrong as it won't change anything?
   
   I would personally prefer to throw an error rather than stripping the aliases and then track down what is adding aliases



##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1148,18 +1150,72 @@ pub struct SubqueryAlias {
 #[derive(Clone)]
 pub struct Filter {
     /// The predicate expression, which must have Boolean type.
-    pub predicate: Expr,
+    predicate: Expr,
     /// The incoming logical plan
-    pub input: Arc<LogicalPlan>,
+    input: Arc<LogicalPlan>,
 }
 
 impl Filter {
+    /// Create a new filter operator.
+    pub fn try_new(
+        predicate: Expr,
+        input: Arc<LogicalPlan>,
+    ) -> datafusion_common::Result<Self> {
+        // Filter predicates must return a boolean value so we try and validate that here.
+        // Note that it is not always possible to resolve the predicate expression during plan
+        // construction (such as with correlated subqueries) so we make a best effort here and
+        // ignore errors resolving the expression against the schema.
+        if let Ok(predicate_type) = predicate.get_type(input.schema()) {
+            if predicate_type != DataType::Boolean {
+                return Err(DataFusionError::Plan(format!(
+                    "Cannot create filter with non-boolean predicate '{}' returning {}",
+                    predicate, predicate_type
+                )));
+            }
+        }
+
+        // filter predicates should not contain aliased expressions so we remove any aliases here
+        // but perhaps we should be failing here instead?
+        struct RemoveAliases {}
+
+        impl ExprRewriter for RemoveAliases {

Review Comment:
   I am not sure about recursively removing all aliases (like what happens if this recurses into suqueries, for example 🤔 ) Removing at the top most level, like
   
   ```rust
   if let Expr::Alias {..} = expr {
   ..
   }
   ``` 
   
   makes more sense



-- 
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 #3796: Add `Filter::try_new` with validation

Posted by GitBox <gi...@apache.org>.
ursabot commented on PR #3796:
URL: https://github.com/apache/arrow-datafusion/pull/3796#issuecomment-1276412143

   Benchmark runs are scheduled for baseline = e27e86baa5a54dd4643055ee3b1521865d0977cd and contender = 3af09fbf2026fc079264b1f67bc7095dc7fe7161. 3af09fbf2026fc079264b1f67bc7095dc7fe7161 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/91f6c17234354130b73953a41aa63858...5b6435c61bfd4d8280f980d9b5f3adb7/)
   [Skipped :warning: Benchmarking of arrow-datafusion-commits is not supported on test-mac-arm] [test-mac-arm](https://conbench.ursa.dev/compare/runs/d31f0d9af0804b4ea75564af90e9bbc8...ec7d2457eed44d919a11834ba6a1267c/)
   [Skipped :warning: Benchmarking of arrow-datafusion-commits is not supported on ursa-i9-9960x] [ursa-i9-9960x](https://conbench.ursa.dev/compare/runs/9411d78efd0c4a55affa81205963db1f...afaaba7c22254964905bddf09663cb11/)
   [Skipped :warning: Benchmarking of arrow-datafusion-commits is not supported on ursa-thinkcentre-m75q] [ursa-thinkcentre-m75q](https://conbench.ursa.dev/compare/runs/410d7c18fe1445d1bf4fc20481ae6eda...fe8759d5c6ea4985ba5375b5719b220c/)
   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] andygrove commented on a diff in pull request #3796: WIP: Add `Filter::try_new` with validation

Posted by GitBox <gi...@apache.org>.
andygrove commented on code in PR #3796:
URL: https://github.com/apache/arrow-datafusion/pull/3796#discussion_r992388547


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1148,18 +1150,78 @@ pub struct SubqueryAlias {
 #[derive(Clone)]
 pub struct Filter {
     /// The predicate expression, which must have Boolean type.
-    pub predicate: Expr,
+    pub(crate) predicate: Expr,
     /// The incoming logical plan
-    pub input: Arc<LogicalPlan>,
+    pub(crate) input: Arc<LogicalPlan>,
 }
 
 impl Filter {
+    /// Create a new filter operator.
+    pub fn try_new(
+        predicate: Expr,
+        input: Arc<LogicalPlan>,
+    ) -> datafusion_common::Result<Self> {
+        // filter predicates must return a boolean value
+        match predicate.get_type(input.schema()) {
+            Ok(predicate_type) => {
+                if predicate_type != DataType::Boolean {
+                    return Err(DataFusionError::Plan(format!(
+                        "Cannot create filter with non-boolean predicate '{}' returning {}",
+                        predicate, predicate_type
+                    )));
+                }
+            }
+            Err(e) => {
+                // We shouldn't really have to deal with an error case here but it looks
+                // like we sometimes have plans that are not valid until they are optimized.
+                // In this case, the optimizer rules will eventually recreate the
+                // filter expression and we'll do the validation at that time.
+                debug!("Could not determine type of filter predicate: {}", e);
+            }
+        }
+
+        // filter predicates should not contain aliased expressions so we remove any aliases here
+        // but perhaps we should be failing here instead?
+        struct RemoveAliases {}
+
+        impl ExprRewriter for RemoveAliases {
+            fn mutate(&mut self, expr: Expr) -> datafusion_common::Result<Expr> {
+                match expr {
+                    Expr::Alias(expr, alias) => {
+                        debug!(
+                            "Attempted to create Filter predicate containing aliased \
+                            expression `{}` AS '{}'",
+                            expr, alias
+                        );
+                        Ok(expr.as_ref().clone())
+                    }
+                    _ => Ok(expr.clone()),
+                }
+            }
+        }
+
+        let mut remove_aliases = RemoveAliases {};
+        let predicate = predicate.rewrite(&mut remove_aliases)?;
+
+        Ok(Self { predicate, input })
+    }

Review Comment:
   This is the main point of this PR - implementing some validation when creating a new filter operator.



-- 
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] andygrove commented on a diff in pull request #3796: WIP: Add `Filter::try_new` with validation

Posted by GitBox <gi...@apache.org>.
andygrove commented on code in PR #3796:
URL: https://github.com/apache/arrow-datafusion/pull/3796#discussion_r992389719


##########
datafusion/optimizer/src/simplify_expressions.rs:
##########
@@ -1930,7 +1930,7 @@ mod tests {
         assert_optimized_plan_eq(
             &plan,
             "\
-	        Filter: test.b > Int32(1) AS test.b > Int32(1) AND test.b > Int32(1)\
+	        Filter: test.b > Int32(1)\

Review Comment:
   The updated tests here demonstrate that we no longer have aliases for filter predicates.



-- 
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] andygrove commented on a diff in pull request #3796: Add `Filter::try_new` with validation

Posted by GitBox <gi...@apache.org>.
andygrove commented on code in PR #3796:
URL: https://github.com/apache/arrow-datafusion/pull/3796#discussion_r992505272


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1148,18 +1150,72 @@ pub struct SubqueryAlias {
 #[derive(Clone)]
 pub struct Filter {
     /// The predicate expression, which must have Boolean type.
-    pub predicate: Expr,
+    predicate: Expr,
     /// The incoming logical plan
-    pub input: Arc<LogicalPlan>,
+    input: Arc<LogicalPlan>,
 }
 
 impl Filter {
+    /// Create a new filter operator.
+    pub fn try_new(
+        predicate: Expr,
+        input: Arc<LogicalPlan>,
+    ) -> datafusion_common::Result<Self> {
+        // Filter predicates must return a boolean value so we try and validate that here.
+        // Note that it is not always possible to resolve the predicate expression during plan
+        // construction (such as with correlated subqueries) so we make a best effort here and
+        // ignore errors resolving the expression against the schema.
+        if let Ok(predicate_type) = predicate.get_type(input.schema()) {
+            if predicate_type != DataType::Boolean {
+                return Err(DataFusionError::Plan(format!(
+                    "Cannot create filter with non-boolean predicate '{}' returning {}",
+                    predicate, predicate_type
+                )));
+            }
+        }
+
+        // filter predicates should not contain aliased expressions so we remove any aliases here
+        // but perhaps we should be failing here instead?
+        struct RemoveAliases {}
+
+        impl ExprRewriter for RemoveAliases {
+            fn mutate(&mut self, expr: Expr) -> datafusion_common::Result<Expr> {
+                match expr {
+                    Expr::Alias(expr, alias) => {
+                        debug!(
+                            "Attempted to create Filter predicate containing aliased \
+                            expression `{}` AS '{}'",
+                            expr, alias
+                        );
+                        Ok(expr.as_ref().clone())
+                    }
+                    _ => Ok(expr.clone()),
+                }
+            }
+        }
+
+        let mut remove_aliases = RemoveAliases {};
+        let predicate = predicate.rewrite(&mut remove_aliases)?;
+
+        Ok(Self { predicate, input })
+    }

Review Comment:
   This is the main point of this PR - implementing some validation when creating a new filter operator.



-- 
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] andygrove commented on a diff in pull request #3796: Add `Filter::try_new` with validation

Posted by GitBox <gi...@apache.org>.
andygrove commented on code in PR #3796:
URL: https://github.com/apache/arrow-datafusion/pull/3796#discussion_r993549376


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1148,18 +1150,72 @@ pub struct SubqueryAlias {
 #[derive(Clone)]
 pub struct Filter {
     /// The predicate expression, which must have Boolean type.
-    pub predicate: Expr,
+    predicate: Expr,
     /// The incoming logical plan
-    pub input: Arc<LogicalPlan>,
+    input: Arc<LogicalPlan>,
 }
 
 impl Filter {
+    /// Create a new filter operator.
+    pub fn try_new(
+        predicate: Expr,
+        input: Arc<LogicalPlan>,
+    ) -> datafusion_common::Result<Self> {
+        // Filter predicates must return a boolean value so we try and validate that here.
+        // Note that it is not always possible to resolve the predicate expression during plan
+        // construction (such as with correlated subqueries) so we make a best effort here and
+        // ignore errors resolving the expression against the schema.
+        if let Ok(predicate_type) = predicate.get_type(input.schema()) {
+            if predicate_type != DataType::Boolean {
+                return Err(DataFusionError::Plan(format!(
+                    "Cannot create filter with non-boolean predicate '{}' returning {}",
+                    predicate, predicate_type
+                )));
+            }
+        }
+
+        // filter predicates should not contain aliased expressions so we remove any aliases here
+        // but perhaps we should be failing here instead?
+        struct RemoveAliases {}
+
+        impl ExprRewriter for RemoveAliases {
+            fn mutate(&mut self, expr: Expr) -> datafusion_common::Result<Expr> {
+                match expr {
+                    Expr::Alias(expr, alias) => {
+                        debug!(
+                            "Attempted to create Filter predicate containing aliased \
+                            expression `{}` AS '{}'",
+                            expr, alias
+                        );
+                        Ok(expr.as_ref().clone())

Review Comment:
   This code no longer exists



##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1148,18 +1150,72 @@ pub struct SubqueryAlias {
 #[derive(Clone)]
 pub struct Filter {
     /// The predicate expression, which must have Boolean type.
-    pub predicate: Expr,
+    predicate: Expr,
     /// The incoming logical plan
-    pub input: Arc<LogicalPlan>,
+    input: Arc<LogicalPlan>,
 }
 
 impl Filter {
+    /// Create a new filter operator.
+    pub fn try_new(
+        predicate: Expr,
+        input: Arc<LogicalPlan>,
+    ) -> datafusion_common::Result<Self> {
+        // Filter predicates must return a boolean value so we try and validate that here.
+        // Note that it is not always possible to resolve the predicate expression during plan
+        // construction (such as with correlated subqueries) so we make a best effort here and
+        // ignore errors resolving the expression against the schema.
+        if let Ok(predicate_type) = predicate.get_type(input.schema()) {
+            if predicate_type != DataType::Boolean {
+                return Err(DataFusionError::Plan(format!(
+                    "Cannot create filter with non-boolean predicate '{}' returning {}",
+                    predicate, predicate_type
+                )));
+            }
+        }
+
+        // filter predicates should not contain aliased expressions so we remove any aliases here
+        // but perhaps we should be failing here instead?
+        struct RemoveAliases {}
+
+        impl ExprRewriter for RemoveAliases {
+            fn mutate(&mut self, expr: Expr) -> datafusion_common::Result<Expr> {
+                match expr {
+                    Expr::Alias(expr, alias) => {
+                        debug!(
+                            "Attempted to create Filter predicate containing aliased \
+                            expression `{}` AS '{}'",
+                            expr, alias
+                        );
+                        Ok(expr.as_ref().clone())
+                    }
+                    _ => Ok(expr.clone()),

Review Comment:
   This code no longer exists



-- 
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] andygrove commented on a diff in pull request #3796: Add `Filter::try_new` with validation

Posted by GitBox <gi...@apache.org>.
andygrove commented on code in PR #3796:
URL: https://github.com/apache/arrow-datafusion/pull/3796#discussion_r993545656


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1148,18 +1150,72 @@ pub struct SubqueryAlias {
 #[derive(Clone)]
 pub struct Filter {
     /// The predicate expression, which must have Boolean type.
-    pub predicate: Expr,
+    predicate: Expr,
     /// The incoming logical plan
-    pub input: Arc<LogicalPlan>,
+    input: Arc<LogicalPlan>,
 }
 
 impl Filter {
+    /// Create a new filter operator.
+    pub fn try_new(
+        predicate: Expr,
+        input: Arc<LogicalPlan>,
+    ) -> datafusion_common::Result<Self> {
+        // Filter predicates must return a boolean value so we try and validate that here.
+        // Note that it is not always possible to resolve the predicate expression during plan
+        // construction (such as with correlated subqueries) so we make a best effort here and
+        // ignore errors resolving the expression against the schema.
+        if let Ok(predicate_type) = predicate.get_type(input.schema()) {
+            if predicate_type != DataType::Boolean {
+                return Err(DataFusionError::Plan(format!(
+                    "Cannot create filter with non-boolean predicate '{}' returning {}",
+                    predicate, predicate_type
+                )));
+            }
+        }
+
+        // filter predicates should not contain aliased expressions so we remove any aliases here

Review Comment:
   `FilterExec::try_new` now throws an exception when passed an aliased predicate and the rewrite logic has moved to `utils::from_plan` which is called from multiple optimizer rules



-- 
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 #3796: Add `Filter::try_new` with validation

Posted by GitBox <gi...@apache.org>.
alamb commented on code in PR #3796:
URL: https://github.com/apache/arrow-datafusion/pull/3796#discussion_r993468214


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1148,18 +1150,72 @@ pub struct SubqueryAlias {
 #[derive(Clone)]
 pub struct Filter {
     /// The predicate expression, which must have Boolean type.
-    pub predicate: Expr,
+    predicate: Expr,
     /// The incoming logical plan
-    pub input: Arc<LogicalPlan>,
+    input: Arc<LogicalPlan>,
 }
 
 impl Filter {
+    /// Create a new filter operator.
+    pub fn try_new(
+        predicate: Expr,
+        input: Arc<LogicalPlan>,
+    ) -> datafusion_common::Result<Self> {
+        // Filter predicates must return a boolean value so we try and validate that here.
+        // Note that it is not always possible to resolve the predicate expression during plan
+        // construction (such as with correlated subqueries) so we make a best effort here and
+        // ignore errors resolving the expression against the schema.
+        if let Ok(predicate_type) = predicate.get_type(input.schema()) {
+            if predicate_type != DataType::Boolean {
+                return Err(DataFusionError::Plan(format!(
+                    "Cannot create filter with non-boolean predicate '{}' returning {}",
+                    predicate, predicate_type
+                )));
+            }
+        }
+
+        // filter predicates should not contain aliased expressions so we remove any aliases here
+        // but perhaps we should be failing here instead?
+        struct RemoveAliases {}
+
+        impl ExprRewriter for RemoveAliases {
+            fn mutate(&mut self, expr: Expr) -> datafusion_common::Result<Expr> {
+                match expr {
+                    Expr::Alias(expr, alias) => {
+                        debug!(
+                            "Attempted to create Filter predicate containing aliased \
+                            expression `{}` AS '{}'",
+                            expr, alias
+                        );
+                        Ok(expr.as_ref().clone())

Review Comment:
   ```suggestion
                           Ok(expr)
   ```



##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1148,18 +1150,72 @@ pub struct SubqueryAlias {
 #[derive(Clone)]
 pub struct Filter {
     /// The predicate expression, which must have Boolean type.
-    pub predicate: Expr,
+    predicate: Expr,
     /// The incoming logical plan
-    pub input: Arc<LogicalPlan>,
+    input: Arc<LogicalPlan>,
 }
 
 impl Filter {
+    /// Create a new filter operator.
+    pub fn try_new(
+        predicate: Expr,
+        input: Arc<LogicalPlan>,
+    ) -> datafusion_common::Result<Self> {
+        // Filter predicates must return a boolean value so we try and validate that here.
+        // Note that it is not always possible to resolve the predicate expression during plan
+        // construction (such as with correlated subqueries) so we make a best effort here and
+        // ignore errors resolving the expression against the schema.
+        if let Ok(predicate_type) = predicate.get_type(input.schema()) {
+            if predicate_type != DataType::Boolean {
+                return Err(DataFusionError::Plan(format!(
+                    "Cannot create filter with non-boolean predicate '{}' returning {}",
+                    predicate, predicate_type
+                )));
+            }
+        }
+
+        // filter predicates should not contain aliased expressions so we remove any aliases here
+        // but perhaps we should be failing here instead?
+        struct RemoveAliases {}
+
+        impl ExprRewriter for RemoveAliases {
+            fn mutate(&mut self, expr: Expr) -> datafusion_common::Result<Expr> {
+                match expr {
+                    Expr::Alias(expr, alias) => {
+                        debug!(
+                            "Attempted to create Filter predicate containing aliased \
+                            expression `{}` AS '{}'",
+                            expr, alias
+                        );
+                        Ok(expr.as_ref().clone())
+                    }
+                    _ => Ok(expr.clone()),

Review Comment:
   ```suggestion
                       _ => 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