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

GH-38382: [R] Explicitly clean up arrow_duck_connection() on exit #38495

Merged
merged 6 commits into from
Nov 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
19 changes: 19 additions & 0 deletions r/R/duckdb.R
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,31 @@ to_duckdb <- function(.data,
tbl
}

arrow_duck_finalizer <- new.env(parent = emptyenv())

arrow_duck_connection <- function() {
con <- getOption("arrow_duck_con")
if (is.null(con) || !DBI::dbIsValid(con)) {
con <- DBI::dbConnect(duckdb::duckdb())
# Use the same CPU count that the arrow library is set to
DBI::dbExecute(con, paste0("PRAGMA threads=", cpu_count()))

# This connection will get cleaned up at exit using the garbage collector,
# but if we don't explicitly run dbDisconnect() the user gets a warning
# that they may not expect (since they did not open a duckdb connection).
# This bit of code will run when the package namespace is cleaned up (i.e.,
# at exit). This is more reliable than .onUnload() or .onDetatch(), which
# don't necessarily run on exit.
reg.finalizer(arrow_duck_finalizer, function(...) {
con <- getOption("arrow_duck_con")
if (is.null(con)) {
return()
}

options(arrow_duck_con = NULL)
DBI::dbDisconnect(con, shutdown = TRUE)
}, onexit = TRUE)

options(arrow_duck_con = con)
}
con
Expand Down
10 changes: 8 additions & 2 deletions r/tests/testthat/test-duckdb.R
Original file line number Diff line number Diff line change
Expand Up @@ -277,8 +277,14 @@ test_that("to_duckdb passing a connection", {
table_four <- ds %>%
select(int, lgl, dbl) %>%
to_duckdb(con = con_separate, auto_disconnect = FALSE)
# dbplyr 2.2.0 renames this internal attribute to lazy_query
table_four_name <- table_four$ops$x %||% table_four$lazy_query$x

# dbplyr 2.3.0 renamed this internal attribute to lazy_query;
# and 2.4.0 reserved $... for internal use + changed the identifier class
if (packageVersion("dbplyr") < "2.4.0") {
table_four_name <- unclass(table_four)$lazy_query$x
} else {
table_four_name <- unclass(unclass(table_four)$lazy_query$x)$table
}

result <- DBI::dbGetQuery(
con_separate,
Expand Down
Loading