DillonHammill / DataEditR

An Interactive R Package for Viewing, Entering Filtering and Editing Data
https://dillonhammill.github.io/DataEditR/
381 stars 40 forks source link

Using data_edit() to Modify Data in Databases #42

Closed DillonHammill closed 2 years ago

DillonHammill commented 2 years ago

This is not yet documented on the website, but data_edit() can be used to modify data stored in databases. The trick is that most database writing functions expect a connection as their first argument, whilst DataEditR passes arguments to these functions in the following order: 1. data -> 2. save_as -> 3. write_args. The workaround is to write a wrapper function that fixes the order of the arguments before passing them to the writing function - naming the arguments is the best way to do this. See example below:

# Load required packages
library(DataEditR)
library(DBI)

# Create database connection
con <- dbConnect(
  RSQLite::SQLite(),
  dbname = ":memory:"
)

# Function to update database
dbWrite <- function(...) {
  # DataEditR argument order - data -> save_as -> write_args
  args <- list(...)
  names(args)[1:2] <- c("value", "conn")
  do.call("dbWriteTable", args)
}

# Edit Data
data_edit(
  mtcars,
  write_fun = "dbWrite",
  write_args = list("name" = "mtcars"),
  save_as = con
)

# Check database is updated
dbListTables(con)

# Read data from database
dbReadTable(con, "mtcars")