R/connect.R

Defines functions claims_db claims_disconnect claims_connect

Documented in claims_connect claims_db claims_disconnect

#' Connect to the Synthetic Claims Database
#'
#' Provides a connection to a DuckDB database of the CMS synthetic claims data.
#' Alternatively, you can use `claims_db()` to manually connect to the
#' database using [DBI::dbConnect()] and [duckdb::duckdb()].
#'
#' @return A connection to the synthetic claims database, or the path to the database.
#'
#' @examples
#' # Manually connect using {duckdb} and {DBI}
#' con <- DBI::dbConnect(
#'   duckdb::duckdb(),
#'   dbdir = claims_db(),
#'   read_only = TRUE
#' )
#'
#' if (requireNamespace("dplyr", quietly = TRUE)) {
#'   dplyr::tbl(con, "bene")
#' }
#'
#' # Disconnect from that database (shutdown is specific to duckdb)
#' DBI::dbDisconnect(con, shutdown = TRUE)
#'
#' # Or connect without worrying about connection details
#' con <- claims_connect()
#'
#' if (requireNamespace("dplyr", quietly = TRUE)) {
#'   dplyr::tbl(con, "bene")
#' }
#'
#' # Similarly, disconnect quickly without worrying about duckdb arguments
#' claims_disconnect(con)
#'
#' @param con A connection to the Star Wars database
#' @name claims_db
NULL


#' @describeIn claims_db Connect to the DuckDB database
#' @inheritParams duckdb::`dbConnect,duckdb_driver-method`
#' @param ... Additional parameters passed to [DBI::dbConnect()]
#' @export
claims_connect <- function(dbdir = ":memory:", ...) {
  con <- DBI::dbConnect(duckdb::duckdb(), dbdir = dbdir, ...)
  tables <- claimsdb_tables()
  for (table in names(tables)) {
    DBI::dbWriteTable(
      con,
      name = table,
      value = as.data.frame(tables[[table]]),
      temporary = FALSE,
      overwrite = TRUE
    )
  }
  con
}

#' @describeIn claims_db Disconnect from the DuckDB database
#' @export
claims_disconnect <- function(con) {
  was_valid <- DBI::dbIsValid(con)
  DBI::dbDisconnect(con, shutdown = TRUE)
  if (inherits(con, "duckdb_connection") && was_valid) {
    if (!identical(con@driver@dbdir, ":memory:") && file.exists(con@driver@dbdir)) {
      unlink(dirname(con@driver@dbdir), recursive = TRUE)
    }
  }
}

#' @describeIn claims_db Returns the path to the claimsdb database
#' @export
claims_db <- function() {
  temp_db <- tempfile("claimsdb")
  dir.create(temp_db)
  dbdir <- file.path(temp_db, "claims.duckdb")
  con <- claims_connect(dbdir = dbdir)
  DBI::dbDisconnect(con, shutdown = TRUE)
  dbdir
}
jfangmeier/claimsdb documentation built on Feb. 14, 2022, 6:01 a.m.