sqlitesystem.data.sqlite

How to simulate a corrupt SQLite database


Part of the startup routine in my application validates its SQLite databases by using the PRAGMA integrity_check; API. I'm looking for a way to legitimately corrupt an SQLite database so that this "integrity check" will fail.

I've tried messing with the database file in a text editor, but this causes a type of corruption that is caught when opening the database, much earlier than my call to "integrity check".

Any ideas?


Solution

  • PRAGMA writable_schema allows you to change the database schema behind SQLite's back, and thus to violate constraints:

    $ sqlite3 test.db
    > CREATE TABLE t(x);
    > CREATE INDEX tx ON t(x);
    > INSERT INTO t VALUES (1), (1);
    > .dbconfig defensive off
    > PRAGMA writable_schema = 1;
    > UPDATE sqlite_master
    >   SET sql = 'CREATE UNIQUE INDEX tx ON t(x)'
    >   WHERE type = 'index' AND name = 'tx';
    > PRAGMA writable_schema = reset;
    > PRAGMA integrity_check;
    non-unique entry in index tx