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: \set ON_ERROR_ROLLBACK interactive keeps a psql transaction alive after a typo

Database
~/tips/tip-database-psql-on-error-rollback

\set ON_ERROR_ROLLBACK interactive

Keeps an open psql transaction usable after one statement fails, instead of aborting all of it.

You open a transaction in psql, run three careful updates, then make a typo in the fourth. PostgreSQL answers every following command with current transaction is aborted, commands ignored until end of transaction block, and the only way out is ROLLBACK, taking the three good updates with it. One psql variable makes that a lot less painful.

Set it in the session, or better, in your ~/.psqlrc so it’s always on:

\set ON_ERROR_ROLLBACK interactive

Now a failing statement inside a transaction only undoes itself:

BEGIN;
UPDATE users SET active = false WHERE last_login < now() - interval '2 years';
UPDATE userz SET note = 'cleanup';   -- ERROR: relation "userz" does not exist
UPDATE users SET note = 'cleanup' WHERE active = false;
COMMIT;

With the variable set, the typo produces its error, the transaction stays usable, and the corrected update and the COMMIT go through. psql does this by quietly setting a savepoint before each statement in a transaction block and rolling back to it when the statement fails.

Why interactive and not on? With interactive, errors are only forgiven when you’re typing at the prompt. When psql runs a script file, a failing statement still aborts the whole transaction, and that is exactly what you want for migrations and scripted changes. I’d keep it that way. Setting it to on means a broken script can commit half its work.

The caveat: this is a psql feature, not a server setting. pgAdmin, your app and other clients behave the normal way. It’s set per session, which is why ~/.psqlrc is the right place.

Further reading: PostgreSQL 17 docs: psql variables (ON_ERROR_ROLLBACK), PostgreSQL 17 docs: SAVEPOINT

More Database tips mariadb -e 'CREATE DATABASE IF NOT EXISTS blog' mariadb-dump --no-create-info --insert-ignore shop orders > orders-rows.sql SELECT table_schema, table_name, CHECKSUM TABLE shop.orders; services: All Database tips (53) All topics

Link