Modern Apps git

← Modern-Apps.git

findfamily,appstore: database upgrades from before v2.6.0 start fresh

Commit
e2e2bbef08b832a57d5391dee419c298b241b5b2
Author
Vayun Mathur <[email protected]>
When
2026-12-01 15:03 UTC (4 days ago)
Parents
1abee61
Owner-approved upgrade floor, versions pinned from git
history: FindFamily floor DB v5, AppStore floor DB v3
(the first AppStore database shipped in app v2.6.4, so no
released pre-v2.6.0 database exists there). Migrations
below the floors are removed (FF 1->5, AppStore 1->3) plus
the only pre-floor schema file on disk (FF v1.json); the
shared destructiveMigrationFrom mechanism recreates a
pre-floor database once on open instead of failing, with
no blanket destructive fallback.

Migration tests rewritten to the policy: floor->current
data-intact for both (incl. the 11->12 backfill and RSA-link
drop), chain tests now start at the floors, and pre-floor
real-file destructive-open tests added. Non-Room
old-version handling (DirectBootStore, legacy backups,
LEGACY repo-URL pruning) was reported and left alone — no
version floor to trim there. 242 production+schema lines
removed. Verified: :findfamily:testDevUnitTest 349 and
:appstore:testDevUnitTest 507 BUILD SUCCESSFUL; lint
errors are pre-existing on untouched files.

Diff

appstore/AGENTS.md
diff --git a/appstore/AGENTS.md b/appstore/AGENTS.mdindex ada007bcf0..ca25b6bbce 100644--- a/appstore/AGENTS.md+++ b/appstore/AGENTS.md@@ -23,6 +23,7 @@ _Install: ./install appstore (dev by default)._ - `util/` is NOT a closed package root — don't add more files there - Signature verification is the product — never shortcut it for UX; trust-profile changes need adversarial review - Anonymous Play auth sessions are fragile by nature; isolate Play failures from other sources+- Upgrades from app versions before v2.6.0 start fresh: the `AppDatabase` floor is DB v3 (the first AppStore database shipped, in app v2.6.4, so no released pre-v2.6.0 database exists), pre-floor DB v1–v2 opens destructively (no data carried over), and DB v3 onward migrates normally  ## Key files ### Root — entry (no Route.kt)
appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.ktindex 5b042fcb66..41f5d343dc 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt@@ -407,19 +407,15 @@ abstract class AppDatabase : RoomDatabase() {     abstract fun pinnedStampDao(): PinnedStampDao     abstract fun accrescentTrustDao(): AccrescentTrustDao -    /** Defines database migrations for AppDatabase. */+    /**+     * Defines database migrations for AppDatabase from the supported floor+     * (version 3, the database first shipped in app v2.6.4) onward.+     */     companion object : com.vayunmathur.library.util.DatabaseMigrations {+        /** Database versions before the supported floor (DB v3): opening one starts fresh. */+        override val destructiveMigrationFrom: Set<Int> = (1..2).toSet()+         override val migrations = listOf(-            object : Migration(1, 2) {-                override suspend fun migrate(connection: SQLiteConnection) {-                    connection.execSQL("DROP TABLE IF EXISTS FavoriteEntity")-                }-            },-            object : Migration(2, 3) {-                override suspend fun migrate(connection: SQLiteConnection) {-                    connection.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN targetSdk INTEGER")-                }-            },             object : Migration(3, 4) {                 override suspend fun migrate(connection: SQLiteConnection) {                     connection.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN expectedSigners TEXT")
appstore/src/test/java/com/vayunmathur/appstore/data/AppDatabaseDestructiveOpenTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/data/AppDatabaseDestructiveOpenTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/data/AppDatabaseDestructiveOpenTest.ktnew file mode 100644index 0000000000..2d1d83110d--- /dev/null+++ b/appstore/src/test/java/com/vayunmathur/appstore/data/AppDatabaseDestructiveOpenTest.kt@@ -0,0 +1,53 @@+package com.vayunmathur.appstore.data++import android.content.Context+import androidx.room3.Room+import androidx.sqlite.driver.bundled.BundledSQLiteDriver+import androidx.sqlite.execSQL+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * A pre-floor (v1) database file opens destructively under the production+ * builder settings: it starts fresh at the current version instead of+ * failing to open for want of a 1->2 migration.+ */+@RunWith(RobolectricTestRunner::class)+class AppDatabaseDestructiveOpenTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private val dbName = "appstore-destructive-test.db"++    @Test+    fun `pre-floor database opens fresh instead of failing`() = runTest {+        ctx.deleteDatabase(dbName)+        val file = ctx.getDatabasePath(dbName)+        file.parentFile?.mkdirs()+        BundledSQLiteDriver().open(file.absolutePath).use { conn ->+            conn.execSQL("CREATE TABLE CachedAppEntity (packageName TEXT NOT NULL PRIMARY KEY, name TEXT NOT NULL)")+            conn.execSQL("CREATE TABLE RepoEntity (url TEXT NOT NULL PRIMARY KEY, name TEXT NOT NULL)")+            conn.execSQL("CREATE TABLE FavoriteEntity (id INTEGER NOT NULL PRIMARY KEY)")+            conn.execSQL("INSERT INTO CachedAppEntity (packageName, name) VALUES ('com.example.old', 'Old')")+            conn.execSQL("CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY, identity_hash TEXT)")+            conn.execSQL("INSERT OR REPLACE INTO room_master_table (id, identity_hash) VALUES (42, 'pre-floor')")+            conn.execSQL("PRAGMA user_version = 1")+        }+        val db = Room.databaseBuilder(ctx, AppDatabase::class.java, dbName)+            .setDriver(BundledSQLiteDriver())+            .addMigrations(*AppDatabase.migrations.toTypedArray())+            .fallbackToDestructiveMigrationFrom(true, *AppDatabase.destructiveMigrationFrom.toIntArray())+            .allowMainThreadQueries()+            .build()+        try {+            assertTrue(db.repoDao().all().isEmpty())+            assertTrue(db.cachedAppDao().all().isEmpty())+        } finally {+            db.close()+            ctx.deleteDatabase(dbName)+        }+    }+}
appstore/src/test/java/com/vayunmathur/appstore/data/AppDatabaseMigrationTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/data/AppDatabaseMigrationTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/data/AppDatabaseMigrationTest.ktindex ad1137229d..23b7f6bae9 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/data/AppDatabaseMigrationTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/data/AppDatabaseMigrationTest.kt@@ -10,21 +10,21 @@ import kotlin.test.assertTrue import kotlinx.coroutines.runBlocking  /**- * The full upgrade path from a v1 database: every migration runs in- * order over a database shaped like the first release, the columns- * and tables each version promised appear, and the rows the 3→4 and- * 8→9 steps deliberately drop (unverifiable / split-less cache rows)- * do not survive.+ * The supported upgrade path from the floor database (v3, the database+ * first shipped in app v2.6.4): every kept migration runs in order over a+ * database shaped like that release, the columns and tables each version+ * promised appear, and the rows the 3->4 and 8->9 steps deliberately drop+ * (unverifiable / split-less cache rows) do not survive. Versions before+ * the floor are declared destructive instead of migrated.  */ class AppDatabaseMigrationTest { -    private fun openV1(): SQLiteConnection {+    private fun openV3(): SQLiteConnection {         val conn = BundledSQLiteDriver().open(":memory:")         conn.execSQL(-            "CREATE TABLE CachedAppEntity (packageName TEXT NOT NULL PRIMARY KEY, name TEXT NOT NULL)",+            "CREATE TABLE CachedAppEntity (packageName TEXT NOT NULL PRIMARY KEY, name TEXT NOT NULL, targetSdk INTEGER)",         )         conn.execSQL("CREATE TABLE RepoEntity (url TEXT NOT NULL PRIMARY KEY, name TEXT NOT NULL)")-        conn.execSQL("CREATE TABLE FavoriteEntity (id INTEGER NOT NULL PRIMARY KEY)")         conn.execSQL(             "INSERT INTO CachedAppEntity (packageName, name) VALUES ('com.example.old', 'Old')",         )@@ -53,23 +53,23 @@ class AppDatabaseMigrationTest {         }      @Test-    fun `migration chain is complete and ordered`() {+    fun `migration chain starts at the floor and pre-floor versions are destructive`() {         assertEquals(-            listOf(1 to 2, 2 to 3, 3 to 4, 4 to 5, 5 to 6, 6 to 7, 7 to 8, 8 to 9),+            listOf(3 to 4, 4 to 5, 5 to 6, 6 to 7, 7 to 8, 8 to 9),             AppDatabase.migrations.map { it.startVersion to it.endVersion },         )+        assertEquals(setOf(1, 2), AppDatabase.destructiveMigrationFrom)     }      @Test-    fun `a v1 database upgrades to the v9 shape`() {-        val conn = openV1()+    fun `a floor v3 database upgrades to the v9 shape`() {+        val conn = openV3()         runBlocking {             for (migration in AppDatabase.migrations.sortedBy { it.startVersion }) {                 migration.migrate(conn)             }         } -        assertFalse(tableExists(conn, "FavoriteEntity"))         assertTrue(tableExists(conn, "PinnedStampEntity"))         assertTrue(tableExists(conn, "AccrescentTrustEntity")) @@ -86,7 +86,7 @@ class AppDatabaseMigrationTest {             ),             "columns were $cached",         )-        // The pre-verification rows and repo rows are dropped, not carried over.+        // The pre-verification rows and repo rows are dropped by 3->4, not carried over.         assertEquals(0, rowCount(conn, "CachedAppEntity"))         assertEquals(0, rowCount(conn, "RepoEntity"))         conn.close()@@ -94,14 +94,12 @@ class AppDatabaseMigrationTest {      @Test     fun `rows cached after the trust upgrade survive to v9 except the split reset`() {-        val conn = openV1()+        val conn = openV3()         runBlocking {-            AppDatabase.migrations.filter { it.startVersion < 4 }-                .sortedBy { it.startVersion }-                .forEach { it.migrate(conn) }+            AppDatabase.migrations.single { it.startVersion == 3 }.migrate(conn)         }         // A row cached under v4 rules (post trust-upgrade) survives the-        // column-only 4→5…7→8 steps, then the 8→9 split reset drops it.+        // column-only 4->5...7->8 steps, then the 8->9 split reset drops it.         conn.execSQL(             "INSERT INTO CachedAppEntity (packageName, name) VALUES ('com.example.new', 'New')",         )
appstore/src/test/java/com/vayunmathur/appstore/data/EntityRoundTripTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/data/EntityRoundTripTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/data/EntityRoundTripTest.ktindex c93f180191..b40826e88f 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/data/EntityRoundTripTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/data/EntityRoundTripTest.kt@@ -133,12 +133,13 @@ class EntityRoundTripTest {     // --- migrations list ---      @Test-    fun `migrations cover every version up to the current one`() {+    fun `migrations cover every version from the floor to the current one`() {         val versions = AppDatabase.migrations.map { it.startVersion to it.endVersion } -        assertEquals(8, versions.size)-        assertTrue(versions.contains(1 to 2))+        assertEquals(6, versions.size)+        assertTrue(versions.contains(3 to 4))         assertTrue(versions.contains(8 to 9))+        assertEquals(setOf(1, 2), AppDatabase.destructiveMigrationFrom)         assertFalse(DB_NAME.isBlank())     } }
findfamily/AGENTS.md
diff --git a/findfamily/AGENTS.md b/findfamily/AGENTS.mdindex 9f86e022c0..ac75d57c96 100644--- a/findfamily/AGENTS.md+++ b/findfamily/AGENTS.md@@ -27,6 +27,7 @@ WebSocket relay host: `wss://api.maproj.org/api/ws` (Cloudflare FIRST_PARTY pins - `singleTop` warm-start invites/UWB taps arrive via `onNewIntent`, not a fresh `onCreate` - `AddTrackerDialog` is dev-only (`DEV_BUILD` custom UWB tracker binding); don't expose it in release flows - Extra non-conforming dirs (`ipc/`, `tracker/`, `uwb/`, `util/`) hold real code — like camera's `util/`, a closed-roots migration is pending+- Upgrades from app versions before v2.6.0 start fresh: the `FFDatabase` floor is DB v5, pre-floor DB v1–v4 opens destructively (no data carried over), and DB v5 onward migrates normally  ## Key files ### Root — entry + inline navigation
findfamily/schemas/com.vayunmathur.findfamily.data.FFDatabase/1.json
diff --git a/findfamily/schemas/com.vayunmathur.findfamily.data.FFDatabase/1.json b/findfamily/schemas/com.vayunmathur.findfamily.data.FFDatabase/1.jsondeleted file mode 100644index 7c0c4e86dd..0000000000--- a/findfamily/schemas/com.vayunmathur.findfamily.data.FFDatabase/1.json+++ /dev/null@@ -1,215 +0,0 @@-{-  "formatVersion": 1,-  "database": {-    "version": 1,-    "identityHash": "421e8c59e4e6cace65161ff1cff99ebb",-    "entities": [-      {-        "tableName": "User",-        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`name` TEXT NOT NULL, `photo` TEXT, `locationName` TEXT NOT NULL, `sendingEnabled` INTEGER NOT NULL, `requestStatus` TEXT NOT NULL, `lastLocationChangeTime` INTEGER NOT NULL, `encryptionKey` TEXT, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)",-        "fields": [-          {-            "fieldPath": "name",-            "columnName": "name",-            "affinity": "TEXT",-            "notNull": true-          },-          {-            "fieldPath": "photo",-            "columnName": "photo",-            "affinity": "TEXT"-          },-          {-            "fieldPath": "locationName",-            "columnName": "locationName",-            "affinity": "TEXT",-            "notNull": true-          },-          {-            "fieldPath": "sendingEnabled",-            "columnName": "sendingEnabled",-            "affinity": "INTEGER",-            "notNull": true-          },-          {-            "fieldPath": "requestStatus",-            "columnName": "requestStatus",-            "affinity": "TEXT",-            "notNull": true-          },-          {-            "fieldPath": "lastLocationChangeTime",-            "columnName": "lastLocationChangeTime",-            "affinity": "INTEGER",-            "notNull": true-          },-          {-            "fieldPath": "encryptionKey",-            "columnName": "encryptionKey",-            "affinity": "TEXT"-          },-          {-            "fieldPath": "id",-            "columnName": "id",-            "affinity": "INTEGER",-            "notNull": true-          }-        ],-        "primaryKey": {-          "autoGenerate": true,-          "columnNames": [-            "id"-          ]-        }-      },-      {-        "tableName": "Waypoint",-        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`name` TEXT NOT NULL, `range` REAL NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `lat` REAL NOT NULL, `lon` REAL NOT NULL)",-        "fields": [-          {-            "fieldPath": "name",-            "columnName": "name",-            "affinity": "TEXT",-            "notNull": true-          },-          {-            "fieldPath": "range",-            "columnName": "range",-            "affinity": "REAL",-            "notNull": true-          },-          {-            "fieldPath": "id",-            "columnName": "id",-            "affinity": "INTEGER",-            "notNull": true-          },-          {-            "fieldPath": "coord.lat",-            "columnName": "lat",-            "affinity": "REAL",-            "notNull": true-          },-          {-            "fieldPath": "coord.lon",-            "columnName": "lon",-            "affinity": "REAL",-            "notNull": true-          }-        ],-        "primaryKey": {-          "autoGenerate": true,-          "columnNames": [-            "id"-          ]-        }-      },-      {-        "tableName": "LocationValue",-        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`userid` INTEGER NOT NULL, `speed` REAL NOT NULL, `acc` REAL NOT NULL, `timestamp` INTEGER NOT NULL, `battery` REAL NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `lat` REAL NOT NULL, `lon` REAL NOT NULL)",-        "fields": [-          {-            "fieldPath": "userid",-            "columnName": "userid",-            "affinity": "INTEGER",-            "notNull": true-          },-          {-            "fieldPath": "speed",-            "columnName": "speed",-            "affinity": "REAL",-            "notNull": true-          },-          {-            "fieldPath": "acc",-            "columnName": "acc",-            "affinity": "REAL",-            "notNull": true-          },-          {-            "fieldPath": "timestamp",-            "columnName": "timestamp",-            "affinity": "INTEGER",-            "notNull": true-          },-          {-            "fieldPath": "battery",-            "columnName": "battery",-            "affinity": "REAL",-            "notNull": true-          },-          {-            "fieldPath": "id",-            "columnName": "id",-            "affinity": "INTEGER",-            "notNull": true-          },-          {-            "fieldPath": "coord.lat",-            "columnName": "lat",-            "affinity": "REAL",-            "notNull": true-          },-          {-            "fieldPath": "coord.lon",-            "columnName": "lon",-            "affinity": "REAL",-            "notNull": true-          }-        ],-        "primaryKey": {-          "autoGenerate": true,-          "columnNames": [-            "id"-          ]-        }-      },-      {-        "tableName": "TemporaryLink",-        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`name` TEXT NOT NULL, `key` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `deleteAt` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)",-        "fields": [-          {-            "fieldPath": "name",-            "columnName": "name",-            "affinity": "TEXT",-            "notNull": true-          },-          {-            "fieldPath": "key",-            "columnName": "key",-            "affinity": "TEXT",-            "notNull": true-          },-          {-            "fieldPath": "publicKey",-            "columnName": "publicKey",-            "affinity": "TEXT",-            "notNull": true-          },-          {-            "fieldPath": "deleteAt",-            "columnName": "deleteAt",-            "affinity": "INTEGER",-            "notNull": true-          },-          {-            "fieldPath": "id",-            "columnName": "id",-            "affinity": "INTEGER",-            "notNull": true-          }-        ],-        "primaryKey": {-          "autoGenerate": true,-          "columnNames": [-            "id"-          ]-        }-      }-    ],-    "setupQueries": [-      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",-      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '421e8c59e4e6cace65161ff1cff99ebb')"-    ]-  }-}\ No newline at end of file
findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.ktindex d0caf5453c..9137f5ca1a 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt@@ -242,24 +242,15 @@ abstract class FFDatabase : RoomDatabase() {     abstract fun temporaryLinkDao(): TemporaryLinkDao     abstract fun noShowAlertDao(): NoShowAlertDao -    /** Schema migrations from version 1 to the current database version. */+    /**+     * Schema migrations from the supported floor (version 5, the database+     * shipped in app v2.6.0) to the current database version.+     */     companion object : com.vayunmathur.library.util.DatabaseMigrations {+        /** Database versions before the supported floor (DB v5): opening one starts fresh. */+        override val destructiveMigrationFrom: Set<Int> = (1..4).toSet()+         override val migrations: List<androidx.room3.migration.Migration> = listOf(-            androidx.room3.migration.Migration(1, 2) {-                it.execSQL("CREATE INDEX IF NOT EXISTS index_LocationValue_timestamp ON LocationValue (timestamp)")-            },-            androidx.room3.migration.Migration(2, 3) {-                it.execSQL(-                    "CREATE INDEX IF NOT EXISTS `index_LocationValue_userid_timestamp` " +-                        "ON `LocationValue` (`userid`, `timestamp`)"-                )-            },-            androidx.room3.migration.Migration(3, 4) {-                it.execSQL("ALTER TABLE `User` ADD COLUMN `lastWaypointId` INTEGER")-            },-            androidx.room3.migration.Migration(4, 5) {-                it.execSQL("ALTER TABLE `User` ADD COLUMN `platform` TEXT")-            },             androidx.room3.migration.Migration(5, 6) {                 it.execSQL("ALTER TABLE `User` ADD COLUMN `sharingAutoToggleAt` INTEGER")             },
findfamily/src/test/java/com/vayunmathur/findfamily/data/FFDatabaseMigrationTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/data/FFDatabaseMigrationTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/data/FFDatabaseMigrationTest.ktindex 6adc7b19c3..134718fd12 100644--- a/findfamily/src/test/java/com/vayunmathur/findfamily/data/FFDatabaseMigrationTest.kt+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/data/FFDatabaseMigrationTest.kt@@ -18,10 +18,12 @@ import kotlin.time.Duration.Companion.minutes import kotlin.time.Instant  /**- * The v1 → v14 upgrade path, driven through Room's real migration machinery:- * a v1 file is created with the exported v1 schema, seeded, then opened by the- * current [FFDatabase]. Room validates the migrated schema against the entities,- * so a migration whose SQL drifts from the entity definitions fails here.+ * The supported upgrade path, driven through Room's real migration machinery:+ * a v5 file (the database shipped in app v2.6.0, the supported floor) is+ * created, seeded, then opened by the current [FFDatabase]. Room validates+ * the migrated schema against the entities, so a migration whose SQL drifts+ * from the entity definitions fails here. A pre-floor (v1) file opens+ * destructively instead: it starts fresh rather than failing to open.  */ @RunWith(AndroidJUnit4::class) class FFDatabaseMigrationTest {@@ -29,61 +31,83 @@ class FFDatabaseMigrationTest {     private val ctx: Context get() = ApplicationProvider.getApplicationContext()     private val dbName = "ff-migration-test.db" -    private fun createV1File() {+    private fun createFile(version: Int, seedV5Columns: Boolean) {         ctx.deleteDatabase(dbName)         val config = SupportSQLiteOpenHelper.Configuration.builder(ctx)             .name(dbName)-            .callback(object : SupportSQLiteOpenHelper.Callback(1) {+            .callback(object : SupportSQLiteOpenHelper.Callback(version) {                 override fun onCreate(db: SupportSQLiteDatabase) = Unit                 override fun onUpgrade(db: SupportSQLiteDatabase, old: Int, new: Int) = Unit             })             .build()         val helper = FrameworkSQLiteOpenHelperFactory().create(config)         val db = helper.writableDatabase-        // Exported v1 schema (findfamily/schemas/.../1.json), verbatim.-        db.execSQL("CREATE TABLE IF NOT EXISTS `User` (`name` TEXT NOT NULL, `photo` TEXT, `locationName` TEXT NOT NULL, `sendingEnabled` INTEGER NOT NULL, `requestStatus` TEXT NOT NULL, `lastLocationChangeTime` INTEGER NOT NULL, `encryptionKey` TEXT, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)")+        // Exported v1 schema (formerly findfamily/schemas/.../1.json), verbatim,+        // plus the columns the 3->4 and 4->5 migrations appended for a v5 file.+        val userColumns = "`name` TEXT NOT NULL, `photo` TEXT, `locationName` TEXT NOT NULL, " ++            "`sendingEnabled` INTEGER NOT NULL, `requestStatus` TEXT NOT NULL, " ++            "`lastLocationChangeTime` INTEGER NOT NULL, `encryptionKey` TEXT, " ++            "`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL" ++            if (seedV5Columns) ", `lastWaypointId` INTEGER, `platform` TEXT" else ""+        db.execSQL("CREATE TABLE IF NOT EXISTS `User` ($userColumns)")         db.execSQL("CREATE TABLE IF NOT EXISTS `Waypoint` (`name` TEXT NOT NULL, `range` REAL NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `lat` REAL NOT NULL, `lon` REAL NOT NULL)")         db.execSQL("CREATE TABLE IF NOT EXISTS `LocationValue` (`userid` INTEGER NOT NULL, `speed` REAL NOT NULL, `acc` REAL NOT NULL, `timestamp` INTEGER NOT NULL, `battery` REAL NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `lat` REAL NOT NULL, `lon` REAL NOT NULL)")+        if (seedV5Columns) {+            db.execSQL("CREATE INDEX IF NOT EXISTS index_LocationValue_timestamp ON LocationValue (timestamp)")+            db.execSQL("CREATE INDEX IF NOT EXISTS `index_LocationValue_userid_timestamp` ON `LocationValue` (`userid`, `timestamp`)")+        }         db.execSQL("CREATE TABLE IF NOT EXISTS `TemporaryLink` (`name` TEXT NOT NULL, `key` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `deleteAt` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)")         db.execSQL("CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)")         db.execSQL("INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '421e8c59e4e6cace65161ff1cff99ebb')")+        val platform = if (seedV5Columns) ", 'android'" else ""+        val platformColumn = if (seedV5Columns) ", platform" else ""         db.execSQL(-            "INSERT INTO `User` (name, locationName, sendingEnabled, requestStatus, lastLocationChangeTime, id) " +-                "VALUES ('Ann', 'Home', 1, 'MUTUAL_CONNECTION', 1700000000, 7)"+            "INSERT INTO `User` (name, locationName, sendingEnabled, requestStatus, lastLocationChangeTime, id$platformColumn) " ++                "VALUES ('Ann', 'Home', 1, 'MUTUAL_CONNECTION', 1700000000, 7$platform)"         )         db.execSQL("INSERT INTO `Waypoint` (name, `range`, id, lat, lon) VALUES ('Home', 150.0, 3, 10.0, 20.0)")         db.execSQL(             "INSERT INTO `LocationValue` (userid, speed, acc, timestamp, battery, id, lat, lon) " +                 "VALUES (7, 1.0, 5.0, 1700000000, 80.0, 11, 10.5, 20.5)"         )-        // A pre-PQC RSA link: the 7→8 rebuild deliberately drops rows with no PQC bundle.+        // A pre-PQC RSA link: the 7->8 rebuild deliberately drops rows with no PQC bundle.         db.execSQL(             "INSERT INTO `TemporaryLink` (name, `key`, publicKey, deleteAt, id) " +                 "VALUES ('Old link', 'rsa-key', 'rsa-pub', 1899999999, 5)"         )-        db.version = 1+        db.version = version         helper.close()     } -    @Test fun v1UpgradesToCurrentWithDataIntact() = runBlocking {-        createV1File()+    @Test fun migrationChainStartsAtTheFloor() {+        assertEquals(+            listOf(5 to 6, 6 to 7, 7 to 8, 8 to 9, 9 to 10, 10 to 11, 11 to 12, 12 to 13, 13 to 14),+            FFDatabase.migrations.map { it.startVersion to it.endVersion },+        )+        assertEquals((1..4).toSet(), FFDatabase.destructiveMigrationFrom)+    }++    @Test fun v5UpgradesToCurrentWithDataIntact() = runBlocking {+        createFile(version = 5, seedV5Columns = true)         val db = Room.databaseBuilder(ctx, FFDatabase::class.java, dbName)             .addMigrations(*FFDatabase.migrations.toTypedArray())+            .fallbackToDestructiveMigrationFrom(true, *FFDatabase.destructiveMigrationFrom.toIntArray())             .allowMainThreadQueries()             .build()         try {             val user = db.userDao().getById(7L)             assertNotNull(user)             assertEquals("Ann", user.name)+            assertEquals("android", user.platform)             assertEquals(UserKind.PERSON, user.kind)             assertEquals(3L, db.waypointDao().getAll().single().id)-            // 11→12 backfill: reportedAt inherits timestamp, source defaults LIVE.+            // 11->12 backfill: reportedAt inherits timestamp, source defaults LIVE.             val fix = db.locationValueDao().getByUseridFlow(7L).first().single()             assertEquals(fix.timestamp, fix.reportedAt)             assertEquals(LocationSource.LIVE, fix.source)             // The RSA-only link was dropped by the PQC-only rebuild, not carried.             assertTrue(db.temporaryLinkDao().getAll().isEmpty())-            // 12→13 created the no-show table; it starts empty and accepts rows.+            // 12->13 created the no-show table; it starts empty and accepts rows.             assertTrue(db.noShowAlertDao().getAll().isEmpty())             val alertId = db.noShowAlertDao().upsert(                 NoShowAlert(@@ -103,4 +127,21 @@ class FFDatabaseMigrationTest {             ctx.deleteDatabase(dbName)         }     }++    @Test fun preFloorDatabaseOpensFreshInsteadOfFailing() = runBlocking {+        createFile(version = 1, seedV5Columns = false)+        val db = Room.databaseBuilder(ctx, FFDatabase::class.java, dbName)+            .addMigrations(*FFDatabase.migrations.toTypedArray())+            .fallbackToDestructiveMigrationFrom(true, *FFDatabase.destructiveMigrationFrom.toIntArray())+            .allowMainThreadQueries()+            .build()+        try {+            assertTrue(db.userDao().getAll().isEmpty())+            assertTrue(db.waypointDao().getAll().isEmpty())+            assertTrue(db.temporaryLinkDao().getAll().isEmpty())+        } finally {+            db.close()+            ctx.deleteDatabase(dbName)+        }+    } }