dbplyr icon indicating copy to clipboard operation
dbplyr copied to clipboard

Use join table alias as name for CTE

Open mgirlich opened this issue 2 years ago • 1 comments

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

lf <- lazy_frame(x = 1, y = 1)

left_join(
  lf,
  lf %>% mutate(y = y + 1),
  by = "x",
  y_as = "y_plus_one"
) %>% 
  show_query(cte = TRUE)

produces

WITH `q01` AS (
  SELECT `x`, `y` + 1.0 AS `y`
  FROM `df`
)
SELECT `df`.`x` AS `x`, `df`.`y` AS `y.x`, `y_plus_one`.`y` AS `y.y`
FROM `df`
LEFT JOIN `q01` AS `y_plus_one`
  ON (`df`.`x` = `y_plus_one`.`x`)

Instead, the CTE should be named y_plus_one, i.e.

WITH `y_plus_one` AS (
...
)
SELECT ...
FROM `df`
LEFT JOIN `y_plus_one`
  ON (`df`.`x` = `y_plus_one`.`x`)

mgirlich avatar May 30 '22 08:05 mgirlich

This still sounds nice but requires a bit more work than initially expected, mostly because the CTE names have to be unique.

mgirlich avatar Aug 16 '22 14:08 mgirlich