Skip to content

Commit

Permalink
Improve median translations (#570)
Browse files Browse the repository at this point in the history
Fixes #419
  • Loading branch information
hadley authored Nov 8, 2023
1 parent 2b3f5ef commit f371c54
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 5 deletions.
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# bigrquery (development version)

* `median()` gets a translation that works in `summarise()` and a clear
error if you use it in `mutate()` (#419).

* `dbGetQuery()`/`dbSendQuery()` gains support for parameterised queries via
the `params` argument (@byapparov, #444).

Expand Down
14 changes: 9 additions & 5 deletions R/dplyr.R
Original file line number Diff line number Diff line change
Expand Up @@ -252,9 +252,6 @@ sql_translation.BigQueryConnection <- function(x) {
pmax = sql_prefix("GREATEST"),
pmin = sql_prefix("LEAST"),

# Median
median = function(x) dbplyr::build_sql("APPROX_QUANTILES(", x, ", 2)[SAFE_ORDINAL(2)]"),

runif = function(n = n(), min = 0, max = 1) {
RAND <- NULL # quiet R CMD check
dbplyr::sql_runif(RAND(), n = {{ n }}, min = min, max = max)
Expand All @@ -269,7 +266,12 @@ sql_translation.BigQueryConnection <- function(x) {
sd = sql_prefix("STDDEV_SAMP"),
var = sql_prefix("VAR_SAMP"),
cor = dbplyr::sql_aggregate_2("CORR"),
cov = dbplyr::sql_aggregate_2("COVAR_SAMP")
cov = dbplyr::sql_aggregate_2("COVAR_SAMP"),

# Median
median = function(x, na.rm = TRUE) {
dbplyr::build_sql("APPROX_QUANTILES(", x, ", 2)[SAFE_ORDINAL(2)]")
}
),
dbplyr::sql_translator(.parent = dbplyr::base_win,
all = dbplyr::win_absent("LOGICAL_AND"),
Expand All @@ -280,7 +282,9 @@ sql_translation.BigQueryConnection <- function(x) {
cor = dbplyr::win_absent("CORR"),
cov = dbplyr::win_absent("COVAR_SAMP"),

n_distinct = dbplyr::win_absent("n_distinct")
n_distinct = dbplyr::win_absent("n_distinct"),

median = dbplyr::win_absent("median")
)
)
}
Expand Down
7 changes: 7 additions & 0 deletions tests/testthat/test-dplyr.R
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,13 @@ test_that("runif is correctly translated", {
)
})

test_that("median is correctly translated", {
expect_equal(
dbplyr::translate_sql(median(x), con = simulate_bigrquery(), window = FALSE),
dbplyr::sql("APPROX_QUANTILES(`x`, 2)[SAFE_ORDINAL(2)]")
)
})

test_that("can correctly print a lazy query", {
con <- DBI::dbConnect(
bigquery(),
Expand Down

0 comments on commit f371c54

Please sign in to comment.