package com.example.data.local import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import com.example.BuildConfig import com.squareup.moshi.Moshi import com.squareup.moshi.Types @Database( entities = [LocalMealEntity::class, LocalCustomFoodEntity::class, LocalRecipeEntity::class], version = 4, exportSchema = false ) @TypeConverters(RoomConverters::class) abstract class AppDatabase : RoomDatabase() { abstract fun mealDao(): LocalMealDao companion object { @Volatile private var INSTANCE: AppDatabase? = null val MIGRATION_1_2 = object : Migration(1, 2) { override fun migrate(db: SupportSQLiteDatabase) { // Version 1 to 2 schema adjustments if needed } } val MIGRATION_2_3 = object : Migration(2, 3) { override fun migrate(db: SupportSQLiteDatabase) { // 1. Create new table matching RoomConverters JSON schema db.execSQL( """ CREATE TABLE IF NOT EXISTS `local_meals_new` ( `id` TEXT NOT NULL PRIMARY KEY, `userId` TEXT NOT NULL, `mealType` TEXT NOT NULL, `mealTimestamp` INTEGER NOT NULL, `hungerBefore` INTEGER NOT NULL, `satietyAfter` INTEGER NOT NULL, `note` TEXT NOT NULL, `foodItems` TEXT NOT NULL, `photoUris` TEXT NOT NULL, `updatedAt` INTEGER NOT NULL ) """.trimIndent() ) // 2. Migrate existing delimiter-separated data to Moshi JSON arrays val moshi = Moshi.Builder().build() val listType = Types.newParameterizedType(List::class.java, String::class.java) val adapter = moshi.adapter>(listType) val cursor = db.query("SELECT id, userId, mealType, mealTimestamp, hungerBefore, satietyAfter, note, foodItemsJoined, photoUrisJoined, updatedAt FROM local_meals") while (cursor.moveToNext()) { val id = cursor.getString(0) val userId = cursor.getString(1) val mealType = cursor.getString(2) val mealTimestamp = cursor.getLong(3) val hungerBefore = cursor.getInt(4) val satietyAfter = cursor.getInt(5) val note = cursor.getString(6) val foodItemsJoined = cursor.getString(7) ?: "" val photoUrisJoined = cursor.getString(8) ?: "" val updatedAt = cursor.getLong(9) val foodList = if (foodItemsJoined.isNotBlank()) { foodItemsJoined.split("###").filter { it.isNotBlank() } } else emptyList() val photoList = if (photoUrisJoined.isNotBlank()) { photoUrisJoined.split("|||").filter { it.isNotBlank() } } else emptyList() val foodJson = adapter.toJson(foodList) val photoJson = adapter.toJson(photoList) db.execSQL( "INSERT INTO local_meals_new (id, userId, mealType, mealTimestamp, hungerBefore, satietyAfter, note, foodItems, photoUris, updatedAt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", arrayOf(id, userId, mealType, mealTimestamp, hungerBefore, satietyAfter, note, foodJson, photoJson, updatedAt) ) } cursor.close() // 3. Drop legacy table and rename new table db.execSQL("DROP TABLE local_meals") db.execSQL("ALTER TABLE local_meals_new RENAME TO local_meals") } } val MIGRATION_3_4 = object : Migration(3, 4) { override fun migrate(db: SupportSQLiteDatabase) { db.execSQL( "ALTER TABLE `local_custom_foods` ADD COLUMN `category` TEXT NOT NULL DEFAULT ''" ) db.execSQL( """ CREATE TABLE IF NOT EXISTS `local_recipes` ( `id` TEXT NOT NULL PRIMARY KEY, `title` TEXT NOT NULL, `categoryTag` TEXT NOT NULL, `prepTimeMinutes` INTEGER NOT NULL, `servings` INTEGER NOT NULL, `ingredients` TEXT NOT NULL, `steps` TEXT NOT NULL, `notes` TEXT NOT NULL, `photoUri` TEXT, `updatedAt` INTEGER NOT NULL ) """.trimIndent() ) } } fun getInstance(context: Context): AppDatabase { return INSTANCE ?: synchronized(this) { INSTANCE ?: buildDatabase(context.applicationContext).also { INSTANCE = it } } } private fun buildDatabase(appContext: Context): AppDatabase { val builder = Room.databaseBuilder( appContext, AppDatabase::class.java, "satiea_local.db" ).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4) // Destructive migration is only permitted on debug builds if (BuildConfig.DEBUG) { builder.fallbackToDestructiveMigrationOnDowngrade(true) } return builder.build() } } }