Most of us read INSERT OR REPLACE in SQLite as “upsert” (I did too, until recently), and this post is about what it does instead, and about a table in an iOS app I’m working on that was getting it wrong for a year without anybody noticing, mostly because nobody was looking at the table at all.
TLDR:
INSERT OR REPLACEdeletes the conflicting row and inserts a new one. With foreign keys on, that delete firesON DELETE CASCADEon every child table, and an FTS5 table gets a second row instead of an updated one. And before fixing a write path like that, check whether anything reads the table.
Where it came from
I was going through a third-party set of review checklists for Apple-platform code and comparing them with the rules this project already has, which is mostly boring work, since most of the rules overlap. One of them stood out, the one saying that INSERT OR REPLACE is not an upsert. A quick grep over the app’s search database (a GRDB “sidecar” that sits next to the Core Data store and holds rebuildable search data) found it on a collections table, which looked roughly like this:
CREATE TABLE collections (
id TEXT PRIMARY KEY,
name TEXT NOT NULL
-- sort order, icon, colour, timestamps...
);
CREATE TABLE collection_items (
id TEXT PRIMARY KEY,
collection_id TEXT NOT NULL,
book_id TEXT,
order_index INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY (collection_id) REFERENCES collections(id) ON DELETE CASCADE
);
CREATE VIRTUAL TABLE fts_collections USING fts5(
collection_id UNINDEXED,
name
);
The code that kept it in sync with Core Data wrote every rename or reorder of a collection like this:
INSERT OR REPLACE INTO collections (id, name, ...) VALUES (?, ?, ...);
INSERT OR REPLACE INTO fts_collections (collection_id, name) VALUES (?, ?);
What REPLACE does
The SQLite docs are clear about it once you read them. When a row would violate a UNIQUE or PRIMARY KEY constraint, REPLACE deletes the rows that cause the conflict and then inserts the new one, which makes it a delete and an insert, and a delete is something foreign keys react to. GRDB turns PRAGMA foreign_keys on by default (plain SQLite has it off), so in this app the cascade was live.
We can see it in the sqlite3 shell (I ran this on 3.51.0):
PRAGMA foreign_keys = ON;
CREATE TABLE collections (id TEXT PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE collection_items (
id TEXT PRIMARY KEY,
collection_id TEXT NOT NULL,
FOREIGN KEY (collection_id) REFERENCES collections(id) ON DELETE CASCADE
);
CREATE VIRTUAL TABLE fts_collections USING fts5(collection_id UNINDEXED, name);
INSERT OR REPLACE INTO collections VALUES ('c1', 'To read');
INSERT OR REPLACE INTO fts_collections VALUES ('c1', 'To read');
INSERT INTO collection_items VALUES ('i1', 'c1');
SELECT count(*) FROM collection_items; -- 1
-- rename the collection
INSERT OR REPLACE INTO collections VALUES ('c1', 'Reading next');
INSERT OR REPLACE INTO fts_collections VALUES ('c1', 'Reading next');
SELECT count(*) FROM collection_items; -- 0
SELECT count(*) FROM fts_collections WHERE collection_id = 'c1'; -- 2
Every rename or reorder of a collection wiped that collection’s items from the mirror, and every write left one more row in the full-text table. The FTS5 half is a different problem from the cascade, because the only key an FTS5 table has is its implicit rowid, and since the insert doesn’t give one, there’s never a conflict and OR REPLACE turns into a plain insert.
INSERT OR REPLACE is a delete followed by an insert. If you want to update the row in place, write INSERT ... ON CONFLICT(id) DO UPDATE SET ....
Continuing in the same shell, we put the item back and rename again with that version, and this time the child row stays:
INSERT INTO collection_items VALUES ('i1', 'c1');
INSERT INTO collections VALUES ('c1', 'Up next')
ON CONFLICT(id) DO UPDATE SET name = excluded.name;
SELECT count(*) FROM collection_items; -- still 1
An FTS5 table has no column we could use as a conflict target, so the usual way to update one is to delete by our own key and insert again:
DELETE FROM fts_collections WHERE collection_id = 'c1';
INSERT INTO fts_collections VALUES ('c1', 'Up next');
SELECT count(*) FROM fts_collections WHERE collection_id = 'c1'; -- 1
Funnily enough, another, newer FTS table in the same database already did exactly that.
Checking for readers first
My first plan was to rewrite the writes as ON CONFLICT DO UPDATE and the delete-then-insert for FTS, add a test, and move on. Before doing that I went looking for whatever read these tables, so I could check what the wrong data had broken, and couldn’t find anything. To make sure it wasn’t just the current code, I searched the whole history:
git log -S 'fts_collections' --oneline
git log -S 'collection_items' --oneline
git log -S lists the commits that changed the number of occurrences of a string, which catches the commit that first used a name and the one that last did (a commit that swaps one mention for another keeps the count the same and doesn’t show up, and -G with a regex is the stricter version). Reading through those showed writes, deletes, schema changes and a test, and no read anywhere in the app. The collections table and its FTS table came in with the first collections data layer, a year earlier, in a commit that announced an FTS5 table “for collection search”, and the items table joined them a few months later, and that search was never built. The app’s collections were always read from Core Data. The mirror was a write-only copy, with sync code, error handling and diagnostics around it, and it was wrong, and none of that mattered to anyone because nothing looked at it.
Instead of fixing the writes, I deleted the mirror, which meant the three tables, the sync code in the collections data layer, a cleanup step that only existed to keep the mirror in step, and the diagnostics for sync failures that could no longer happen. That came to about 740 lines removed, and the collections code got noticeably simpler, since it didn’t need the search database at all anymore.
The leftover tables still held user data
The second question was what to do about stores that already had those tables on disk. The sidecar has a schema version, and bumping it resets the sidecar, which drops its tables and builds the search index again (it also throws away a few things that can’t be rebuilt, which is fine only because the app hasn’t shipped yet). The project had a precedent for dropping an unread column without a bump, so my first take was to stop creating the tables and let them sit there until some unrelated bump cleaned them up.
The privacy review of the change pointed out what was still in them, though. The full-text table held every old name a collection had ever had, because of the duplicate rows, and the mirror could still hold collections the user had deleted, if the delete had never reached it, including protected ones that the app hides behind a passcode. With the code gone, nothing would ever update or remove those rows, so the user would think those names were gone while the app kept them. The version went up by one, and the reset’s list of tables to drop keeps the old names, which have to stay in that list for as long as a store from before the bump could still be opened. An old store loses the tables on its next launch, and nothing in the app can read or write them after that.
INSERT OR REPLACE and unread tables
It’s worth a grep for INSERT OR REPLACE in any codebase that has foreign keys turned on, since every hit on a parent table is a cascade waiting for the next update.
The bigger lesson for me was the order of checks. Before fixing how something writes, we should find out who reads it, and git log -S over the whole history is a quick way to do that for a table or a column. When the answer is “nobody” and the thing gets deleted, the next thing to look at is what it still holds on disk, because a table nobody reads can still be keeping data the user deleted, and leaving it there is a privacy problem even when it isn’t a bug.