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: psql -1 with ON_ERROR_STOP makes a SQL script all or nothing

Database
~/tips/tip-database-psql-single-transaction-on-error-stop

psql -1 -v ON_ERROR_STOP=1 -d appdb -f migrate.sql

Runs a SQL script as one transaction and stops at the first error, rolling everything back.

Running a SQL script through psql has an unpleasant default: when a statement fails, psql prints the error and carries on with the next one. After a long migration you can end up with half of it applied and a scrolled-away error. Two small options fix that.

psql -1 -v ON_ERROR_STOP=1 -d appdb -f migrate.sql

-1 (--single-transaction) makes psql send BEGIN before the script and COMMIT after it, so either all commands succeed or no change is applied. The docs add one detail: if a command fails and ON_ERROR_STOP is set, psql sends ROLLBACK instead of COMMIT. Without ON_ERROR_STOP psql keeps going and still commits what worked, which defeats the purpose.

The variable also changes the exit code. When an error stops a script, psql exits with 3, while a fatal error of its own gives 1. That makes it easy to use in a shell script:

psql -1 -v ON_ERROR_STOP=1 -d appdb -f migrate.sql || echo "migration failed, nothing applied"

Two caveats. The docs say -1 only works together with -c and/or -f, so you cannot use it for an interactive session. The other limit is that psql then reports a rollback and your data stays as it was, so you must fix the script and run it again from the top.

It is a small habit that I think should be the default for any script that changes a schema.

Further reading: PostgreSQL documentation: psql

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