Skip to content

Commit

Permalink
Support data masking pronouns in slice_*() (#1302)
Browse files Browse the repository at this point in the history
* Support data masking pronouns in `slice_*()`

* Add test
  • Loading branch information
mgirlich authored Jun 13, 2023
1 parent 2697e50 commit c56e61a
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 1 deletion.
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)

* `slice_*()` now supports the data masking pronouns `.env` and `.data` (@mgirlich, #1294).

* `tbl()` now informs when the user probably forgot to wrap the table identifier
with `in_schema()` or `sql()` (@mgirlich, #1287).

Expand Down
3 changes: 2 additions & 1 deletion R/verb-slice.R
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,8 @@ slice_by <- function(.data, order_by, size, .by, with_ties = FALSE) {

# must use `add_order()` as `window_order()` only allows variables
# this is only okay to do because the previous, legal window order is restored
.data$lazy_query <- add_order(.data, quos({{order_by}}))
dots <- partial_eval_dots(.data, !!!quos({{order_by}}), .named = FALSE)
.data$lazy_query <- add_order(.data, dots)

out <- filter(.data, !!window_fun) %>%
window_order(!!!old_frame)
Expand Down
33 changes: 33 additions & 0 deletions tests/testthat/_snaps/verb-slice.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,39 @@
! `na_rm = FALSE` isn't supported on database backends.
i It must be TRUE instead.

# slice_* can use data masking pronouns

Code
lf %>% slice_max(x)
Output
<SQL>
SELECT `x`, `id`
FROM (
SELECT `df`.*, RANK() OVER (ORDER BY `x` DESC) AS `q01`
FROM `df`
) AS `q01`
WHERE (`q01` <= 1)
Code
lf %>% slice_max(.data$x)
Output
<SQL>
SELECT `x`, `id`
FROM (
SELECT `df`.*, RANK() OVER (ORDER BY `x` DESC) AS `q01`
FROM `df`
) AS `q01`
WHERE (`q01` <= 1)
Code
lf %>% slice_max(.data$x * .env$x)
Output
<SQL>
SELECT `x`, `id`
FROM (
SELECT `df`.*, RANK() OVER (ORDER BY `x` * -1 DESC) AS `q01`
FROM `df`
) AS `q01`
WHERE (`q01` <= 1)

# slice_sample errors when expected

Code
Expand Down
11 changes: 11 additions & 0 deletions tests/testthat/test-verb-slice.R
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,17 @@ test_that("slice_max orders in opposite order", {
expect_snapshot(error = TRUE, db %>% slice_max(id, n = 1, na_rm = FALSE))
})

test_that("slice_* can use data masking pronouns", {
lf <- lazy_frame(x = c(1, 1, 2), id = c(1, 2, 3))
x <- -1L

expect_snapshot({
lf %>% slice_max(x)
lf %>% slice_max(.data$x)
lf %>% slice_max(.data$x * .env$x)
})
})

test_that("slice_sample errors when expected", {
db <- memdb_frame(x = c(1, 1, 2), id = c(1, 2, 3))

Expand Down

0 comments on commit c56e61a

Please sign in to comment.