Detect if Room Destructive Migration is Performed

Viewed 389

If I run a Room migration with destructive fallback enabled:

Room.databaseBuilder(applicationContext, MyDb::class.java, "database-name")
        .fallbackToDestructiveMigration()
        .build()

Is there a way to determine if the destructive migration was triggered vs if the migration completed successfully? I'd like to be able to log some information for tracking.

1 Answers

You can use use Room Callback and add it to your database, it has below methods: where you can use onDestructiveMigration

Here is a sample example

@Database(entities = {.....}, version = 1)

public abstract class MyDatabase extends RoomDatabase {

    private static final String DATABASE_NAME = “myDatabaseName.db”;

    private static final Object LOCK = new Object();

    private static volatile MyDatabase instance; 

    public static MyDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (MyDatabase.class) {
                if (INSTANCE == null) {
                    // Create database here.
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            MyDatabase.class, DATABASE_NAME)
                            .fallbackToDestructiveMigration()
                            .addCallback(mCallback) // Trigger the callback
                            .build();
                }
            }
        }
        return INSTANCE;
    }


    /*
     * Callback when database is created & when it’s opened
     * */
    static RoomDatabase.Callback mCallback = new Callback() {
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) { // Callback when database is first-time created or recreated after destruction  
            super.onCreate(db);
            Log.i("LOG_TAG", “Database is created”);
        }

        @Override
        public void onOpen(@NonNull SupportSQLiteDatabase db) { // callback when the activity is opened 
            super.onOpen(db); 
            Log.i("LOG_TAG", “Database is opened”);  
        }
    };


        @Override
        public void onDestructiveMigration(@NonNull SupportSQLiteDatabase db) { // Called after the database was destructively migrated
            super.onDestructiveMigration(db);
            Log.i(LOG_TAG, “Database is destructed”);
        }

}
Related