From ea29e09fc6f685c9d7c33068e5017c1c14544c46 Mon Sep 17 00:00:00 2001 From: Jim Hester Date: Fri, 27 Jul 2018 10:49:00 -0400 Subject: [PATCH] Suppport lists of Id objects in glue_sql --- NEWS.md | 2 ++ R/sql.R | 10 +++++++++- tests/testthat/test-sql.R | 11 +++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index c60b4ff..db247ea 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,5 @@ +* `glue_sql()` now supports unquoting lists of Id objects. + # glue 1.3.0 ## Breaking changes diff --git a/R/sql.R b/R/sql.R index dcfafd7..7bde915 100644 --- a/R/sql.R +++ b/R/sql.R @@ -48,6 +48,7 @@ #' AND {`tbl`}.species = {val} #' ", .con = con) #' +#' #' # `glue_sql()` can be used in conjuction with parameterized queries using #' # `DBI::dbBind()` to provide protection for SQL Injection attacks #' sql <- glue_sql(" @@ -110,7 +111,14 @@ sql_quote_transformer <- function(connection) { if (is_quoted) { regmatches(text, m) <- "" res <- eval(parse(text = text, keep.source = FALSE), envir) - res <- DBI::dbQuoteIdentifier(conn = connection, res) + + if (length(res) == 1) { + res <- DBI::dbQuoteIdentifier(conn = connection, res) + } else { + + # Support lists as well + res[] <- lapply(res, DBI::dbQuoteIdentifier, conn = connection) + } } else { res <- eval(parse(text = text, keep.source = FALSE), envir) diff --git a/tests/testthat/test-sql.R b/tests/testthat/test-sql.R index 62a14bd..bc346a9 100644 --- a/tests/testthat/test-sql.R +++ b/tests/testthat/test-sql.R @@ -22,6 +22,17 @@ describe("glue_sql", { var <- "foo" expect_identical(glue_sql("{`var`}", .con = con), DBI::SQL("`foo`")) }) + it("quotes Id identifiers", { + var <- DBI::Id(schema = "foo", table = "bar", columm = "baz") + expect_identical(glue_sql("{`var`}", .con = con), DBI::SQL("`foo`.`bar`.`baz`")) + }) + it("quotes lists of Id identifiers", { + var <- c( + DBI::Id(schema = "foo", table = "bar", columm = "baz"), + DBI::Id(schema = "foo", table = "bar", columm = "baz2") + ) + expect_identical(glue_sql("{`var`*}", .con = con), DBI::SQL("`foo`.`bar`.`baz`, `foo`.`bar`.`baz2`")) + }) it("Does not quote numbers", { var <- 1 expect_identical(glue_sql("{var}", .con = con), DBI::SQL("1"))