Watch at Ease看見世界,讀懂生活。

科技 · 實用指南

SQLite 顯示「database disk image is malformed」?recover 前先保全原件

將 SQLITE_CORRUPT 視為 preservation incident。停止 writers,連同 journal/WAL 保存 database,對 read-only copy 做 hash,只 recover 到新檔並驗證 constraints、totals 與 application behavior。

SQLite 顯示「database disk image is malformed」?recover 前先保全原件
原創技術示意圖: evidence and working-copy boundary. Watch at Ease

將 SQLITE_CORRUPT 視為 preservation incident。停止 writers,連同 journal/WAL 保存 database,對 read-only copy 做 hash,只 recover 到新檔並驗證 constraints、totals 與 application behavior。

import 成功只表示 SQL 可執行,不證明每個 recovered value 正確。

1. 停止變化並確認檔案

停止 application 與所有 writers,記錄 resolved path、SQLite library/CLI version、size、timestamp 與第一份完整 error;不要在唯一 copy 上跑 VACUUM、REINDEX 或寫入 pragma。

使用 rollback journal 或 WAL 時,保留相符的 -journal、-wal、-shm。分離 hot journal/WAL 會破壞 automatic recovery。

2. 建立 evidence 與 working copies

hash 原始檔案組並設 read-only,所有 recovery 只用獨立 working copy。普通 file copy 只有 writers 停止後才安全;live healthy DB 應用 backup API、VACUUM INTO 或 sqlite3_rsync。

保留 untouched evidence,記錄 command、tool version 與 output filename。partial success 不可覆蓋 original;疑似 storage failure 要先保留 device evidence。

3. 診斷 copy,不承諾 repair

在 working copy 執行 PRAGMA integrity_check 並保存所有 rows。它查 structure、missing/duplicate pages 與部分 constraints;foreign keys 要另跑 foreign_key_check。

其他 copy 的 ok 不代表 original 正常。確認實際開啟檔案,並比較 schema、page count 與 critical tables;I/O error 與 SQLITE_CORRUPT 分開記錄。

4. 先 restore backup,再 salvage

先測試 known-good backup。沒有足夠 backup 時,對 working copy 執行 .recover,將 SQL 寫到新檔再匯入另一個新 database,絕不覆蓋 original。

Recovery 是 salvage:deleted rows 可能復活、values 可能改變、constraints 可能失效、rows 可能進 lost_and_found。.recover 可能比 .dump 取回更多但不保證正確。

5. 回到 service 前驗證

對 recovered DB 跑 integrity_check、foreign_key_check,並核對 UNIQUE/CHECK、row counts、relationships、balances 與 critical totals;審查 lost_and_found。

只有 application test 通過才切換,並準備新 backup 與 rollback。保留 original evidence,記錄資料缺失並調查 unsafe copy、journal 分離、filesystem 或 rogue write。

SQLite 顯示「database disk image is malformed」?recover 前先保全原件
原創技術示意圖: recovered-file validation and return-to-service boundary. Watch at Ease