Question

I have been trying to execute PSQL from system() within R in RStudio. I have PSQL setup in my PATH and can execute PSQL from the cmd line. I cannot for the life of me figure out the correct method for executing psql from within R on windows. I have code supplied from a ubuntu environment. I have not used system() previously before this and researching for this specific issue has been unsuccessful.

The hardest part is not receiving any output after executing system in R. I have tried a few different setting from looking at ?system. With no luck.

This code should execute a simple sql statement and pass the output to a local file. Ultimately this will be more robust to include dynamic elements in an application. Just having the basics working seems like the hardest part.

system(paste("export PGPASSWORD=db_password;psql -h db_host -d db_name -c 'copy(select * from large_table limit 1000) to stdout csv' > C:/temp_data/db_test.dat", sep=""))

I am curious as to if anyone has a working windows environment using PSQL in R. My greenplum server is not local.

My echo %PATH% includes C:\Program Files (x86)\pgAdmin III\1.12 included in both system and user vars.

Was it helpful?

Solution

There are a few problems with your command.

  • system cannot be used with redirects, you must use shell
  • You cannot use single quotes to quote commands in Windows, you must use double quotes.
  • To concatenate commands, you use the & operator, not a ; like in Unix.

So your command would look like (it appears to be necessary to include this in one line):

cmd<-'set PGPASSWORD=db_password& psql -h db_host -d db_name -c "copy(select * from large_table limit 1000) TO STDOUT CSV;" > C:/temp_data/db_test.dat'
shell(cmd)

But, have you considered using the RPostgresql driver, which is a much simpler, platform-independent way to do your task?

# Load up the driver
library(RPGsql)
drv <- dbDriver("PostgreSQL")
# Create a connection
con <- dbConnect(drv, dbname="db_name", host='db_host',password='db_password',user='db_user')
# Query the database
db_test=dbGetQuery(con, 'select * from large_table limit 1000')
# Write your file
write.csv(db_test,'C:/temp_data/db_test.dat')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top