db_with: Execute code with a managed database connection

View source: R/connection_helpers.R

db_withR Documentation

Execute code with a managed database connection

Description

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

connection_name

Character. Name of the connection in config.yml

code

Expression to evaluate with the connection (use conn to access the connection)

Value

The result of evaluating code

Examples


if (FALSE) {
# 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)
)
}



framework documentation built on Feb. 18, 2026, 1:07 a.m.