Skip to content

Commit

Permalink
Unary minus doesn't need parens for simple expressions (#1427)
Browse files Browse the repository at this point in the history
Fixes #1420
  • Loading branch information
hadley authored Jan 9, 2024
1 parent 3894093 commit 260690c
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 3 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# dbplyr (development version)

* `-1 + x` is now translated correctly (#1420).

* SQL server: clear error if you attempt to use `n_distinct()` in `mutate()`
or `filter()` (#1366).

Expand Down
5 changes: 3 additions & 2 deletions R/translate-sql-helpers.R
Original file line number Diff line number Diff line change
Expand Up @@ -175,10 +175,11 @@ sql_infix <- function(f, pad = TRUE) {
escape_infix_expr <- function(xq, x, escape_unary_minus = FALSE) {
infix_calls <- c("+", "-", "*", "/", "%%", "^")
is_infix <- is_call(xq, infix_calls, n = 2)
is_unary_minus <- escape_unary_minus && is_call(xq, "-", n = 1)
is_unary_minus <- escape_unary_minus &&
is_call(xq, "-", n = 1) && !is_atomic(x, n = 1)

if (is_infix || is_unary_minus) {
enpared <- glue_sql2(sql_current_con(), "({x})")
enpared <- glue_sql2(sql_current_con(), "({.val x})")
return(enpared)
}

Expand Down
1 change: 1 addition & 0 deletions tests/testthat/test-backend-.R
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ test_that("unary plus works for non-numeric expressions", {
test_that("unary minus flips sign of number", {
local_con(simulate_dbi())
expect_equal(test_translate_sql(-10L), sql("-10"))
expect_equal(test_translate_sql(-10L + x), sql("-10 + `x`"))
expect_equal(test_translate_sql(x == -10), sql('`x` = -10.0'))
expect_equal(test_translate_sql(x %in% c(-1L, 0L)), sql('`x` IN (-1, 0)'))
})
Expand Down
2 changes: 1 addition & 1 deletion tests/testthat/test-translate-sql-helpers.R
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ test_that("can translate infix expression without parentheses", {
test_that("unary minus works with expressions", {
local_con(simulate_dbi())
expect_equal(test_translate_sql(-!!expr(x+2)), sql("-(`x` + 2.0)"))
expect_equal(test_translate_sql(--x), sql("-(-`x`)"))
expect_equal(test_translate_sql(--x), sql("--`x`"))
})

test_that("pad = FALSE works", {
Expand Down

0 comments on commit 260690c

Please sign in to comment.