Search code examples
rdplyrmagrittrrsqliter-dbi

Write table to multiple database connections using pipes


I've created two sqlite databases, and I'd like to use the magrittr/dplyr piping convention to write a single data frame to each dabatabse.

conn1 <- DBI::dbConnect(drv = RSQLite::SQLite(), dbname = "db1")
conn2 <- DBI::dbConnect(drv = RSQLite::SQLite(), dbname = "db2")

iris %>%
 DBI::dbWriteTable(conn1, "iris", .) %>%  # works
 DBI::dbWriteTable(conn2, "iris", .)      # does not work because lhs is not a table

Another (failed) attempt, because dbWriteTable only accepts a single connection

iris %>%
 DBI::dbWriteTable(c(conn1, conn2), "iris", .)

I prefer a solution that utilizes a pipe variation, perhaps a variation that retains the output from iris


Solution

  • The normal pipe operator %>% passed along the result of the previous function to the next. The DBI::dbWriteTable function returns TRUE if it works. It does not re-pass along the data.frame that was passed to it

    If you import magrittr you can instead use the "tee" operator %T>%. This essentially throws away whatever the previous function returns and just passes along the original input again. For example

    iris %T>%
     DBI::dbWriteTable(conn1, "iris", .) %T>%
     DBI::dbWriteTable(conn2, "iris", .) 
    

    See the magrittr documentation for more information about the tee operator.