使用R的池程序包重新连接到PostgreSQL数据库

时间:2019-03-04 18:00:12

标签: r postgresql r-dbi rpostgresql plumber

我有一个使用R plumber构建的API,该API使用RPostgreSQLpool连接到PostgreSQL数据库(尽管如果使用的是Shiny应用,这也适用):

# create the connection pool
pool <- dbPool(
  drv = PostgreSQL(),
  host = Sys.getenv("DB_HOST"),
  port = 5432,
  dbname = "db",
  user = Sys.getenv("DB_USER"),
  password = Sys.getenv("DB_PASSWORD")
)

# start the API
pr <- plumb("plumber.R")

# on stop, close the pool
pr$registerHooks(
  list("exit" = function() { poolClose(pool) })
)

我想每天导入新数据。最简单的方法是创建一个新数据库并将其推广到生产环境:

CREATE DATABASE db_new;
-- create the tables
-- bulk-insert the data
SELECT pg_terminate_backend (pid) FROM pg_stat_activity WHERE datname = 'db';
DROP DATABASE db;
ALTER DATABASE db_new RENAME TO db;

这是快速的,最大程度地减少了停机时间。问题是pool然后失去了与数据库的连接,并且不会自动尝试重新连接:

> tbl(pool, "users")
Error in postgresqlExecStatement(conn, statement, ...) : 
  RS-DBI driver: (could not Retrieve the result : FATAL:  terminating connection due to administrator command
server closed the connection unexpectedly
    This probably means the server terminated abnormally
    before or while processing the request.
)

即使我不是每天更换数据库,数据库服务器也偶尔会重启,这也会导致我的应用程序损坏。重新连接似乎不是池,RPostgreSQL或DBI的功能。有人知道解决这个问题的方法吗?

2 个答案:

答案 0 :(得分:1)

我最近遇到了类似的问题,这是由于超过实例的wait_timeout时MySQL连接已关闭。我遇到了your post on RStudio Community,并从您的解决方案中得到启发。如果您仍在使用它,并且正在寻找一种在包装您使用的实际函数时避免额外查询的解决方案,那么这里是一个reprex演示了我的想法,并提供了一个示例来证明它可行: / p>

library(dplyr, warn.conflicts = FALSE)
library(pool)
library(RMariaDB)

generate_safe_query <- function(pool) {
  function(db_function, ...) {
    tryCatch({
      db_function(pool, ...)
    }, error = function(e) {
      if (grepl("Lost connection to MySQL server during query", e$message)) {
        # Preserve `validationInterval` so that it can be restored
        validation_interval <- pool$validationInterval
        # Trigger destruction of dead connection
        pool$validationInterval <- 0
        refreshed_connection <- poolCheckout(pool)
        poolReturn(refreshed_connection)
        # Restore original `validationInterval`
        pool$validationInterval <- validation_interval
        # Execute the query with the new connection
        db_function(pool, ...)
      } else {
        # Unexpected error
        stop(e)
      }
    })
  }
}

mysql_pool <- dbPool(MariaDB(),
                     host = "127.0.0.1",
                     username = "root",
                     password = "",
                     dbname = "test")

safe_query <- generate_safe_query(mysql_pool)

# Works
safe_query(tbl, "notes")
#> # Source:   table<notes> [?? x 2]
#> # Database: mysql 8.0.15 [root@127.0.0.1:/test]
#>      id note 
#>   <int> <chr>
#> 1     1 NOTE1

# Set the `wait_timeout` to 5 seconds for this session
invisible(safe_query(dbExecute, "SET SESSION wait_timeout = 5"))

# Wait longer than `wait_timeout` to trigger a disconnect
Sys.sleep(6)

# Still works; warning will appear notifying that connection was
# destroyed and replaced with a new one
safe_query(tbl, "notes")
#> Warning: It wasn't possible to activate and/or validate the object. Trying
#> again with a new object.
#> # Source:   table<notes> [?? x 2]
#> # Database: mysql 8.0.15 [root@127.0.0.1:/test]
#>      id note 
#>   <int> <chr>
#> 1     1 NOTE1

safe_query(poolClose)
# Or, equivalently: 
# poolClose(mysql_pool)

reprex package(v0.3.0)于2019-05-30创建

generate_safe_query返回的函数可以与任何数据库查询函数一起使用(例如dbExecutedbGetQuery等)。显然,您需要更新匹配的错误消息以适合您的需求。

我还打开了自己的Community topic,我认为应该将其包含在dbPool中,以减轻对此类变通方法的需求。

答案 1 :(得分:0)

我正在使用具有以下功能的普通DBI(不带池),以始终为DBI调用保持活动连接(例如DBI :: dbExistsTable(rdsConnect(),“ mytable”))。

#' Connect returns a database connection.
#' Retrieves the connection parameters from configuration.
#' 
#' FIXME: dbIsValid is not implemented
#' https://github.com/tomoakin/RPostgreSQL/issues/76
#' workaround implemented with isPostgresqlIdCurrent()
#' @return rds allocated connection
rdsConnect <- function() {
  if (!((exists("rds") && (isPostgresqlIdCurrent(rds))))) {
    source('./config.R', local = TRUE)
    print("New PostgreSQL connection")
    rds <<- DBI::dbConnect(RPostgreSQL::PostgreSQL(),
      dbname = rds_params("rds_database"),
      host = rds_params("rds_host"),
      user = rds_params("rds_user"),
      password = rds_params("rds_password")
    )
  } else print("Valid PostgreSQL connection")
  return(rds)
}