This site has no external database. The admin's to-dos, done log, decisions and action log all live in one SQLite file, data/admin.db. It has two writers: the website (admin buttons) and the command-line script I use day to day, scripts/admin-db.js, and both may write at the same time.
In the default mode, reads and writes wait for each other
SQLite's default journal_mode is delete: while someone writes, others cannot read, and all you can do is wait with busy_timeout. I had set 3 seconds, which is enough normally, but when someone presses a decision button in the admin while another process adds a to-do on the command line, it is a bet on who finishes writing first.
I switched to WAL (Write-Ahead Logging): writes are recorded first in a side file, admin.db-wal, readers are not blocked, and writes are usually faster too. Two lines when opening the file:
WAL mode is stored in the file, so once set it applies every time it is opened. Also, a read-only connection cannot switch modes, so the command-line script runs these two lines only when it is about to write.
The real trap: the backup script copies the .db directly
The daily backup script backup.ps1 used to back up the database like this:
In the default mode, if the copy happens to coincide with a write, the backup might be a broken file, but at least all the data is in that one file. In WAL mode it is worse: recent writes may still be in admin.db-wal, and copying only admin.db simply misses them, with no error at all: the backup looks successful, and only on restore do you find things missing.
So the same change that switches to WAL must also change the backup.
Switch to VACUUM INTO: a consistent single-file backup
VACUUM INTO '<file>' compacts the whole database (including what is in the WAL) into a clean single-file copy, without affecting reads and writes meanwhile. I added a backup subcommand to the command line that, besides VACUUM INTO, immediately opens the backup file, runs integrity_check, and counts the to-dos, to confirm it really opens:
backup.ps1 now calls it, and on failure throws so the whole backup reports failure, instead of quietly copying a file that may be broken.
I tested on a copy of the database: journal_mode really became wal; the backup file's integrity_check returned ok, with 187 to-dos in it. The actual scheduled backup has to wait for the next round to run the new code, so I have not yet seen its log in production.
Summary
- Two programs writing the same SQLite file: use WAL so reads and writes do not block each other; a read-only connection cannot change the mode, so set it only when writing
- If you switch to WAL, you must change the backup: copying
.dbdirectly can miss data still in-wal, and it raises no error - Use
VACUUM INTOto produce a consistent single-file backup, and verify it immediately withintegrity_check - A failed backup must fail the whole flow, not be swallowed quietly