Question

I'm using RPostgreSQL and sqldf inside my function like this:

MyFunction <- function(Connection) {

    options(sqldf.RPostgreSQL.user      = Connection[1], 
            sqldf.RPostgreSQL.password  = Connection[2],
            sqldf.RPostgreSQL.dbname    = Connection[3],
            sqldf.RPostgreSQL.host      = Connection[4], 
            sqldf.RPostgreSQL.port      = Connection[5])

    # ... some sqldf() stuff
}

How do I test that connection is valid?

Was it helpful?

Solution 3

One approach is to simply try executing the code, and catching any errors with a nice informative error message. Have a look at the documentation of tryCatch to see the details regarding how this works.

The following blog post provides an introduction to the exception-based style of programming.

OTHER TIPS

You can check that an existing connection is valid using isPostgresqlIdCurrent.

conn <- dbConnect("RPgSQL", your_database_details)
isPostgresqlIdCurrent(conn)

For testing new connections, I don't think that there is a way to know if a connection is valid without trying it. (How would R know that the database exists and is available until it tries to connect?)

For most analysis purposes, just stopping on an error and fixing the login details is the best approach. So just call dbConnect and don't worry about extra check functions.

If you are creating some kind of application where you need to to handle errors gracefully, a simple tryCatch wrapper should do the trick.

conn <- tryCatch(conn <- dbConnection(wherever), error = function(e) do_something)

My current design uses tryCatch:

Connection <- c('usr','secret','db','host','5432')

CheckDatabase <- function(Connection) {

  require(sqldf)
  require(RPostgreSQL)
    
  options(sqldf.RPostgreSQL.user      = Connection[1], 
          sqldf.RPostgreSQL.password  = Connection[2],
          sqldf.RPostgreSQL.dbname    = Connection[3],
          sqldf.RPostgreSQL.host      = Connection[4], 
          sqldf.RPostgreSQL.port      = Connection[5])
    
  out <- tryCatch(
  {
    sqldf("select TRUE;")
  },
  error=function(cond) {
    out <- FALSE
  }
  )    
  return(out)
}

if (!CheckDatabase(Connection)) {
  stop("Not valid PostgreSQL connection.") 
} else {
  message("PostgreSQL connection is valid.")
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top