Modern Apps git

← Modern-Apps.git

db: restore the missing 1-to-4 migration chains (crash on upgrade)

Commit
dd6b2dbfd92bc2217765dc4b74e657894f9f356a
Author
Vayun Mathur <[email protected]>
When
2026-11-21 04:31 UTC (15 days ago)
Parents
2ad4d68
EmailDatabase (v23) and health's Record database (v12) had
registered migrations only from 4->5, with no destructive
fallback - a device holding a v1-v3 database crashes on open.
History shows no v2 was ever committed or shipped (changes
went unversioned before the jump), so the 1->3 diff is split
into two staging migrations whose combined result is exactly
the historically attested v3 schema (Room validates the final
state), then the attested 3->4. v1 rows are preserved (email:
stamped with empty account rather than the era's wipe).
Migration tests now run the full 1->23 and 1->12 chains with
rows surviving.

Also: version.txt is validated at configuration time (2-line
format, positive integer code) instead of silently falling
back to versionCode 1, and appstore's F-Droid version
selection now picks the highest versionCode (ABI fitness
first) instead of first-added. The appstore play-error
line test failure is pre-existing and unrelated (reproduces
in isolation, no path through selection).

Verified: email 580, health 618 tests pass; appstore selection
tests pass.

Diff

appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.ktindex 4e92b4d29e..5982778cbf 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt@@ -651,10 +651,16 @@ object FDroidRepository {             .filter { it.requiredSplitTypes.isNotEmpty() || it.versionCode !in splitSetCodes }             .mapNotNull { candidate -> abiRank(candidate.nativeCode, deviceAbis)?.let { candidate to it } }             .minWithOrNull(-                compareByDescending<Pair<VersionCandidate, Int>> { it.first.added }-                    .thenBy { it.second }-                    .thenByDescending { it.first.requiredSplitTypes.isNotEmpty() }+                // ABI fitness first (a build for the wrong ABI cannot be used+                // at all), then the highest versionCode - `added` alone used+                // to win here, so a re-indexed older release could shadow the+                // latest versionCode and the store offered a downgrade. `added`+                // is now only the tie-break between equal versionCodes, ahead+                // of the split-base and size tie-breaks as before.+                compareBy<Pair<VersionCandidate, Int>> { it.second }                     .thenByDescending { it.first.versionCode }+                    .thenByDescending { it.first.added }+                    .thenByDescending { it.first.requiredSplitTypes.isNotEmpty() }                     .thenByDescending { it.first.size }             )             ?.first
appstore/src/test/java/com/vayunmathur/appstore/data/FDroidVersionSelectionTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/data/FDroidVersionSelectionTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/data/FDroidVersionSelectionTest.ktindex 6a5b09535d..713740c34c 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/data/FDroidVersionSelectionTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/data/FDroidVersionSelectionTest.kt@@ -82,6 +82,26 @@ class FDroidVersionSelectionTest {         assertEquals("/app_new_arm64.apk", FDroidRepository.selectVersion(versions, arm64Device)?.fileName)     } +    @Test+    fun `highest versionCode wins even when a lower versionCode was added later`() {+        val versions = listOf(+            version(200, "/app_reindexed_old.apk", versionCode = 11, nativeCode = listOf("arm64-v8a")),+            version(100, "/app_latest.apk", versionCode = 12, nativeCode = listOf("arm64-v8a")),+        )++        assertEquals("/app_latest.apk", FDroidRepository.selectVersion(versions, arm64Device)?.fileName)+    }++    @Test+    fun `added breaks the tie between equal versionCodes`() {+        val versions = listOf(+            version(100, "/app_first.apk", versionCode = 12, nativeCode = listOf("arm64-v8a")),+            version(200, "/app_second.apk", versionCode = 12, nativeCode = listOf("arm64-v8a")),+        )++        assertEquals("/app_second.apk", FDroidRepository.selectVersion(versions, arm64Device)?.fileName)+    }+     @Test     fun `falls back to an older release when the newest has no build for this device`() {         val versions = listOf(
build-logic/src/main/kotlin/common-conventions-app.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts b/build-logic/src/main/kotlin/common-conventions-app.gradle.ktsindex e690b8a337..ed30061e7e 100644--- a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-app.gradle.kts@@ -39,14 +39,48 @@ fun readVersionInfoOnce(): Pair<Int, String> {         return extra.get("modernAppsVersionInfo") as Pair<Int, String>     }     val versionFile = File(rootDir, "version.txt")+    // Fail the build loudly on a missing or malformed version.txt. This used+    // to fall back to versionCode 1 for a non-numeric first line, which once+    // shipped a build whose code was lower than the previous release (and so+    // could never be installed as an update). There is no safe default for a+    // release version code: every app in the build shares this one file.     val info = if (versionFile.exists()) {         val lines = versionFile.readLines()-        if (lines.size >= 2) {-            val code = lines[0].trim().toIntOrNull() ?: 1-            val name = lines[1].trim()-            code to name-        } else throw IllegalStateException("Invalid version.txt format")-    } else throw IllegalStateException("version.txt not found")+        if (lines.size < 2) {+            throw IllegalStateException(+                "Invalid version.txt at ${versionFile.absolutePath}: expected 2 lines " ++                    "(versionCode, versionName) but found ${lines.size}. " ++                    "Fix version.txt - refusing to build with a guessed versionCode."+            )+        }+        val codeText = lines[0].trim()+        val code = codeText.toIntOrNull()+            ?: throw IllegalStateException(+                "Invalid version.txt at ${versionFile.absolutePath}: first line must be the " ++                    "integer versionCode but was '$codeText'. " ++                    "Fix version.txt - refusing to build with a guessed versionCode."+            )+        if (code <= 0) {+            throw IllegalStateException(+                "Invalid version.txt at ${versionFile.absolutePath}: versionCode must be " ++                    "positive but was $code. Fix version.txt."+            )+        }+        val name = lines[1].trim()+        if (name.isBlank()) {+            throw IllegalStateException(+                "Invalid version.txt at ${versionFile.absolutePath}: second line (versionName) " ++                    "is blank. Fix version.txt."+            )+        }+        code to name+    } else {+        throw IllegalStateException(+            "version.txt not found at ${versionFile.absolutePath}: every app build reads its " ++                "versionCode/versionName from that 2-line file (code, name). " ++                "Restore version.txt - refusing to build with a guessed versionCode."+        )+    }     extra.set("modernAppsVersionInfo", info)     return info }@@ -71,8 +105,18 @@ val (releaseVersionCode, appVersionName) = readVersionInfo()  *  * Read at configuration time, which the configuration cache requires.  */-val appVersionCode: Int =-    (findProperty("versionCodeOverride") as String?)?.trim()?.toIntOrNull() ?: releaseVersionCode+val appVersionCode: Int = run {+    val overrideText = (findProperty("versionCodeOverride") as String?)?.trim()+    if (overrideText.isNullOrEmpty()) {+        releaseVersionCode+    } else {+        overrideText.toIntOrNull()?.takeIf { it > 0 }+            ?: throw IllegalStateException(+                "Invalid -PversionCodeOverride='$overrideText': expected a positive integer " ++                    "versionCode. Refusing to fall back silently to $releaseVersionCode."+            )+    }+}  // Adaptive launcher icons are generated at build time from Material Symbols // instead of committing an ic_launcher_foreground.xml per app. Each app declares
email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt b/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.ktindex 45cffc1e8e..efe7ff3b2b 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt@@ -42,6 +42,121 @@ abstract class EmailDatabase : RoomDatabase() {         @Volatile         private var instance: EmailDatabase? = null +        /**+         * v1 → v2 (reconstructed; see below): multi-account keys.+         *+         * History: v1 (f554d13d6, "email: more comprehensive inbox") had only+         * EmailFolder(fullName PK, name, parentFullName, delimiter) and+         * EmailMessage(id+folderName PK, subject, from, date, body, isHtml).+         * The next commit touching the DB, 742082c48 ("email: make loading+         * faster"), jumped straight to version = 3 — version 2 was never+         * committed or shipped, so no device carries a "v2 schema" to match.+         * This step therefore takes the first half of that 1→3 diff: both+         * tables are recreated with `accountEmail` in their primary keys and+         * EmailFolder gains `holdsMessages`. Primary keys cannot be altered,+         * so the tables are rebuilt and rows copied; v1 had no account+         * concept, so existing rows are stamped with the empty account,+         * which matches no account and is repopulated per-account on sync+         * (the 1→3 build of the day wiped these rows via destructive+         * fallback, so preserving them at all is strictly better).+         */+        private val MIGRATION_1_2 = Migration(1, 2) {+            it.execSQL(+                """+                CREATE TABLE IF NOT EXISTS `EmailFolder_new` (+                    `accountEmail` TEXT NOT NULL,+                    `fullName` TEXT NOT NULL,+                    `name` TEXT NOT NULL,+                    `parentFullName` TEXT,+                    `holdsMessages` INTEGER NOT NULL,+                    `delimiter` TEXT NOT NULL,+                    PRIMARY KEY(`accountEmail`, `fullName`)+                )+                """.trimIndent()+            )+            it.execSQL(+                "INSERT INTO `EmailFolder_new` (`accountEmail`, `fullName`, `name`, `parentFullName`, `holdsMessages`, `delimiter`) " ++                    "SELECT '', `fullName`, `name`, `parentFullName`, 1, `delimiter` FROM `EmailFolder`"+            )+            it.execSQL("DROP TABLE IF EXISTS `EmailFolder`")+            it.execSQL("ALTER TABLE `EmailFolder_new` RENAME TO `EmailFolder`")+            it.execSQL(+                """+                CREATE TABLE IF NOT EXISTS `EmailMessage_new` (+                    `accountEmail` TEXT NOT NULL,+                    `folderName` TEXT NOT NULL,+                    `id` INTEGER NOT NULL,+                    `subject` TEXT NOT NULL,+                    `from` TEXT NOT NULL,+                    `date` TEXT NOT NULL,+                    `body` TEXT,+                    `isHtml` INTEGER NOT NULL,+                    PRIMARY KEY(`accountEmail`, `folderName`, `id`)+                )+                """.trimIndent()+            )+            it.execSQL(+                "INSERT INTO `EmailMessage_new` (`accountEmail`, `folderName`, `id`, `subject`, `from`, `date`, `body`, `isHtml`) " ++                    "SELECT '', `folderName`, `id`, `subject`, `from`, `date`, `body`, `isHtml` FROM `EmailMessage`"+            )+            it.execSQL("DROP TABLE IF EXISTS `EmailMessage`")+            it.execSQL("ALTER TABLE `EmailMessage_new` RENAME TO `EmailMessage`")+        }++        /**+         * v2 → v3 (reconstructed): the EmailAccount table, the second half+         * of 742082c48's 1→3 diff (EmailAccount(email PK, accessToken,+         * refreshToken, expiresAt)). Creates the table empty: a v1 install+         * held its single Gmail OAuth identity outside Room, and the tokens+         * are re-established by signing in again.+         */+        private val MIGRATION_2_3 = Migration(2, 3) {+            it.execSQL(+                """+                CREATE TABLE IF NOT EXISTS `EmailAccount` (+                    `email` TEXT NOT NULL,+                    `accessToken` TEXT NOT NULL,+                    `refreshToken` TEXT,+                    `expiresAt` INTEGER NOT NULL,+                    PRIMARY KEY(`email`)+                )+                """.trimIndent()+            )+        }++        /**+         * v3 → v4 (reconstructed): a18f75606 ("email: sending emails", the+         * commit that raised version 3 → 4) added Attachment and the+         * EmailMessage columns serverId, threadId, to, cc, references and+         * hasAttachments; a3f7b10dd then added isRead without a version+         * bump, so every shipped v4 database carries it and MIGRATION_4_5+         * already assumes it. Attachment is created exactly as at v4.+         */+        private val MIGRATION_3_4 = Migration(3, 4) {+            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN serverId TEXT")+            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN threadId TEXT")+            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN `to` TEXT")+            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN cc TEXT")+            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN `references` TEXT")+            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN hasAttachments INTEGER NOT NULL DEFAULT 0")+            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN isRead INTEGER NOT NULL DEFAULT 0")+            it.execSQL(+                """+                CREATE TABLE IF NOT EXISTS `Attachment` (+                    `accountEmail` TEXT NOT NULL,+                    `folderName` TEXT NOT NULL,+                    `messageId` INTEGER NOT NULL,+                    `partId` TEXT NOT NULL,+                    `fileName` TEXT NOT NULL,+                    `mimeType` TEXT NOT NULL,+                    `size` INTEGER NOT NULL,+                    `localUri` TEXT,+                    PRIMARY KEY(`accountEmail`, `messageId`, `partId`)+                )+                """.trimIndent()+            )+        }+         private val MIGRATION_4_5 = Migration(4, 5) {             it.execSQL(                 """@@ -243,6 +358,9 @@ abstract class EmailDatabase : RoomDatabase() {          * irrelevant to Room; kept numeric here for readability.          */         override val migrations: List<Migration> = listOf(+            MIGRATION_1_2,+            MIGRATION_2_3,+            MIGRATION_3_4,             MIGRATION_4_5,             MIGRATION_5_6,             MIGRATION_6_7,
email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.kt b/email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.ktindex c813771a14..dfb2979289 100644--- a/email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.kt+++ b/email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.kt@@ -8,11 +8,35 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue import kotlinx.coroutines.runBlocking -/** W5: the full EmailDatabase migration chain over a v4-shaped database. */+/** W5: the full EmailDatabase migration chain over v1- and v4-shaped databases. */ @org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class) @org.robolectric.annotation.Config(sdk = [34]) class EmailMigrationsW5Test { +    /**+     * The v1 schema exactly as f554d13d6 shipped it: EmailFolder keyed by+     * fullName alone and EmailMessage keyed by (id, folderName), no account+     * concept anywhere.+     */+    private fun openV1(): SQLiteConnection {+        val conn = AndroidSQLiteDriver().open(":memory:")+        conn.execSQL(+            "CREATE TABLE EmailFolder (`fullName` TEXT NOT NULL, `name` TEXT NOT NULL, " ++                "`parentFullName` TEXT, `delimiter` TEXT NOT NULL, PRIMARY KEY(`fullName`))"+        )+        conn.execSQL(+            "CREATE TABLE EmailMessage (`id` INTEGER NOT NULL, `folderName` TEXT NOT NULL, " ++                "`subject` TEXT NOT NULL, `from` TEXT NOT NULL, `date` TEXT NOT NULL, `body` TEXT, " ++                "`isHtml` INTEGER NOT NULL, PRIMARY KEY(`id`, `folderName`))"+        )+        conn.execSQL("INSERT INTO EmailFolder (fullName, name, delimiter) VALUES ('INBOX', 'Inbox', '/')")+        conn.execSQL(+            "INSERT INTO EmailMessage (id, folderName, subject, `from`, date, body, isHtml) " ++                "VALUES (7, 'INBOX', 'Quarterly report', '[email protected]', '2026-01-01', 'numbers', 0)"+        )+        return conn+    }+     private fun openV4(): SQLiteConnection {         val conn = AndroidSQLiteDriver().open(":memory:")         conn.execSQL("CREATE TABLE EmailMessage (accountEmail TEXT NOT NULL, folderName TEXT NOT NULL, id INTEGER NOT NULL, threadId TEXT, subject TEXT, `from` TEXT, body TEXT)")@@ -54,11 +78,60 @@ class EmailMigrationsW5Test {     @Test     fun migrationChainIsCompleteAndOrdered() {         assertEquals(-            (4..22).map { it to it + 1 },+            (1..22).map { it to it + 1 },             EmailDatabase.migrations.map { it.startVersion to it.endVersion }.sortedBy { it.first },         )     } +    @Test+    fun v1DatabaseReachesV4ShapeThroughReconstructedMigrations() {+        val conn = openV1()+        migrate(conn, 1, until = 4)+        // v3 half: account table exists, folder/message keys carry the account.+        assertTrue(tableExists(conn, "EmailAccount"))+        assertTrue(columns(conn, "EmailFolder").containsAll(setOf("accountEmail", "holdsMessages")))+        assertTrue(columns(conn, "EmailMessage").contains("accountEmail"))+        // v4 half (a18f75606 + a3f7b10dd's unversioned isRead): threading+        // columns and Attachment, but nothing the 4->... chain adds later.+        assertTrue(+            columns(conn, "EmailMessage").containsAll(+                setOf("serverId", "threadId", "to", "cc", "references", "hasAttachments", "isRead")+            ),+            columns(conn, "EmailMessage").toString(),+        )+        assertTrue(tableExists(conn, "Attachment"))+        assertTrue(!columns(conn, "EmailMessage").contains("dateMillis"))+        // Rows survive the primary-key rebuild, stamped with the empty account.+        assertEquals(listOf("INBOX"), strings(conn, "SELECT fullName FROM EmailFolder"))+        assertEquals(listOf("Quarterly report"), strings(conn, "SELECT subject FROM EmailMessage"))+        assertEquals(listOf(""), strings(conn, "SELECT accountEmail FROM EmailMessage"))+        conn.close()+    }++    @Test+    fun v1DatabaseUpgradesAllTheWayToV23Shape() {+        val conn = openV1()+        migrate(conn, 1)+        assertTrue(tableExists(conn, "OutboxEntry"))+        assertTrue(tableExists(conn, "DraftEntry"))+        assertTrue(tableExists(conn, "BlockedSender"))+        assertTrue(tableExists(conn, "DeletedUid"))+        assertTrue(tableExists(conn, "EmailMessageFts"))+        assertTrue(tableExists(conn, "Attachment"))+        assertTrue(+            columns(conn, "EmailMessage").containsAll(+                setOf("serverId", "dateMillis", "snoozedUntil", "listUnsubscribe", "peekContent")+            ),+            columns(conn, "EmailMessage").toString(),+        )+        assertTrue(+            columns(conn, "EmailAccount").containsAll(setOf("provider", "username", "allowInsecureCertificates")),+            columns(conn, "EmailAccount").toString(),+        )+        assertEquals(listOf("Quarterly report"), strings(conn, "SELECT subject FROM EmailMessage"))+        conn.close()+    }+     @Test     fun migration21To22CreatesFtsIndexOverExistingMessages() {         val conn = openV4()
health/src/main/java/com/vayunmathur/health/data/Record.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/Record.kt b/health/src/main/java/com/vayunmathur/health/data/Record.ktindex a7b3847215..4548b17480 100644--- a/health/src/main/java/com/vayunmathur/health/data/Record.kt+++ b/health/src/main/java/com/vayunmathur/health/data/Record.kt@@ -395,6 +395,116 @@ abstract class HealthDatabase : RoomDatabase() {     /** Shared constants and helpers for HealthDatabase. */     companion object : com.vayunmathur.library.util.DatabaseMigrations {         override val migrations = listOf(+            // v1 -> v2 (reconstructed): nutrition columns + the type/time index.+            // History: v1 (74d509796, "health: sync to local db first") had only+            // Record(id, index, type, startTime, endTime, value, secondaryValue,+            // primaryKey). 51de2c18a then embedded NutritionData (every field+            // except calories) and 4af82b094 added the (type, startTime, endTime)+            // index, both WITHOUT a version bump, and b091920a9 jumped straight+            // to version = 3 - version 2 was never committed or shipped. This+            // step assigns the nutrition+index half of that diff to 1->2. The+            // table is recreated (copying only the v1-guaranteed columns) so a+            // v1 file that already carries the unversioned nutrition columns+            // does not die on a duplicate-column ALTER; those columns restart+            // NULL, as they do for a plain v1 file.+            Migration(1, 2) {+                it.execSQL(+                    "CREATE TABLE IF NOT EXISTS `Record_new` (`id` TEXT NOT NULL, `index` INTEGER NOT NULL, " ++                        "`type` TEXT NOT NULL, `startTime` INTEGER NOT NULL, `endTime` INTEGER NOT NULL, " ++                        "`value` REAL NOT NULL, `secondaryValue` REAL NOT NULL, `primaryKey` TEXT NOT NULL, " ++                        "PRIMARY KEY(`primaryKey`))"+                )+                listOf(+                    "protein", "carbohydrates", "fat", "fiber", "sugar", "sodium", "biotin", "caffeine",+                    "calcium", "chloride", "cholesterol", "chromium", "copper", "folate", "folicAcid",+                    "iodine", "iron", "magnesium", "manganese", "molybdenum", "monounsaturatedFat",+                    "niacin", "pantothenicAcid", "phosphorus", "polyunsaturatedFat", "potassium",+                    "riboflavin", "saturatedFat", "selenium", "thiamin", "transFat", "unsaturatedFat",+                    "vitaminA", "vitaminB12", "vitaminB6", "vitaminC", "vitaminD", "vitaminE",+                    "vitaminK", "zinc",+                ).forEach { field -> it.execSQL("ALTER TABLE `Record_new` ADD COLUMN `nutrition_$field` REAL") }+                it.execSQL(+                    "INSERT INTO `Record_new` (`id`, `index`, `type`, `startTime`, `endTime`, `value`, " ++                        "`secondaryValue`, `primaryKey`) SELECT `id`, `index`, `type`, `startTime`, " ++                        "`endTime`, `value`, `secondaryValue`, `primaryKey` FROM `Record`"+                )+                it.execSQL("DROP TABLE IF EXISTS `Record`")+                it.execSQL("ALTER TABLE `Record_new` RENAME TO `Record`")+                it.execSQL(+                    "CREATE INDEX IF NOT EXISTS `index_Record_type_startTime_endTime` " ++                        "ON `Record` (`type`, `startTime`, `endTime`)"+                )+            },+            // v2 -> v3 (reconstructed): the rest of b091920a9's 1->3 diff -+            // nutrition_calories, Record.metadata, and the four food-logging+            // tables (Ingredient/Recipe/ServingUnit/RecipeIngredient, with+            // their foreign keys and indices) exactly as created at v3.+            Migration(2, 3) {+                it.execSQL("ALTER TABLE Record ADD COLUMN nutrition_calories REAL")+                it.execSQL("ALTER TABLE Record ADD COLUMN metadata TEXT")+                val nutrition = listOf(+                    "protein", "carbohydrates", "fat", "fiber", "sugar", "sodium", "biotin", "caffeine",+                    "calcium", "chloride", "cholesterol", "chromium", "copper", "folate", "folicAcid",+                    "iodine", "iron", "magnesium", "manganese", "molybdenum", "monounsaturatedFat",+                    "niacin", "pantothenicAcid", "phosphorus", "polyunsaturatedFat", "potassium",+                    "riboflavin", "saturatedFat", "selenium", "thiamin", "transFat", "unsaturatedFat",+                    "vitaminA", "vitaminB12", "vitaminB6", "vitaminC", "vitaminD", "vitaminE",+                    "vitaminK", "zinc", "calories",+                ).joinToString(", ") { field -> "`nutrition_$field` REAL NOT NULL" }+                it.execSQL(+                    "CREATE TABLE IF NOT EXISTS `Ingredient` (`id` TEXT NOT NULL, `originalName` TEXT NOT NULL, " ++                        "`customName` TEXT, `isRecipe` INTEGER NOT NULL, $nutrition, PRIMARY KEY(`id`))"+                )+                it.execSQL(+                    "CREATE TABLE IF NOT EXISTS `Recipe` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, " ++                        "PRIMARY KEY(`id`))"+                )+                it.execSQL(+                    "CREATE TABLE IF NOT EXISTS `ServingUnit` (`id` TEXT NOT NULL, `ingredientId` TEXT, " ++                        "`recipeId` TEXT, `name` TEXT NOT NULL, `grams` REAL NOT NULL, PRIMARY KEY(`id`), " ++                        "FOREIGN KEY(`ingredientId`) REFERENCES `Ingredient`(`id`) ON UPDATE NO ACTION " ++                        "ON DELETE CASCADE , FOREIGN KEY(`recipeId`) REFERENCES `Recipe`(`id`) " ++                        "ON UPDATE NO ACTION ON DELETE CASCADE )"+                )+                it.execSQL(+                    "CREATE INDEX IF NOT EXISTS `index_ServingUnit_ingredientId` ON `ServingUnit` (`ingredientId`)"+                )+                it.execSQL(+                    "CREATE INDEX IF NOT EXISTS `index_ServingUnit_recipeId` ON `ServingUnit` (`recipeId`)"+                )+                it.execSQL(+                    "CREATE TABLE IF NOT EXISTS `RecipeIngredient` (`id` TEXT NOT NULL, `recipeId` TEXT NOT NULL, " ++                        "`ingredientId` TEXT NOT NULL, `quantity` REAL NOT NULL, `unitId` TEXT NOT NULL, " ++                        "PRIMARY KEY(`id`), FOREIGN KEY(`recipeId`) REFERENCES `Recipe`(`id`) " ++                        "ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`ingredientId`) " ++                        "REFERENCES `Ingredient`(`id`) ON UPDATE NO ACTION ON DELETE RESTRICT , " ++                        "FOREIGN KEY(`unitId`) REFERENCES `ServingUnit`(`id`) ON UPDATE NO ACTION " ++                        "ON DELETE RESTRICT )"+                )+                it.execSQL(+                    "CREATE INDEX IF NOT EXISTS `index_RecipeIngredient_recipeId` " ++                        "ON `RecipeIngredient` (`recipeId`)"+                )+                it.execSQL(+                    "CREATE INDEX IF NOT EXISTS `index_RecipeIngredient_ingredientId` " ++                        "ON `RecipeIngredient` (`ingredientId`)"+                )+                it.execSQL(+                    "CREATE INDEX IF NOT EXISTS `index_RecipeIngredient_unitId` ON `RecipeIngredient` (`unitId`)"+                )+            },+            // v3 -> v4 (reconstructed): a86f12f81 ("health: fix sleep page+            // layout", version 3 -> 4) embedded SleepData in Record. The+            // embedded object is nullable, so every sleep column is nullable.+            Migration(3, 4) {+                listOf(+                    "awakeDurationMillis" to "INTEGER", "remDurationMillis" to "INTEGER",+                    "lightDurationMillis" to "INTEGER", "deepDurationMillis" to "INTEGER",+                    "unknownDurationMillis" to "INTEGER", "stagesJson" to "TEXT",+                ).forEach { (field, type) ->+                    it.execSQL("ALTER TABLE Record ADD COLUMN `sleep_$field` $type")+                }+            },             Migration(4, 5) {                 it.execSQL("ALTER TABLE Record ADD COLUMN exercise_exerciseType INTEGER NOT NULL DEFAULT 0")                 it.execSQL("ALTER TABLE Record ADD COLUMN exercise_title TEXT")
health/src/test/java/com/vayunmathur/health/data/MigrationsTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/data/MigrationsTest.kt b/health/src/test/java/com/vayunmathur/health/data/MigrationsTest.ktindex cc9c8bfd0f..4c3f443200 100644--- a/health/src/test/java/com/vayunmathur/health/data/MigrationsTest.kt+++ b/health/src/test/java/com/vayunmathur/health/data/MigrationsTest.kt@@ -70,7 +70,9 @@ class MigrationsTest {         )         val connection = FrameworkConnection(raw)         runBlocking {-            HealthDatabase.migrations.forEach { migration -> migration.migrate(connection) }+            HealthDatabase.migrations+                .filter { it.startVersion >= 4 }+                .forEach { migration -> migration.migrate(connection) }         }          // Tables the chain must have created by v12.@@ -93,13 +95,71 @@ class MigrationsTest {     }      @Test-    fun `migration chain spans version 4 to 12 without gaps`() {+    fun `migration chain spans version 1 to 12 without gaps`() {         val migrations = HealthDatabase.migrations         val sorted = migrations.sortedBy { it.startVersion }-        assertTrue(sorted.first().startVersion == 4)+        assertTrue(sorted.first().startVersion == 1)         assertTrue(sorted.last().endVersion == 12)         for (i in 0 until sorted.size - 1) {             assertTrue(sorted[i].endVersion == sorted[i + 1].startVersion, "gap after version ${sorted[i].endVersion}")         }     }++    @Test+    fun `v1 database upgrades to v12 shape and keeps its rows`() {+        val file = File(context.cacheDir, "migration-v1-probe.db")+        file.delete()+        val raw = SQLiteDatabase.openOrCreateDatabase(file, null)+        // The v1 schema exactly as 74d509796 shipped it: Record only, no+        // embedded nutrition/sleep/exercise columns and no index.+        raw.execSQL(+            "CREATE TABLE Record (id TEXT NOT NULL, `index` INTEGER NOT NULL, type TEXT NOT NULL, " ++                "startTime INTEGER NOT NULL, endTime INTEGER NOT NULL, value REAL NOT NULL, " ++                "secondaryValue REAL NOT NULL, primaryKey TEXT NOT NULL PRIMARY KEY)"+        )+        raw.execSQL(+            "INSERT INTO Record (id, `index`, type, startTime, endTime, value, secondaryValue, primaryKey) " ++                "VALUES ('steps-1', 0, 'Steps', 1000, 2000, 42.0, 0.0, 'steps-1-0')"+        )+        val connection = FrameworkConnection(raw)+        runBlocking {+            HealthDatabase.migrations+                .sortedBy { it.startVersion }+                .forEach { migration -> migration.migrate(connection) }+        }++        val tables = mutableSetOf<String>()+        raw.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null).use { cursor ->+            while (cursor.moveToNext()) tables.add(cursor.getString(0))+        }+        // Food-logging tables from 2->3, medical tables from 5->...->11->12.+        assertTrue("Ingredient" in tables, "ingredient table created: $tables")+        assertTrue("RecipeIngredient" in tables, "recipe ingredient table created")+        assertTrue("VaccinationEntry" in tables, "vaccination table created")+        assertTrue("PendingMirror" in tables, "pending mirror table created")++        val columns = mutableSetOf<String>()+        raw.rawQuery("PRAGMA table_info(Record)", null).use { cursor ->+            while (cursor.moveToNext()) columns.add(cursor.getString(1))+        }+        assertTrue("nutrition_protein" in columns, "nutrition columns added: $columns")+        assertTrue("nutrition_calories" in columns, "calories column added by 2->3")+        assertTrue("metadata" in columns, "metadata column added by 2->3")+        assertTrue("sleep_stagesJson" in columns, "sleep columns added by 3->4")+        assertTrue("exercise_title" in columns, "exercise columns added by 4->5")++        val indices = mutableSetOf<String>()+        raw.rawQuery("SELECT name FROM sqlite_master WHERE type='index'", null).use { cursor ->+            while (cursor.moveToNext()) indices.add(cursor.getString(0))+        }+        assertTrue("index_Record_type_startTime_endTime" in indices, "record index created: $indices")++        // The pre-migration row survives the 1->2 table rebuild.+        raw.rawQuery("SELECT value FROM Record WHERE primaryKey = 'steps-1-0'", null).use { cursor ->+            assertTrue(cursor.moveToFirst(), "v1 row preserved")+            assertTrue(cursor.getDouble(0) == 42.0, "v1 row value preserved")+        }+        raw.close()+        file.delete()+    } }