Add DB migration

Signed-off-by: Andy Scherzinger <info@andy-scherzinger.de>
This commit is contained in:
Andy Scherzinger 2023-09-21 22:48:53 +02:00
parent 3c20251047
commit 079e527f21
No known key found for this signature in database
GPG key ID: 6CADC7E3523C308B
2 changed files with 33 additions and 1 deletions

View file

@ -40,6 +40,13 @@ object Migrations {
} }
} }
val MIGRATION_8_9 = object : Migration(8, 9) {
override fun migrate(database: SupportSQLiteDatabase) {
Log.i("Migrations", "Migrating 8 to 9")
migrateToDualPrimaryKeyArbitraryStorage(database)
}
}
fun migrateToRoom(database: SupportSQLiteDatabase) { fun migrateToRoom(database: SupportSQLiteDatabase) {
database.execSQL( database.execSQL(
"CREATE TABLE User_new (" + "CREATE TABLE User_new (" +
@ -92,4 +99,29 @@ object Migrations {
database.execSQL("ALTER TABLE User_new RENAME TO User") database.execSQL("ALTER TABLE User_new RENAME TO User")
database.execSQL("ALTER TABLE ArbitraryStorage_new RENAME TO ArbitraryStorage") database.execSQL("ALTER TABLE ArbitraryStorage_new RENAME TO ArbitraryStorage")
} }
fun migrateToDualPrimaryKeyArbitraryStorage(database: SupportSQLiteDatabase) {
database.execSQL(
"CREATE TABLE ArbitraryStorage_dualPK (" +
"accountIdentifier INTEGER NOT NULL, " +
"\"key\" TEXT NOT NULL, " +
"object TEXT, " +
"value TEXT, " +
"PRIMARY KEY(accountIdentifier, \"key\")" +
")"
)
// Copy the data
database.execSQL(
"INSERT INTO ArbitraryStorage_dualPK (" +
"accountIdentifier, \"key\", object, value) " +
"SELECT " +
"accountIdentifier, \"key\", object, value " +
"FROM ArbitraryStorage"
)
// Remove the old table
database.execSQL("DROP TABLE ArbitraryStorage")
// Change the table name to the correct one
database.execSQL("ALTER TABLE ArbitraryStorage_dualPK RENAME TO ArbitraryStorage")
}
} }

View file

@ -97,7 +97,7 @@ abstract class TalkDatabase : RoomDatabase() {
.databaseBuilder(context.applicationContext, TalkDatabase::class.java, dbName) .databaseBuilder(context.applicationContext, TalkDatabase::class.java, dbName)
// comment out openHelperFactory to view the database entries in Android Studio for debugging // comment out openHelperFactory to view the database entries in Android Studio for debugging
.openHelperFactory(factory) .openHelperFactory(factory)
.addMigrations(Migrations.MIGRATION_6_8, Migrations.MIGRATION_7_8) .addMigrations(Migrations.MIGRATION_6_8, Migrations.MIGRATION_7_8, Migrations.MIGRATION_8_9)
.allowMainThreadQueries() .allowMainThreadQueries()
.addCallback( .addCallback(
object : RoomDatabase.Callback() { object : RoomDatabase.Callback() {