Skip to main content

DB File corruption fix

1) Stop writes + backup

# stop the bot/container first

cp -a bot.db bot.db.bak.$(date +%Y%m%d-%H%M%S)
[ -f bot.db-wal ] && cp -a bot.db-wal bot.db-wal.bak.$(date +%Y%m%d-%H%M%S)
[ -f bot.db-shm ] && cp -a bot.db-shm bot.db-shm.bak.$(date +%Y%m%d-%H%M%S)

sqlite3 bot.db "PRAGMA integrity_check;"

2) Recover with the sqlite3 docker image

rm -f recover.sql bot_recovered.db

docker run --rm -v "$PWD:/work" -w /work nouchka/sqlite3:latest \
  bot.db ".output recover.sql" ".recover" ".exit"

sqlite3 bot_recovered.db < recover.sql
sqlite3 bot_recovered.db "PRAGMA integrity_check;"
sqlite3 bot_recovered.db ".tables"

3) Swap in the recovered DB

mv bot.db bot.db.corrupt.$(date +%Y%m%d-%H%M%S)
mv bot_recovered.db bot.db
rm -f bot.db-wal bot.db-shm 2>/dev/null || true
sqlite3 bot.db "PRAGMA integrity_check;"