Skip to content

Joins and set operations queries not reused in CTEs #978

@mgirlich

Description

@mgirlich
library(dbplyr)
library(dplyr, warn.conflicts = FALSE)

lf1 <- lazy_frame(x = 1, .name = "lf1")
lf <- lf1 %>% 
  filter(x == 1)

# the CTE for `lf` is reused
union_all(
  lf,
  lf
) %>% 
  show_query(cte = TRUE)
#> <SQL>
#> WITH `q01` AS (
#>   SELECT *
#>   FROM `lf1`
#>   WHERE (`x` = 1.0)
#> )
#> (
#>   SELECT *
#>   FROM `q01`
#> )
#> UNION ALL
#> (
#>   SELECT *
#>   FROM `q01`
#> )

# the CTE for `lf` is not reused
lf <- lf1 %>% 
  inner_join(lf1, by = "x")
union_all(
  lf,
  lf
) %>% 
  show_query(cte = TRUE)
#> <SQL>
#> WITH `q01` AS (
#>   SELECT `lf1_LHS`.`x` AS `x`
#>   FROM `lf1` AS `lf1_LHS`
#>   INNER JOIN `lf1` AS `lf1_RHS`
#>     ON (`lf1_LHS`.`x` = `lf1_RHS`.`x`)
#> ),
#> `q02` AS (
#>   SELECT `lf1_LHS`.`x` AS `x`
#>   FROM `lf1` AS `lf1_LHS`
#>   INNER JOIN `lf1` AS `lf1_RHS`
#>     ON (`lf1_LHS`.`x` = `lf1_RHS`.`x`)
#> )
#> (
#>   SELECT *
#>   FROM `q01`
#> )
#> UNION ALL
#> (
#>   SELECT *
#>   FROM `q02`
#> )

Created on 2022-08-16 by the reprex package (v2.0.1)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions