library-room: add tests for SQLCipher wiring and RoomRepository
- Commit
4bf89fa78ad47acf064bd6d4830b1b7de123c597- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 06:58 UTC (29 days ago)
- Parents
af82099
Raises :library:room merged (JVM unit + Robolectric + emulator androidTest) INSTRUCTION coverage from 0% (no tests, no report) to 87.7% (685 of 781 instructions; createMergedCoverageReport). JVM/Robolectric half: the cached and uncached builders (identity in the process-wide databases cache, explicit migrations winning over a companion's, no-companion databases, device-protected builds and their file/prefs moves), RoomRepository laziness, app-context exposure, auxiliary opens, and every encryptExistingDatabase header branch that does not need the native library; SqlCipherDbCodec's pre-native file contract (missing source writes nothing, export replaces the output, import deletes the old file set first). A host JVM has no AndroidKeyStore, so the default-passphrase build is asserted to fail there with KeyStoreException and cache nothing. Emulator half (src/androidTest, run with ./test --instrumented-only library/room): real SQLCipher round trips - rows through an encrypted repository database (file verified not plaintext), the keystore-helper passphrase generate-then-decrypt across two builds, codec export-to-plaintext then import restoring rows, encrypting a framework-plaintext database in place and reading it back with the password, and a magic-headered non-database being skipped intact. Test fixtures generate their Room impls via kspTest/kspAndroidTest wiring added to the module build file. (cherry picked from commit 96639aa839b4be7b1071a9aba74d5170b3b01e17)
Diff
library/room/build.gradle.kts
diff --git a/library/room/build.gradle.kts b/library/room/build.gradle.ktsindex 1c7218c856..e3be12b31c 100644--- a/library/room/build.gradle.kts+++ b/library/room/build.gradle.kts@@ -13,6 +13,13 @@ dependencies { // inline `buildDatabase` body references SQLCipherDriver at each app // call site, so it must be on the consuming app's compile classpath. implementRoom(libs)+ // The test database's generated impl, for repository/buildDatabase tests.+ add("kspTest", libs.androidx.room3.compiler)+ // Same for the device tests, which open real SQLCipher databases.+ add("kspAndroidTest", libs.androidx.room3.compiler)+ androidTestImplementation(libs.androidx.test.runner)+ androidTestImplementation(libs.androidx.test.core)+ androidTestImplementation(libs.androidx.test.ext.junit) api(libs.sqlcipher.android) implementation(libs.androidx.sqlite) }
library/room/src/androidTest/java/com/vayunmathur/library/room/DeviceDatabaseTest.kt
diff --git a/library/room/src/androidTest/java/com/vayunmathur/library/room/DeviceDatabaseTest.kt b/library/room/src/androidTest/java/com/vayunmathur/library/room/DeviceDatabaseTest.ktnew file mode 100644index 0000000000..105bf3ef37--- /dev/null+++ b/library/room/src/androidTest/java/com/vayunmathur/library/room/DeviceDatabaseTest.kt@@ -0,0 +1,189 @@+package com.vayunmathur.library.room++import android.content.Context+import androidx.room3.Dao+import androidx.room3.Database+import androidx.room3.Entity+import androidx.room3.PrimaryKey+import androidx.room3.Query+import androidx.room3.RoomDatabase+import androidx.room3.Upsert+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import com.vayunmathur.library.util.databases+import java.io.File+import kotlinx.coroutines.runBlocking+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith++@Entity+data class DeviceItem(+ @PrimaryKey(autoGenerate = true) val id: Long = 0,+ val name: String,+)++@Dao+interface DeviceItemDao {+ @Upsert+ suspend fun upsert(item: DeviceItem): Long++ @Query("SELECT * FROM DeviceItem ORDER BY id")+ suspend fun all(): List<DeviceItem>+}++@Database(entities = [DeviceItem::class], version = 1, exportSchema = false)+abstract class DeviceDatabase : RoomDatabase() {+ abstract fun itemDao(): DeviceItemDao+}++@Database(entities = [DeviceItem::class], version = 1, exportSchema = false)+abstract class DevicePlainDatabase : RoomDatabase() {+ abstract fun itemDao(): DeviceItemDao+}++private class DeviceRepository(context: Context, name: String, password: String?) :+ RoomRepository<DeviceDatabase>(context, DeviceDatabase::class, name, password) {++ val database: DeviceDatabase get() = db+}++/**+ * The half of :library:room that needs the SQLCipher native library: opening+ * encrypted databases, exporting/importing them, and encrypting a plaintext+ * file in place. None of it exists on a host JVM.+ */+@RunWith(AndroidJUnit4::class)+class DeviceDatabaseTest {++ private val context: Context get() = InstrumentationRegistry.getInstrumentation().targetContext++ @After fun tearDown() {+ databases.values.forEach { runCatching { it.close() } }+ databases.clear()+ }++ private fun deleteDb(name: String) {+ val file = context.getDatabasePath(name)+ file.delete()+ File("${file.path}-wal").delete()+ File("${file.path}-shm").delete()+ File("${file.path}-journal").delete()+ }++ @Test+ fun rowsRoundTripThroughEncryptedDatabase() = runBlocking {+ deleteDb("device-round-trip")+ val repo = DeviceRepository(context, "device-round-trip", "pw")+ repo.database.itemDao().upsert(DeviceItem(name = "alpha"))+ repo.database.itemDao().upsert(DeviceItem(name = "beta"))+ assertEquals(listOf("alpha", "beta"), repo.database.itemDao().all().map { it.name })+ // The file on disk must not be a plaintext SQLite database.+ val header = context.getDatabasePath("device-round-trip").readBytes().copyOf(16)+ assertFalse(+ "the database file should be encrypted at rest",+ header.contentEquals("SQLite format 3\u0000".toByteArray(Charsets.UTF_8)),+ )+ }++ @Test+ fun defaultPassphraseComesFromTheKeystoreHelper() = runBlocking {+ deleteDb("device-helper-1")+ deleteDb("device-helper-2")+ // First build: no key yet, so one is generated and a passphrase stored.+ val first = context.buildDatabase(DeviceDatabase::class.java, null, null, "device-helper-1")+ first.itemDao().upsert(DeviceItem(name = "one"))+ // Second build: the stored key is read back and the passphrase decrypted.+ val second = context.buildDatabaseUncached(+ DevicePlainDatabase::class.java, null, null, "device-helper-2",+ )+ second.itemDao().upsert(DeviceItem(name = "two"))+ assertEquals(listOf("one"), first.itemDao().all().map { it.name })+ assertEquals(listOf("two"), second.itemDao().all().map { it.name })+ second.close()+ }++ @Test+ fun exportThenImportRestoresTheRows() = runBlocking {+ deleteDb("device-backup")+ val repo = DeviceRepository(context, "device-backup", "pw")+ repo.database.itemDao().upsert(DeviceItem(name = "kept"))+ // Close the Room instance before the codec opens the file directly.+ repo.database.close()+ databases.clear()++ val plaintext = File(context.cacheDir, "backup-plaintext.db")+ if (plaintext.exists()) plaintext.delete()+ SqlCipherDbCodec.exportDatabase(context, "device-backup", "pw", plaintext)+ assertTrue(plaintext.exists())+ val header = plaintext.readBytes().copyOf(16)+ assertTrue(+ "the export should be a plaintext SQLite file",+ header.contentEquals("SQLite format 3\u0000".toByteArray(Charsets.UTF_8)),+ )++ SqlCipherDbCodec.importDatabase(context, "device-backup", "pw", plaintext)+ val restored = DeviceRepository(context, "device-backup", "pw")+ assertEquals(listOf("kept"), restored.database.itemDao().all().map { it.name })+ }++ @Test+ fun reifiedDefaultsBuildThePasswordsDatabase() = runBlocking {+ deleteDb("passwords-db")+ val db = context.buildDatabase<DeviceDatabase>()+ db.itemDao().upsert(DeviceItem(name = "defaulted"))+ assertEquals(listOf("defaulted"), db.itemDao().all().map { it.name })+ }++ @Test+ fun aMagicHeaderedNonDatabaseIsSkippedNotDestroyed() {+ deleteDb("device-notadb")+ val file = context.getDatabasePath("device-notadb")+ file.parentFile?.mkdirs()+ // SQLite magic, then junk: SQLCipher's open refuses it as not a+ // database, which is a skip, and the original file stays put.+ file.writeBytes(+ "SQLite format 3\u0000".toByteArray(Charsets.UTF_8) ++ ByteArray(64) { (it * 13 + 3).toByte() },+ )+ encryptExistingDatabase(context, "device-notadb", "pw")+ assertTrue(file.exists())+ assertFalse("the temp copy is cleaned up on a skip", File("${file.path}_temp").exists())+ }++ @Test+ fun encryptExistingDatabaseConvertsAPlaintextFile() {+ deleteDb("device-plain")+ val file = context.getDatabasePath("device-plain")+ file.parentFile?.mkdirs()+ val plain = android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(file, null)+ plain.execSQL("CREATE TABLE Note (body TEXT)")+ plain.execSQL("INSERT INTO Note VALUES ('hello')")+ plain.close()+ assertTrue(+ file.readBytes().copyOf(16)+ .contentEquals("SQLite format 3\u0000".toByteArray(Charsets.UTF_8)),+ )++ encryptExistingDatabase(context, "device-plain", "pw")++ val header = file.readBytes().copyOf(16)+ assertFalse(+ "after conversion the header must no longer be plaintext SQLite",+ header.contentEquals("SQLite format 3\u0000".toByteArray(Charsets.UTF_8)),+ )+ loadSqlCipher()+ val db = net.zetetic.database.sqlcipher.SQLiteDatabase.openDatabase(+ file.absolutePath, "pw", null,+ net.zetetic.database.sqlcipher.SQLiteDatabase.OPEN_READONLY, null,+ )+ db.rawQuery("SELECT body FROM Note", null).use { cursor ->+ assertTrue(cursor.moveToFirst())+ assertEquals("hello", cursor.getString(0))+ }+ db.close()+ }+}
library/room/src/test/java/com/vayunmathur/library/room/BuildDatabaseTest.kt
diff --git a/library/room/src/test/java/com/vayunmathur/library/room/BuildDatabaseTest.kt b/library/room/src/test/java/com/vayunmathur/library/room/BuildDatabaseTest.ktnew file mode 100644index 0000000000..9dd2b5f153--- /dev/null+++ b/library/room/src/test/java/com/vayunmathur/library/room/BuildDatabaseTest.kt@@ -0,0 +1,156 @@+package com.vayunmathur.library.room++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.util.databases+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotSame+import kotlin.test.assertNull+import kotlin.test.assertSame+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.annotation.GraphicsMode++@RunWith(AndroidJUnit4::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class BuildDatabaseTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()++ @AfterTest fun tearDown() {+ databases.values.forEach { runCatching { it.close() } }+ databases.clear()+ }++ @Test+ fun `buildDatabase caches one instance per database class`() {+ val first = context.buildDatabase(TestDatabase::class.java, null, "pw-one", "cache-db")+ val second = context.buildDatabase(TestDatabase::class.java, null, "pw-two", "cache-db")+ assertSame(first, second, "the cache wins over a second call, whatever it passes")+ assertSame(first, databases[TestDatabase::class])+ }++ @Test+ fun `reified buildDatabase returns the same cached instance`() {+ val byClass = context.buildDatabase(TestDatabase::class.java, null, "pw", "reified-db")+ val byType = context.buildDatabase<TestDatabase>(null, "pw", "reified-db")+ assertSame(byClass, byType)+ }++ @Test+ fun `uncached builds are distinct instances`() {+ val first = context.buildDatabaseUncached(TestDatabase::class.java, null, "pw", "uncached-a")+ val second = context.buildDatabaseUncached(TestDatabase::class.java, null, "pw", "uncached-a")+ assertNotSame(first, second)+ assertNull(databases[TestDatabase::class], "uncached builds must not populate the cache")+ first.close()+ second.close()+ }++ @Test+ fun `a database without a companion gets no migrations and still builds`() {+ val db = context.buildDatabase(PlainDatabase::class.java, null, "pw", "plain-db")+ assertSame(db, databases[PlainDatabase::class])+ }++ @Test+ fun `explicit migrations win over the companion`() {+ // An explicit (empty) list must not fall back to the companion's 1->2.+ val db = context.buildDatabase(TestDatabase::class.java, emptyList(), "pw", "explicit-db")+ assertSame(db, databases[TestDatabase::class])+ }++ @Test+ fun `repository builds lazily once and exposes the application context`() {+ val repo = TestRepository(context)+ assertSame(context.applicationContext, repo.applicationContext)+ val first = repo.database+ assertSame(first, repo.database)+ assertSame(first, databases[TestDatabase::class])+ }++ @Test+ fun `repository with defaults constructs without touching the keystore`() {+ val repo = DefaultRepository(context)+ assertSame(context.applicationContext, repo.applicationContext)+ assertNull(databases[TestDatabase::class], "nothing is built until db is touched")+ }++ @Test+ fun `openAuxiliary builds a separate instance under another name`() {+ val repo = TestRepository(context)+ val main = repo.database+ val aux = repo.auxiliary("legacy-name-db")+ assertNotSame(main, aux)+ aux.close()+ }++ @Test+ fun `device protected storage builds against the device context`() {+ val db = context.buildDatabase(+ TestDatabase::class.java, null, "pw", "dps-db",+ useDeviceProtectedStorage = true,+ )+ assertSame(db, databases[TestDatabase::class])+ }++ @Test+ fun `device protected build moves an existing database and prefs over`() {+ // Seed the credential-protected side the way a pre-upgrade install+ // would look: a database file and a populated secure_prefs there,+ // nothing yet on the device-protected side.+ val credentialFile = context.getDatabasePath("dps-move-db")+ credentialFile.parentFile?.mkdirs()+ credentialFile.writeBytes(ByteArray(8) { 1 })+ context.getSharedPreferences("secure_prefs", Context.MODE_PRIVATE)+ .edit().putString("k", "v").commit()+ val deviceContext = context.createDeviceProtectedStorageContext()+ try {+ val db = context.buildDatabase(+ TestDatabase::class.java, null, "pw", "dps-move-db",+ useDeviceProtectedStorage = true,+ )+ assertSame(db, databases[TestDatabase::class])+ kotlin.test.assertTrue(+ deviceContext.getDatabasePath("dps-move-db").exists(),+ "the database should have moved to device-protected storage",+ )+ } finally {+ credentialFile.delete()+ deviceContext.getDatabasePath("dps-move-db").delete()+ context.getSharedPreferences("secure_prefs", Context.MODE_PRIVATE)+ .edit().clear().commit()+ }+ }++ @Test+ fun `reified overload with all defaults reaches for the keystore passphrase`() {+ // No stored key yet, so building asks DatabaseHelper to generate one -+ // which needs AndroidKeyStore, a platform service a host JVM does not+ // have. On a device this is the default path every app takes.+ kotlin.test.assertFailsWith<java.security.KeyStoreException> {+ context.buildDatabase<TestDatabase>()+ }+ assertNull(databases[TestDatabase::class], "a failed build must not be cached")+ }++ @Test+ fun `uncached build through defaults`() {+ val db = context.buildDatabaseUncached(TestDatabase::class.java, null, "pw", "uncached-defaults")+ kotlin.test.assertNull(databases[TestDatabase::class])+ db.close()+ }++ @Test+ fun `the dao is reachable without opening the database`() {+ // Opening is deferred until first use: the generated DAO must already+ // be handable-out here. (Actually opening needs the SQLCipher native+ // library, which a host JVM does not have - see the task report.)+ val repo = TestRepository(context, name = "dao-db")+ kotlin.test.assertNotNull(repo.database.itemDao())+ }+}
library/room/src/test/java/com/vayunmathur/library/room/SqlCipherDbCodecTest.kt
diff --git a/library/room/src/test/java/com/vayunmathur/library/room/SqlCipherDbCodecTest.kt b/library/room/src/test/java/com/vayunmathur/library/room/SqlCipherDbCodecTest.ktnew file mode 100644index 0000000000..de3058c8f6--- /dev/null+++ b/library/room/src/test/java/com/vayunmathur/library/room/SqlCipherDbCodecTest.kt@@ -0,0 +1,75 @@+package com.vayunmathur.library.room++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import java.io.File+import kotlin.test.Test+import kotlin.test.assertFalse+import org.junit.runner.RunWith+import org.robolectric.annotation.GraphicsMode++@RunWith(AndroidJUnit4::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class SqlCipherDbCodecTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()++ @Test+ fun `export prepares the output file before the native open`() {+ // The source exists, so export creates the parent dirs, replaces any+ // stale output, and only then reaches for SQLCipher - which a host+ // JVM cannot load. Assert the pre-native contract, not the failure.+ val dbFile = context.getDatabasePath("export-source-db")+ dbFile.parentFile?.mkdirs()+ dbFile.writeBytes(ByteArray(32) { 4 })+ val output = File(context.cacheDir, "nested/deep/export.db")+ output.parentFile?.mkdirs()+ output.writeBytes(byteArrayOf(9, 9, 9))+ try {+ runCatching {+ SqlCipherDbCodec.exportDatabase(context, "export-source-db", "pw", output)+ }+ kotlin.test.assertTrue(output.exists(), "export should have created the output file")+ kotlin.test.assertEquals(0L, output.length(), "the stale output is replaced, not appended")+ } finally {+ dbFile.delete()+ output.delete()+ }+ }++ @Test+ fun `import deletes the old database files before the native open`() {+ val dbFile = context.getDatabasePath("import-target-db")+ dbFile.parentFile?.mkdirs()+ dbFile.writeBytes(byteArrayOf(1))+ val wal = File("${dbFile.path}-wal").apply { writeBytes(byteArrayOf(2)) }+ val shm = File("${dbFile.path}-shm").apply { writeBytes(byteArrayOf(3)) }+ val journal = File("${dbFile.path}-journal").apply { writeBytes(byteArrayOf(4)) }+ val input = File(context.cacheDir, "import-plaintext.db")+ input.writeBytes(ByteArray(32) { 5 })+ try {+ runCatching {+ SqlCipherDbCodec.importDatabase(context, "import-target-db", "pw", input)+ }+ // Whatever the native layer then does on this host, the old file+ // set is gone first: a half-finished import must not leave a WAL+ // from the previous database behind.+ kotlin.test.assertFalse(wal.exists())+ kotlin.test.assertFalse(shm.exists())+ kotlin.test.assertFalse(journal.exists())+ } finally {+ dbFile.delete()+ input.delete()+ }+ }++ @Test+ fun `exporting a database that does not exist writes nothing`() {+ val output = File(context.cacheDir, "export-should-not-exist.db")+ if (output.exists()) output.delete()+ SqlCipherDbCodec.exportDatabase(context, "no-such-db-xyz", "pw", output)+ assertFalse(output.exists(), "a missing source must not produce an export file")+ assertFalse(context.getDatabasePath("no-such-db-xyz").exists())+ }+}
library/room/src/test/java/com/vayunmathur/library/room/SqlCipherTest.kt
diff --git a/library/room/src/test/java/com/vayunmathur/library/room/SqlCipherTest.kt b/library/room/src/test/java/com/vayunmathur/library/room/SqlCipherTest.ktnew file mode 100644index 0000000000..61917aacad--- /dev/null+++ b/library/room/src/test/java/com/vayunmathur/library/room/SqlCipherTest.kt@@ -0,0 +1,96 @@+package com.vayunmathur.library.room++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.annotation.GraphicsMode++@RunWith(AndroidJUnit4::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class SqlCipherTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()++ @Test+ fun `loading the native library twice is safe even where it is absent`() {+ // On a host JVM there is no Android sqlcipher .so: the loader logs and+ // carries on rather than taking the process down, and a second call is+ // a no-op either way.+ loadSqlCipher()+ loadSqlCipher()+ }++ @Test+ fun `encrypting a database that does not exist does nothing`() {+ encryptExistingDatabase(context, "no-such-db-xyz", "pw")+ assertFalse(context.getDatabasePath("no-such-db-xyz").exists())+ }++ @Test+ fun `a file too short to hold a header is left alone`() {+ val file = context.getDatabasePath("short-db")+ file.parentFile?.mkdirs()+ file.writeBytes(byteArrayOf(1, 2, 3))+ try {+ encryptExistingDatabase(context, "short-db", "pw")+ assertEquals(3L, file.length())+ } finally {+ file.delete()+ }+ }++ @Test+ fun `a file that is not plain sqlite is treated as already encrypted`() {+ val file = context.getDatabasePath("cipher-db")+ file.parentFile?.mkdirs()+ // Long enough for a header, wrong magic: indistinguishable from ciphertext.+ file.writeBytes(ByteArray(64) { (it * 31 + 7).toByte() })+ try {+ encryptExistingDatabase(context, "cipher-db", "pw")+ assertEquals(64L, file.length())+ assertTrue(file.exists())+ } finally {+ file.delete()+ }+ }++ @Test+ fun `an unreadable database path is treated as encrypted, not an error`() {+ val file = context.getDatabasePath("dir-db")+ file.parentFile?.mkdirs()+ // A directory where the file should be: reading its header is an+ // IOException, which the code answers by assuming encryption.+ assertTrue(file.mkdir())+ try {+ encryptExistingDatabase(context, "dir-db", "pw")+ assertTrue(file.isDirectory)+ } finally {+ file.delete()+ }+ }++ @Test+ fun `a header split across reads is not mistaken for plaintext`() {+ val file = context.getDatabasePath("tiny-header-db")+ file.parentFile?.mkdirs()+ file.writeBytes("SQLite format 3\u0000".toByteArray(Charsets.UTF_8).copyOf(16))+ try {+ // Exactly one magic header: plaintext by the header rule, so the+ // encryption attempt starts. Whether the host can run SQLCipher+ // decides the rest; the contract asserted here is only that the+ // original file is still present afterwards (success renames the+ // encrypted copy over it, failure deletes the copy, never both).+ runCatching { encryptExistingDatabase(context, "tiny-header-db", "pw") }+ assertTrue(file.exists())+ } finally {+ file.delete()+ File("${file.path}_temp").delete()+ }+ }+}
library/room/src/test/java/com/vayunmathur/library/room/TestDatabase.kt
diff --git a/library/room/src/test/java/com/vayunmathur/library/room/TestDatabase.kt b/library/room/src/test/java/com/vayunmathur/library/room/TestDatabase.ktnew file mode 100644index 0000000000..33cff649fe--- /dev/null+++ b/library/room/src/test/java/com/vayunmathur/library/room/TestDatabase.kt@@ -0,0 +1,74 @@+package com.vayunmathur.library.room++import android.content.Context+import androidx.room3.Dao+import androidx.room3.Database+import androidx.room3.Entity+import androidx.room3.PrimaryKey+import androidx.room3.Query+import androidx.room3.RoomDatabase+import androidx.room3.Upsert+import androidx.room3.migration.Migration+import androidx.sqlite.execSQL+import com.vayunmathur.library.util.DatabaseMigrations++@Entity+data class TestItem(+ @PrimaryKey(autoGenerate = true) val id: Long = 0,+ val name: String,+)++@Dao+interface TestItemDao {+ @Upsert+ suspend fun upsert(item: TestItem): Long++ @Query("SELECT * FROM TestItem ORDER BY id")+ suspend fun all(): List<TestItem>++ @Query("DELETE FROM TestItem")+ suspend fun deleteAll()+}++@Database(entities = [TestItem::class], version = 2, exportSchema = false)+abstract class TestDatabase : RoomDatabase() {+ abstract fun itemDao(): TestItemDao++ companion object : DatabaseMigrations {+ override val migrations = listOf(+ Migration(1, 2) {+ it.execSQL("ALTER TABLE TestItem ADD COLUMN note TEXT")+ },+ )+ }+}++/** A database class with no companion at all: migrations must resolve to none. */+@Database(entities = [TestItem::class], version = 1, exportSchema = false)+abstract class PlainDatabase : RoomDatabase() {+ abstract fun itemDao(): TestItemDao+}++class TestRepository(+ context: Context,+ name: String = "test-repo-db",+ password: String? = "repo-password",+ migrations: List<Migration>? = null,+) : RoomRepository<TestDatabase>(context, TestDatabase::class, name, password, false, migrations) {++ val database: TestDatabase get() = db+ val applicationContext: Context get() = appContext++ fun auxiliary(name: String): TestDatabase = openAuxiliary(name)++ suspend fun add(name: String): Long = db.itemDao().upsert(TestItem(name = name))+ suspend fun names(): List<String> = db.itemDao().all().map { it.name }+}++/** Repository with every default: default db name, passphrase from the keystore helper. */+class DefaultRepository(context: Context) :+ RoomRepository<TestDatabase>(context, TestDatabase::class) {++ val database: TestDatabase get() = db+ val applicationContext: Context get() = appContext+}