1

I'm trying to write a script in R to export a query from a Postgresql database to a csv file.

If I do this from cmd it works fine :

psql -U postgres
\copy (select * from clickthru.train limit 10) to 'c:\\me\\psql_test.csv' with csv header;

However when I try this in R it looks like it executes (no errors) but no file is generated:

system('psql -U postgres COPY (select * from clickthru.train limit 10;) TO "C:\\me\\psql_test.csv" with CSV')

Any suggestions?

3
  • queryResult <- however you're running your query then use write.csv(queryResult, 'c:\\me\\psql_test.csv' Commented Feb 1, 2015 at 20:12
  • @FeargalRyan: That could work but the result set is too big to pass it to R via ODBC. Ignore the 'limit 10' in the example. Commented Feb 1, 2015 at 20:29
  • Hey, looks like this behaviour has been encountered before here: stackoverflow.com/questions/7393579/… . I think you need to concatenate your system commands with & Commented Feb 1, 2015 at 21:45

2 Answers 2

1

use;

\copy (select * from clickthru.train limit 10) to 'c:\\me\\psql_test.csv' DELIMITER ',' CSV HEADER;
Sign up to request clarification or add additional context in comments.

Comments

0

There are several issues here

  1. Query should be passed via -c argument: psql -U postgres -c '... query ...'
  2. COPY and \copy work differently. COPY operates on servers disk space, \copy operates on client disk space. If you run both on one computer, then the difference is that COPY will work as postgres user, and \copy as user who runs the script.
  3. In your example you have extra semicolon (;) in query ...COPY (select * from clickthru.train limit 10;)...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.