3

I'm a newbie at this. I want to write a script that I can execute from command line to run a query on a Heroku-hosted PostgreSQL database.

Right I have a script script.sh with executable permissions that looks like:

echo "Starting pull from postgres ..."
heroku pg:psql <db> --app <app-name>
\copy (<query>) to 'file.csv' WITH CSV
\q
echo "Done!"

The echo and heroku ... commands runs fine, however, once Heroku launches, the script no longer injects the commands. Only after I manually close out the Heroku app does it inject the last three lines.

I understand that this is a bash script that isn't intended to input postgreSQL commands once Heroku is open, but is there a way to do this?

I get the sense that it might involve connecting to Heroku and submitting the query in one line -- I searched around Heroku's documentation but didn't see anything that would be helpful.

1 Answer 1

5

You can use the --command flag to pass SQL commands to heroku pg:psql along with the server-based COPY and then redirect the output to a file:

echo "Starting pull from postgres ..."
heroku pg:psql <db> --app <app-name> --command "COPY (<query>) TO STDOUT WITH CSV" > file.csv
echo "Done!"
Sign up to request clarification or add additional context in comments.

1 Comment

pg:psql is an interactive command. It requires you to enter commands directly. The --command flag changes that by providing the commands upfront to be executed automatically.

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.