I am working on a sql file within rstudio. This allows me to build and run sql using the preview feature.
r script to create a con
library(dplyr)
library(dbplyr)
library(glue)
iris_db <- tbl_memdb(iris)
con <- src_memdb()$con
Then I can run queries using sql:
example_query.sql
-- !preview conn=con
select *
from iris
where Species = 'setosa'
Within my .sql script, if I press the preview button, I can view the results of my query. This is handy for developing larger queries, so that I can test and check along the way if the data are as expected.
On a recent post on here I learned how to read in the .sql script into r:
query <- read_lines("example_query.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", …
I also learned that I can pass variables from r to the sql script using the glue package along with curly braces e.g.
in my r script add
var1 <- "setosa"
Then in my sql script change where Species = 'setosa'
to where Species = {var1}
However, when I switch to using {variables} in the sql query, I am no longer able to use the preview function to view my results. This can actually be done in a Rmd file when working on a sql chunk by using ?syntax
to refer to variables within the chunk and then pressing play.
Is there a way to both be able to use r variables within a sql script AND use preview to run the query?