kmp-room-database
Use when adding, configuring, upgrading or debugging Room in a Kotlin Multiplatform project — Room 3 (androidx.room3, room3 Gradle plugin, @ColumnTypeConverter, room3-paging), migrating from Room 2.8 (androidx.room) to Room 3, @Database, @Dao, @Entity in commonMain, RoomDatabaseC
Install
npx skills add https://github.com/Kushpawan/kmp-mobile-skills/tree/main/skills/kmp-room-database
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install kushpawan-kmp-mobile-skills@llmmart
git clone https://github.com/Kushpawan/kmp-mobile-skills.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole kushpawan/kmp-mobile-skills collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
Room in Kotlin Multiplatform
Room 3 (androidx.room3, stable since 3.0.0 on 1 Jul 2026) is the default for new KMP code; Room
2.8 (androidx.room) is what existing projects migrate from. Entities, DAOs and the @Database
class live in commonMain; only the file path is platform code. Most Room KMP failures compile
cleanly and crash at runtime on one platform — a missing KSP target, the wrong SQLite on the iOS
link line, a missing migration — so check the build wiring as carefully as the Kotlin.
When to use
- Adding Room to a KMP module, or adding entities, DAOs, converters or a migration.
- Moving a KMP project from Room 2.8 to Room 3.
Cannot find the associated ...RoomDatabaseConstructor(iOS),... _Impl does not exist(Android),SQLITE_MISUSE,Undefined symbols ... _sqlite3_...,Migration didn't properly handle,A migration from N to M was required but not found, or a DAOFlowthat stops emitting.
When not to use
- The project uses SQLDelight — follow SQLDelight (https://sqldelight.github.io/sqldelight/); do not add Room beside it. The iOS linking rules in references/ios-sqlite-linking.md still apply.
- Key-value settings — DataStore or multiplatform-settings.
- Tokens and secrets — kmp-secure-storage. Never store a token in a plain Room table.
- Repository, caching and sync design — kmp-data-layer.
Step 0 — Read the project first
grep -nE "room|sqlite|ksp|sqldelight" gradle/libs.versions.toml
grep -rnE "ksp(Android|Ios|Jvm|CommonMainMetadata)|room3? *\{|linkerOpts|lsqlite3" --include=*.gradle.kts .
grep -rnE "ios(Arm64|SimulatorArm64|X64)\(\)|jvm\(\)|androidTarget|androidLibrary" --include=*.gradle.kts .
grep -rnE "import androidx\.room3?\.|@Database|setDriver|TypeConverter" --include=*.kt . | head -40
| Finding | Then |
|---|---|
androidx.room3:*, plugin androidx.room3, room3 { } |
Room 3. Follow the workflow below. |
androidx.room:*, plugin androidx.room, room { } |
Room 2.x. Stay on it unless the user asks to upgrade — never as a side effect of another task. Room 2 names: references/migrating-from-room2.md §5; the upgrade itself: the rest of that file. |
| No Room, no SQLDelight | New database: Room 3. |
| SQLDelight | Stop; see When not to use. |
iosX64() declared |
Room 3 and androidx.sqlite 2.7+ publish no iosx64 artifacts (Google Maven index). Drop the target before using Room 3. |
Existing @Database |
Add to it. One database per app unless there is a reason. |
Workflow
1. Catalog and plugins
# gradle/libs.versions.toml — keep versions the catalog already pins
[versions]
room3 = "3.0.3" # latest stable on 3 Dec 2026; 3.1.0 is alpha
sqlite = "2.7.1"
ksp = "..." # a KSP release built for the project's Kotlin version
[libraries]
androidx-room3-runtime = { module = "androidx.room3:room3-runtime", version.ref = "room3" }
androidx-room3-compiler = { module = "androidx.room3:room3-compiler", version.ref = "room3" }
androidx-sqlite-bundled = { module = "androidx.sqlite:sqlite-bundled", version.ref = "sqlite" }
[plugins]
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
androidx-room3 = { id = "androidx.room3", version.ref = "room3" }
// shared/build.gradle.kts
plugins {
alias(libs.plugins.ksp)
alias(libs.plugins.androidx.room3)
}
kotlin {
// keep the project's existing target declarations
sourceSets.commonMain.dependencies {
implementation(libs.androidx.room3.runtime)
implementation(libs.androidx.sqlite.bundled)
}
}
room3 {
schemaDirectory("$projectDir/schemas") // required by the plugin; commit this directory
}
KSP only — Room 3 has no KAPT or Java annotation-processor path. The extension is room3 { }
(the plugin registers room3), although one snippet on Google's KMP setup page still shows room { }.
2. KSP for every target
// shared/build.gradle.kts — top-level dependencies block, one line per declared target
dependencies {
add("kspAndroid", libs.androidx.room3.compiler)
add("kspIosArm64", libs.androidx.room3.compiler)
add("kspIosSimulatorArm64", libs.androidx.room3.compiler)
// add("kspJvm", ...) for a jvm() target, and so on
}
A missing line compiles and then crashes on that platform the first time the database is built:
iOS throws Cannot find the associated RoomDatabaseConstructor, Android throws
Cannot find implementation for .... Do not add the compiler to kspCommonMainMetadata — the
generated actual objects belong to each platform compilation.
Done when every declared target has its line: compare grep -oE "(ios(Arm64|SimulatorArm64)|jvm)\(\)" shared/build.gradle.kts with grep -o "\"ksp[A-Za-z]*\"" shared/build.gradle.kts.
3. Entities, DAOs and converters — commonMain
// commonMain — notes/data/local/NoteEntity.kt (all Room imports come from androidx.room3.*)
@Entity(tableName = "notes")
data class NoteEntity(
@PrimaryKey val id: String,
val title: String,
val body: String,
@ColumnInfo(name = "updated_at") val updatedAtEpochMillis: Long,
@ColumnInfo(name = "is_pinned", defaultValue = "0") val isPinned: Boolean = false,
)
// commonMain — notes/data/local/NoteDao.kt
@Dao
abstract class NoteDao {
@Query("SELECT * FROM notes ORDER BY updated_at DESC")
abstract fun observeAll(): Flow<List<NoteEntity>>
@Upsert
abstract suspend fun upsertAll(notes: List<NoteEntity>)
@Query("DELETE FROM notes")
abstract suspend fun deleteAll()
@Transaction // one transaction: observers never see the empty table in between
open suspend fun replaceAll(notes: List<NoteEntity>) {
deleteAll()
upsertAll(notes)
}
}
- Every DAO function is
suspendor returnsFlow(or a type a registered DAO return type converter produces). Blocking DAO functions do not exist in Room 3. - Give every non-null column added later a
defaultValue, or the migration cannot fill old rows. - Entities are storage types; map them to domain models in the repository (kmp-data-layer).
- Custom column types:
@ColumnTypeConverterfunctions (renamed from@TypeConverterin 3.0.0-rc01), registered with@ColumnTypeConverters(...)on the@Database; runtime instances use@ProvidedColumnTypeConverter+builder.addColumnTypeConverter(...).
4. Database and constructor — commonMain
// commonMain — core/database/AppDatabase.kt
@Database(entities = [NoteEntity::class], version = 1, exportSchema = true)
@ConstructedBy(AppDatabaseConstructor::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun noteDao(): NoteDao
}
// Room's KSP processor generates the `actual` per target; the suppression silences the IDE warning.
@Suppress("KotlinNoActualForExpect")
expect object AppDatabaseConstructor : RoomDatabaseConstructor<AppDatabase> {
override fun initialize(): AppDatabase
}
internal const val DATABASE_NAME = "app.db"
5. Platform builders — the only platform code
// androidMain — core/database/DatabaseBuilder.android.kt
fun databaseBuilder(context: Context): RoomDatabase.Builder<AppDatabase> {
val appContext = context.applicationContext
return Room.databaseBuilder<AppDatabase>(appContext, appContext.getDatabasePath(DATABASE_NAME).absolutePath)
}
// iosMain — core/database/DatabaseBuilder.ios.kt
fun databaseBuilder(): RoomDatabase.Builder<AppDatabase> =
Room.databaseBuilder<AppDatabase>(name = documentDirectory() + "/$DATABASE_NAME")
@OptIn(ExperimentalForeignApi::class)
private fun documentDirectory(): String {
val url = NSFileManager.defaultManager.URLForDirectory(
directory = NSDocumentDirectory,
inDomain = NSUserDomainMask,
appropriateForURL = null,
create = false,
error = null,
)
return requireNotNull(url?.path) { "Documents directory unavailable" }
}
Never use the NSHomeDirectory() root (not writable), Library/Caches or tmp (purged by the OS).
NSApplicationSupportDirectory also works and stays out of the Files app; pass create = true for it.
6. Build once, in common code — the driver is mandatory
// commonMain — core/database/AppDatabaseFactory.kt
import androidx.sqlite.driver.bundled.BundledSQLiteDriver
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO // Dispatchers.IO is an extension outside the JVM
fun createAppDatabase(builder: RoomDatabase.Builder<AppDatabase>): AppDatabase =
builder
.setDriver(BundledSQLiteDriver()) // Room 3 cannot build without a SQLiteDriver
.setQueryCoroutineContext(Dispatchers.IO) // the default; set it to make the choice visible
.addMigrations(*AppMigrations.ALL)
.build()
Provide it as a singleton — one instance per database file per process. The invalidation
tracker only sees writes made through the same RoomDatabase instance, so a second instance makes
Flows miss changes. With Koin: bind databaseBuilder(...) per platform, then
single { createAppDatabase(get()) } and single { get<AppDatabase>().noteDao() } in common code
(kmp-koin-di).
Minified Android builds need -keep class * extends androidx.room3.RoomDatabase { <init>(); }.
7. iOS linking — keep the project's driver, then follow its rule
BundledSQLiteDriver(recommended): never add-lsqlite3— the driver ships its own SQLite, and the system library would put two providers of everysqlite3_*symbol on the link line.NativeSQLiteDriver(iosMainonly):-lsqlite3is required on every binary, tests included —binaries.all { linkerOpts("-lsqlite3") }— or the link fails withUndefined symbols ... _sqlite3_....
Observed: a large static iOS framework with the bundled driver plus -lsqlite3 shipped without
the bundled SQLite and crashed with SQLITE_MISUSE on iOS 26. Diagnosis, nm checks and where
-lsqlite3 sneaks in: references/ios-sqlite-linking.md.
8. Observing changes
- DAO
Flowqueries re-emit when a table they read changes. For anything else,database.invalidationTracker.createFlow("notes")emits the changed table names (passemitInitialState = falseto skip the first emission);InvalidationTracker.Observeris gone. - Paging: add
room3-pagingand register@DaoReturnTypeConverters(PagingSourceDaoReturnTypeConverter::class)on the@Dao(or@Database) before a DAO function may returnPagingSource.
9. Migrations — from the first release on
Once a build ships, every schema change bumps version and comes with a migration — for an added
column with a defaultValue, version = 2, autoMigrations = [AutoMigration(from = 1, to = 2)].
- Auto-migrations need the exported JSON for both versions in
schemas/— commit it. - Renames and deletions need an
AutoMigrationSpec(@RenameColumn,@DeleteColumn,@RenameTable,@DeleteTable); anything else gets a manualMigration, whosemigrateis asuspend funtaking aSQLiteConnectionin Room 3. fallbackToDestructiveMigration(dropAllTables = true)deletes user data. Use it only for a pure cache that can be refetched — never for a table holding unsynced writes.
Specs, manual migrations and migration tests: references/migrations-and-testing.md.
10. Transactions
| Scope | API (common code) |
|---|---|
| Inside one DAO | @Transaction open suspend fun in an abstract-class DAO (step 3) |
| Across DAOs, write | database.withWriteTransaction { noteDao.deleteAll(); tagDao.upsertAll(tags) } (IMMEDIATE) |
| Consistent multi-query read | database.withReadTransaction { ... } (DEFERRED) |
| Raw connection | database.useWriterConnection { it.immediateTransaction { ... } } / useReaderConnection { it.deferredTransaction { ... } } |
Room 2's runInTransaction / withTransaction do not exist in Room 3. Reader connections allow
only deferred transactions.
11. Tests
- Repository and ViewModel tests: fake the data source behind an interface — no database.
- DAO tests: a real in-memory database —
Room.inMemoryDatabaseBuilder<AppDatabase>() .setDriver(BundledSQLiteDriver()).build()(Room 3 builders need noContext) — run iniosTest, andjvmTestif there is ajvm()target. Close it in@AfterTest.
A @Database declared only in test sources needs its own KSP
test configuration (for example kspIosSimulatorArm64Test). DAO test template and
MigrationTestHelper for Android, JVM and iOS: references/migrations-and-testing.md.
Migrating from Room 2.8
Google's 3.0.0 notes: for a project already on Room KMP, migrating "mostly involves updating import references"; an Android-only Room project follows the Room KMP migration path first. Package, coordinates, plugin, converter annotations, driver, suspend migrations and DAO return type converters all change. Change table, order of work, and Room 2.8 setup for projects that stay: references/migrating-from-room2.md.
Quick reference
| Item | Rule |
|---|---|
| Coordinates | androidx.room3:room3-runtime, ksp androidx.room3:room3-compiler, androidx.sqlite:sqlite-bundled |
| Plugin | androidx.room3, room3 { schemaDirectory("$projectDir/schemas") }, committed |
| KSP | kspAndroid + one kspIos… per iOS target (+ kspJvm, …); never kspCommonMainMetadata; no KAPT |
| Driver | Mandatory. BundledSQLiteDriver; Dispatchers.IO with import kotlinx.coroutines.IO |
| DAO shape | suspend or Flow (or a registered DAO return type) |
| Converters | @ColumnTypeConverter + @ColumnTypeConverters; Paging via room3-paging converter |
| iOS linker | Bundled: no -lsqlite3. Native: -lsqlite3 on all binaries |
| Targets | No iosX64 artifacts in Room 3; watchosArm32 dropped in 3.1.0-alpha04 |
Verify
Report each as PASS, FAIL or NOT RUN (with the reason). A green compile is not evidence the
database opens on iOS — run the iOS tests or the app.
./gradlew :shared:tasks --all | grep -iE "^ksp" # one KSP task per target exists
./gradlew :shared:allTests # includes iosSimulatorArm64Test (DAO tests on Kotlin/Native)
./gradlew :shared:linkDebugFrameworkIosSimulatorArm64 # framework links (undefined _sqlite3_ symbols show here)
./gradlew :composeApp:assembleDebug # or the project's Android app module
find shared/schemas -name "*.json" | sort # one JSON per version, committed
grep -n "lsqlite3" shared/build.gradle.kts # must be empty with BundledSQLiteDriver
grep -rn "import androidx\.room\." --include=*.kt . # after a Room 3 migration: must be empty
Then open the database once on an iOS simulator or device (any screen that reads it). After a Room 2 to 3 migration, also install the last Room 2 build, create data, upgrade to the new build and confirm the data is still there.
Common mistakes
| Mistake | Why it bites | Fix |
|---|---|---|
| KSP line missing for one target | Compiles; crashes on first database access on that platform | One ksp<Target> per declared target |
Room compiler on kspCommonMainMetadata, or KAPT |
Misplaced generated code; Room 3 has no KAPT path | Platform KSP configurations only |
room { } with the androidx.room3 plugin |
Unknown extension; schemas not configured | room3 { schemaDirectory(...) } |
No setDriver(...) |
Room 3 cannot build a database without a SQLiteDriver |
setDriver(BundledSQLiteDriver()) |
Mixed androidx.room and androidx.room3 imports |
They are separate libraries (different package, group and artifacts); a half-moved database does not compile or misbehaves | Move every import in the module in one change |
@TypeConverter / @TypeConverters in Room 3 code |
Renamed in 3.0.0-rc01 | @ColumnTypeConverter / @ColumnTypeConverters |
DAO returns PagingSource with no converter registered |
Room 3 no longer special-cases Paging | room3-paging + @DaoReturnTypeConverters(PagingSourceDaoReturnTypeConverter::class) |
iosX64() kept while moving to Room 3 |
No iosx64 artifacts; dependency resolution fails |
Remove the target |
-lsqlite3 with BundledSQLiteDriver |
Two SQLite providers; observed: bundled copy dropped, SQLITE_MISUSE on iOS |
Remove it; verify with nm |
| Schema change without version bump or migration | Room cannot verify the data integrity or A migration from N to M was required but not found after an update |
Bump version, add an auto or manual migration |
Related skills
- kmp-data-layer — repositories, offline-first reads, write-through refresh.
- kmp-koin-di — providing the database and DAOs per platform.
- kmp-gradle-version-catalog — catalog entries and version bumps.
- kmp-secure-storage — secrets that must not live in Room; wiping tables on logout.
- kmp-xcframework-distribution — shipping the shared framework to iOS consumers.
- kmp-crash-triage — symbolicating an iOS crash that ends in SQLite.
- Room 3 release notes: https://developer.android.com/jetpack/androidx/releases/room3
- Room KMP setup and migration: https://developer.android.com/kotlin/multiplatform/room
- Room migrations: https://developer.android.com/training/data-storage/room/migrating-db-versions
Files (kmp-mobile-skills)
-
references
-
ios-sqlite-linking.md 6.3 KB
Loading… -
migrating-from-room2.md 9.4 KB
Loading… -
migrations-and-testing.md 9.9 KB
Loading…
-
-
SKILL.md 18.1 KB
--- name: kmp-room-database description: Use when adding, configuring, upgrading or debugging Room in a Kotlin Multiplatform project — Room 3 (androidx.room3, room3 Gradle plugin, @ColumnTypeConverter, room3-paging), migrating from Room 2.8 (androidx.room) to Room 3, @Database, @Dao, @Entity in commonMain, RoomDatabaseConstructor, BundledSQLiteDriver, KSP per target, schema export, migrations — or on "Cannot find the associated RoomDatabaseConstructor", "_Impl does not exist", SQLITE_MISUSE or undefined _sqlite3_ symbols on iOS, a migration crash after an app update, or Flows that stop updating. license: Apache-2.0 compatibility: Kotlin Multiplatform project (Android + iOS) with Room 3.x (androidx.room3) or Room 2.7/2.8 (androidx.room) and KSP. iOS steps need macOS with Xcode. metadata: category: data platforms: android, ios --- # Room in Kotlin Multiplatform Room 3 (`androidx.room3`, stable since 3.0.0 on 1 Jul 2026) is the default for new KMP code; Room 2.8 (`androidx.room`) is what existing projects migrate from. Entities, DAOs and the `@Database` class live in `commonMain`; only the file path is platform code. Most Room KMP failures compile cleanly and crash at runtime on one platform — a missing KSP target, the wrong SQLite on the iOS link line, a missing migration — so check the build wiring as carefully as the Kotlin. ## When to use - Adding Room to a KMP module, or adding entities, DAOs, converters or a migration. - Moving a KMP project from Room 2.8 to Room 3. - `Cannot find the associated ...RoomDatabaseConstructor` (iOS), `... _Impl does not exist` (Android), `SQLITE_MISUSE`, `Undefined symbols ... _sqlite3_...`, `Migration didn't properly handle`, `A migration from N to M was required but not found`, or a DAO `Flow` that stops emitting. ## When not to use - The project uses **SQLDelight** — follow SQLDelight (<https://sqldelight.github.io/sqldelight/>); do not add Room beside it. The iOS linking rules in [references/ios-sqlite-linking.md](references/ios-sqlite-linking.md) still apply. - Key-value settings — DataStore or multiplatform-settings. - Tokens and secrets — **kmp-secure-storage**. Never store a token in a plain Room table. - Repository, caching and sync design — **kmp-data-layer**. ## Step 0 — Read the project first ```bash grep -nE "room|sqlite|ksp|sqldelight" gradle/libs.versions.toml grep -rnE "ksp(Android|Ios|Jvm|CommonMainMetadata)|room3? *\{|linkerOpts|lsqlite3" --include=*.gradle.kts . grep -rnE "ios(Arm64|SimulatorArm64|X64)\(\)|jvm\(\)|androidTarget|androidLibrary" --include=*.gradle.kts . grep -rnE "import androidx\.room3?\.|@Database|setDriver|TypeConverter" --include=*.kt . | head -40 ``` | Finding | Then | |---|---| | `androidx.room3:*`, plugin `androidx.room3`, `room3 { }` | Room 3. Follow the workflow below. | | `androidx.room:*`, plugin `androidx.room`, `room { }` | Room 2.x. **Stay on it** unless the user asks to upgrade — never as a side effect of another task. Room 2 names: [references/migrating-from-room2.md](references/migrating-from-room2.md) §5; the upgrade itself: the rest of that file. | | No Room, no SQLDelight | New database: Room 3. | | SQLDelight | Stop; see **When not to use**. | | `iosX64()` declared | Room 3 and `androidx.sqlite` 2.7+ publish no `iosx64` artifacts (Google Maven index). Drop the target before using Room 3. | | Existing `@Database` | Add to it. One database per app unless there is a reason. | ## Workflow ### 1. Catalog and plugins ```toml # gradle/libs.versions.toml — keep versions the catalog already pins [versions] room3 = "3.0.3" # latest stable on 3 Dec 2026; 3.1.0 is alpha sqlite = "2.7.1" ksp = "..." # a KSP release built for the project's Kotlin version [libraries] androidx-room3-runtime = { module = "androidx.room3:room3-runtime", version.ref = "room3" } androidx-room3-compiler = { module = "androidx.room3:room3-compiler", version.ref = "room3" } androidx-sqlite-bundled = { module = "androidx.sqlite:sqlite-bundled", version.ref = "sqlite" } [plugins] ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } androidx-room3 = { id = "androidx.room3", version.ref = "room3" } ``` ```kotlin // shared/build.gradle.kts plugins { alias(libs.plugins.ksp) alias(libs.plugins.androidx.room3) } kotlin { // keep the project's existing target declarations sourceSets.commonMain.dependencies { implementation(libs.androidx.room3.runtime) implementation(libs.androidx.sqlite.bundled) } } room3 { schemaDirectory("$projectDir/schemas") // required by the plugin; commit this directory } ``` KSP only — Room 3 has no KAPT or Java annotation-processor path. The extension is `room3 { }` (the plugin registers `room3`), although one snippet on Google's KMP setup page still shows `room { }`. ### 2. KSP for every target ```kotlin // shared/build.gradle.kts — top-level dependencies block, one line per declared target dependencies { add("kspAndroid", libs.androidx.room3.compiler) add("kspIosArm64", libs.androidx.room3.compiler) add("kspIosSimulatorArm64", libs.androidx.room3.compiler) // add("kspJvm", ...) for a jvm() target, and so on } ``` **A missing line compiles and then crashes on that platform** the first time the database is built: iOS throws `Cannot find the associated RoomDatabaseConstructor`, Android throws `Cannot find implementation for ...`. Do not add the compiler to `kspCommonMainMetadata` — the generated `actual` objects belong to each platform compilation. Done when every declared target has its line: compare `grep -oE "(ios(Arm64|SimulatorArm64)|jvm)\(\)" shared/build.gradle.kts` with `grep -o "\"ksp[A-Za-z]*\"" shared/build.gradle.kts`. ### 3. Entities, DAOs and converters — `commonMain` ```kotlin // commonMain — notes/data/local/NoteEntity.kt (all Room imports come from androidx.room3.*) @Entity(tableName = "notes") data class NoteEntity( @PrimaryKey val id: String, val title: String, val body: String, @ColumnInfo(name = "updated_at") val updatedAtEpochMillis: Long, @ColumnInfo(name = "is_pinned", defaultValue = "0") val isPinned: Boolean = false, ) // commonMain — notes/data/local/NoteDao.kt @Dao abstract class NoteDao { @Query("SELECT * FROM notes ORDER BY updated_at DESC") abstract fun observeAll(): Flow<List<NoteEntity>> @Upsert abstract suspend fun upsertAll(notes: List<NoteEntity>) @Query("DELETE FROM notes") abstract suspend fun deleteAll() @Transaction // one transaction: observers never see the empty table in between open suspend fun replaceAll(notes: List<NoteEntity>) { deleteAll() upsertAll(notes) } } ``` - Every DAO function is `suspend` or returns `Flow` (or a type a registered DAO return type converter produces). Blocking DAO functions do not exist in Room 3. - Give every non-null column added later a `defaultValue`, or the migration cannot fill old rows. - Entities are storage types; map them to domain models in the repository (**kmp-data-layer**). - Custom column types: `@ColumnTypeConverter` functions (renamed from `@TypeConverter` in 3.0.0-rc01), registered with `@ColumnTypeConverters(...)` on the `@Database`; runtime instances use `@ProvidedColumnTypeConverter` + `builder.addColumnTypeConverter(...)`. ### 4. Database and constructor — `commonMain` ```kotlin // commonMain — core/database/AppDatabase.kt @Database(entities = [NoteEntity::class], version = 1, exportSchema = true) @ConstructedBy(AppDatabaseConstructor::class) abstract class AppDatabase : RoomDatabase() { abstract fun noteDao(): NoteDao } // Room's KSP processor generates the `actual` per target; the suppression silences the IDE warning. @Suppress("KotlinNoActualForExpect") expect object AppDatabaseConstructor : RoomDatabaseConstructor<AppDatabase> { override fun initialize(): AppDatabase } internal const val DATABASE_NAME = "app.db" ``` ### 5. Platform builders — the only platform code ```kotlin // androidMain — core/database/DatabaseBuilder.android.kt fun databaseBuilder(context: Context): RoomDatabase.Builder<AppDatabase> { val appContext = context.applicationContext return Room.databaseBuilder<AppDatabase>(appContext, appContext.getDatabasePath(DATABASE_NAME).absolutePath) } // iosMain — core/database/DatabaseBuilder.ios.kt fun databaseBuilder(): RoomDatabase.Builder<AppDatabase> = Room.databaseBuilder<AppDatabase>(name = documentDirectory() + "/$DATABASE_NAME") @OptIn(ExperimentalForeignApi::class) private fun documentDirectory(): String { val url = NSFileManager.defaultManager.URLForDirectory( directory = NSDocumentDirectory, inDomain = NSUserDomainMask, appropriateForURL = null, create = false, error = null, ) return requireNotNull(url?.path) { "Documents directory unavailable" } } ``` Never use the `NSHomeDirectory()` root (not writable), `Library/Caches` or `tmp` (purged by the OS). `NSApplicationSupportDirectory` also works and stays out of the Files app; pass `create = true` for it. ### 6. Build once, in common code — the driver is mandatory ```kotlin // commonMain — core/database/AppDatabaseFactory.kt import androidx.sqlite.driver.bundled.BundledSQLiteDriver import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO // Dispatchers.IO is an extension outside the JVM fun createAppDatabase(builder: RoomDatabase.Builder<AppDatabase>): AppDatabase = builder .setDriver(BundledSQLiteDriver()) // Room 3 cannot build without a SQLiteDriver .setQueryCoroutineContext(Dispatchers.IO) // the default; set it to make the choice visible .addMigrations(*AppMigrations.ALL) .build() ``` Provide it as a singleton — **one instance per database file per process**. The invalidation tracker only sees writes made through the same `RoomDatabase` instance, so a second instance makes `Flow`s miss changes. With Koin: bind `databaseBuilder(...)` per platform, then `single { createAppDatabase(get()) }` and `single { get<AppDatabase>().noteDao() }` in common code (**kmp-koin-di**). Minified Android builds need `-keep class * extends androidx.room3.RoomDatabase { <init>(); }`. ### 7. iOS linking — keep the project's driver, then follow its rule - `BundledSQLiteDriver` (recommended): **never add `-lsqlite3`** — the driver ships its own SQLite, and the system library would put two providers of every `sqlite3_*` symbol on the link line. - `NativeSQLiteDriver` (`iosMain` only): `-lsqlite3` is **required** on every binary, tests included — `binaries.all { linkerOpts("-lsqlite3") }` — or the link fails with `Undefined symbols ... _sqlite3_...`. Observed: a large static iOS framework with the bundled driver plus `-lsqlite3` shipped without the bundled SQLite and crashed with `SQLITE_MISUSE` on iOS 26. Diagnosis, `nm` checks and where `-lsqlite3` sneaks in: [references/ios-sqlite-linking.md](references/ios-sqlite-linking.md). ### 8. Observing changes - DAO `Flow` queries re-emit when a table they read changes. For anything else, `database.invalidationTracker.createFlow("notes")` emits the changed table names (pass `emitInitialState = false` to skip the first emission); `InvalidationTracker.Observer` is gone. - Paging: add `room3-paging` and register `@DaoReturnTypeConverters(PagingSourceDaoReturnTypeConverter::class)` on the `@Dao` (or `@Database`) before a DAO function may return `PagingSource`. ### 9. Migrations — from the first release on Once a build ships, every schema change bumps `version` and comes with a migration — for an added column with a `defaultValue`, `version = 2, autoMigrations = [AutoMigration(from = 1, to = 2)]`. - Auto-migrations need the exported JSON for **both** versions in `schemas/` — commit it. - Renames and deletions need an `AutoMigrationSpec` (`@RenameColumn`, `@DeleteColumn`, `@RenameTable`, `@DeleteTable`); anything else gets a manual `Migration`, whose `migrate` is a `suspend fun` taking a `SQLiteConnection` in Room 3. - `fallbackToDestructiveMigration(dropAllTables = true)` deletes user data. Use it only for a pure cache that can be refetched — never for a table holding unsynced writes. Specs, manual migrations and migration tests: [references/migrations-and-testing.md](references/migrations-and-testing.md). ### 10. Transactions | Scope | API (common code) | |---|---| | Inside one DAO | `@Transaction open suspend fun` in an abstract-class DAO (step 3) | | Across DAOs, write | `database.withWriteTransaction { noteDao.deleteAll(); tagDao.upsertAll(tags) }` (IMMEDIATE) | | Consistent multi-query read | `database.withReadTransaction { ... }` (DEFERRED) | | Raw connection | `database.useWriterConnection { it.immediateTransaction { ... } }` / `useReaderConnection { it.deferredTransaction { ... } }` | Room 2's `runInTransaction` / `withTransaction` do not exist in Room 3. Reader connections allow only deferred transactions. ### 11. Tests - **Repository and ViewModel tests:** fake the data source behind an interface — no database. - **DAO tests:** a real in-memory database — `Room.inMemoryDatabaseBuilder<AppDatabase>() .setDriver(BundledSQLiteDriver()).build()` (Room 3 builders need no `Context`) — run in `iosTest`, and `jvmTest` if there is a `jvm()` target. Close it in `@AfterTest`. A `@Database` declared only in test sources needs its own KSP test configuration (for example `kspIosSimulatorArm64Test`). DAO test template and `MigrationTestHelper` for Android, JVM and iOS: [references/migrations-and-testing.md](references/migrations-and-testing.md). ## Migrating from Room 2.8 Google's 3.0.0 notes: for a project already on Room KMP, migrating "mostly involves updating import references"; an Android-only Room project follows the Room KMP migration path first. Package, coordinates, plugin, converter annotations, driver, suspend migrations and DAO return type converters all change. Change table, order of work, and Room 2.8 setup for projects that stay: [references/migrating-from-room2.md](references/migrating-from-room2.md). ## Quick reference | Item | Rule | |---|---| | Coordinates | `androidx.room3:room3-runtime`, `ksp` `androidx.room3:room3-compiler`, `androidx.sqlite:sqlite-bundled` | | Plugin | `androidx.room3`, `room3 { schemaDirectory("$projectDir/schemas") }`, committed | | KSP | `kspAndroid` + one `kspIos…` per iOS target (+ `kspJvm`, …); never `kspCommonMainMetadata`; no KAPT | | Driver | Mandatory. `BundledSQLiteDriver`; `Dispatchers.IO` with `import kotlinx.coroutines.IO` | | DAO shape | `suspend` or `Flow` (or a registered DAO return type) | | Converters | `@ColumnTypeConverter` + `@ColumnTypeConverters`; Paging via `room3-paging` converter | | iOS linker | Bundled: no `-lsqlite3`. Native: `-lsqlite3` on all binaries | | Targets | No `iosX64` artifacts in Room 3; `watchosArm32` dropped in 3.1.0-alpha04 | ## Verify Report each as `PASS`, `FAIL` or `NOT RUN` (with the reason). A green compile is not evidence the database opens on iOS — run the iOS tests or the app. ```bash ./gradlew :shared:tasks --all | grep -iE "^ksp" # one KSP task per target exists ./gradlew :shared:allTests # includes iosSimulatorArm64Test (DAO tests on Kotlin/Native) ./gradlew :shared:linkDebugFrameworkIosSimulatorArm64 # framework links (undefined _sqlite3_ symbols show here) ./gradlew :composeApp:assembleDebug # or the project's Android app module find shared/schemas -name "*.json" | sort # one JSON per version, committed grep -n "lsqlite3" shared/build.gradle.kts # must be empty with BundledSQLiteDriver grep -rn "import androidx\.room\." --include=*.kt . # after a Room 3 migration: must be empty ``` Then open the database once on an iOS simulator or device (any screen that reads it). After a Room 2 to 3 migration, also install the last Room 2 build, create data, upgrade to the new build and confirm the data is still there. ## Common mistakes | Mistake | Why it bites | Fix | |---|---|---| | KSP line missing for one target | Compiles; crashes on first database access on that platform | One `ksp<Target>` per declared target | | Room compiler on `kspCommonMainMetadata`, or KAPT | Misplaced generated code; Room 3 has no KAPT path | Platform KSP configurations only | | `room { }` with the `androidx.room3` plugin | Unknown extension; schemas not configured | `room3 { schemaDirectory(...) }` | | No `setDriver(...)` | Room 3 cannot build a database without a `SQLiteDriver` | `setDriver(BundledSQLiteDriver())` | | Mixed `androidx.room` and `androidx.room3` imports | They are separate libraries (different package, group and artifacts); a half-moved database does not compile or misbehaves | Move every import in the module in one change | | `@TypeConverter` / `@TypeConverters` in Room 3 code | Renamed in 3.0.0-rc01 | `@ColumnTypeConverter` / `@ColumnTypeConverters` | | DAO returns `PagingSource` with no converter registered | Room 3 no longer special-cases Paging | `room3-paging` + `@DaoReturnTypeConverters(PagingSourceDaoReturnTypeConverter::class)` | | `iosX64()` kept while moving to Room 3 | No `iosx64` artifacts; dependency resolution fails | Remove the target | | `-lsqlite3` with `BundledSQLiteDriver` | Two SQLite providers; observed: bundled copy dropped, `SQLITE_MISUSE` on iOS | Remove it; verify with `nm` | | Schema change without version bump or migration | `Room cannot verify the data integrity` or `A migration from N to M was required but not found` after an update | Bump `version`, add an auto or manual migration | ## Related skills - **kmp-data-layer** — repositories, offline-first reads, write-through refresh. - **kmp-koin-di** — providing the database and DAOs per platform. - **kmp-gradle-version-catalog** — catalog entries and version bumps. - **kmp-secure-storage** — secrets that must not live in Room; wiping tables on logout. - **kmp-xcframework-distribution** — shipping the shared framework to iOS consumers. - **kmp-crash-triage** — symbolicating an iOS crash that ends in SQLite. - Room 3 release notes: <https://developer.android.com/jetpack/androidx/releases/room3> - Room KMP setup and migration: <https://developer.android.com/kotlin/multiplatform/room> - Room migrations: <https://developer.android.com/training/data-storage/room/migrating-db-versions>
Reviews (0)
No reviews yet.
Comments
Sign in to join the conversation.
No comments yet. Start the conversation.