brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: \gexec runs the SQL that a psql query just generated

CLI
~/tips/tip-postgresql-psql-gexec

\gexec

Takes every value a query returns and executes it as its own SQL statement.

Typing the same CREATE INDEX twenty times is the kind of chore I’d happily hand to the database. psql has a meta-command for it: write a query that produces SQL, then let psql run the result.

SELECT format('CREATE INDEX ON my_table (%I)', attname)
FROM pg_attribute
WHERE attrelid = 'my_table'::regclass AND attnum > 0
ORDER BY attnum
\gexec

End the query with \gexec instead of a semicolon. psql sends the query, then treats each column of each row as an SQL statement and executes it. The docs use exactly this example: one index per column of a table. Rows run in the order they come back, and left to right within a row. NULL values are skipped.

The same trick works for things like granting rights on every table in a schema, or running ANALYZE on a list of tables. Build the statements with format() and %I, so names with capitals or spaces get quoted properly.

Two caveats. The generated text goes to the server as it is, so it can’t be a psql meta-command and can’t contain psql variables such as :name. And if one statement fails, psql carries on with the rest unless ON_ERROR_STOP is set. Run the generating query without \gexec first to read what it will do. Setting ECHO to queries also prints each statement as it runs, which the docs recommend.

Further reading: psql documentation

More CLI tips printf 'GET /\r\n' | hexdump -C hexdump -C -s 512 -n 64 disk.img wget --limit-rate=2m https://example.com/big-file.iso wget --spider https://example.com/file.zip rg 'apiKey' -g '!*.min.js' -g '!package-lock.json' All CLI tips (46) All topics

Link