I've got a (singleton) connection setup inside a package with the following:
the <- new.env(parent = emptyenv())
db_conn <- function() {
if (exists("con", the) && DBI::dbIsValid(the$con)) {
return(the$con)
}
the$con <- DBI::dbConnect(...)
the$con
}
I've tried using reg.finalizer to disconnect the connection, but I'm not sure if it does what I expect. Is there a best practice for this pattern?
the <- new.env(parent = emptyenv())
db_conn <- function() {
if (exists("con", the) && DBI::dbIsValid(the$con)) {
return(the$con)
}
the$con <- DBI::dbConnect(...)
reg.finalizer(
the,
\(env) if (DBI::dbIsValid(env$con)) DBI::dbDisconnect(env$con),
onexit = TRUE
)
the$con
}