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:

cogs/staffdesk.py · before
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:

utils/cloud_backup.py · now
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:

scripts/backup_to_gdrive.sh
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

  1. A database in use isn't just a file: copy it with its own tools (the backup API or VACUUM INTO in SQLite, pg_dump in PostgreSQL).
  2. A backup you've never checked isn't a backup.