Room database pitfalls on Android
androidroomsqliteftsmigrationskotlin
Room (Jetpack's SQLite layer) is pleasant until it silently does something destructive. These are the traps hit while building the Message SMS app, with the rule each one taught.
Upsert replaces the whole row
@Upsert (and REPLACE inserts) write every column, so any local-only flag with a default value is reset. Check for an existing row and run a targeted UPDATE of the synced columns instead. See Syncing an SMS app with the Android telephony provider.
Destructive migration fallback
fallbackToDestructiveMigration() wipes the database whenever an upgrade migration is missing, which deletes everything that exists only locally (stars, drafts, scheduled messages). Use fallbackToDestructiveMigrationOnDowngrade() only: a missing upgrade migration then crashes loudly instead of erasing data. Consequence: never drop a column in a hotfix build that has to open files created by a newer schema, since that is a downgrade and gets wiped.
PRAGMA user_version is the schema version
Room's open helper decides between onCreate and onUpgrade from user_version. A file with real tables but user_version = 0 goes to onCreate, whose CREATE TABLE IF NOT EXISTS does nothing, and then schema validation throws IllegalStateException: Pre-packaged database has an invalid schema. Any tool that copies a database (for example sqlcipher_export) must carry user_version across. See SQLCipher on Android (keys, KDF cost, rekeying safely).
Kotlin soft keywords break code generation
A DAO parameter named private is legal Kotlin but Room's KSP generates Java from it, producing about 100 compile errors in the generated _Impl. Name it isPrivate.
FTS
- Manual FTS sync triggers conflicted with the ones Room generates for
@Fts4entities; drop the manual ones in a migration. - An empty or whitespace
MATCHquery is a SQLite error; guard it, sanitize input, and add*for prefix matching. - A
LIKEsearch where FTS exists is both slow and an injection surface; escape%and_if you must use it.
Concurrency patterns that work
- Atomic claim:
UPDATE ... SET status = SENDING WHERE id = ? AND status = PENDINGand check the affected row count. - Monotonic status:
SET status = MAX(status, :new). - Do the row change and the recount in one
@Transaction.
Paging
Wiring Paging 3 to an old, unused query found two latent bugs: a missing isDeleted = 0 filter (trash reappeared) and no id tie-breaker in the ORDER BY, so rows with equal timestamps shuffled between pages.
Migration testing
Export schemas (room.schemaLocation) and test each migration against the exported JSON with MigrationTestHelper. Run only the debug unit-test variant; the release variant may lack the schema assets and report false failures.
See also
- SQLCipher on Android (keys, KDF cost, rekeying safely)
- Syncing an SMS app with the Android telephony provider