Sub topic 10
Customizing psql with a psqlrc file
This chapter assumes you can start psql and connect to a database, and that you know the meta-commands for output formatting (\x, \timing, \pset). Here you will put those settings in a startup file so they apply to every session, and you will learn how that file is found, what it can safely contain, and where it causes trouble.
What psqlrc is
When psql starts, it looks for a startup file and runs its contents as if you had typed them at the prompt. The user-level file is ~/.psqlrc. A system-wide file, psqlrc in the directory reported by pg_config --sysconfdir, is read first if it exists. The user file is read second, so your settings win.
You can also point psql at a different file with the PSQLRC environment variable. This is handy for keeping separate configurations for different projects.
PSQLRC=~/projects/shop/psqlrc psql -d mydbVersion-specific files are also supported. If you create ~/.psqlrc-16, psql reads it instead of ~/.psqlrc when it connects with a version 16 client. The suffix can also be a full version string such as ~/.psqlrc-16.2. This is rarely needed, but it helps when one client version lacks a setting that another one supports.
A starter file
The following file is the one from the topic examples. Save it as ~/.psqlrc.
\set ON_ERROR_ROLLBACK interactive
\x auto
\timing on
\pset null '(null)'Each line does one job:
\set ON_ERROR_ROLLBACK interactivewraps each statement you type inside an open transaction in a hidden savepoint. If a statement fails, only that statement is undone and the transaction stays usable. The valueinteractiveapplies this only when you type at the prompt, so scripts keep the default behavior of aborting the transaction.\x autouses expanded display only when a row is too wide for the terminal.\timing onprints how long each statement took, measured on the client side. The time includes network round trips.\pset null '(null)'prints NULL as(null)instead of an empty string, so you can tell NULL from an empty text value.
How psql processes the file
psql reads the file line by line, and each line is either a meta-command or SQL. Most startup files contain only meta-commands. Settings made here are ordinary session settings, so you can override any of them at the prompt later.
The diagram below shows the order in which psql reads startup files.
Two details are worth knowing:
- psql reads the startup file after it connects, so you can use
\conninfo-style output or conditional logic that depends on the connection. - When you run
psql -corpsql -f, the startup file is still read unless you pass-X. This is why the scripting example in the topic uses-X: without it, your personal settings would change the output of a script.
psql -X -d mydb -f inspect.sqlMaking startup output quiet
Some settings print a confirmation. With \timing on, psql prints Timing is on. every time it starts. In a script that parses output this is noise, and in an interactive session it is clutter. Wrap the file in \set QUIET 1 and \unset QUIET to suppress the messages.
\set QUIET 1
\set ON_ERROR_ROLLBACK interactive
\x auto
\timing on
\pset null '(null)'
\unset QUIETUseful additions
Once the basics work, these settings are common in real startup files.
\set QUIET 1
\set ON_ERROR_ROLLBACK interactive
\set COMP_KEYWORD_CASE upper
\set HISTCONTROL ignoredups
\set HISTSIZE 5000
\set PROMPT1 '%n@%/%R%x%# '
\x auto
\timing on
\pset null '(null)'
\pset linestyle unicode
\pset border 2
\pset pager off
\unset QUIETWhat the new lines do:
| Setting | Effect |
|---|---|
| `COMP_KEYWORD_CASE upper` | Tab completion writes SQL keywords in uppercase. |
| `HISTCONTROL ignoredups` | Repeated identical commands are saved to history once. |
| `HISTSIZE 5000` | Keeps up to 5000 commands in history. |
| `PROMPT1 '%n@%/%R%x%# '` | Shows user, database, a status marker, a transaction status marker, and `#` for superusers or `>` for others. |
| `\pset linestyle unicode` | Draws table borders with line-drawing characters. |
| `\pset border 2` | Draws a full outer border around results. |
| `\pset pager off` | Turns off the pager so long results scroll in the terminal. |
The %x in the prompt is useful for exploring: it shows * when you are inside a transaction and ! when the transaction has failed. That tells you at a glance whether your last BEGIN is still open.
Storing frequent queries as variables
You can save a query in a variable and run it by name. The colon syntax expands the variable and \set stores text. Put this in ~/.psqlrc:
\set biggest 'SELECT n.nspname, c.relname, 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 10;'Then, at the prompt, type :biggest and press Enter. Note the doubled single quotes: inside a quoted \set value, a literal quote must be written twice. The query must be one line, because \set reads a single line.
Gotchas
- Settings that change script output. If a shared script depends on default formatting, your
\psetsettings alter it. Run scripts with-X, or set what the script needs explicitly at the top of the script. - A broken line does not stop startup. If a line in the file has an error, psql prints a message and continues. Run psql once after editing and look for messages at the top.
- SQL in the startup file runs on every connection. Avoid SQL statements that change data. Even harmless
SETstatements apply only to the first database you connect to. After\c otherdb, session settings made with SQLSETdo not carry over, though psql's own\psetand\setsettings do. ON_ERROR_ROLLBACKis not free. Each statement inside a transaction gets a savepoint. For interactive exploration this cost is negligible, but it is the reason the value isinteractiveand noton.ON_ERROR_STOPdoes not belong here. Setting it in the startup file would change how every-fscript behaves. Pass it as-v ON_ERROR_STOP=1on the command line for the scripts that need it.
Checking that it worked
Start psql normally, then inspect a setting. Use \pset with no value to print the current value, and \echo :VARIABLE to print a psql variable.
\pset null
\echo :ON_ERROR_ROLLBACK
\timingTo test a change without touching your real file, create a copy and point PSQLRC at it.
cp ~/.psqlrc /tmp/test-psqlrc
PSQLRC=/tmp/test-psqlrc psql -d mydbExercise
You added \pset null '(null)' to ~/.psqlrc. A teammate runs your script report.sql with psql -d mydb -f report.sql and says the output has (null) in it, but the output on a build server shows empty cells. Why do the two differ, and how do you make the output the same everywhere?
Show answer
The teammate's psql reads their own ~/.psqlrc, which sets the NULL display, while the build server has no such file, so it prints the default empty string. Running the script with psql -X -d mydb -f report.sql skips all startup files, so both machines use defaults. If the script needs a specific NULL display, put \pset null '(null)' at the top of the script itself.
Exercise
Why is \set ON_ERROR_ROLLBACK interactive a better choice for a startup file than \set ON_ERROR_ROLLBACK on?
Show answer
With interactive, the hidden savepoints are used only when you type at the prompt, so a typo inside a transaction does not abort the whole transaction. Scripts run with -f keep the default behavior and stop the transaction on an error, which is what you usually want for batch work. With on, the savepoint behavior would also apply to scripts and could hide errors.