Manohar
Manohar

Reputation: 23394

Room : How migration with fallbackToDestructiveMigrationFrom() works?

I have an app with room database version 1 up and running . At version 2 , I want to destroy all the tables and recreate schema instead of writing Migration(1, 2) logic . So I read the docs and found method .fallbackToDestructiveMigrationFrom() . So if I pass 2 in argument here then I think it should recreate all tables at version 2 . The thing I cannot under stand is In docs they mentioned a note

Note: No versions passed to this method may also exist as either starting or ending versions in the Migrations provided to addMigrations(Migration). If a version passed to this method is found as a starting or ending version in a Migration, an exception will be thrown

Does this mean If I upgrade database version to 3 and there are some schema changes , If I write Migration(2, 3) it will throw an exception ?

Upvotes: 3

Views: 1404

Answers (2)

Manohar
Manohar

Reputation: 23394

Every thing I said in the Question was right except that I had to pass 1 as argument to .fallbackToDestructiveMigrationFrom() .

.fallbackToDestructiveMigrationFrom(1) would mean to destroy database if the old database version is 1 . Its not like destroy database if the current version is 1 . This was the confusion in my case .

Credit to Itamar Kerbel for the clarification in the chat .

Upvotes: 4

Itamar Kerbel
Itamar Kerbel

Reputation: 2568

This is correct if you pass .fallbackToDestructiveMigrationFrom(3) and also provide Migration(2, 3), Room will throw an exception.

That said it does sound like what you really want to do is use fallbackToDestructiveMigration(). In this case, it will do exactly what you asked:

  1. Try to upgrade from version X (installed on the device) to version Y
  2. If there is no Migration(X, Y) it will destroy the schema and data and create a new one for version Y.

In this way, you should not get an exception. I think that is what you were asking for...

Upvotes: 1

Related Questions