Sourcing a file and reading it in console

rstudio

#1

Hi,

I am sourcing a file with some connectivity details, however, I would like to see the contents inside to ensure the correct credentials are used, below is my code:

Source Code: source(paste("mypath/credentials.r",sep=""))

I tried using dput(source(paste("mypath/credentials.r",sep="")))
but it doesn't really gives the content inside credentials.r

The output after dput is :structure(list(value = <S4 object of class structure("PostgreSQLConnection", package = "RPostgreSQL")>,
visible = FALSE), .Names = c("value", "visible"))

Can somebody please help?


#2

I am a little confused by as to what you are asking.

  • I think I and others would benefit if you could supply a copy of the minimal example of credentials.r credential contents. (obviously, pls don't actually include any private credentials)
  • And with that example, could you be explicit about what you expect to get?

#3

Hi,

Thanks for your reply. Please see below sample code of credentials.r


driver<-dbDriver("PostgreSQL")
connection <-dbConnect(driver,dbname="serverxxx", host="XXXX.com",port=5432,user="XXXX",password="XXXX")


Basically, when I source the same, I need to see the contents inside, so that I can verify whether correct credentials are used or not.


#4

Hadley wrote this nice doc on Handling Secrets with R.

You might consider following the advice under "Environment variables".
It suggests you setup a ~/.Renviron file in your base directory (be sure your version control ignores it). Put your host, dbname(s), port, user and password inside it.

E.g.

# .Renviron
CONNECTION_HOST=XXXX.com # not the website i was expecting
CONNECTION_PORT=5432
CONNECTION_DBNAME= serverxxx
CONNECTION_PASSWORD=XXXX
CONNECTION_USR=XXXX

Note that .Renviron is only processed on startup, so you’ll need to restart R to see changes.

And then you can access those values in R with Sys.getenv("CONNECTION_HOST"),

driver<-dbDriver("PostgreSQL")
connection <-dbConnect(
  driver,
  dbname=Sys.getenv("CONNECTION_DBNAME"), 
  ...

And there are other options there (eg keyring) to be even more secure with your credential information.


#5

hey @bhavaniasok008, you can read a file as a string and display it to the screen like this:

fileName <- 'mypath/credentials.r'
readChar(fileName, file.info(fileName)$size)

#6

@jdlong, thanks a ton :slight_smile: It's working fine.


#7

Hi Hadley,

Thanks for your reply. let me try this. In between @jdlong suggestion worked for me. Thanks once again :smile: