為 KMP 設定 Room 資料庫

Room 永久保存程式庫透過 SQLite 提供抽象層,可提升資料庫存取的穩固性,並同時充分利用 SQLite 的強大功能。本頁面著重說明如何在 Kotlin Multiplatform (KMP) 專案中使用 Room。如要進一步瞭解如何使用 Room,請參閱「使用 Room 將資料儲存在本機資料庫」或官方範例。

設定依附元件

如要在 KMP 專案中設定 Room,請在 KMP 模組的 build.gradle.kts 檔案中,新增構件的依附元件。

在 libs.versions.toml 檔案中定義依附元件:

[versions]
room3 = "3.1.0-alpha03"
sqlite = "2.7.1"
ksp = "<kotlinCompatibleKspVersion>"

[libraries]
androidx-sqlite-bundled = { module = "androidx.sqlite:sqlite-bundled", version.ref = "sqlite" }
androidx-room3-runtime = { module = "androidx.room3:room3-runtime", version.ref = "room3" }
androidx-room3-compiler = { module = "androidx.room3:room3-compiler", version.ref = "room3" }

# Optional SQLite Wrapper
androidx-room3-sqlite-wrapper = { module = "androidx.room3:room3-sqlite-wrapper", version.ref = "room3" }

[plugins]
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
androidx-room3 = { id = "androidx.room3", version.ref = "room3" }

新增 Room Gradle 外掛程式,設定 Room 結構定義和 KSP 外掛程式。

plugins {
  alias(libs.plugins.ksp)
  alias(libs.plugins.androidx.room3)
}

新增 Room 執行階段依附元件和隨附的 SQLite 程式庫:

commonMain.dependencies {
  implementation(libs.androidx.room3.runtime)
  implementation(libs.androidx.sqlite.bundled)
}

// Optional when using Room SQLite Wrapper
androidMain.dependencies {
  implementation(libs.androidx.room3.sqlite.wrapper)
}

將 KSP 依附元件新增至根 dependencies 區塊。您必須新增應用程式使用的所有目標。詳情請參閱「搭配使用 KSP 與 Kotlin Multiplatform」。

dependencies {
    add("kspAndroid", libs.androidx.room3.compiler)
    add("kspIosSimulatorArm64", libs.androidx.room3.compiler)
    add("kspIosX64", libs.androidx.room3.compiler)
    add("kspIosArm64", libs.androidx.room3.compiler)
    // Add any other platform target you use in your project, for example kspDesktop
}

定義 Room 結構定義目錄。詳情請參閱「使用 Room Gradle 外掛程式設定結構定義位置」。

room {
    schemaDirectory("$projectDir/schemas")
}

定義資料庫類別

您需要建立一個資料庫類別,並在共用 KMP 模組的通用來源集中,加上 @Database 註解,以及 DAO 和實體。將這些類別放在通用來源中,即可在所有目標平台共用。

// shared/src/commonMain/kotlin/Database.kt

@Database(entities = [TodoEntity::class], version = 1)
@ConstructedBy(AppDatabaseConstructor::class)
abstract class AppDatabase : RoomDatabase() {
    abstract fun getDao(): TodoDao
}

// The Room compiler generates the `actual` implementations.
@Suppress("KotlinNoActualForExpect")
expect object AppDatabaseConstructor : RoomDatabaseConstructor<AppDatabase> {
    override fun initialize(): AppDatabase
}

使用 RoomDatabaseConstructor 介面宣告 expect 物件時,Room 編譯器會產生 actual 實作。Android Studio 可能會發出下列警告,您可以使用 @Suppress("KotlinNoActualForExpect") 隱藏:

