db_with
Execute code with a managed database connection
Provides automatic connection lifecycle management. The connection is automatically closed when the code block finishes, even if an error occurs. This prevents connection leaks and ensures proper resource cleanup.
Usage
db_with(connection_name, code)
Arguments
| Argument | Description |
|---|---|
connection_name
|
Character. Name of the connection in config.yml |
code
|
Expression to evaluate with the connection (use |
Returns
The result of evaluating code
Examples
# Safe - connection auto-closes
users <- db_with("my_db", {
DBI::dbGetQuery(conn, "SELECT * FROM users WHERE active = TRUE")
})
# Multiple operations with same connection
result <- db_with("my_db", {
DBI::dbExecute(conn, "INSERT INTO users (name) VALUES ('Alice')")
DBI::dbGetQuery(conn, "SELECT * FROM users")
})
# Connection closes even on error
tryCatch(
db_with("my_db", {
stop("Something went wrong") # Connection still closes
}),
error = function(e) message(e$message)
)
Source: R/connection_helpers.R