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 2021/11/19 15:41:38 UTC

[GitHub] [arrow-datafusion] xudong963 opened a new pull request #1339: fix: filter pushdown with unsafe null

xudong963 opened a new pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339


   # 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/1321
   
    # 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.
   -->
   
   # 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] xudong963 commented on a change in pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on a change in pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#discussion_r753348167



##########
File path: datafusion/src/optimizer/filter_push_down.rs
##########
@@ -408,10 +412,20 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
             //
             // Join clauses with `Using` constraints also take advantage of this logic to make sure
             // predicates reference the shared join columns are pushed to both sides.
+            let mut null_unsafe_predicates = vec![];
             let join_side_filters = state
                 .filters
                 .iter()
                 .filter_map(|(predicate, columns)| {
+                    if join_type == &JoinType::Left
+                        || join_type == &JoinType::Right

Review comment:
       > Yes, that's why I suggest to add the "safe" variants here instead, to not allow the safe variant by default if we would add another type.
   > 
   > Even better would be IMO to extract this to a function with a normal (without wildcard) pattern match. This way, when a new variant is added, it will be a compile error.
   > 
   > ```rust
   > fun is_null_safe(join_type: JoinType) -> bool {
   >     match join_type...
   > }
   > ```
   
   Nice, I like the way!




-- 
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] xudong963 commented on a change in pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on a change in pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#discussion_r753335321



##########
File path: datafusion/src/optimizer/filter_push_down.rs
##########
@@ -408,10 +412,20 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
             //
             // Join clauses with `Using` constraints also take advantage of this logic to make sure
             // predicates reference the shared join columns are pushed to both sides.
+            let mut null_unsafe_predicates = vec![];
             let join_side_filters = state
                 .filters
                 .iter()
                 .filter_map(|(predicate, columns)| {
+                    if join_type == &JoinType::Left
+                        || join_type == &JoinType::Right
+                        || join_type == &JoinType::Full
+                    {
+                        if let Expr::IsNull(..) | Expr::IsNotNull(..) = predicate {

Review comment:
       Nice caught! I'll add a function to check if an `Expr` contains `IsNotNuLL` or `IsNull`




-- 
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 #1339: fix: filter pushdown with unsafe null

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


   @xudong963  thank you for the examples
   
   Given this input:
   ```sql
   ❯ create table table1 as SELECT * FROM (VALUES (1), (2), (null)) as t;
   0 rows in set. Query took 0.006 seconds.
   ❯ create table table2 as SELECT * FROM (VALUES (1), (3), (null)) as t;
   0 rows in set. Query took 0.003 seconds.
   ```
   
   The plan that comes out is incorrect:
   
   ```sql
   ❯ explain SELECT *
   FROM table1
   LEFT JOIN table2
       ON table1.column1 = table2.column1
   WHERE table2.column1 IS NOT NULL;
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   | plan_type     | plan                                                                                                                                  |
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                          |
   |               |   Join: #table1.column1 = #table2.column1                                                                                             |
   |               |     Filter: #table1.column1 IS NOT NULL                                                                                               |
   |               |       TableScan: table1 projection=Some([0])                                                                                          |
   |               |     Filter: #table2.column1 IS NOT NULL                                                                                               |
   |               |       TableScan: table2 projection=Some([0])                                                                                          |
   
   ```
   
   I think the problem is this line:
   ```
   |               |     Filter: #table1.column1 IS NOT NULL                                                                                               |
   ```
   
   Namely something has added a predicate to `table1.column1` (where the original query has only a predicate on `table2`).
   
   The same problem happens for `>5` type predicates too:
   
   ```sql
   explain SELECT *
   FROM table1
   LEFT JOIN table2
       ON table1.column1 = table2.column1
   WHERE table2.column1 > 5;
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   | plan_type     | plan                                                                                                                                  |
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                          |
   |               |   Join: #table1.column1 = #table2.column1                                                                                             |
   |               |     Filter: #table1.column1 > Int64(5)                                                                                                |
   |               |       TableScan: table1 projection=Some([0])                                                                                          |
   |               |     Filter: #table2.column1 > Int64(5)                                                                                                |
   |               |       TableScan: table2 projection=Some([0])                                                                                          
   ```
   
   The equivalent plan from postgres only pushes the filter down for `table2` (there is no filter on `table1.column1`):
   
   ```sql
   alamb=# explain SELECT *
   FROM table1
   LEFT JOIN table2
       ON table1.column1 = table2.column1
   WHERE table2.column1 > 5;
                                 QUERY PLAN                              
   ----------------------------------------------------------------------
    Merge Join  (cost=263.02..429.84 rows=10838 width=8)
      Merge Cond: (table2.column1 = table1.column1)
      ->  Sort  (cost=83.23..85.36 rows=850 width=4)
            Sort Key: table2.column1
            ->  Seq Scan on table2  (cost=0.00..41.88 rows=850 width=4)
                  Filter: (column1 > 5)
      ->  Sort  (cost=179.78..186.16 rows=2550 width=4)
            Sort Key: table1.column1
            ->  Seq Scan on table1  (cost=0.00..35.50 rows=2550 width=4)
   (9 rows)
   ```


-- 
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] xudong963 commented on a change in pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on a change in pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#discussion_r753654701



##########
File path: datafusion/src/optimizer/filter_push_down.rs
##########
@@ -408,10 +412,20 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
             //
             // Join clauses with `Using` constraints also take advantage of this logic to make sure
             // predicates reference the shared join columns are pushed to both sides.
+            let mut null_unsafe_predicates = vec![];
             let join_side_filters = state
                 .filters
                 .iter()
                 .filter_map(|(predicate, columns)| {
+                    if join_type == &JoinType::Left
+                        || join_type == &JoinType::Right
+                        || join_type == &JoinType::Full
+                    {
+                        if let Expr::IsNull(..) | Expr::IsNotNull(..) = predicate {

Review comment:
       > I don't think we can push _ANY_ filers from the `ON` clause down the non preserved side(s) of an outer join -- in other words, this is not a problem with `IS NULL` and `IS NOT NULL`.
   
   Yes, I agree. Luckily, we don't implement the case. https://github.com/apache/arrow-datafusion/blob/0facd4d483e8c289ee4e3a89487d0cd1ede1a110/datafusion/src/sql/planner.rs#L564
   
   However, I think there is a problem with `IS NULL` and `IS NOT NULL` in `WHERE` clause, we shouldn't push them down.




-- 
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] xudong963 commented on a change in pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on a change in pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#discussion_r753654701



##########
File path: datafusion/src/optimizer/filter_push_down.rs
##########
@@ -408,10 +412,20 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
             //
             // Join clauses with `Using` constraints also take advantage of this logic to make sure
             // predicates reference the shared join columns are pushed to both sides.
+            let mut null_unsafe_predicates = vec![];
             let join_side_filters = state
                 .filters
                 .iter()
                 .filter_map(|(predicate, columns)| {
+                    if join_type == &JoinType::Left
+                        || join_type == &JoinType::Right
+                        || join_type == &JoinType::Full
+                    {
+                        if let Expr::IsNull(..) | Expr::IsNotNull(..) = predicate {

Review comment:
       > I don't think we can push _ANY_ filers from the `ON` clause down the non preserved side(s) of an outer join -- in other words, this is not a problem with `IS NULL` and `IS NOT NULL`.
   
   Yes, I agree. Luckily, we don't implement the case. https://github.com/apache/arrow-datafusion/blob/0facd4d483e8c289ee4e3a89487d0cd1ede1a110/datafusion/src/sql/planner.rs#L564
   
   However, I think there is a problem with `IS NULL` and `IS NOT NULL` in `WHERE` clause with an outer join, we shouldn't push them down.  I think the ticket is solving the problem.




-- 
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] xudong963 edited a comment on pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 edited a comment on pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#issuecomment-981733521


   > @xudong963 thank you for the examples
   > 
   > Given this input:
   > 
   > ```sql
   > ❯ create table table1 as SELECT * FROM (VALUES (1), (2), (null)) as t;
   > 0 rows in set. Query took 0.006 seconds.
   > ❯ create table table2 as SELECT * FROM (VALUES (1), (3), (null)) as t;
   > 0 rows in set. Query took 0.003 seconds.
   > ```
   > 
   > The plan that comes out is incorrect:
   > 
   > ```sql
   > ❯ explain SELECT *
   > FROM table1
   > LEFT JOIN table2
   >     ON table1.column1 = table2.column1
   > WHERE table2.column1 IS NOT NULL;
   > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > | plan_type     | plan                                                                                                                                  |
   > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                          |
   > |               |   Join: #table1.column1 = #table2.column1                                                                                             |
   > |               |     Filter: #table1.column1 IS NOT NULL                                                                                               |
   > |               |       TableScan: table1 projection=Some([0])                                                                                          |
   > |               |     Filter: #table2.column1 IS NOT NULL                                                                                               |
   > |               |       TableScan: table2 projection=Some([0])                                                                                          |
   > ```
   > 
   > I think the problem is this line:
   > 
   > ```
   > |               |     Filter: #table1.column1 IS NOT NULL      
   > ```
   
   ```sql
   postgres=# select * from table1;
    column1
   ---------
          1
          2
   
   (3 rows)
   
   postgres=# select * from table2;
    column1
   ---------
          1
          3
   
   (3 rows)
   
   df
   ❯ select * from table1;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 2       |
   |         |
   +---------+
   3 rows in set. Query took 0.004 seconds.
   ❯ select * from table2;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 3       |
   |         |
   +---------+
   3 rows in set. Query took 0.004 seconds.
   ```
   I changed my code according to your comments and got the following result:
   
   ```sql
   ❯ explain SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   | plan_type     | plan                                                                                                                                  |
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                          |
   |               |   Join: #table1.column1 = #table2.column1                                                                                             |
   |               |     TableScan: table1 projection=Some([0])                                                                                            |
   |               |     Filter: #table2.column1 IS NOT NULL                                                                                               |
   |               |       TableScan: table2 projection=Some([0])                                                                                          |
   | physical_plan | ProjectionExec: expr=[column1@0 as column1, column1@1 as column1]                                                                     |
   |               |   CoalesceBatchesExec: target_batch_size=4096                                                                                         |
   |               |     HashJoinExec: mode=Partitioned, join_type=Left, on=[(Column { name: "column1", index: 0 }, Column { name: "column1", index: 0 })] |
   |               |       CoalesceBatchesExec: target_batch_size=4096                                                                                     |
   |               |         RepartitionExec: partitioning=Hash([Column { name: "column1", index: 0 }], 8)                                                 |
   |               |           MemoryExec: partitions=8, partition_sizes=[1, 0, 0, 0, 0, 0, 0, 0]                                                          |
   |               |       CoalesceBatchesExec: target_batch_size=4096                                                                                     |
   |               |         RepartitionExec: partitioning=Hash([Column { name: "column1", index: 0 }], 8)                                                 |
   |               |           CoalesceBatchesExec: target_batch_size=4096                                                                                 |
   |               |             FilterExec: column1@0 IS NOT NULL                                                                                         |
   |               |               MemoryExec: partitions=8, partition_sizes=[1, 0, 0, 0, 0, 0, 0, 0]                                                      |
   |               |                                                                                                                                       |
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   2 rows in set. Query took 0.013 seconds.
   ❯ SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
   +---------+---------+
   | column1 | column1 |
   +---------+---------+
   | 2       |         |
   |         |         |
   | 1       | 1       |
   +---------+---------+
   3 rows in set. Query took 0.014 seconds.
   ```
   
   But postgresql's result is different
   ```sql
   postgres=# explain SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
                                 QUERY PLAN
   ----------------------------------------------------------------------
    Merge Join  (cost=358.74..856.63 rows=32347 width=8)
      Merge Cond: (table2.column1 = table1.column1)
      ->  Sort  (cost=178.95..185.30 rows=2537 width=4)
            Sort Key: table2.column1
            ->  Seq Scan on table2  (cost=0.00..35.50 rows=2537 width=4)
                  Filter: (column1 IS NOT NULL)
      ->  Sort  (cost=179.78..186.16 rows=2550 width=4)
            Sort Key: table1.column1
            ->  Seq Scan on table1  (cost=0.00..35.50 rows=2550 width=4)
   (9 rows)
   
   postgres=# SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL
   postgres-# ;
    column1 | column1
   ---------+---------
          1 |       1
   (1 row)
   
   
   ```


-- 
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] xudong963 edited a comment on pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 edited a comment on pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#issuecomment-1013836655


   @alamb , I thought about this again, I think we can open a new issue #1586  to summarize the conclusion, and close this old ticket.
   
   


-- 
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] xudong963 commented on pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#issuecomment-974191228


   FYI, PostgreSQL has the following results.
   
   ```sql
   postgres=# create table table1 as SELECT * FROM (VALUES (1), (2), (null)) as t;
   SELECT 3
   postgres=# create table table2 as SELECT * FROM (VALUES (1), (3), (null)) as t;
   SELECT 3
   
   postgres=# SELECT *
   FROM table1
   LEFT JOIN table2
       ON table1.column1 = table2.column1
   WHERE table2.column1 IS NULL;
    column1 | column1
   ---------+---------
          2 |
            |
   (2 rows)
   
   postgres=# SELECT *
   FROM table1
   LEFT JOIN table2
       ON table1.column1 = table2.column1
   WHERE table2.column1 IS NOT NULL;
    column1 | column1
   ---------+---------
          1 |       1
   (1 row)
   
   postgres=# SELECT *
   FROM table2
   RIGHT JOIN table1
       ON table1.column1 = table2.column1
   WHERE table2.column1 IS NULL;
    column1 | column1
   ---------+---------
            |       2
            |
   (2 rows)
   
   postgres=# SELECT *
   FROM table2
   RIGHT JOIN table1
       ON table1.column1 = table2.column1
   WHERE table2.column1 IS NOT NULL;
    column1 | column1
   ---------+---------
          1 |       1
   (1 row)
   
   postgres=# SELECT *
   FROM table1
   FULL JOIN table2
       ON table1.column1 = table2.column1
   WHERE table2.column1 IS NULL;
    column1 | column1
   ---------+---------
          2 |
            |
            |
   (3 rows)
   
   postgres=# SELECT *
   FROM table1
   FULL JOIN table2
       ON table1.column1 = table2.column1
   WHERE table2.column1 IS NOT NULL;
    column1 | column1
   ---------+---------
          1 |       1
            |       3
   (2 rows)
   ```


-- 
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] xudong963 removed a comment on pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 removed a comment on pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#issuecomment-982194847


   > > @xudong963 thank you for the examples
   > > Given this input:
   > > ```sql
   > > ❯ create table table1 as SELECT * FROM (VALUES (1), (2), (null)) as t;
   > > 0 rows in set. Query took 0.006 seconds.
   > > ❯ create table table2 as SELECT * FROM (VALUES (1), (3), (null)) as t;
   > > 0 rows in set. Query took 0.003 seconds.
   > > ```
   > > 
   > > 
   > >     
   > >       
   > >     
   > > 
   > >       
   > >     
   > > 
   > >     
   > >   
   > > The plan that comes out is incorrect:
   > > ```sql
   > > ❯ explain SELECT *
   > > FROM table1
   > > LEFT JOIN table2
   > >     ON table1.column1 = table2.column1
   > > WHERE table2.column1 IS NOT NULL;
   > > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > > | plan_type     | plan                                                                                                                                  |
   > > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > > | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                          |
   > > |               |   Join: #table1.column1 = #table2.column1                                                                                             |
   > > |               |     Filter: #table1.column1 IS NOT NULL                                                                                               |
   > > |               |       TableScan: table1 projection=Some([0])                                                                                          |
   > > |               |     Filter: #table2.column1 IS NOT NULL                                                                                               |
   > > |               |       TableScan: table2 projection=Some([0])                                                                                          |
   > > ```
   > > 
   > > 
   > >     
   > >       
   > >     
   > > 
   > >       
   > >     
   > > 
   > >     
   > >   
   > > I think the problem is this line:
   > > ```
   > > |               |     Filter: #table1.column1 IS NOT NULL      
   > > ```
   > 
   > ```sql
   > postgres=# select * from table1;
   >  column1
   > ---------
   >        1
   >        2
   > 
   > (3 rows)
   > 
   > postgres=# select * from table2;
   >  column1
   > ---------
   >        1
   >        3
   > 
   > (3 rows)
   > 
   > df
   > ❯ select * from table1;
   > +---------+
   > | column1 |
   > +---------+
   > | 1       |
   > | 2       |
   > |         |
   > +---------+
   > 3 rows in set. Query took 0.004 seconds.
   > ❯ select * from table2;
   > +---------+
   > | column1 |
   > +---------+
   > | 1       |
   > | 3       |
   > |         |
   > +---------+
   > 3 rows in set. Query took 0.004 seconds.
   > ```
   > 
   > I changed my code according to your comments
   > 
   > ```rust
   > fn optimize_join(
   >     mut state: State,
   >     plan: &LogicalPlan,
   >     left: &LogicalPlan,
   >     right: &LogicalPlan,
   >     join_type: Option<&JoinType>,
   > ) -> Result<LogicalPlan> {
   >     let (mut pushable_to_left, mut pushable_to_right, keep) =
   >         get_join_predicates(&state, left.schema(), right.schema());
   >     if join_type.is_some() {
   >         match join_type.unwrap() {
   >             JoinType::Left => pushable_to_left.clear(),
   >             JoinType::Right => pushable_to_right.clear(),
   >             JoinType::Full => {
   >                 pushable_to_left.clear();
   >                 pushable_to_right.clear()
   >             }
   >             _ => {}
   >         }
   >     }
   > ```
   > 
   > and got the following result:
   > 
   > ```sql
   > ❯ explain SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
   > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > | plan_type     | plan                                                                                                                                  |
   > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                          |
   > |               |   Join: #table1.column1 = #table2.column1                                                                                             |
   > |               |     TableScan: table1 projection=Some([0])                                                                                            |
   > |               |     Filter: #table2.column1 IS NOT NULL                                                                                               |
   > |               |       TableScan: table2 projection=Some([0])                                                                                          |
   > | physical_plan | ProjectionExec: expr=[column1@0 as column1, column1@1 as column1]                                                                     |
   > |               |   CoalesceBatchesExec: target_batch_size=4096                                                                                         |
   > |               |     HashJoinExec: mode=Partitioned, join_type=Left, on=[(Column { name: "column1", index: 0 }, Column { name: "column1", index: 0 })] |
   > |               |       CoalesceBatchesExec: target_batch_size=4096                                                                                     |
   > |               |         RepartitionExec: partitioning=Hash([Column { name: "column1", index: 0 }], 8)                                                 |
   > |               |           MemoryExec: partitions=8, partition_sizes=[1, 0, 0, 0, 0, 0, 0, 0]                                                          |
   > |               |       CoalesceBatchesExec: target_batch_size=4096                                                                                     |
   > |               |         RepartitionExec: partitioning=Hash([Column { name: "column1", index: 0 }], 8)                                                 |
   > |               |           CoalesceBatchesExec: target_batch_size=4096                                                                                 |
   > |               |             FilterExec: column1@0 IS NOT NULL                                                                                         |
   > |               |               MemoryExec: partitions=8, partition_sizes=[1, 0, 0, 0, 0, 0, 0, 0]                                                      |
   > |               |                                                                                                                                       |
   > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > 2 rows in set. Query took 0.013 seconds.
   > ❯ SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
   > +---------+---------+
   > | column1 | column1 |
   > +---------+---------+
   > | 2       |         |
   > |         |         |
   > | 1       | 1       |
   > +---------+---------+
   > 3 rows in set. Query took 0.014 seconds.
   > ```
   > 
   > But postgresql's result is different
   > 
   > ```sql
   > postgres=# explain SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
   >                               QUERY PLAN
   > ----------------------------------------------------------------------
   >  Merge Join  (cost=358.74..856.63 rows=32347 width=8)
   >    Merge Cond: (table2.column1 = table1.column1)
   >    ->  Sort  (cost=178.95..185.30 rows=2537 width=4)
   >          Sort Key: table2.column1
   >          ->  Seq Scan on table2  (cost=0.00..35.50 rows=2537 width=4)
   >                Filter: (column1 IS NOT NULL)
   >    ->  Sort  (cost=179.78..186.16 rows=2550 width=4)
   >          Sort Key: table1.column1
   >          ->  Seq Scan on table1  (cost=0.00..35.50 rows=2550 width=4)
   > (9 rows)
   > 
   > postgres=# SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL
   > postgres-# ;
   >  column1 | column1
   > ---------+---------
   >        1 |       1
   > (1 row)
   > ```
   
   I guess 


-- 
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] xudong963 closed pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 closed pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339


   


-- 
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] xudong963 commented on a change in pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on a change in pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#discussion_r753655676



##########
File path: datafusion/tests/sql.rs
##########
@@ -5999,3 +5999,86 @@ async fn test_expect_distinct() -> Result<()> {
     assert_batches_eq!(expected, &actual);
     Ok(())
 }
+
+#[tokio::test]
+async fn test_predicate_push_down_with_unsafe_null() -> Result<()> {
+    let mut ctx = ExecutionContext::new();
+    let create_table1_sql =
+        "create table table1 as SELECT * FROM (VALUES (1), (2), (null)) as t";
+    ctx.sql(create_table1_sql).await.unwrap();
+    let create_table2_sql =
+        "create table table2 as SELECT * FROM (VALUES (1), (3), (null)) as t";
+    ctx.sql(create_table2_sql).await.unwrap();
+    // left join with is_not_null filter
+    let sql = "SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL";
+    let actual = execute_to_batches(&mut ctx, sql).await;
+    let expected = vec![
+        "+---------+---------+",
+        "| column1 | column1 |",
+        "+---------+---------+",
+        "| 1       | 1       |",
+        "+---------+---------+",
+    ];
+    assert_batches_eq!(expected, &actual);
+    // left join with is_null filter
+    let sql = "SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NULL ORDER BY table1.column1";
+    let actual = execute_to_batches(&mut ctx, sql).await;
+    let expected = vec![
+        "+---------+---------+",
+        "| column1 | column1 |",
+        "+---------+---------+",
+        "|         |         |",
+        "| 2       |         |",
+        "+---------+---------+",

Review comment:
       This is because currently, DF is by default nulls first to be consistent with spark. I'll pull a request to make it be consistent with postgresql. 
   
   FYI, pg rule: https://www.postgresql.org/docs/current/queries-order.html
   > The NULLS FIRST and NULLS LAST options can be used to determine whether nulls appear before or after non-null values in the sort ordering. By default, null values sort as if larger than any non-null value; that is, NULLS FIRST is the default for DESC order, and NULLS LAST otherwise.




-- 
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] xudong963 commented on a change in pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on a change in pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#discussion_r753654701



##########
File path: datafusion/src/optimizer/filter_push_down.rs
##########
@@ -408,10 +412,20 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
             //
             // Join clauses with `Using` constraints also take advantage of this logic to make sure
             // predicates reference the shared join columns are pushed to both sides.
+            let mut null_unsafe_predicates = vec![];
             let join_side_filters = state
                 .filters
                 .iter()
                 .filter_map(|(predicate, columns)| {
+                    if join_type == &JoinType::Left
+                        || join_type == &JoinType::Right
+                        || join_type == &JoinType::Full
+                    {
+                        if let Expr::IsNull(..) | Expr::IsNotNull(..) = predicate {

Review comment:
       > I don't think we can push _ANY_ filers from the `ON` clause down the non preserved side(s) of an outer join -- in other words, this is not a problem with `IS NULL` and `IS NOT NULL`.
   
   Yes, I agree. Luckily, we don't implement the case. https://github.com/apache/arrow-datafusion/blob/0facd4d483e8c289ee4e3a89487d0cd1ede1a110/datafusion/src/sql/planner.rs#L564
   
   However, I think there is a problem with `IS NULL` and `IS NOT NULL` in `WHERE` clause, we shouldn't push them down.

##########
File path: datafusion/tests/sql.rs
##########
@@ -5999,3 +5999,86 @@ async fn test_expect_distinct() -> Result<()> {
     assert_batches_eq!(expected, &actual);
     Ok(())
 }
+
+#[tokio::test]
+async fn test_predicate_push_down_with_unsafe_null() -> Result<()> {
+    let mut ctx = ExecutionContext::new();
+    let create_table1_sql =
+        "create table table1 as SELECT * FROM (VALUES (1), (2), (null)) as t";
+    ctx.sql(create_table1_sql).await.unwrap();
+    let create_table2_sql =
+        "create table table2 as SELECT * FROM (VALUES (1), (3), (null)) as t";
+    ctx.sql(create_table2_sql).await.unwrap();
+    // left join with is_not_null filter
+    let sql = "SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL";
+    let actual = execute_to_batches(&mut ctx, sql).await;
+    let expected = vec![
+        "+---------+---------+",
+        "| column1 | column1 |",
+        "+---------+---------+",
+        "| 1       | 1       |",
+        "+---------+---------+",
+    ];
+    assert_batches_eq!(expected, &actual);
+    // left join with is_null filter
+    let sql = "SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NULL ORDER BY table1.column1";
+    let actual = execute_to_batches(&mut ctx, sql).await;
+    let expected = vec![
+        "+---------+---------+",
+        "| column1 | column1 |",
+        "+---------+---------+",
+        "|         |         |",
+        "| 2       |         |",
+        "+---------+---------+",

Review comment:
       This is because currently DF is by default nulls first to be consistent with spark. I'll pull a request to make it be consistent with postgresql. 
   
   FYI, pg rule: https://www.postgresql.org/docs/current/queries-order.html
   > The NULLS FIRST and NULLS LAST options can be used to determine whether nulls appear before or after non-null values in the sort ordering. By default, null values sort as if larger than any non-null value; that is, NULLS FIRST is the default for DESC order, and NULLS LAST otherwise.

##########
File path: datafusion/tests/sql.rs
##########
@@ -5999,3 +5999,86 @@ async fn test_expect_distinct() -> Result<()> {
     assert_batches_eq!(expected, &actual);
     Ok(())
 }
+
+#[tokio::test]
+async fn test_predicate_push_down_with_unsafe_null() -> Result<()> {
+    let mut ctx = ExecutionContext::new();
+    let create_table1_sql =
+        "create table table1 as SELECT * FROM (VALUES (1), (2), (null)) as t";
+    ctx.sql(create_table1_sql).await.unwrap();
+    let create_table2_sql =
+        "create table table2 as SELECT * FROM (VALUES (1), (3), (null)) as t";
+    ctx.sql(create_table2_sql).await.unwrap();
+    // left join with is_not_null filter
+    let sql = "SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL";
+    let actual = execute_to_batches(&mut ctx, sql).await;
+    let expected = vec![
+        "+---------+---------+",
+        "| column1 | column1 |",
+        "+---------+---------+",
+        "| 1       | 1       |",
+        "+---------+---------+",
+    ];
+    assert_batches_eq!(expected, &actual);
+    // left join with is_null filter
+    let sql = "SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NULL ORDER BY table1.column1";
+    let actual = execute_to_batches(&mut ctx, sql).await;
+    let expected = vec![
+        "+---------+---------+",
+        "| column1 | column1 |",
+        "+---------+---------+",
+        "|         |         |",
+        "| 2       |         |",
+        "+---------+---------+",

Review comment:
       This is because currently, DF is by default nulls first to be consistent with spark. I'll pull a request to make it be consistent with postgresql. 
   
   FYI, pg rule: https://www.postgresql.org/docs/current/queries-order.html
   > The NULLS FIRST and NULLS LAST options can be used to determine whether nulls appear before or after non-null values in the sort ordering. By default, null values sort as if larger than any non-null value; that is, NULLS FIRST is the default for DESC order, and NULLS LAST otherwise.

##########
File path: datafusion/src/optimizer/filter_push_down.rs
##########
@@ -408,10 +412,20 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
             //
             // Join clauses with `Using` constraints also take advantage of this logic to make sure
             // predicates reference the shared join columns are pushed to both sides.
+            let mut null_unsafe_predicates = vec![];
             let join_side_filters = state
                 .filters
                 .iter()
                 .filter_map(|(predicate, columns)| {
+                    if join_type == &JoinType::Left
+                        || join_type == &JoinType::Right
+                        || join_type == &JoinType::Full
+                    {
+                        if let Expr::IsNull(..) | Expr::IsNotNull(..) = predicate {

Review comment:
       > I don't think we can push _ANY_ filers from the `ON` clause down the non preserved side(s) of an outer join -- in other words, this is not a problem with `IS NULL` and `IS NOT NULL`.
   
   Yes, I agree. Luckily, we don't implement the case. https://github.com/apache/arrow-datafusion/blob/0facd4d483e8c289ee4e3a89487d0cd1ede1a110/datafusion/src/sql/planner.rs#L564
   
   However, I think there is a problem with `IS NULL` and `IS NOT NULL` in `WHERE` clause with an outer join, we shouldn't push them down.

##########
File path: datafusion/tests/sql.rs
##########
@@ -5999,3 +5999,86 @@ async fn test_expect_distinct() -> Result<()> {
     assert_batches_eq!(expected, &actual);
     Ok(())
 }
+
+#[tokio::test]
+async fn test_predicate_push_down_with_unsafe_null() -> Result<()> {
+    let mut ctx = ExecutionContext::new();
+    let create_table1_sql =
+        "create table table1 as SELECT * FROM (VALUES (1), (2), (null)) as t";
+    ctx.sql(create_table1_sql).await.unwrap();
+    let create_table2_sql =
+        "create table table2 as SELECT * FROM (VALUES (1), (3), (null)) as t";
+    ctx.sql(create_table2_sql).await.unwrap();
+    // left join with is_not_null filter
+    let sql = "SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL";
+    let actual = execute_to_batches(&mut ctx, sql).await;
+    let expected = vec![
+        "+---------+---------+",
+        "| column1 | column1 |",
+        "+---------+---------+",
+        "| 1       | 1       |",
+        "+---------+---------+",
+    ];
+    assert_batches_eq!(expected, &actual);
+    // left join with is_null filter
+    let sql = "SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NULL ORDER BY table1.column1";
+    let actual = execute_to_batches(&mut ctx, sql).await;
+    let expected = vec![
+        "+---------+---------+",
+        "| column1 | column1 |",
+        "+---------+---------+",
+        "|         |         |",
+        "| 2       |         |",
+        "+---------+---------+",

Review comment:
       > I'll pull a request to make it be consistent with postgresql.
   
   Here: https://github.com/apache/arrow-datafusion/pull/1344

##########
File path: datafusion/src/optimizer/filter_push_down.rs
##########
@@ -408,10 +412,20 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
             //
             // Join clauses with `Using` constraints also take advantage of this logic to make sure
             // predicates reference the shared join columns are pushed to both sides.
+            let mut null_unsafe_predicates = vec![];
             let join_side_filters = state
                 .filters
                 .iter()
                 .filter_map(|(predicate, columns)| {
+                    if join_type == &JoinType::Left
+                        || join_type == &JoinType::Right
+                        || join_type == &JoinType::Full
+                    {
+                        if let Expr::IsNull(..) | Expr::IsNotNull(..) = predicate {

Review comment:
       > I don't think we can push _ANY_ filers from the `ON` clause down the non preserved side(s) of an outer join -- in other words, this is not a problem with `IS NULL` and `IS NOT NULL`.
   
   Yes, I agree. Luckily, we don't implement the case. https://github.com/apache/arrow-datafusion/blob/0facd4d483e8c289ee4e3a89487d0cd1ede1a110/datafusion/src/sql/planner.rs#L564
   
   However, I think there is a problem with `IS NULL` and `IS NOT NULL` in `WHERE` clause with an outer join, we shouldn't push them down.  I think the ticket is solving the problem.




-- 
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] xudong963 commented on pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#issuecomment-1013836655


   @alamb , I thought about this again, I think we can open a new issue to summarize the conclusion, and close this old ticket.


-- 
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 change in pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
alamb commented on a change in pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#discussion_r758304029



##########
File path: datafusion/src/optimizer/filter_push_down.rs
##########
@@ -409,10 +420,15 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
             //
             // Join clauses with `Using` constraints also take advantage of this logic to make sure
             // predicates reference the shared join columns are pushed to both sides.

Review comment:
       I think you are on the right track here that the filter_push_down is not correct for outer joins 
   
   However, I don't think the ability to push filters is related to if there is an `IS NULL` predicate. The code should NEVER try to push predicates for outer join
   
   So schematically, given this input:
   
   ```
   Filter: A.a > 5
     Inner Join(A.a = B.b)
       Scan A
       Scan B
   ```
   
   The code is effectively both pushing down `A.a > 5` as well as adding a *new* predicate, `B.b > 5` during the scan:
   ```
   Filter: A.a > 5
     Inner Join(A.a = B.b)
       Scan A (A.a > 5) 
       Scan B (B.b > 5)
   ```
   
   However, this transformation is not correct for outer joins where only the predicates on the preserved side (A in this case) can be pushed down. Thus for
   
   ```
   Filter: A.a > 5
     LEFT OUTER Join(A.a = B.b)
       Scan A
       Scan B
   ```
   
   We should still push `A.a > 5` but not introduce `B.b > 5`:
   ```
   Filter: A.a > 5
     LEFT OUTER Join(A.a = B.b)
       Scan A (A.a > 5)
       Scan B
   ```
   
   
   




-- 
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] xudong963 commented on a change in pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on a change in pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#discussion_r753654701



##########
File path: datafusion/src/optimizer/filter_push_down.rs
##########
@@ -408,10 +412,20 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
             //
             // Join clauses with `Using` constraints also take advantage of this logic to make sure
             // predicates reference the shared join columns are pushed to both sides.
+            let mut null_unsafe_predicates = vec![];
             let join_side_filters = state
                 .filters
                 .iter()
                 .filter_map(|(predicate, columns)| {
+                    if join_type == &JoinType::Left
+                        || join_type == &JoinType::Right
+                        || join_type == &JoinType::Full
+                    {
+                        if let Expr::IsNull(..) | Expr::IsNotNull(..) = predicate {

Review comment:
       > I don't think we can push _ANY_ filers from the `ON` clause down the non preserved side(s) of an outer join -- in other words, this is not a problem with `IS NULL` and `IS NOT NULL`.
   
   Yes, I agree. Luckily, we don't implement the case. https://github.com/apache/arrow-datafusion/blob/0facd4d483e8c289ee4e3a89487d0cd1ede1a110/datafusion/src/sql/planner.rs#L564
   
   However, I think there is a problem with `IS NULL` and `IS NOT NULL` in `WHERE` clause with an outer join, we shouldn't push them down.




-- 
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] xudong963 commented on a change in pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on a change in pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#discussion_r753664106



##########
File path: datafusion/tests/sql.rs
##########
@@ -5999,3 +5999,86 @@ async fn test_expect_distinct() -> Result<()> {
     assert_batches_eq!(expected, &actual);
     Ok(())
 }
+
+#[tokio::test]
+async fn test_predicate_push_down_with_unsafe_null() -> Result<()> {
+    let mut ctx = ExecutionContext::new();
+    let create_table1_sql =
+        "create table table1 as SELECT * FROM (VALUES (1), (2), (null)) as t";
+    ctx.sql(create_table1_sql).await.unwrap();
+    let create_table2_sql =
+        "create table table2 as SELECT * FROM (VALUES (1), (3), (null)) as t";
+    ctx.sql(create_table2_sql).await.unwrap();
+    // left join with is_not_null filter
+    let sql = "SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL";
+    let actual = execute_to_batches(&mut ctx, sql).await;
+    let expected = vec![
+        "+---------+---------+",
+        "| column1 | column1 |",
+        "+---------+---------+",
+        "| 1       | 1       |",
+        "+---------+---------+",
+    ];
+    assert_batches_eq!(expected, &actual);
+    // left join with is_null filter
+    let sql = "SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NULL ORDER BY table1.column1";
+    let actual = execute_to_batches(&mut ctx, sql).await;
+    let expected = vec![
+        "+---------+---------+",
+        "| column1 | column1 |",
+        "+---------+---------+",
+        "|         |         |",
+        "| 2       |         |",
+        "+---------+---------+",

Review comment:
       > I'll pull a request to make it be consistent with postgresql.
   
   Here: https://github.com/apache/arrow-datafusion/pull/1344




-- 
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 a change in pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
Dandandan commented on a change in pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#discussion_r753323175



##########
File path: datafusion/src/optimizer/filter_push_down.rs
##########
@@ -408,10 +412,20 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
             //
             // Join clauses with `Using` constraints also take advantage of this logic to make sure
             // predicates reference the shared join columns are pushed to both sides.
+            let mut null_unsafe_predicates = vec![];
             let join_side_filters = state
                 .filters
                 .iter()
                 .filter_map(|(predicate, columns)| {
+                    if join_type == &JoinType::Left
+                        || join_type == &JoinType::Right

Review comment:
       I think it would be safer to check on it being not anti or semi join here (to avoid problems whenever we want to add another join type).




-- 
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 change in pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
alamb commented on a change in pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#discussion_r757903433



##########
File path: datafusion/src/logical_plan/expr.rs
##########
@@ -508,6 +508,56 @@ impl Expr {
         }
     }
 
+    /// Return if Expr contains Expr::IsNull or Expr::IsNotNull
+    pub fn has_null_expr(&self) -> Result<bool> {

Review comment:
       I'll check this PR out more carefully tomorrow. I still don't fully understand the need for this function (as I don't think any column exprs can be pushed down past the non preserved join side)




-- 
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] xudong963 edited a comment on pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 edited a comment on pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#issuecomment-981117810


   @alamb @Dandandan 
   ### Case1
   In Datafusion:
   
   ```sql
   ❯ select * from C;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 2       |
   +---------+
   2 rows in set. Query took 0.004 seconds.
   ❯ select * from D;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 2       |
   +---------+
   2 rows in set. Query took 0.004 seconds.
   
   ❯  select * from C LEFT JOIN D ON (C.column1 = D.column1 and D.column1>5);
   +---------+---------+
   | column1 | column1 |
   +---------+---------+
   | 2       |         |
   | 1       |         |
   +---------+---------+
   2 rows in set. Query took 0.011 seconds.
   
   select * from C LEFT JOIN D ON (C.column1 = D.column1 and C.column1>5);
   NotImplemented("Unsupported expressions in Left JOIN: [#C.column1 > Int64(5)]")
   ```
   
   vs
   
   In postgres:
   
   ```sql
   postgres=# select * from C;
    c
   ---
    1
    2
   (2 rows)
   
   postgres=# select * from D;
    d
   ---
    2
    1
   (2 rows)
   
   postgres=# select * from C LEFT JOIN D ON (C.c = D.d and D.d>5);
    c | d
   ---+---
    1 |
    2 |
   (2 rows)
   
   postgres=# select * from C LEFT JOIN D ON (C.c = D.d and C.c>5);
    c | d
   ---+---
    1 |
    2 |
   (2 rows)
   ```
   
   If filters in the `On` clause are about the non preserved join side, we got the same result between Datafusion and Postgresql. Notes that datafusion doesn't support filters in the `On` clause are about the **preserved** join side, so in the ticket let's put that aside for the moment.
   
   ---
   
   ### Case2 (contains null row)
   In datafusion:
   ```sql
   ❯ SELECT * FROM table1;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 2       |
   |         |
   +---------+
   3 rows in set. Query took 0.005 seconds.
   
   ❯ SELECT * FROM table2;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 3       |
   |         |
   +---------+
   3 rows in set. Query took 0.003 seconds.
   ❯
   
   ❯ SELECT *
   FROM table1
   LEFT JOIN table2
       ON table1.column1 = table2.column1
   and table2.column1 IS NOT NULL;
   +---------+---------+
   | column1 | column1 |
   +---------+---------+
   | 2       |         |
   |         |         |
   | 1       | 1       |
   +---------+---------+
   3 rows in set. Query took 0.011 seconds.
   
   ❯ SELECT *
   FROM table1
   LEFT JOIN table2
       ON table1.column1 = table2.column1
   and table1.column1 IS NOT NULL;
   NotImplemented("Unsupported expressions in Left JOIN: [#table1.column1 IS NOT NULL]")
   
   ```
   
   vs
   
   In postgresql:
   
   ```sql
   postgres=# SELECT *
   FROM table1
   LEFT JOIN table2
       ON table1.column1 = table2.column1
   and table2.column1 IS NOT NULL;
    column1 | column1
   ---------+---------
          1 |       1
          2 |
            |
   (3 rows)
   
   postgres=# SELECT *
   FROM table1
   LEFT JOIN table2
       ON table1.column1 = table2.column1
   and table1.column1 IS NOT NULL;
    column1 | column1
   ---------+---------
          1 |       1
          2 |
            |
   (3 rows)
   ```
   Case1 and Case2 show the same behavior, this is not a problem with IS NULL and IS NOT NULL.
   
   ---
   
   ### Case 3
   In datafusion:
   
   ```sql
   ❯  select * from C LEFT JOIN D ON (C.column1 = D.column1) where C.column1>5;
   0 rows in set. Query took 0.013 seconds.
   
   ❯  select * from C LEFT JOIN D ON (C.column1 = D.column1) where D.column1>5;
   0 rows in set. Query took 0.012 seconds.
   ```
   
   In postgresql:
   ```sql
   postgres=# select * from C LEFT JOIN D ON (C.c = D.d) where  C.c>5;
    c | d
   ---+---
   (0 rows)
   
   postgres=# select * from C LEFT JOIN D ON (C.c = D.d) where  D.d>5;
    c | d
   ---+---
   (0 rows)
   ```
   They are consistent.
   
   ---
   
   Case4(contains null row)
   
   In datafusion:
   ```sql
   ❯ SELECT * FROM table1;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 2       |
   |         |
   +---------+
   3 rows in set. Query took 0.005 seconds.
   
   ❯ SELECT * FROM table2;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 3       |
   |         |
   +---------+
   3 rows in set. Query took 0.003 seconds.
   ❯
   
   ❯ SELECT *
   FROM table1
   LEFT JOIN table2
       ON table1.column1 = table2.column1
   WHERE table2.column1 IS NOT NULL;
   +---------+---------+
   | column1 | column1 |
   +---------+---------+
   | 2       |         |
   | 1       | 1       |
   +---------+---------+
   2 rows in set. Query took 0.013 seconds.
   ```
   vs
   
   In postgresql:
   
   ```sql
   postgres=# SELECT *
   FROM table1
   LEFT JOIN table2
       ON table1.column1 = table2.column1
   WHERE table2.column1 IS NOT NULL;
    column1 | column1
   ---------+---------
          1 |       1
   (1 row)
   ```
   If the `WHERE` clause contains `NULL` expr, we shouldn't push down the filter expr in `WHERE`.
   
   ```
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   | plan_type     | plan                                                                                                                                  |
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                          |
   |               |   Join: #table1.column1 = #table2.column1                                                                                             |
   |               |     Filter: #table1.column1 IS NOT NULL                                                                                               |
   |               |       TableScan: table1 projection=Some([0])                                                                                          |
   |               |     Filter: #table2.column1 IS NOT NULL                                                                                               |
   |               |       TableScan: table2 projection=Some([0])
   ```
   
   should be
   
   ```
   +---------------+-------------------------------------------------------------------------------------------------------------------------------------------+
   | plan_type     | plan                                                                                                                                      |
   +---------------+-------------------------------------------------------------------------------------------------------------------------------------------+
   | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                              |
   |               |   Filter: #table1.column1 IS NOT NULL                                                                                                     |
   |               |     Join: #table1.column1 = #table2.column1                                                                                               |
   |               |       TableScan: table1 projection=Some([0])                                                                                              |
   |               |       TableScan: table2 projection=Some([0])                                                                                              |
   ```


-- 
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 a change in pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
Dandandan commented on a change in pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#discussion_r753326120



##########
File path: datafusion/src/optimizer/filter_push_down.rs
##########
@@ -408,10 +412,20 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
             //
             // Join clauses with `Using` constraints also take advantage of this logic to make sure
             // predicates reference the shared join columns are pushed to both sides.
+            let mut null_unsafe_predicates = vec![];
             let join_side_filters = state
                 .filters
                 .iter()
                 .filter_map(|(predicate, columns)| {
+                    if join_type == &JoinType::Left
+                        || join_type == &JoinType::Right
+                        || join_type == &JoinType::Full
+                    {
+                        if let Expr::IsNull(..) | Expr::IsNotNull(..) = predicate {

Review comment:
       Should we check that the expression to *contains* `is null` and `is not null`?
   Silly example:  `1=1 AND x is null` I think should have the same effect as `x is null` for denying the optimization.




-- 
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 change in pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
alamb commented on a change in pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#discussion_r753458634



##########
File path: datafusion/tests/sql.rs
##########
@@ -5999,3 +5999,86 @@ async fn test_expect_distinct() -> Result<()> {
     assert_batches_eq!(expected, &actual);
     Ok(())
 }
+
+#[tokio::test]
+async fn test_predicate_push_down_with_unsafe_null() -> Result<()> {
+    let mut ctx = ExecutionContext::new();
+    let create_table1_sql =
+        "create table table1 as SELECT * FROM (VALUES (1), (2), (null)) as t";
+    ctx.sql(create_table1_sql).await.unwrap();
+    let create_table2_sql =
+        "create table table2 as SELECT * FROM (VALUES (1), (3), (null)) as t";
+    ctx.sql(create_table2_sql).await.unwrap();
+    // left join with is_not_null filter
+    let sql = "SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL";
+    let actual = execute_to_batches(&mut ctx, sql).await;
+    let expected = vec![
+        "+---------+---------+",
+        "| column1 | column1 |",
+        "+---------+---------+",
+        "| 1       | 1       |",
+        "+---------+---------+",
+    ];
+    assert_batches_eq!(expected, &actual);
+    // left join with is_null filter
+    let sql = "SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NULL ORDER BY table1.column1";
+    let actual = execute_to_batches(&mut ctx, sql).await;
+    let expected = vec![
+        "+---------+---------+",
+        "| column1 | column1 |",
+        "+---------+---------+",
+        "|         |         |",
+        "| 2       |         |",
+        "+---------+---------+",

Review comment:
       This appears to be different than postgres:
   
   ```
   alamb=# select * from table1;
    column1 
   ---------
          1
          2
           
   (3 rows)
   
   alamb=# select * from table2;
    column1 
   ---------
          1
          3
           
   (3 rows)
   
   alamb=# SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NULL ORDER BY table1.column1;
    column1 | column1 
   ---------+---------
          2 |        
            |        
   (2 rows)
   ```

##########
File path: datafusion/src/optimizer/filter_push_down.rs
##########
@@ -408,10 +412,20 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
             //
             // Join clauses with `Using` constraints also take advantage of this logic to make sure
             // predicates reference the shared join columns are pushed to both sides.
+            let mut null_unsafe_predicates = vec![];
             let join_side_filters = state
                 .filters
                 .iter()
                 .filter_map(|(predicate, columns)| {
+                    if join_type == &JoinType::Left
+                        || join_type == &JoinType::Right
+                        || join_type == &JoinType::Full
+                    {
+                        if let Expr::IsNull(..) | Expr::IsNotNull(..) = predicate {

Review comment:
       I haven't had a chance to study this PR yeet in depth, but I wanted to point out a few things:
   
   I don't think we can push *ANY* filers from the `ON` clause down the non preserved side(s) of an outer join -- in other words, this is not a problem with `IS NULL` and `IS NOT NULL`.
   
   For example
   
   ```sql
   alamb=# select * from A;
    a 
   ---
    1
    2
   (2 rows)
   
   alamb=# select * from B;
    b 
   ---
    1
    2
   (2 rows)
   ```
   
   Note if you pushed the predicate `a>5` down, there would be no rows, but the output is:
   ```sql
   alamb=# select * from A LEFT JOIN B ON (a=b and a>5);
    a | b 
   ---+---
    1 |  
    2 |  
   ```
   
   Note the semantics of predicates in the `WHERE` clause are different (they are always pushed down)
   
   ```
   alamb=# select * from A LEFT JOIN B ON (a=b) WHERE  a>5;
    a | b 
   ---+---
   (0 rows)
   ```
   
   
   However, note you *CAN* push `b>5` down and get the correct output (because b is not preserved):
   
   ```sql
   alamb=# select * from A LEFT JOIN B ON (a=b and b>5);
    a | b 
   ---+---
    1 |  
    2 |  
   (2 rows)
   ```
   
   The criteria is more like "refers to a column on the non preserved side"




-- 
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] xudong963 commented on pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#issuecomment-1002624486


   > @xudong963 what is the current status of this PR. I can't remember where we left it
   
   I'm so sorry, I totally forgot it. I'll find free time to continue 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] xudong963 removed a comment on pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 removed a comment on pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#issuecomment-982205288


   I clicked it wrong. Can we open it again? 🤣


-- 
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 a change in pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
Dandandan commented on a change in pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#discussion_r753341351



##########
File path: datafusion/src/optimizer/filter_push_down.rs
##########
@@ -408,10 +412,20 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
             //
             // Join clauses with `Using` constraints also take advantage of this logic to make sure
             // predicates reference the shared join columns are pushed to both sides.
+            let mut null_unsafe_predicates = vec![];
             let join_side_filters = state
                 .filters
                 .iter()
                 .filter_map(|(predicate, columns)| {
+                    if join_type == &JoinType::Left
+                        || join_type == &JoinType::Right

Review comment:
       Yes, that's why I suggest to add the "safe" variants here instead, to not allow the safe variant by default if we would add another type.
   
   Even better would be IMO to extract this to a function 
   with a normal (without wildcard) pattern match. This way, when a new variant is added, it will be a compile error. 
   
   ```rust
   fn is_null_safe(join_type: JoinType) -> bool {
       match join_type...
   }
   ```
   
   It also makes sense to me that this would be a method on `JoinType`.




-- 
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] xudong963 closed pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 closed pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339


   


-- 
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] xudong963 commented on a change in pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on a change in pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#discussion_r753655676



##########
File path: datafusion/tests/sql.rs
##########
@@ -5999,3 +5999,86 @@ async fn test_expect_distinct() -> Result<()> {
     assert_batches_eq!(expected, &actual);
     Ok(())
 }
+
+#[tokio::test]
+async fn test_predicate_push_down_with_unsafe_null() -> Result<()> {
+    let mut ctx = ExecutionContext::new();
+    let create_table1_sql =
+        "create table table1 as SELECT * FROM (VALUES (1), (2), (null)) as t";
+    ctx.sql(create_table1_sql).await.unwrap();
+    let create_table2_sql =
+        "create table table2 as SELECT * FROM (VALUES (1), (3), (null)) as t";
+    ctx.sql(create_table2_sql).await.unwrap();
+    // left join with is_not_null filter
+    let sql = "SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL";
+    let actual = execute_to_batches(&mut ctx, sql).await;
+    let expected = vec![
+        "+---------+---------+",
+        "| column1 | column1 |",
+        "+---------+---------+",
+        "| 1       | 1       |",
+        "+---------+---------+",
+    ];
+    assert_batches_eq!(expected, &actual);
+    // left join with is_null filter
+    let sql = "SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NULL ORDER BY table1.column1";
+    let actual = execute_to_batches(&mut ctx, sql).await;
+    let expected = vec![
+        "+---------+---------+",
+        "| column1 | column1 |",
+        "+---------+---------+",
+        "|         |         |",
+        "| 2       |         |",
+        "+---------+---------+",

Review comment:
       This is because currently DF is by default nulls first to be consistent with spark. I'll pull a request to make it be consistent with postgresql. 
   
   FYI, pg rule: https://www.postgresql.org/docs/current/queries-order.html
   > The NULLS FIRST and NULLS LAST options can be used to determine whether nulls appear before or after non-null values in the sort ordering. By default, null values sort as if larger than any non-null value; that is, NULLS FIRST is the default for DESC order, and NULLS LAST otherwise.




-- 
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] xudong963 commented on pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#issuecomment-974191627


   PTAL, thanks! @alamb @houqp 


-- 
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] xudong963 edited a comment on pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 edited a comment on pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#issuecomment-981733521


   > @xudong963 thank you for the examples
   > 
   > Given this input:
   > 
   > ```sql
   > ❯ create table table1 as SELECT * FROM (VALUES (1), (2), (null)) as t;
   > 0 rows in set. Query took 0.006 seconds.
   > ❯ create table table2 as SELECT * FROM (VALUES (1), (3), (null)) as t;
   > 0 rows in set. Query took 0.003 seconds.
   > ```
   > 
   > The plan that comes out is incorrect:
   > 
   > ```sql
   > ❯ explain SELECT *
   > FROM table1
   > LEFT JOIN table2
   >     ON table1.column1 = table2.column1
   > WHERE table2.column1 IS NOT NULL;
   > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > | plan_type     | plan                                                                                                                                  |
   > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                          |
   > |               |   Join: #table1.column1 = #table2.column1                                                                                             |
   > |               |     Filter: #table1.column1 IS NOT NULL                                                                                               |
   > |               |       TableScan: table1 projection=Some([0])                                                                                          |
   > |               |     Filter: #table2.column1 IS NOT NULL                                                                                               |
   > |               |       TableScan: table2 projection=Some([0])                                                                                          |
   > ```
   > 
   > I think the problem is this line:
   > 
   > ```
   > |               |     Filter: #table1.column1 IS NOT NULL      
   > ```
   
   ```sql
   postgres=# select * from table1;
    column1
   ---------
          1
          2
   
   (3 rows)
   
   postgres=# select * from table2;
    column1
   ---------
          1
          3
   
   (3 rows)
   
   df
   ❯ select * from table1;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 2       |
   |         |
   +---------+
   3 rows in set. Query took 0.004 seconds.
   ❯ select * from table2;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 3       |
   |         |
   +---------+
   3 rows in set. Query took 0.004 seconds.
   ```
   I changed my code according to your comments 
   ```rust
   fn optimize_join(
       mut state: State,
       plan: &LogicalPlan,
       left: &LogicalPlan,
       right: &LogicalPlan,
       join_type: Option<&JoinType>,
   ) -> Result<LogicalPlan> {
       let (mut pushable_to_left, mut pushable_to_right, keep) =
           get_join_predicates(&state, left.schema(), right.schema());
       if join_type.is_some() {
           match join_type.unwrap() {
               JoinType::Left => pushable_to_left.clear(),
               JoinType::Right => pushable_to_right.clear(),
               JoinType::Full => {
                   pushable_to_left.clear();
                   pushable_to_right.clear()
               }
               _ => {}
           }
       }
   ```
   and got the following result:
   
   ```sql
   ❯ explain SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   | plan_type     | plan                                                                                                                                  |
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                          |
   |               |   Join: #table1.column1 = #table2.column1                                                                                             |
   |               |     TableScan: table1 projection=Some([0])                                                                                            |
   |               |     Filter: #table2.column1 IS NOT NULL                                                                                               |
   |               |       TableScan: table2 projection=Some([0])                                                                                          |
   | physical_plan | ProjectionExec: expr=[column1@0 as column1, column1@1 as column1]                                                                     |
   |               |   CoalesceBatchesExec: target_batch_size=4096                                                                                         |
   |               |     HashJoinExec: mode=Partitioned, join_type=Left, on=[(Column { name: "column1", index: 0 }, Column { name: "column1", index: 0 })] |
   |               |       CoalesceBatchesExec: target_batch_size=4096                                                                                     |
   |               |         RepartitionExec: partitioning=Hash([Column { name: "column1", index: 0 }], 8)                                                 |
   |               |           MemoryExec: partitions=8, partition_sizes=[1, 0, 0, 0, 0, 0, 0, 0]                                                          |
   |               |       CoalesceBatchesExec: target_batch_size=4096                                                                                     |
   |               |         RepartitionExec: partitioning=Hash([Column { name: "column1", index: 0 }], 8)                                                 |
   |               |           CoalesceBatchesExec: target_batch_size=4096                                                                                 |
   |               |             FilterExec: column1@0 IS NOT NULL                                                                                         |
   |               |               MemoryExec: partitions=8, partition_sizes=[1, 0, 0, 0, 0, 0, 0, 0]                                                      |
   |               |                                                                                                                                       |
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   2 rows in set. Query took 0.013 seconds.
   ❯ SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
   +---------+---------+
   | column1 | column1 |
   +---------+---------+
   | 2       |         |
   |         |         |
   | 1       | 1       |
   +---------+---------+
   3 rows in set. Query took 0.014 seconds.
   ```
   
   But postgresql's result is different
   ```sql
   postgres=# explain SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
                                 QUERY PLAN
   ----------------------------------------------------------------------
    Merge Join  (cost=358.74..856.63 rows=32347 width=8)
      Merge Cond: (table2.column1 = table1.column1)
      ->  Sort  (cost=178.95..185.30 rows=2537 width=4)
            Sort Key: table2.column1
            ->  Seq Scan on table2  (cost=0.00..35.50 rows=2537 width=4)
                  Filter: (column1 IS NOT NULL)
      ->  Sort  (cost=179.78..186.16 rows=2550 width=4)
            Sort Key: table1.column1
            ->  Seq Scan on table1  (cost=0.00..35.50 rows=2550 width=4)
   (9 rows)
   
   postgres=# SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL
   postgres-# ;
    column1 | column1
   ---------+---------
          1 |       1
   (1 row)
   
   
   ```


-- 
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] xudong963 commented on pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#issuecomment-981117810


   ### Case1
   In Datafusion:
   
   ```sql
   ❯ select * from C;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 2       |
   +---------+
   2 rows in set. Query took 0.004 seconds.
   ❯ select * from D;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 2       |
   +---------+
   2 rows in set. Query took 0.004 seconds.
   
   ❯  select * from C LEFT JOIN D ON (C.column1 = D.column1 and D.column1>5);
   +---------+---------+
   | column1 | column1 |
   +---------+---------+
   | 2       |         |
   | 1       |         |
   +---------+---------+
   2 rows in set. Query took 0.011 seconds.
   
   select * from C LEFT JOIN D ON (C.column1 = D.column1 and C.column1>5);
   NotImplemented("Unsupported expressions in Left JOIN: [#C.column1 > Int64(5)]")
   ```
   
   vs
   
   In postgres:
   
   ```sql
   postgres=# select * from C;
    c
   ---
    1
    2
   (2 rows)
   
   postgres=# select * from D;
    d
   ---
    2
    1
   (2 rows)
   
   postgres=# select * from C LEFT JOIN D ON (C.c = D.d and D.d>5);
    c | d
   ---+---
    1 |
    2 |
   (2 rows)
   
   postgres=# select * from C LEFT JOIN D ON (C.c = D.d and C.c>5);
    c | d
   ---+---
    1 |
    2 |
   (2 rows)
   ```
   
   If filters in the `On` clause are about the non preserved join side, we got the same result between Datafusion and Postgresql. Notes that datafusion doesn't support filters in the `On` clause are about the **preserved** join side, so in the ticket let's put that aside for the moment.
   
   ---
   
   ### Case2 (contains null row)
   In datafusion:
   ```sql
   ❯ SELECT * FROM table1;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 2       |
   |         |
   +---------+
   3 rows in set. Query took 0.005 seconds.
   
   ❯ SELECT * FROM table2;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 3       |
   |         |
   +---------+
   3 rows in set. Query took 0.003 seconds.
   ❯
   
   ❯ SELECT *
   FROM table1
   LEFT JOIN table2
       ON table1.column1 = table2.column1
   and table2.column1 IS NOT NULL;
   +---------+---------+
   | column1 | column1 |
   +---------+---------+
   | 2       |         |
   |         |         |
   | 1       | 1       |
   +---------+---------+
   3 rows in set. Query took 0.011 seconds.
   
   ❯ SELECT *
   FROM table1
   LEFT JOIN table2
       ON table1.column1 = table2.column1
   and table1.column1 IS NOT NULL;
   NotImplemented("Unsupported expressions in Left JOIN: [#table1.column1 IS NOT NULL]")
   
   ```
   
   vs
   
   In postgresql:
   
   ```sql
   postgres=# SELECT *
   FROM table1
   LEFT JOIN table2
       ON table1.column1 = table2.column1
   and table2.column1 IS NOT NULL;
    column1 | column1
   ---------+---------
          1 |       1
          2 |
            |
   (3 rows)
   
   postgres=# SELECT *
   FROM table1
   LEFT JOIN table2
       ON table1.column1 = table2.column1
   and table1.column1 IS NOT NULL;
    column1 | column1
   ---------+---------
          1 |       1
          2 |
            |
   (3 rows)
   ```
   Case1 and Case2 show the same behavior, this is not a problem with IS NULL and IS NOT NULL.
   
   ---
   
   ### Case 3
   In datafusion:
   
   ```sql
   ❯  select * from C LEFT JOIN D ON (C.column1 = D.column1) where C.column1>5;
   0 rows in set. Query took 0.013 seconds.
   
   ❯  select * from C LEFT JOIN D ON (C.column1 = D.column1) where D.column1>5;
   0 rows in set. Query took 0.012 seconds.
   ```
   
   In postgresql:
   ```sql
   postgres=# select * from C LEFT JOIN D ON (C.c = D.d) where  C.c>5;
    c | d
   ---+---
   (0 rows)
   
   postgres=# select * from C LEFT JOIN D ON (C.c = D.d) where  D.d>5;
    c | d
   ---+---
   (0 rows)
   ```
   They are consistent.
   
   ---
   
   Case4(contains null row)
   
   In datafusion:
   ```sql
   ❯ SELECT * FROM table1;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 2       |
   |         |
   +---------+
   3 rows in set. Query took 0.005 seconds.
   
   ❯ SELECT * FROM table2;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 3       |
   |         |
   +---------+
   3 rows in set. Query took 0.003 seconds.
   ❯
   
   ❯ SELECT *
   FROM table1
   LEFT JOIN table2
       ON table1.column1 = table2.column1
   WHERE table2.column1 IS NOT NULL;
   +---------+---------+
   | column1 | column1 |
   +---------+---------+
   | 2       |         |
   | 1       | 1       |
   +---------+---------+
   2 rows in set. Query took 0.013 seconds.
   ```
   vs
   
   In postgresql:
   
   ```sql
   postgres=# SELECT *
   FROM table1
   LEFT JOIN table2
       ON table1.column1 = table2.column1
   WHERE table2.column1 IS NOT NULL;
    column1 | column1
   ---------+---------
          1 |       1
   (1 row)
   ```
   If the `WHERE` clause contains `NULL` expr, we shouldn't push down the filter expr in `WHERE`.
   
   ```
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   | plan_type     | plan                                                                                                                                  |
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                          |
   |               |   Join: #table1.column1 = #table2.column1                                                                                             |
   |               |     Filter: #table1.column1 IS NOT NULL                                                                                               |
   |               |       TableScan: table1 projection=Some([0])                                                                                          |
   |               |     Filter: #table2.column1 IS NOT NULL                                                                                               |
   |               |       TableScan: table2 projection=Some([0])
   ```
   
   should be
   
   ```
   +---------------+-------------------------------------------------------------------------------------------------------------------------------------------+
   | plan_type     | plan                                                                                                                                      |
   +---------------+-------------------------------------------------------------------------------------------------------------------------------------------+
   | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                              |
   |               |   Filter: #table1.column1 IS NOT NULL                                                                                                     |
   |               |     Join: #table1.column1 = #table2.column1                                                                                               |
   |               |       TableScan: table1 projection=Some([0])                                                                                              |
   |               |       TableScan: table2 projection=Some([0])                                                                                              |
   ```


-- 
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] xudong963 edited a comment on pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 edited a comment on pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#issuecomment-981733521


   > @xudong963 thank you for the examples
   > 
   > Given this input:
   > 
   > ```sql
   > ❯ create table table1 as SELECT * FROM (VALUES (1), (2), (null)) as t;
   > 0 rows in set. Query took 0.006 seconds.
   > ❯ create table table2 as SELECT * FROM (VALUES (1), (3), (null)) as t;
   > 0 rows in set. Query took 0.003 seconds.
   > ```
   > 
   > The plan that comes out is incorrect:
   > 
   > ```sql
   > ❯ explain SELECT *
   > FROM table1
   > LEFT JOIN table2
   >     ON table1.column1 = table2.column1
   > WHERE table2.column1 IS NOT NULL;
   > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > | plan_type     | plan                                                                                                                                  |
   > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                          |
   > |               |   Join: #table1.column1 = #table2.column1                                                                                             |
   > |               |     Filter: #table1.column1 IS NOT NULL                                                                                               |
   > |               |       TableScan: table1 projection=Some([0])                                                                                          |
   > |               |     Filter: #table2.column1 IS NOT NULL                                                                                               |
   > |               |       TableScan: table2 projection=Some([0])                                                                                          |
   > ```
   > 
   > I think the problem is this line:
   > 
   > ```
   > |               |     Filter: #table1.column1 IS NOT NULL      
   > ```
   
   ```sql
   postgres=# select * from table1;
    column1
   ---------
          1
          2
   
   (3 rows)
   
   postgres=# select * from table2;
    column1
   ---------
          1
          3
   
   (3 rows)
   
   df
   ❯ select * from table1;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 2       |
   |         |
   +---------+
   3 rows in set. Query took 0.004 seconds.
   ❯ select * from table2;
   +---------+
   | column1 |
   +---------+
   | 1       |
   | 3       |
   |         |
   +---------+
   3 rows in set. Query took 0.004 seconds.
   ```
   I changed my code according to your comments 
   ```rust
   fn optimize_join(
       mut state: State,
       plan: &LogicalPlan,
       left: &LogicalPlan,
       right: &LogicalPlan,
       join_type: Option<&JoinType>,
   ) -> Result<LogicalPlan> {
       let (mut pushable_to_left, mut pushable_to_right, keep) =
           get_join_predicates(&state, left.schema(), right.schema());
       if join_type.is_some() {
           match join_type.unwrap() {
               JoinType::Left => pushable_to_left.clear(),
               JoinType::Right => pushable_to_right.clear(),
               JoinType::Full => {
                   pushable_to_left.clear();
                   pushable_to_right.clear()
               }
               _ => {}
           }
       }
   ```
   and got the following result:
   
   ```sql
   ❯ explain SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   | plan_type     | plan                                                                                                                                  |
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                          |
   |               |   Join: #table1.column1 = #table2.column1                                                                                             |
   |               |     TableScan: table1 projection=Some([0])                                                                                            |
   |               |     Filter: #table2.column1 IS NOT NULL                                                                                               |
   |               |       TableScan: table2 projection=Some([0])                                                                                          |
   | physical_plan | ProjectionExec: expr=[column1@0 as column1, column1@1 as column1]                                                                     |
   |               |   CoalesceBatchesExec: target_batch_size=4096                                                                                         |
   |               |     HashJoinExec: mode=Partitioned, join_type=Left, on=[(Column { name: "column1", index: 0 }, Column { name: "column1", index: 0 })] |
   |               |       CoalesceBatchesExec: target_batch_size=4096                                                                                     |
   |               |         RepartitionExec: partitioning=Hash([Column { name: "column1", index: 0 }], 8)                                                 |
   |               |           MemoryExec: partitions=8, partition_sizes=[1, 0, 0, 0, 0, 0, 0, 0]                                                          |
   |               |       CoalesceBatchesExec: target_batch_size=4096                                                                                     |
   |               |         RepartitionExec: partitioning=Hash([Column { name: "column1", index: 0 }], 8)                                                 |
   |               |           CoalesceBatchesExec: target_batch_size=4096                                                                                 |
   |               |             FilterExec: column1@0 IS NOT NULL                                                                                         |
   |               |               MemoryExec: partitions=8, partition_sizes=[1, 0, 0, 0, 0, 0, 0, 0]                                                      |
   |               |                                                                                                                                       |
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   2 rows in set. Query took 0.013 seconds.
   ❯ SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
   +---------+---------+
   | column1 | column1 |
   +---------+---------+
   | 2       |         |
   |         |         |
   | 1       | 1       |
   +---------+---------+
   3 rows in set. Query took 0.014 seconds.
   ```
   
   But postgresql's result is different
   ```sql
   postgres=# explain SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
                                 QUERY PLAN
   ----------------------------------------------------------------------
    Merge Join  (cost=358.74..856.63 rows=32347 width=8)
      Merge Cond: (table2.column1 = table1.column1)
      ->  Sort  (cost=178.95..185.30 rows=2537 width=4)
            Sort Key: table2.column1
            ->  Seq Scan on table2  (cost=0.00..35.50 rows=2537 width=4)
                  Filter: (column1 IS NOT NULL)
      ->  Sort  (cost=179.78..186.16 rows=2550 width=4)
            Sort Key: table1.column1
            ->  Seq Scan on table1  (cost=0.00..35.50 rows=2550 width=4)
   (9 rows)
   
   postgres=# SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL
   postgres-# ;
    column1 | column1
   ---------+---------
          1 |       1
   (1 row)
   
   
   ```
   
   I guess PostgreSQL does some other special processing that isn't included in the plan. So interesting ticket, I think I should take a look at Postgres. 
   
   Any thoughts? @alamb 


-- 
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 #1339: fix: filter pushdown with unsafe null

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


   @xudong963  what is the current status of this PR.  I can't remember where we left 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] xudong963 commented on pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#issuecomment-982205288


   I clicked it wrong. Can we open it again? 🤣


-- 
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] xudong963 commented on pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#issuecomment-981070938


   Fix conflicts and comments, ready for 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 pull request #1339: fix: filter pushdown with unsafe null

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


   > I guess PostgreSQL does some other special processing that isn't included in the plan. So interesting ticket, I think I should take a look at Postgres.
   
   > Any thoughts? @alamb
   
   ❯ explain SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
   
   Since the predicate is on `table2` and table 2 is not preserved, I don't think predicates can be pushed down in this case (only predicates on table1). 
   
   Perhaps something more like (swapped `pushable_to_right` and `pushable_to_left`): 
   
   ```rust
           match join_type.unwrap() {
               JoinType::Left => pushable_to_right.clear(),
               JoinType::Right => pushable_to_left.clear(),
               JoinType::Full => {
                   pushable_to_left.clear();
                   pushable_to_right.clear()
               }
   ```
   
   Also, I am not sure if you have handled / encountered this, but  there is a (very subtle) semantic difference between 
   
   ```sql 
   SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
   ```
   
   ```sql 
   SELECT * FROM table1 LEFT JOIN table2 ON (table1.column1 = table2.column1 AND table2.column1 IS NOT NULL);
   ```
   
   Semantically, in SQL, a filter in the `WHERE` clause (first query) happens *AFTER* all joins, while a filter in the `ON` clause (second query) happens *during* the join (so if nothing matches a predicate during an outer join for a particular row on the preserved side, a row is still produced)
   
   


-- 
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] xudong963 commented on pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#issuecomment-981733521


   > @xudong963 thank you for the examples
   > 
   > Given this input:
   > 
   > ```sql
   > ❯ create table table1 as SELECT * FROM (VALUES (1), (2), (null)) as t;
   > 0 rows in set. Query took 0.006 seconds.
   > ❯ create table table2 as SELECT * FROM (VALUES (1), (3), (null)) as t;
   > 0 rows in set. Query took 0.003 seconds.
   > ```
   > 
   > The plan that comes out is incorrect:
   > 
   > ```sql
   > ❯ explain SELECT *
   > FROM table1
   > LEFT JOIN table2
   >     ON table1.column1 = table2.column1
   > WHERE table2.column1 IS NOT NULL;
   > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > | plan_type     | plan                                                                                                                                  |
   > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                          |
   > |               |   Join: #table1.column1 = #table2.column1                                                                                             |
   > |               |     Filter: #table1.column1 IS NOT NULL                                                                                               |
   > |               |       TableScan: table1 projection=Some([0])                                                                                          |
   > |               |     Filter: #table2.column1 IS NOT NULL                                                                                               |
   > |               |       TableScan: table2 projection=Some([0])                                                                                          |
   > ```
   > 
   > I think the problem is this line:
   > 
   > ```
   > |               |     Filter: #table1.column1 IS NOT NULL      
   > ```
   
   I changed my code according to your comments and got the following result
   
   ```sql
   ❯ explain SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   | plan_type     | plan                                                                                                                                  |
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                          |
   |               |   Join: #table1.column1 = #table2.column1                                                                                             |
   |               |     TableScan: table1 projection=Some([0])                                                                                            |
   |               |     Filter: #table2.column1 IS NOT NULL                                                                                               |
   |               |       TableScan: table2 projection=Some([0])                                                                                          |
   | physical_plan | ProjectionExec: expr=[column1@0 as column1, column1@1 as column1]                                                                     |
   |               |   CoalesceBatchesExec: target_batch_size=4096                                                                                         |
   |               |     HashJoinExec: mode=Partitioned, join_type=Left, on=[(Column { name: "column1", index: 0 }, Column { name: "column1", index: 0 })] |
   |               |       CoalesceBatchesExec: target_batch_size=4096                                                                                     |
   |               |         RepartitionExec: partitioning=Hash([Column { name: "column1", index: 0 }], 8)                                                 |
   |               |           MemoryExec: partitions=8, partition_sizes=[1, 0, 0, 0, 0, 0, 0, 0]                                                          |
   |               |       CoalesceBatchesExec: target_batch_size=4096                                                                                     |
   |               |         RepartitionExec: partitioning=Hash([Column { name: "column1", index: 0 }], 8)                                                 |
   |               |           CoalesceBatchesExec: target_batch_size=4096                                                                                 |
   |               |             FilterExec: column1@0 IS NOT NULL                                                                                         |
   |               |               MemoryExec: partitions=8, partition_sizes=[1, 0, 0, 0, 0, 0, 0, 0]                                                      |
   |               |                                                                                                                                       |
   +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   2 rows in set. Query took 0.013 seconds.
   ❯ SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
   +---------+---------+
   | column1 | column1 |
   +---------+---------+
   | 2       |         |
   |         |         |
   | 1       | 1       |
   +---------+---------+
   3 rows in set. Query took 0.014 seconds.
   ```
   
   But postgresql's result is different
   ```sql
   postgres=# SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL
   postgres-# ;
    column1 | column1
   ---------+---------
          1 |       1
   (1 row)
   
   
   ```


-- 
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] xudong963 commented on pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#issuecomment-982194847


   > > @xudong963 thank you for the examples
   > > Given this input:
   > > ```sql
   > > ❯ create table table1 as SELECT * FROM (VALUES (1), (2), (null)) as t;
   > > 0 rows in set. Query took 0.006 seconds.
   > > ❯ create table table2 as SELECT * FROM (VALUES (1), (3), (null)) as t;
   > > 0 rows in set. Query took 0.003 seconds.
   > > ```
   > > 
   > > 
   > >     
   > >       
   > >     
   > > 
   > >       
   > >     
   > > 
   > >     
   > >   
   > > The plan that comes out is incorrect:
   > > ```sql
   > > ❯ explain SELECT *
   > > FROM table1
   > > LEFT JOIN table2
   > >     ON table1.column1 = table2.column1
   > > WHERE table2.column1 IS NOT NULL;
   > > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > > | plan_type     | plan                                                                                                                                  |
   > > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > > | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                          |
   > > |               |   Join: #table1.column1 = #table2.column1                                                                                             |
   > > |               |     Filter: #table1.column1 IS NOT NULL                                                                                               |
   > > |               |       TableScan: table1 projection=Some([0])                                                                                          |
   > > |               |     Filter: #table2.column1 IS NOT NULL                                                                                               |
   > > |               |       TableScan: table2 projection=Some([0])                                                                                          |
   > > ```
   > > 
   > > 
   > >     
   > >       
   > >     
   > > 
   > >       
   > >     
   > > 
   > >     
   > >   
   > > I think the problem is this line:
   > > ```
   > > |               |     Filter: #table1.column1 IS NOT NULL      
   > > ```
   > 
   > ```sql
   > postgres=# select * from table1;
   >  column1
   > ---------
   >        1
   >        2
   > 
   > (3 rows)
   > 
   > postgres=# select * from table2;
   >  column1
   > ---------
   >        1
   >        3
   > 
   > (3 rows)
   > 
   > df
   > ❯ select * from table1;
   > +---------+
   > | column1 |
   > +---------+
   > | 1       |
   > | 2       |
   > |         |
   > +---------+
   > 3 rows in set. Query took 0.004 seconds.
   > ❯ select * from table2;
   > +---------+
   > | column1 |
   > +---------+
   > | 1       |
   > | 3       |
   > |         |
   > +---------+
   > 3 rows in set. Query took 0.004 seconds.
   > ```
   > 
   > I changed my code according to your comments
   > 
   > ```rust
   > fn optimize_join(
   >     mut state: State,
   >     plan: &LogicalPlan,
   >     left: &LogicalPlan,
   >     right: &LogicalPlan,
   >     join_type: Option<&JoinType>,
   > ) -> Result<LogicalPlan> {
   >     let (mut pushable_to_left, mut pushable_to_right, keep) =
   >         get_join_predicates(&state, left.schema(), right.schema());
   >     if join_type.is_some() {
   >         match join_type.unwrap() {
   >             JoinType::Left => pushable_to_left.clear(),
   >             JoinType::Right => pushable_to_right.clear(),
   >             JoinType::Full => {
   >                 pushable_to_left.clear();
   >                 pushable_to_right.clear()
   >             }
   >             _ => {}
   >         }
   >     }
   > ```
   > 
   > and got the following result:
   > 
   > ```sql
   > ❯ explain SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
   > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > | plan_type     | plan                                                                                                                                  |
   > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > | logical_plan  | Projection: #table1.column1, #table2.column1                                                                                          |
   > |               |   Join: #table1.column1 = #table2.column1                                                                                             |
   > |               |     TableScan: table1 projection=Some([0])                                                                                            |
   > |               |     Filter: #table2.column1 IS NOT NULL                                                                                               |
   > |               |       TableScan: table2 projection=Some([0])                                                                                          |
   > | physical_plan | ProjectionExec: expr=[column1@0 as column1, column1@1 as column1]                                                                     |
   > |               |   CoalesceBatchesExec: target_batch_size=4096                                                                                         |
   > |               |     HashJoinExec: mode=Partitioned, join_type=Left, on=[(Column { name: "column1", index: 0 }, Column { name: "column1", index: 0 })] |
   > |               |       CoalesceBatchesExec: target_batch_size=4096                                                                                     |
   > |               |         RepartitionExec: partitioning=Hash([Column { name: "column1", index: 0 }], 8)                                                 |
   > |               |           MemoryExec: partitions=8, partition_sizes=[1, 0, 0, 0, 0, 0, 0, 0]                                                          |
   > |               |       CoalesceBatchesExec: target_batch_size=4096                                                                                     |
   > |               |         RepartitionExec: partitioning=Hash([Column { name: "column1", index: 0 }], 8)                                                 |
   > |               |           CoalesceBatchesExec: target_batch_size=4096                                                                                 |
   > |               |             FilterExec: column1@0 IS NOT NULL                                                                                         |
   > |               |               MemoryExec: partitions=8, partition_sizes=[1, 0, 0, 0, 0, 0, 0, 0]                                                      |
   > |               |                                                                                                                                       |
   > +---------------+---------------------------------------------------------------------------------------------------------------------------------------+
   > 2 rows in set. Query took 0.013 seconds.
   > ❯ SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
   > +---------+---------+
   > | column1 | column1 |
   > +---------+---------+
   > | 2       |         |
   > |         |         |
   > | 1       | 1       |
   > +---------+---------+
   > 3 rows in set. Query took 0.014 seconds.
   > ```
   > 
   > But postgresql's result is different
   > 
   > ```sql
   > postgres=# explain SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL;
   >                               QUERY PLAN
   > ----------------------------------------------------------------------
   >  Merge Join  (cost=358.74..856.63 rows=32347 width=8)
   >    Merge Cond: (table2.column1 = table1.column1)
   >    ->  Sort  (cost=178.95..185.30 rows=2537 width=4)
   >          Sort Key: table2.column1
   >          ->  Seq Scan on table2  (cost=0.00..35.50 rows=2537 width=4)
   >                Filter: (column1 IS NOT NULL)
   >    ->  Sort  (cost=179.78..186.16 rows=2550 width=4)
   >          Sort Key: table1.column1
   >          ->  Seq Scan on table1  (cost=0.00..35.50 rows=2550 width=4)
   > (9 rows)
   > 
   > postgres=# SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column1 WHERE table2.column1 IS NOT NULL
   > postgres-# ;
   >  column1 | column1
   > ---------+---------
   >        1 |       1
   > (1 row)
   > ```
   
   I guess 


-- 
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] xudong963 commented on a change in pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
xudong963 commented on a change in pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#discussion_r753325444



##########
File path: datafusion/src/optimizer/filter_push_down.rs
##########
@@ -408,10 +412,20 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
             //
             // Join clauses with `Using` constraints also take advantage of this logic to make sure
             // predicates reference the shared join columns are pushed to both sides.
+            let mut null_unsafe_predicates = vec![];
             let join_side_filters = state
                 .filters
                 .iter()
                 .filter_map(|(predicate, columns)| {
+                    if join_type == &JoinType::Left
+                        || join_type == &JoinType::Right

Review comment:
       If we add another join type, we should check if it's null safe. If it's null safe, we should allow it to push down.




-- 
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 a change in pull request #1339: fix: filter pushdown with unsafe null

Posted by GitBox <gi...@apache.org>.
Dandandan commented on a change in pull request #1339:
URL: https://github.com/apache/arrow-datafusion/pull/1339#discussion_r753341351



##########
File path: datafusion/src/optimizer/filter_push_down.rs
##########
@@ -408,10 +412,20 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
             //
             // Join clauses with `Using` constraints also take advantage of this logic to make sure
             // predicates reference the shared join columns are pushed to both sides.
+            let mut null_unsafe_predicates = vec![];
             let join_side_filters = state
                 .filters
                 .iter()
                 .filter_map(|(predicate, columns)| {
+                    if join_type == &JoinType::Left
+                        || join_type == &JoinType::Right

Review comment:
       Yes, that's why I suggest to add the "safe" variants here instead, to not allow the safe variant by default if we would add another type.
   
   Even better would be IMO to extract this to a function 
   with a normal (without wildcard) pattern match. This way, when a new variant is added, it will be a compile error. 
   
   ```rust
   fun is_null_safe(join_type: JoinType) -> bool {
       match join_type...
   }
   ```
   
   It also makes sense to me that this would be a method on `JoinType`.




-- 
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