Skip to content

Commit

Permalink
Collapse empty vectors to empty string (#292)
Browse files Browse the repository at this point in the history
* Collapse empty vectors to empty string

Fixes #272

* Fix typo

---------

Co-authored-by: Jennifer (Jenny) Bryan <jenny.f.bryan@gmail.com>
  • Loading branch information
hadley and jennybc authored Mar 13, 2023
1 parent 3a784a3 commit 43e366e
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 9 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# glue (development version)

* `glue_sql()` now collapses an empty vector to `""` not `"NULL"` (#272).

* `glue_sql()` now uses `DBI::dbQuoteLiteral()` for all object types. This
should increase fidelity of escaping for different object types (#279).

Expand Down
13 changes: 7 additions & 6 deletions R/sql.R
Original file line number Diff line number Diff line change
Expand Up @@ -223,13 +223,17 @@ sql_quote_transformer <- function(connection, .na) {
}
} else {
res <- eval(parse(text = text, keep.source = FALSE), envir)
if (length(res) == 0L) {
if (should_collapse) {
return("")
} else {
return(NULL)
}
}
if (inherits(res, "SQL")) {
if (should_collapse) {
res <- glue_collapse(res, ", ")
}
if (length(res) == 0L) {
res <- DBI::SQL("NULL")
}
return(res)
}
}
Expand All @@ -243,9 +247,6 @@ sql_quote_transformer <- function(connection, .na) {
if (should_collapse) {
res <- glue_collapse(res, ", ")
}
if (length(res) == 0L) {
res <- DBI::SQL("NULL")
}
res
}
}
11 changes: 8 additions & 3 deletions tests/testthat/test-sql.R
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,15 @@ describe("glue_sql", {
expect_identical(glue_sql("{var*}", .con = con, var = "a"), DBI::SQL("'a'"))
expect_identical(glue_sql("{var*}", .con = con, var = letters[1:5]), DBI::SQL("'a', 'b', 'c', 'd', 'e'"))
})
it('collapses values should return NULL for length zero vector', {
expect_identical(glue_sql("{var*}", .con = con, var = character()), DBI::SQL("NULL"))
expect_identical(glue_sql("{var*}", .con = con, var = DBI::SQL(character())), DBI::SQL("NULL"))
it('collapses empty values to empty string', {
expect_identical(glue_sql("{var*}", .con = con, var = NULL), DBI::SQL(""))
expect_identical(glue_sql("{var*}", .con = con, var = character()), DBI::SQL(""))
expect_identical(glue_sql("{var*}", .con = con, var = DBI::SQL(character())), DBI::SQL(""))
})
it("mimics glue() when not collapsing", {
expect_equal(glue_sql("{var}", var = NULL), DBI::SQL(glue("{var}", var = NULL)))
})

it("should return an SQL NULL by default for missing values", {
var <- list(NA, NA_character_, NA_real_, NA_integer_)
expect_identical(glue_sql("x = {var}", .con = con), rep(DBI::SQL("x = NULL"), 4))
Expand Down

0 comments on commit 43e366e

Please sign in to comment.