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: sqlite3 -bail stops a SQLite script at the first error

Sqlite
~/tips/tip-sqlite-bail-stop-on-error

sqlite3 -bail app.db < migrate.sql

Makes a SQL script stop at the first failing statement instead of running the rest.

When you feed a script to sqlite3, it prints an error for a bad statement and then carries on with the next line. For a migration, that is usually the opposite of what you want.

sqlite3 -bail app.db < migrate.sql
echo $?

With -bail the shell stops at the first error and exits with a non-zero code, so a shell script or CI job can react. Take a three-line script where the second line fails: without the option the third line still runs, and with it the third line never does. Inside the shell, .bail on does the same, which I find handy before a .read migrate.sql.

Stopping is not undoing, though. Statements that succeeded before the error are already committed, so you can end up with half a migration. To get all or nothing, wrap the script itself in a transaction:

BEGIN;
ALTER TABLE users ADD COLUMN last_login TEXT;
UPDATE users SET last_login = created_at;
COMMIT;

Combined with -bail, a failure stops before COMMIT. The shell exits, the open transaction is rolled back when the connection closes, and the file stays as it was. Without -bail, the COMMIT would still run after the error and keep the first half, which is the trap here.

Further reading: Command Line Shell For SQLite

More Sqlite tips SELECT unixepoch('2026-01-01 00:00:00'); SELECT name, iif(qty > 0, 'in stock', 'sold out') AS state CREATE INDEX 'orders_user_id' ON 'orders'('user_id'); –> users(id) CREATE INDEX users_active_email ON users(email) WHERE active = 1; sqlite> .once users.csv All Sqlite tips (27) All topics

Link