| 1 |
#' DBMS Connections which disconnect themselves. |
| 2 |
#' |
| 3 |
#' Connections to Database Management Systems which automatically disconnect. In |
| 4 |
#' particular connections which are created with `DBI::dbConnect()` and closed |
| 5 |
#' with `DBI::dbDisconnect()`. |
| 6 |
#' |
| 7 |
#' @template with |
| 8 |
#' @param con For `with_db_connection()` a named list with the connection(s) to |
| 9 |
#' create. For `local_db_connection()` the code to create a single connection, |
| 10 |
#' which is then returned. |
| 11 |
#' @param .local_envir `[environment]`\cr The environment to use for scoping. |
| 12 |
#' @examples |
| 13 |
#' db <- tempfile() |
| 14 |
#' with_db_connection( |
| 15 |
#' list(con = DBI::dbConnect(RSQLite::SQLite(), db)), { |
| 16 |
#' DBI::dbWriteTable(con, "mtcars", mtcars) |
| 17 |
#' }) |
| 18 |
#' |
| 19 |
#' head_db_table <- function(...) { |
| 20 |
#' con <- local_db_connection(DBI::dbConnect(RSQLite::SQLite(), db)) |
| 21 |
#' head(DBI::dbReadTable(con, "mtcars"), ...) |
| 22 |
#' } |
| 23 |
#' head_db_table() |
| 24 |
#' unlink(db) |
| 25 |
#' @export |
| 26 |
with_db_connection <- function(con, code) { |
| 27 |
requireNamespace("DBI", quietly = TRUE) |
| 28 |
|
| 29 |
stopifnot(all(is.named(con))) |
| 30 |
stopifnot(all(vlapply(con, methods::is, "DBIConnection"))) |
| 31 |
|
| 32 |
nme <- tempfile() |
| 33 |
(get("attach", baseenv()))(con, name = nme, warn.conflicts = FALSE) |
| 34 |
on.exit({ |
| 35 |
for (connection in con) { |
| 36 |
DBI::dbDisconnect(connection) |
| 37 |
} |
| 38 |
detach(nme, character.only = TRUE) |
| 39 |
}) |
| 40 |
force(code) |
| 41 |
} |
| 42 |
|
| 43 |
#' @rdname with_db_connection |
| 44 |
#' @export |
| 45 |
local_db_connection <- function(con, .local_envir = parent.frame()) { |
| 46 |
requireNamespace("DBI", quietly = TRUE) |
| 47 |
stopifnot(methods::is(con, "DBIConnection")) |
| 48 |
|
| 49 |
defer(DBI::dbDisconnect(con), envir = .local_envir) |
| 50 |
con |
| 51 |
} |