This one is a note about SQLite in WAL mode, and about a recovery path I wrote for a small on-device store in an iOS app I’m working on, which looked fine in review and still managed to lose a committed transaction in a test.
The setup
The app keeps a few settings in a SQLite database opened through GRDB, in WAL mode, which means that on disk the database is three files and not one:
store/
store.sqlite # the database itself
store.sqlite-wal # committed transactions not yet copied into the database
store.sqlite-shm # shared-memory index for the WAL
When the app opens the store and finds something it can’t trust (it was written by a different install, or it’s corrupt), it doesn’t delete anything. It moves the files into a fresh quarantine folder, so that the user can still recover them later, and starts over with an empty store.
The first version of that move did what you’d probably write without thinking about it too much, one rename per file, database first:
try fileManager.createDirectory(at: quarantine, withIntermediateDirectories: false)
for url in [databaseURL, walURL, shmURL] where fileManager.fileExists(atPath: url.path) {
try fileManager.moveItem(at: url, to: quarantine.appendingPathComponent(url.lastPathComponent))
}
If the app dies, or a move fails, between the first rename and the last, the database is in quarantine and its -wal (and maybe -shm) are still sitting in the live folder with nothing beside them. My first guess was that SQLite would pick up that orphan WAL and replay it into the new empty database, which would be bad, but at least the data would still exist somewhere, and it turned out to be the other way around.
What SQLite does with a WAL that has no database
The first time a connection reads a database, the pager checks for a -wal file next to it. This is pagerOpenWalIfPresent in src/pager.c, trimmed a bit:
if( isWal ){
Pgno nPage; /* Size of the database file */
rc = pagerPagecount(pPager, &nPage);
if( rc ) return rc;
if( nPage==0 ){
rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
}else{
rc = sqlite3PagerOpenWal(pPager, 0);
}
}
So if the database file is empty (zero pages), and a database that SQLite has just created because the file wasn’t there is exactly that, the WAL beside it gets deleted. It isn’t replayed and there’s no error, so the next launch goes on with a new empty store, and the WAL that held the newest commit of the quarantined database is gone. The quarantined database alone doesn’t have that commit, because it was never checkpointed into it, so the commit now exists nowhere.
To be fair to SQLite, the WAL documentation says it plainly, the WAL “should be kept with the database if the database is copied or moved”, and it warns that separating them can lose committed transactions. I just hadn’t thought of a three-step move as “separating them” until a test showed it.
Reproducing it in a test
Getting a test into that state needs a bit of care, because SQLite works hard to not leave a WAL lying around. Closing the last connection checkpoints the WAL into the database and deletes it, and an automatic checkpoint, once the WAL grows past 1000 pages, would copy it into the database too (it reuses the file rather than deleting it). So in the test fixture, and only there, we turn the autocheckpoint off, write something, and copy the three files while the pool is still open:
var configuration = Configuration()
configuration.prepareDatabase { db in
try db.execute(sql: "PRAGMA wal_autocheckpoint = 0") // test fixture only
}
let pool = try DatabasePool(path: databaseURL.path, configuration: configuration)
try pool.write { db in
try db.execute(sql: "CREATE TABLE probe(x INTEGER); INSERT INTO probe VALUES (1)")
}
// Copy store.sqlite, -wal and -shm aside here, before close() checkpoints and deletes the WAL
try pool.close()
// ...then replace the live files with the copies, which is what an app kill leaves on disk
Now the database file on its own doesn’t have the probe table, and the database together with its WAL does, which gives us a check for “is the commit still somewhere”. The check has to run on copies (the database and the WAL copied into a scratch folder under matching names), because opening the staged files in place and closing them again checkpoints the WAL and deletes it, and then there’s nothing left to lose. With a file-manager fake that fails the sidecar moves, the test showed the database in quarantine, the WAL stranded in the live folder, and the next open deleting that WAL.
Checking for sidecars without a database
The first fix taught the store to look before opening. If the live folder has a -wal or -shm but no database, that’s not a fresh store, so instead of opening SQLite beside them it quarantines them as well. That keeps every byte, but (as review pointed out) in two different quarantine folders, the database in one and its WAL in another with nothing pairing them, so restoring the first folder later would lose the same commit.
The order of that presence check matters, and it’s easy to get backwards. A normal relaunch after the app was killed finds a database with a hot WAL and SHM next to it, which is a perfectly healthy store, so we have to check for the database first and only treat sidecars as orphans when it isn’t there:
enum StorePresence { case present, orphanedSidecars, absent }
func storePresence() -> StorePresence {
if fileManager.fileExists(atPath: databaseURL.path) { return .present }
if fileManager.fileExists(atPath: walURL.path) || fileManager.fileExists(atPath: shmURL.path) {
return .orphanedSidecars
}
return .absent
}
Swap those first two checks and every launch after an app kill would quarantine an intact store.
One rename instead of three
Since the store’s folder holds those three files and nothing else (which is the thing that makes this work, so if your database shares a folder, give it one of its own first), we don’t have to move the files at all, we can rename the folder:
func moveStoreAside(to quarantine: URL) throws {
guard !fileManager.fileExists(atPath: quarantine.path) else {
throw StoreFileError.destinationExists
}
try fileManager.moveItem(at: storeDirectory, to: quarantine)
}
The quarantine folder is a sibling of the store folder with a unique name (we use a UUID in it, because with a fixed name the second quarantine would hit the guard forever), and since it’s on the same volume, moveItem does a single rename, which either happens or it doesn’t. Across volumes moveItem falls back to copying and deleting without telling you, and that can split the files again, so the sibling part matters. After a successful rename the triple is all in quarantine, and the next open finds no store folder and creates a new one, which SQLite won’t do for us, so it has to go through the same code that created the folder the first time, file protection and backup exclusion included. If the rename fails, nothing has moved and there’s no empty quarantine folder left behind, the untrusted store is still where it was, and the next open tries the quarantine again. The presence check stays, but now only for a WAL without a database that something outside the store caused, since the store itself can no longer produce one.
The test for it is the same staging as before, with the sidecar moves still made to fail, and the assertion turned around, the WAL in quarantine is byte for byte the one that was live, and the quarantined database together with that WAL still has probe. Putting the per-file loop back makes it fail, but only because of that injected failure, since when all three moves succeed the loop keeps the commit too.
One more thing to watch for is a connection that is still open when the folder moves, and the likeliest one is the connection we just used to decide the store can’t be trusted. When it closes, SQLite checkpoints into the moved files and then deletes the
-waland-shmby their old path, which by then can belong to the new store, and the new store’s newest commits go with them. Close the pool, and make sure nothing can reopen it, before moving the folder.
Summary
A WAL-mode SQLite database is the database file plus its -wal and -shm, and anything that moves it has to treat the three as one thing (and anything that copies or backs it up has to either close every connection first or use SQLite’s backup API or VACUUM INTO, since copying files that are still being written can tear). If they get separated and SQLite then opens an empty database where the old one was, it deletes the orphan WAL without an error, and every transaction that hadn’t been checkpointed goes with it. When we need to move a database aside, keeping it alone in its own folder and renaming that folder to a unique sibling is simpler and safer than any careful order of file moves, and the test for it should make one of the moves fail and then check that the commit still exists, not only that the files ended up somewhere.