The context
Dabot keeps almost everything in a single SQLite file in WAL mode, shared by the bot and the web dashboard. Until October, the backup command did this:
shutil.copy2(src, dest)
wal = src + "-wal"
if os.path.exists(wal):
shutil.copy2(wal, dest + "-wal")
The problem
In WAL mode, recent writes live in the -wal file until a checkpoint moves them into the main database. Copying the two files one after the other isn't an atomic snapshot: between the two copies the bot can write or checkpoint, and you end up with a database and a WAL that don't match. At best you lose the latest transactions; at worst the copy is corrupt and you find out the day you need it.
The fix: SQLite's backup API
SQLite knows how to copy itself consistently even while another process is writing. Now every Dabot backup goes through the same function:
def _do_backup():
sconn = sqlite3.connect(src_db_path, timeout=30)
dconn = sqlite3.connect(dest_file, timeout=30)
with dconn:
sconn.backup(dconn)
dconn.close()
sconn.close()
os.chmod(dest_file, 0o600)
await asyncio.to_thread(_do_backup)
integrity_ok = await asyncio.to_thread(verify_sqlite_integrity, dest_file)
Three details: the copy runs in asyncio.to_thread because copying a large database would block the bot's event loop; the file gets 600 permissions because it holds user data; and it has to pass PRAGMA integrity_check before it counts.
And the nightly copy
A cron job at 04:30 uses the other good tool, VACUUM INTO (SQLite 3.27 or later), which also leaves a compacted copy. If the integrity check fails, nothing is uploaded to Google Drive:
sqlite3 "$SOURCE_DB" "VACUUM INTO '$BACKUP_FILE';"
INTEGRITY="$(sqlite3 "$BACKUP_FILE" "PRAGMA integrity_check;" 2>&1 || echo "failed")"
if [[ "$INTEGRITY" != "ok" ]]; then
exit 1 # nothing gets uploaded to Drive
fi
What I took away
- A database in use isn't just a file: copy it with its own tools (the backup API or
VACUUM INTOin SQLite,pg_dumpin PostgreSQL). - A backup you've never checked isn't a backup.