Skip to content

best practice disconnecting connection inside a package #532

@m-muecke

Description

@m-muecke

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
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions