I have an r script and a sql script:
library(tidyverse)
library(dbplyr)
library(DBI)
library(glue)
iris_db <- tbl_memdb(iris)
con <- src_memdb()$con
var1 <- "setosa"
query <- read_lines("example.sql") %>% glue_collapse(sep = "\n") %>% glue_sql(.con = con)
setosa <- dbGetQuery(con, query)
setosa %>% glimpse()
Observations: 50
Variables: 5
$ Sepal.Length <dbl> 5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9, 5.4, 4.8, 4.8, 4.3, 5.8, 5.7, 5.4, 5.1, 5.7, 5.1, 5.4, 5.1, …
$ Sepal.Width <dbl> 3.5, 3.0, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.4, 3.0, 3.0, 4.0, 4.4, 3.9, 3.5, 3.8, 3.8, 3.4, 3.7, …
$ Petal.Length <dbl> 1.4, 1.4, 1.3, 1.5, 1.4, 1.7, 1.4, 1.5, 1.4, 1.5, 1.5, 1.6, 1.4, 1.1, 1.2, 1.5, 1.3, 1.4, 1.7, 1.5, 1.7, 1.5, …
$ Petal.Width <dbl> 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 0.2, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2, 0.4, 0.4, 0.3, 0.3, 0.3, 0.2, 0.4, …
$ Species <chr> "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", …
example.sql:
-- !preview conn=con
select *
from iris
where species = {var1}
So far so good.
I would like to name my field in select using a variable e.g.
-- !preview conn=con
select
Sepal.Length,
Species as Species || "-" {var1}
from iris
where species = {var1}
Wanted the results to look like:
Sepal.Length ....
Species-setosa ...
Running the above gives:
Error: near "||": syntax error
Tried:
Species as concat(Species, {var1})
which gives:
Error: near "(": syntax error
Tried:
Species as concat('Species', {var1})
Error: near "(": syntax error
Tried (per examples here: GitHub - tidyverse/glue: Glue strings to data in R. Small, fast, dependency free interpreted string literals.):
Species as {'Species-', var1}
Error in parse(text = text, keep.source = FALSE) :
:1:11: unexpected ','
1: 'Species-',
^
Is there a way to include the variable enclosed within crly braces in the final field name of a query?