Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Room Database schema update without data loss

I have developed one application in Android using Kotlin and it is available on playstore. I have used Room database to store the values. I have following queries:

  1. Database schema is changed now, How to I need to handle that. I referred to below tutorial but still not clear to handle the schema change in Migration. Visit https://developer.android.com/training/data-storage/room/migrating-db-versions.html

  2. How can I test my current application with playstore version?

Thanks for the help in advance.

like image 849
Rajiv Ranjan Avatar asked Oct 15 '22 14:10

Rajiv Ranjan


1 Answers

That's quite a complex question but basically you have 2 strategies:

  • fallbackToDestructiveMigration -> simple to implement but your users will lose their data once the app is updated
  • Provide a Migrationstrategy (preferable)

Case 1 - fallbackToDestructiveMigration

In your database initialization, simply invoke fallbackToDestructiveMigration on your database builder:

database = Room.databaseBuilder(context.getApplicationContext(),
                        UsersDatabase.class, "Sample.db")
                .fallbackToDestructiveMigration()
                .build();

In this case, since you have updated your database version (suppose from version 1 to version 2) Room can't find any migration strategy, so it will fallback to distructive migration, tables are dropped.

Case 2 - Smart migration

Suppose you have a table called "Users" and suppose you added a column to this table in version 2 of your database. Let's call this column "user_score" You should implement migrate interface of Migration class in order to update your "Users version 1" schema to "Users version 2" schema. To do so, you need an alter table, you can write it directly inside the migrate method:

static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(SupportSQLiteDatabase database) {
            // Your migration strategy here
            database.execSQL("ALTER TABLE Users ADD COLUMN user_score INTEGER")
        }
    };
database =  Room.databaseBuilder(context.getApplicationContext(),
        UsersDatabase.class, "Sample.db")
        .addMigrations(MIGRATION_1_2)
        .build();

More references here :

  • https://medium.com/androiddevelopers/understanding-migrations-with-room-f01e04b07929
  • https://medium.com/@elye.project/android-sqlite-database-migration-b9ad47811d34
like image 184
Nicola Gallazzi Avatar answered Oct 19 '22 01:10

Nicola Gallazzi