Skip to content
Draft
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ Suggests:
callr,
clock,
DBItest,
dbplyr,
dbplyr (>= 2.5.2),
dplyr,
rlang,
testthat,
Expand Down
11 changes: 5 additions & 6 deletions R/backend-dbplyr__duckdb_connection.R
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,6 @@ duckdb_grepl <- function(pattern, x, ignore.case = FALSE, perl = FALSE, fixed =
}

duckdb_n_distinct <- function(..., na.rm = FALSE) {
sql <- pkg_method("sql", "dbplyr")
glue_sql2 <- pkg_method("glue_sql2", "dbplyr")
sql_current_con <- pkg_method("sql_current_con", "dbplyr")
check_dots_unnamed <- pkg_method("check_dots_unnamed", "rlang")

Expand All @@ -82,22 +80,23 @@ duckdb_n_distinct <- function(..., na.rm = FALSE) {
check_dots_unnamed()

# https://duckdb.org/docs/sql/data_types/struct.html#creating-structs-with-the-row-function
# Requires dbplyr >= 2.5.2 with exported sql_glue()
if (!identical(na.rm, FALSE)) {
if (length(list(...)) == 1L) {
# in case of only one column fall back to the "simple" version
return(glue_sql2(con, "COUNT(DISTINCT {.col {list(...)}*})"))
return(dbplyr::sql_glue(con, "COUNT(DISTINCT {.col {list(...)}*})"))
} else {
str_null_check <-
sql(paste0(paste0(list(...), " IS NOT NULL"), collapse = " AND "))
dbplyr::sql(paste0(paste0(list(...), " IS NOT NULL"), collapse = " AND "))

return(glue_sql2(
return(dbplyr::sql_glue(
con,
"COUNT(DISTINCT row({.col {list(...)}*})) FILTER (",
str_null_check, ")"
))
}
} else {
return(glue_sql2(con, "COUNT(DISTINCT row({.col {list(...)}*}))"))
return(dbplyr::sql_glue(con, "COUNT(DISTINCT row({.col {list(...)}*}))"))
}
}

Expand Down
Loading