1

Using the RPostgreSQL package, is there a way to connect to a remote PostgreSQL instance other than hardcoding the credentials into the dbConnect method?

As far as I can tell, this is the only way to do it:

dbConnect(drv, host='some.com', port='5432', dbname='some-db', user='usr', password='secrecy')

Certainly there's a way to use a connection string or something?

Edit: I mean referencing some file (separate from the source code) or environment variable that contains the connection string. Sort of like .pgpass in my home directory, or DATABASE_URL on heroku. Just some way to avoid having DB credentials in the source code.

yalestar
  • 9,334
  • 6
  • 39
  • 52
  • Have a look at the docs for RPostgres - I think I documented what you need there – hadley Apr 03 '15 at 02:42
  • Thanks @hadley. I've looked through these docs http://cran.r-project.org/web/packages/RPostgreSQL/RPostgreSQL.pdf, but I didn't see any means of connecting using something that doesn't have the credentials right in the source code. Can you point me to such a thing? – yalestar Apr 03 '15 at 16:24
  • _RPostgres_, not _RPostgreSQL_: https://github.com/rstats-db/RPostgres/blob/master/R/connection.R#L41-L45 – hadley Apr 03 '15 at 19:26

1 Answers1

1

On Windows at least, in an interactive session you can prompt the user for a name and password with winDialogString.

user <- winDialogString("Enter your username", "")
pwd <- winDialogString("Enter your password", "")
dbConnect(..., user=user, password=pwd)

But what does a connection string do that a function call doesn't? Either way, you still have to hardcode your credentials somewhere.


You can also store the credentials in a file somewhere, and read them in using the usual methods (readLines, scan, read.table etc).

### assuming dbcreds.txt contains the single line "username    password"
cred <- strsplit(readLines("dbcreds.txt"), "[[:blank:]]+")[[1]]
user <- cred[1]
pwd <- cred[2]
dbConnect(..., user=user, pass=pwd)
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
  • You're right about the hardcoded connection string. I guess I meant referencing some file (separate from the source code) or environment variable that contains the connection string. Sort of like `.pgpass` in my home directory, or `DATABASE_URL` on heroku. – yalestar Apr 02 '15 at 20:48
  • I may in fact go with something like your solution: prompt the user for input. – yalestar Apr 02 '15 at 20:50