📚 Encyclopedia

Databases · updated 2026-10-13

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

Concurrency patterns that work

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

Linked from

Sources: message memory (project_bugs_fixed, project_pending_work, startup_perf_2026_09)