As part of my R workflow for one of my projects, I load in data from a postgreSQL table located on a remote server.
My code looks like this (anonymized credentials).
I first open an ssh connection to the remote server in terminal.
ssh -p Port -L LocalPort:IP:RemotePort servername"
I then connect to the postgres database in R.
# Load the RPostgreSQL package
library("RPostgreSQL")
# Create a connection
Driver <- dbDriver("PostgreSQL") # Establish database driver
Connection <- dbConnect(Driver, dbname = "DBName", host = "localhost", port = LocalPort, user = "User")
# Download the data
Data<-dbGetQuery(Connection,"SELECT * FROM remote_postgres_table")
This approach works fine, and I am able to download the data with no problems.
However, I would like to do the first step - i.e., creating the ssh connection - in R, rather than in terminal. Here is my attempt to do so, with accompanying error.
# Open the ssh connection in R
system("ssh -T -p Port -L LocalPort:IP:RemotePort servername")
# Load the RPostgreSQL package
library("RPostgreSQL")
# Create a connection
Driver <- dbDriver("PostgreSQL") # Establish database driver
Connection <- dbConnect(Driver, dbname = "DBName", host = "localhost", port = LocalPort, user = "User")
# Download the data
Data<-dbGetQuery(Connection,"SELECT * FROM remote_postgres_table")
Error in postgresqlExecStatement(conn, statement, ...) :
RS-DBI driver: (could not Retrieve the result : server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
To clarify my question, I would like to perform this entire workflow (establish a connection, download postgreSQL data) entirely in R without any steps in terminal.
system2("ssh", c("-L8080:localhost:80", "-N", "-T", "otherhost"), wait=FALSE)worked for me on linux. Doesn't work on windows, though, likely due to lack offork, so you might need something in the background (such asparallelorfutureto run another R session). Stopping it might work withtools::pskill, haven't tested.