I have a JDBI query that returns many columns from few tables which I need to write to a CSV file. How can I achieve this? I have a REST end point that receives POST of search criteria using which I am constructing a query to fire against the Postgres db. I am using Dropwizard and JDBI.
1 Answer
Use COPY TO.
COPY (SELECT ... ) TO '/path/to/myfile1.csv' FORMAT csv; You need superuser privileges if you want to write to a file. The manual:
COPYnaming a file or command is only allowed to database superusers, since it allows reading or writing any file that the server has privileges to access.
Or you can send the output to STDOUT directly without saving to a file (possible without superuser privileges!).
To write the file on your client (can be separate from the DB server or not) use the meta-command \copy of psql encapsulating the same functionality. This does not require superuser privileges:
This means that file accessibility and privileges are those of the local user, not the server, and no SQL superuser privileges are required.
Details:
4 Comments
COPY due to superuser privilege requirements. We are using SuperCSV which has CsvResultSetWriter. But, not sure how to achieve this as my actual query result is set of columns from few tables and I don't have to have @RegisterMapper class and I don't have one.\copy of psql does not require superuser privileges. Consider added details.