Expected object 'AppDatabaseConstructor' has no actual declaration in module`

接著,定義新的 DAO 介面,或將現有介面移至 commonMain:

// shared/src/commonMain/kotlin/TodoDao.kt

@Dao
interface TodoDao {
    @Insert
    suspend fun insert(item: TodoEntity)

    @Query("SELECT count(*) FROM TodoEntity")
    suspend fun count(): Int

    @Query("SELECT * FROM TodoEntity")
    fun getAllAsFlow(): Flow<List<TodoEntity>>
}

定義實體或將其移至 commonMain:

// shared/src/commonMain/kotlin/TodoEntity.kt

@Entity
data class TodoEntity(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    val title: String,
    val content: String
)

建立平台專屬資料庫建構工具

您需要定義資料庫建構工具,在各平台上例項化 Room。由於檔案系統 API 有所不同,因此您必須在平台專屬來源集中定義 API 的這個部分。

Android

在 Android 上,您通常會使用 Context.getDatabasePath API 取得資料庫位置。如要建立資料庫執行個體,請指定 Context 和資料庫路徑。

// shared/src/androidMain/kotlin/Database.android.kt

fun getDatabaseBuilder(context: Context): RoomDatabase.Builder<AppDatabase> {
    val appContext = context.applicationContext
    val dbFile = appContext.getDatabasePath("my_room.db")
    return Room.databaseBuilder<AppDatabase>(
        context = appContext,
        name = dbFile.absolutePath
    )
}

iOS

如要在 iOS 上建立資料庫執行個體,請使用 NSFileManager 提供資料庫路徑,通常位於 NSDocumentDirectory。

// shared/src/iosMain/kotlin/Database.ios.kt

fun getDatabaseBuilder(): RoomDatabase.Builder<AppDatabase> {
    val dbFilePath = documentDirectory() + "/my_room.db"
    return Room.databaseBuilder<AppDatabase>(
        name = dbFilePath,
    )
}

@OptIn(ExperimentalForeignApi::class)
private fun documentDirectory(): String {
    val documentDirectory = NSFileManager.defaultManager.URLForDirectory(
        directory = NSDocumentDirectory,
        inDomain = NSUserDomainMask,
        appropriateForURL = null,
        create = false,
        error = null,
    )
    return requireNotNull(documentDirectory?.path)
}

JVM 桌面

如要建立資料庫執行個體,請使用 Java 或 Kotlin API 提供資料庫路徑。

// shared/src/jvmMain/kotlin/Database.desktop.kt

fun getDatabaseBuilder(): RoomDatabase.Builder<AppDatabase> {
    val dbFile = File(System.getProperty("java.io.tmpdir"), "my_room.db")
    return Room.databaseBuilder<AppDatabase>(
        name = dbFile.absolutePath,
    )
}

例項化資料庫

從其中一個平台專屬建構函式取得 RoomDatabase.Builder 後,您可以在通用程式碼中設定 Room 資料庫的其餘部分,以及實際的資料庫例項化。

// shared/src/commonMain/kotlin/Database.kt

fun getRoomDatabase(
    builder: RoomDatabase.Builder<AppDatabase>
): AppDatabase {
    return builder
        .setDriver(BundledSQLiteDriver())
        .setQueryCoroutineContext(Dispatchers.IO)
        .build()
}

選取 SQLite 驅動程式

上述程式碼片段會呼叫 setDriver 建構工具函式,定義 Room 資料庫應使用的 SQLite 驅動程式。這些驅動程式會因目標平台而異。上述程式碼片段使用 BundledSQLiteDriver。建議使用這個驅動程式,其中包含從來源編譯的 SQLite,可在所有平台上提供最一致且最新的 SQLite 版本。

如要使用 OS 提供的 SQLite,請在指定平台專屬驅動程式的平台專屬來源集中,使用 setDriver API。如需可用驅動程式實作的說明,請參閱「驅動程式實作」。您可以使用下列任一方式:

如要使用 NativeSQLiteDriver,您必須提供連結器選項 -lsqlite3,讓 iOS 應用程式與系統 SQLite 動態連結。

// shared/build.gradle.kts

kotlin {
    listOf(
        iosX64(),
        iosArm64(),
        iosSimulatorArm64()
    ).forEach { iosTarget ->
        iosTarget.binaries.framework {
            baseName = "TodoApp"
            isStatic = true
            // Required when using NativeSQLiteDriver
            linkerOpts.add("-lsqlite3")
        }
    }
}

設定協同程式內容

Android 上的 RoomDatabase 物件可選擇使用 RoomDatabase.Builder.setQueryExecutor 設定共用應用程式執行器,以執行資料庫作業。

由於執行器與 KMP 不相容,因此 Room 的 setQueryExecutor API 無法在 commonMain 中使用。相反地,RoomDatabase 物件必須使用 CoroutineContext 進行設定,您可以使用 RoomDatabase.Builder.setCoroutineContext 進行設定。如未設定,RoomDatabase 物件會預設為 Dispatchers.IO。

壓縮與模糊處理

如果專案經過縮減或模糊處理,則必須加入下列 ProGuard 規則,Room 才能找到產生的資料庫定義實作:

-keep class * extends androidx.room3.RoomDatabase { <init>(); }

遷移至 Kotlin Multiplatform

Room 最初是 Android 程式庫,後來遷移至 KMP,並著重於 API 相容性。Room 的 KMP 版本在不同平台之間,以及與 Android 專用版本之間有些許差異。這些差異列出並說明如下。

從 Support SQLite 遷移至 SQLite 驅動程式

androidx.sqlite.db 中任何 SupportSQLiteDatabase 和其他 API 的使用方式,都必須使用 SQLite 驅動程式 API 重構,因為 androidx.sqlite.db 中的 API 僅適用於 Android (請注意,套件與 KMP 套件不同)。

為了兼顧回溯相容性,只要 RoomDatabase 是使用 SupportSQLiteOpenHelper.Factory 設定 (例如未設定 SQLiteDriver),Room 就會以「相容模式」運作,支援 SQLite 和 SQLite 驅動程式 API 都能正常運作。這樣一來,您就能逐步遷移,不必一次將所有 Support SQLite 用法轉換為 SQLite 驅動程式。

使用 Room SQLite 包裝函式

androidx.room3:room3-sqlite-wrapper 構件提供 API,可在遷移期間橋接 SQLiteDriver 和 SupportSQLiteDatabase。

如要從使用 SQLiteDriver 設定的 RoomDatabase 取得 SupportSQLiteDatabase,請使用新的擴充功能函式 RoomDatabase.getSupportWrapper。這個相容性包裝函式有助於維護 SupportSQLiteDatabase 的現有用途 (通常從 RoomDatabase.openHelper.writableDatabase 取得),同時採用 SQLiteDriver,特別是針對大量使用 SupportSQLite API 且想要使用 BundledSQLiteDriver 的程式碼集。

轉換遷移子類別

Migrations 子類別必須遷移至對應的 SQLite 驅動程式:

Kotlin Multiplatform

遷移子類別

object Migration_1_2 : Migration(1, 2) {
    override suspend fun migrate(connection: SQLiteConnection) {
        // ...
    }
}

自動遷移規格子類別

class AutoMigrationSpec_1_2 : AutoMigrationSpec {
    override suspend fun onPostMigrate(connection: SQLiteConnection) {
        // ...
    }
}

僅限 Android

遷移子類別

object Migration_1_2 : Migration(1, 2) {
  override fun migrate(db: SupportSQLiteDatabase) {
    // …
  }
}

自動遷移規格子類別

class AutoMigrationSpec_1_2 : AutoMigrationSpec {
  override fun onPostMigrate(db: SupportSQLiteDatabase) {
    // …
  }
}

轉換資料庫回呼

資料庫回呼必須遷移至對應的 SQLite 驅動程式:

Kotlin Multiplatform

object MyRoomCallback : RoomDatabase.Callback() {
    override suspend fun onCreate(connection: SQLiteConnection) {
        // ...
    }

    override suspend fun onDestructiveMigration(connection: SQLiteConnection) {
        // ...
    }

    override suspend fun onOpen(connection: SQLiteConnection) {
        // ...
    }
}

僅限 Android

object MyRoomCallback : RoomDatabase.Callback() {
  override fun onCreate(db: SupportSQLiteDatabase) {
    // …
  }

  override fun onDestructiveMigration(db: SupportSQLiteDatabase) {
    // …
  }

  override fun onOpen(db: SupportSQLiteDatabase) {
    // …
  }
}

轉換 @RawQuery DAO 函式

針對非 Android 平台編譯、並加上 @RawQuery 註解的函式,必須宣告 RoomRawQuery 類型的參數,而非 SupportSQLiteQuery。

Kotlin Multiplatform

定義原始查詢

@Dao
interface TodoDao {
    @RawQuery
    suspend fun getTodos(query: RoomRawQuery): List<TodoEntity>
}

接著,您可以使用 RoomRawQuery 在執行階段建立查詢:

suspend fun AppDatabase.getTodosWithLowercaseTitle(title: String): List<TodoEntity> {
    val query = RoomRawQuery(
        sql = "SELECT * FROM TodoEntity WHERE title = ?",
        onBindStatement = {
            it.bindText(1, title.lowercase())
        }
    )

    return getDao().getTodos(query)
}

僅限 Android

定義原始查詢

@Dao
interface TodoDao {
  @RawQuery
  suspend fun getTodos(query: SupportSQLiteQuery): List<TodoEntity>
}

接著,您可以使用 SimpleSQLiteQuery 在執行階段建立查詢:

suspend fun AndroidOnlyDao.getTodosWithLowercaseTitle(title: String): List<TodoEntity> {
  val query = SimpleSQLiteQuery(
      query = "SELECT * FROM TodoEntity WHERE title = ?",
      bindArgs = arrayOf(title.lowercase())
  )
  return getTodos(query)
}

轉換封鎖 DAO 函式

Room 受益於 Kotlin 為多個平台提供的功能豐富非同步 kotlinx.coroutines 程式庫。為確保功能正常運作,在 KMP 專案中編譯的 DAO 會強制執行 suspend 函式,但以 androidMain 實作的 DAO 除外,以便與現有程式碼集回溯相容。使用 Room for KMP 時,為非 Android 平台編譯的所有 DAO 函式都必須是 suspend 函式。

Kotlin Multiplatform

暫停查詢

@Query("SELECT * FROM Todo")
suspend fun getAllTodos(): List<Todo>

暫停交易

@Transaction
suspend fun transaction() {
    // ...
}

僅限 Android

封鎖查詢

@Query("SELECT * FROM Todo")
fun getAllTodos(): List<Todo>

封鎖交易

@Transaction
fun blockingTransaction() { … }

將反應式類型轉換為 Flow

並非所有 DAO 函式都必須是暫停函式。傳回反應式類型 (例如 LiveData 或 RxJava 的 Flowable) 的 DAO 函式不應轉換為暫停函式。不過,部分類型 (例如 LiveData) 與 KMP 不相容。具有反應式傳回類型的 DAO 函式必須遷移至協同程式流程。

Kotlin Multiplatform

反應類型:Flows

@Query("SELECT * FROM Todo")
fun getTodosFlow(): Flow<List<Todo>>

僅限 Android

LiveData 或 RxJava 的 Flowable 等反應類型

@Query("SELECT * FROM Todo")
fun getTodosLiveData(): LiveData<List<Todo>>

轉換交易 API

Room KMP 的資料庫交易 API 可區分寫入 (useWriterConnection) 和讀取 (useReaderConnection) 交易。

Kotlin Multiplatform

val database: RoomDatabase = getRoomDatabase(builder)
database.useWriterConnection { transactor ->
    transactor.immediateTransaction {
        // perform database operations in transaction.
    }
}

僅限 Android

val database: RoomDatabase = …
database.withTransaction {
  // perform database operations in transaction
}

寫入交易

使用寫入交易,確保多個查詢以不可分割的方式寫入資料,讓讀取器能一致地存取資料。您可以使用 useWriterConnection 搭配下列三種交易類型:

  • immediateTransaction:在預寫記錄 (WAL) 模式 (預設) 下,這類交易會在啟動時取得鎖定,但讀取器可以繼續讀取。在大多數情況下,這是首選。

  • deferredTransaction:交易在第一個寫入陳述式之前不會取得鎖定。如果您不確定交易中是否需要寫入作業,請使用這類交易做為最佳化。舉例來說,如果您啟動交易,要從僅提供名稱的播放清單中刪除歌曲,但播放清單不存在,則不需要執行寫入 (刪除) 作業。

  • exclusiveTransaction:這個模式的運作方式與 WAL 模式中的 immediateTransaction 相同。在其他日誌模式中,這會防止其他資料庫連線在交易進行時讀取資料庫。

讀取交易

使用讀取交易,多次從資料庫讀取資料。例如,當您有兩個或多個獨立查詢,且未使用 JOIN 子句時。讀卡機連線僅允許延遲交易。嘗試在讀取器連線中啟動立即或專屬交易會擲回例外狀況,因為這些交易會視為「寫入」作業。

val database: RoomDatabase = getRoomDatabase(builder)
database.useReaderConnection { transactor ->
    transactor.deferredTransaction {
        // perform database operations in transaction.
    }
}

不適用於 Kotlin Multiplatform

部分適用於 Android 的 API 不適用於 Kotlin Multiplatform。

查詢回呼

下列用於設定查詢回呼的 API 不適用於一般平台,因此不適用於 Android 以外的平台。

  • RoomDatabase.Builder.setQueryCallback
  • RoomDatabase.QueryCallback

自動關閉資料庫

RoomDatabase.Builder.setAutoCloseTimeout API 可在逾時後自動關閉,但僅適用於 Android。

預先封裝的資料庫

下列 API 用於使用現有資料庫 (預先封裝的資料庫) 建立 RoomDatabase,但無法在一般平台使用,因此無法在 Android 以外的平台使用:

  • RoomDatabase.Builder.createFromAsset
  • RoomDatabase.Builder.createFromFile
  • RoomDatabase.Builder.createFromInputStream
  • RoomDatabase.PrepackagedDatabaseCallback

多實體撤銷

用於啟用多實體失效的 API RoomDatabase.Builder.enableMultiInstanceInvalidation 僅適用於 Android,不適用於一般或其他平台。