Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unary minus doesn't need parens for simple expressions #1427

Merged
merged 2 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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: `filter()` does a better job of converting logical vectors
from bit to boolean (@ejneer, #1288).

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
Loading