Skip to content

mutate() is incorrectly inlined after distinct() #1119

Description

@vadim-cherepanov

I just updated to dplyr v1.1.0 + dbplyr 2.3.0, and my code broke. Upon investigation it seems that now a wrong SQL query is generated. Namely, in my case, I have distinct prior to the group_by block.

> remote_table %>% distinct(x, y) %>% count(y) %>% filter(y == "YYY") 
# Source:     SQL [1 x 2]
# Database:   postgres  [.../postgres]
# Ordered by: x, y
  y        n
  <chr>  <int64>
1 YYY       1
> remote_table %>% distinct(x, y) %>% group_by(y) %>% tally() %>% ungroup() %>% filter(y == "YYY") 
# Source:     SQL [1 x 2]
# Database:   postgres  [.../postgres]
# Ordered by: x, y
  y        n
  <chr>  <int64>
1 YYY       1
> remote_table %>% distinct(x, y) %>% group_by(y) %>% mutate(n = n()) %>% ungroup() %>% filter(y == "YYY") 
# Source:     SQL [1 x 3]
# Database:   postgres  [.../postgres]
# Ordered by: x, y
  x y        n
      <int64> <chr>  <int64>
1        XXX YYY       2

If I add compute between them, i.e. the result of distinct is actually computed and stored in a temporary table, n() returns values as expected.

> remote_table %>% distinct(x, y) %>% compute() %>% group_by(y) %>% mutate(n = n()) %>% ungroup() %>% filter(y == "YYY") 
# Source:     SQL [1 x 3]
# Database:   postgres  [.../postgres]
# Ordered by: x, y
  x y        n
      <int64> <chr>  <int64>
1        XXX YYY       1

This is the SQL query generated by dplyr v1.1.0 + dbplyr 2.3.0:

> remote_table %>% distinct(x, y) %>% group_by(y) %>% mutate(n = n()) %>% ungroup() %>% filter(y == "YYY") %>% show_query() 
<SQL>
SELECT DISTINCT
  "x",
  "y",
  COUNT(*) OVER (PARTITION BY "y") AS "n"
FROM "dbplyr_026"
WHERE ("y" = 'YYY')

Note how it extended distinct onto the subsequent query.

And this one is generated (as expected) by dplyr v1.0.10 + dbplyr 2.2.1:

> remote_table %>% distinct(x, y) %>% group_by(y) %>% mutate(n = n()) %>% ungroup() %>% filter(y == "YYY") %>% show_query() 
<SQL>
SELECT *
FROM (
  SELECT *, COUNT(*) OVER (PARTITION BY "y") AS "n"
  FROM (
    SELECT DISTINCT "x", "y"
    FROM "dbplyr_026"
  ) "q01"
) "q02"
WHERE ("y" = 'YYY')

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions