OHDSI / OHDSI/DatabaseConnector

Implement a `withConnection` context function for ensuring connections close in scripts

Open
#269 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement good first issue
Dominant language
R
Stars
57
Forks
93
Avg merge
10d 12h
Merged PRs (30d)
1

Description

This was discussed in the last HADES meeting and I think it would be good to implement something that we can say is our best practice principles for working with db connections to ensure they aren't left hanging. Something I'm sure everyone is guilty of in scripts at some point.

Toy example

The following is along the lines of how I think the function should look. This heavily borrows from the withr package style.

library(DatabaseConnector)

withConnection <- function (connection, code)
{
  stopifnot(dbIsValid(connection))
  on.exit({
    if (dbIsValid(connection)) disconnect(connection)
  })
  force(code)
}

# Example
connectionDetails <- createConnectionDetails(server = ":memory:", dbms = "sqlite")
connection <- connect(connectionDetails)
withConnection(connection, {
  insertTable(connection, tableName = "cars", data = mtcars)
  result <- renderTranslateQuerySql(connection, "SELECT * FROM cars")
})

# Should print 50
print(nrow(cars))
# Should print FALSE
print(dbIsValid(connection))

Most OHDSI functions already use the on.exit to be clean but this approach is more general and could be applied everywhere.

Some semantic sugar could be added around the connection details instance so you auto assign a connection with this.

A part of any PR for this should be to update any guides and examples in this package to use the agreed standard practice for ensuring the connection is closed after usage.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing DatabaseConnector’s existing connection functions, guides, and examples, then compare them with the proposed withConnection toy example. Clarify the agreed connection and semantic-sugar API before implementation. Done means the agreed pattern is implemented and the package guides and examples consistently show connections being closed after use.

Written by the indexing model from the issue text.

Assessment

Tech stack
r
Domain
database, documentation
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.