Skip to content

Commit

Permalink
Translate [[ with numeric indexes
Browse files Browse the repository at this point in the history
Fixes #520
  • Loading branch information
hadley committed Oct 19, 2020
1 parent d626780 commit 6679ed8
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 14 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@

* You can now use `::` in translations, so that (e.g.) `dbplyr::n()` is
translated to `count(*)` (#207).

* `[[` can now also translate numeric indices (#520).

* `%/%` now generates a clear error message; previously it was translated to
`/` which is not correct (#108).
Expand Down
10 changes: 7 additions & 3 deletions R/backend-.R
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,14 @@ base_scalar <- sql_translator(
`$` = sql_infix(".", pad = FALSE),
`[[` = function(x, i) {
i <- enexpr(i)
if (!is.character(i)) {
stop("Can only index with strings", call. = FALSE)
if (is.character(i)) {
build_sql(x, ".", ident(i))
} else if (is.numeric(i)) {
build_sql(x, "[", as.integer(i), "]")
} else {
stop("Can only index with strings and numbers", call. = FALSE)
}
build_sql(x, ".", ident(i))

},
`[` = function(x, i) {
build_sql("CASE WHEN (", i, ") THEN (", x, ") END")
Expand Down
8 changes: 8 additions & 0 deletions tests/testthat/test-backend-.R
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ test_that("log becomes ln", {
expect_equal(translate_sql(log(x)), sql('LN(`x`)'))
})

test_that("can translate subsetting", {
expect_equal(translate_sql(a$b), sql("`a`.`b`"))
expect_equal(translate_sql(a[["b"]]), sql("`a`.`b`"))

expect_equal(translate_sql(a[["b"]][[1]]), sql('`a`.`b`[1]'))
})


# binary/bitwise ---------------------------------------------------------------

test_that("bitwise operations", {
Expand Down
11 changes: 0 additions & 11 deletions tests/testthat/test-translate-sql.R
Original file line number Diff line number Diff line change
Expand Up @@ -183,17 +183,6 @@ test_that("str_trim() translates correctly ", {

# subsetting --------------------------------------------------------------

test_that("$ and [[ index into nested fields", {
expect_equal(translate_sql(a$b), sql("`a`.`b`"))

expect_equal(translate_sql(a[["b"]]), sql("`a`.`b`"))
})

test_that("can only subset with strings", {
expect_error(translate_sql(a[[1]]), "index with strings")
expect_error(translate_sql(a[[x]]), "index with strings")
})

test_that("[ treated as if it is logical subsetting", {
expect_equal(translate_sql(y[x == 0L]), sql("CASE WHEN (`x` = 0) THEN (`y`) END"))
})
Expand Down

0 comments on commit 6679ed8

Please sign in to comment.