Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disconnecting src_tbls connection in dplyr

Tags:

sql

r

dplyr

Is there a way to force disconnection of a src_tbls object in dplyr similar to RPostgreSQL::dbDisconnect?

See for example:

> src_temp <- src_postgres(dbname = "temp", host = "127.0.0.1", port = 5432, user = "x", password = "y")
Error in postgresqlNewConnection(drv, ...) : 
  RS-DBI driver: (cannot allocate a new connection -- maximum of 16 connections already opened)

As a side note, it does auto-disconnect quite quickly after a few seconds:

Auto-disconnecting postgres connection (3734, 26)

after which you can run the src_postgres command again.

like image 279
Alex Avatar asked Oct 12 '14 23:10

Alex


1 Answers

You can do:

RPostgreSQL::dbDisconnect(src_temp$con)

to force a disconnect.

That's what's called on garbage collection from this function in dplyr (via the dbi-s3.r source file):

# Creates an environment that disconnects the database when it's
# garbage collected
db_disconnector <- function(con, name, quiet = FALSE) {
  reg.finalizer(environment(), function(...) {
    if (!quiet) {
      message("Auto-disconnecting ", name, " connection ",
        "(", paste(con@Id, collapse = ", "), ")")
    }
    dbDisconnect(con)
  })
  environment()
}
like image 105
hrbrmstr Avatar answered Oct 09 '22 02:10

hrbrmstr