Sub topic 6
Running commands and script files from psql
This chapter assumes you can already connect with psql, use basic meta-commands such as \dt, and write simple SQL. Everything below is about running psql without typing into its prompt, so that an inspection becomes repeatable.
Why run psql non-interactively
An interactive session suits exploring. Once you have a useful inspection, you will want to rerun it on another server, save its output, or call it from a shell script. psql supports this with command-line options that run commands and exit, and with meta-commands that read and write files from inside a session.
Running one command with -c
The -c option runs a single command string and then exits:
psql -d mydb -c '\dt public.*'
psql -d mydb -c 'SELECT count(*) FROM orders;'The string must be either one backslash meta-command or SQL. You cannot mix them, so -c '\dt; SELECT 1' fails. You can repeat -c to run several commands in order:
psql -d mydb -c '\conninfo' -c 'SELECT now();'Several SQL statements inside one -c string are sent to the server as a single request. The server treats that request as one implicit transaction, so if one statement fails, none of them take effect.
Running a script file with -f
The -f option reads commands from a file, one after another, and then exits. A script can mix SQL and meta-commands freely. Here is inspect.sql:
\echo Inspecting :"DBNAME" as :"USER"
\pset null '(null)'
\echo == Largest tables ==
SELECT n.nspname AS schema_name,
c.relname AS table_name,
pg_size_pretty(pg_total_relation_size(c.oid)) AS total_size
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
ORDER BY pg_total_relation_size(c.oid) DESC
LIMIT 5;
\echo == Columns of public.orders ==
\d+ public.ordersRun it like this:
psql -X -d mydb -f inspect.sqlDBNAME and USER are variables that psql sets for you. The syntax :"DBNAME" inserts the variable's value as a quoted string, which is safe for any content. The -X option skips your ~/.psqlrc, so the script behaves the same on every machine, whatever personal settings each user has. Put -X first when you use it, because it must come before the other options.
Reading commands from standard input
psql also reads commands from a pipe or a here-document. This is handy for short, generated inspections:
psql -X -d mydb <<'SQL'
\conninfo
SELECT current_user, current_database();
SQLQuoting the delimiter ('SQL') stops the shell from expanding $ and backticks inside the text. Without the quotes, the shell edits your SQL before psql sees it.
Handling errors
By default, psql keeps going after an error. A script that fails on line 3 still runs lines 4 to 300, and the exit status can still be 0. That is risky for anything that changes data.
Set the variable ON_ERROR_STOP to make psql stop at the first error:
psql -X -d mydb -v ON_ERROR_STOP=1 -f migrate.sql
echo "exit status: $?"With -f, an error then ends the run with exit status 3. Exit status 1 means psql itself failed, and 2 means it could not connect. Scripts and CI jobs should check these.
To make the whole file all-or-nothing, add -1 (long form --single-transaction). psql wraps the file in BEGIN and COMMIT:
psql -X -d mydb -v ON_ERROR_STOP=1 -1 -f migrate.sqlChoosing what the output looks like
For output that another program will read, strip the decoration:
psql -X -At -d mydb -c 'SELECT count(*) FROM orders;'-A turns off column alignment, and -t removes headers and the row-count footer. The result is a bare value you can capture in a shell variable. Add -q to silence informational messages, and -o file to send query output to a file. For tabular exports, -A -F ',' gives a quick comma-separated layout. It does not quote fields, so for real CSV use \copy ... CSV HEADER or --csv.
Meta-commands for scripts
A few meta-commands matter most inside script files.
| Command | What it does |
|---|---|
| `\echo text` | Prints text to standard output. Useful for section headings. |
| `\qecho text` | Prints text to the `\o` output target, so headings land in the saved file. |
| `\i file` | Runs another file. The path is relative to the current directory. |
| `\ir file` | Like `\i`, but the path is relative to the script that contains it. |
| `\o file` | Sends later query output to a file. `\o` with no argument restores the screen. |
| `\g file` | Ends a query and sends only that query's output to a file. |
| `\gset` | Ends a query and stores its single result row in psql variables. |
| `\set name value` | Sets a psql variable. Read it back with `:name` or `:'name'`. |
Prefer \ir when you split a large script into parts, because \i breaks when someone runs the script from a different directory.
The following script combines several of these. It stores a count in a variable, uses it in a message, and saves one report to a file:
SELECT count(*) AS order_count FROM orders \gset
\echo Orders found: :order_count
\o orders_by_status.txt
SELECT status, count(*) FROM orders GROUP BY status ORDER BY 2 DESC;
\o
\echo Report written to orders_by_status.txt\gset replaces the semicolon, so the query ends with \gset and not with ;. The column alias becomes the variable name. If the query returns zero rows or more than one, \gset reports an error and sets nothing.
You can also pass variables from the shell and use them in the script:
psql -X -d mydb -v tbl=orders -f describe_table.sqlInside describe_table.sql, \d+ :"tbl" describes the table. The :"tbl" form quotes the value as an identifier, so odd names do not break the command or inject SQL. Use :'tbl' instead when the value is a string literal, for example in a WHERE clause.
Common mistakes
- Forgetting
-Xin shared scripts. A colleague's\psetor\timingsetting changes your output. - Using
-cwith a meta-command and SQL together. Use-f, a here-document, or two-coptions. - Trusting exit status 0. Without
ON_ERROR_STOP, a script with errors can still exit with 0. - Using
\iwith relative paths. Switch to\irfor scripts that include other scripts. - Building commands by pasting untrusted text into the shell. Pass values with
-vand quote them in the script with:"name"or:'name'.
Exercise
You run psql -X -d mydb -f cleanup.sql in a CI job. Line 5 of the file fails, but the job reports success. What two changes make the job fail correctly, and make the file apply all-or-nothing?
Show answer
Add -v ON_ERROR_STOP=1 so psql stops at the first error and exits with status 3, which the CI job treats as a failure. Add -1 (--single-transaction) so the whole file runs inside one transaction that is rolled back on error. The command becomes psql -X -d mydb -v ON_ERROR_STOP=1 -1 -f cleanup.sql.
Exercise
Write a command that prints only the number of rows in public.orders, with no header, alignment or footer, so a shell script can store it in a variable.
Show answer
psql -X -At -d mydb -c 'SELECT count(*) FROM public.orders;'. The -A option turns off alignment, and -t removes the header and footer. In a shell script, wrap the command in $(...) to capture the output.