glue
glue copied to clipboard
Translate named elements to aliases in glue_sql()
library(glue)
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
# I like this
x <- c("a", "b")
glue_sql("SELECT {`x`*} FROM TABLE1", .con = con)
#> <SQL> SELECT `a`, `b` FROM TABLE1
# But we also have this
y <- setNames(x, c("A", "B"))
glue_sql("SELECT {`y`*} FROM TABLE1", .con = con)
#> <SQL> SELECT `a`, `b` FROM TABLE1
# And I wish it would translate to
#> <SQL> SELECT `a` `A`, `b` `B` FROM TABLE1
# tedious workaround
selected <- toString(paste(glue_sql("{`y`}", .con = con), glue_sql("{`names(y)`}", .con = con)))
glue_sql("SELECT ", selected, " FROM TABLE1", .con = con)
#> <SQL> SELECT `a` `A`, `b` `B` FROM TABLE1
Created on 2022-08-31 by the reprex package (v2.0.1)
It's a breaking change but maybe worth it ? Or have a named_to_alias = FALSE
arg that we might switch on for this behaviour ?
I don't see an obvious way to do this as I'm pretty sure we'll need different variants for different SQL dialects, and DBI::dbQuoteIdentifier()
ignores names:
con <- DBI::dbConnect(RSQLite::SQLite())
DBI::dbQuoteIdentifier(con, c(x = "y", a = "b"))
#> <SQL> `y`
#> <SQL> `b`
Created on 2023-01-25 with reprex v2.0.2
OTOH it looks like dbplyr always uses names_to_as
for this, and that doesn't vary from connection to connection, so maybe it's possible.