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 .recover rescues rows from a corrupt database where .dump gives up

Database
~/tips/tip-database-sqlite3-recover-corrupt-db

sqlite3 broken.db ".recover" | sqlite3 recovered.db

Rebuilds a new SQLite database from every readable page of a damaged file.

When a SQLite file is damaged, my first instinct would be .dump, since it turns the whole database into SQL. The SQLite shell has a second, more stubborn command for exactly this situation, and it is good to know it exists before you need it.

sqlite3 broken.db ".recover" | sqlite3 recovered.db

The docs explain the difference. Like .dump, .recover converts the database to a text script. But .dump reads through the normal SQL interface and stops at the first sign of corruption. .recover reassembles the database from data it extracts directly from as many database pages as possible, and is usually able to get everything from the undamaged parts.

Rows that it cannot attribute to a table end up in a table called lost_and_found, with the page number, the number of fields and the values in columns c0, c1 and so on. If you already have a table with that name, the docs say it uses lost_and_found0, then lost_and_found1. You can choose the name yourself:

sqlite3 broken.db ".recover --lost-and-found orphaned_rows" | sqlite3 recovered.db

A few habits I would keep. Work on a copy of the damaged file, never on the only one. Write into a new file, so the original stays as it is for another attempt. And use PRAGMA integrity_check on the result, since a recovered database is a best effort and not a guarantee.

The caveat is in the name: you get back as much as can be read, which can mean missing rows, and the lost_and_found rows need a human to decide what they belong to.

Further reading: SQLite: Command Line Shell For SQLite (Recover Data From a Corrupted Database)

More Database tips mariadb -e 'CREATE DATABASE IF NOT EXISTS blog' mariadb-dump --no-create-info --insert-ignore shop orders > orders-rows.sql SELECT table_schema, table_name, CHECKSUM TABLE shop.orders; services: All Database tips (53) All topics

Link