My application is in release mode and I am using room database and my previous database version was 2 with fallback to destructive migration enabled.
@Database(entities = {
User.class,ApplicationSetting.class},
version = 2,
exportSchema = false)
abstract public class DatabaseContext extends RoomDatabase {
private static final Object sLock = new Object();
private static DatabaseContext INSTANCE;
public static String DATABASE_NAME = AppConstants.DATABASE_NAME;
public static DatabaseContext getInstance(Context context) {
synchronized (sLock) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
DatabaseContext.class, DATABASE_NAME)
.fallbackToDestructiveMigration()
.build();
}
return INSTANCE;
}
}
I have added a new column in table and change version to 3. Now I want to provide migration from version 2 to version 3 so that data not lost. But I am confused because in version 2 I have enabled fallback destructive migration, and now in version 3 I want to keep user data and remove fallback destruction.
How can I achieve this?
More precisely, every time you alter your schema by adding, removing or modifying tables, you have to increase the database version number and update your implementation of SQLiteOpenHelper. onUpgrade method. This is how you tell SQLite what it needs to do when going from an old version to a new version.
Export schemas Room can export your database's schema information into a JSON file at compile time. To export the schema, set the room. schemaLocation annotation processor argument via a [ CommandLineArgumentProvider ][15]{:. external} in app/build. gradle file.
Room is what's called an ORM (Object Relational Mapping) library, which as the name implies, maps the tables in a relational database to objects usable in Kotlin code.
A migration can handle more than 1 version (e.g. if you have a faster path to choose when going version 3 to 5 without going to version 4). If Room opens a database at version 3 and latest version is >= 5, Room will use the migration object that can migrate from 3 to 5 instead of 3 to 4 and 4 to 5.
When using fallbackToDestructiveMigration, it only destroys (drops the tables and recreates them) if there is not a defined migration for the migration so you could add a 2 to 3 Migration.
That is, if a Migration is provided then it is used and bypasses fallback/destruction.
An alternative, which is recommended, is to use fallbacktodestructivemigrationfrom, this can be used to define specific missing migrations where fallback is to be applied.
e.g. you could use .fallbackToDestructiveMigrationFrom(1,7)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With