realm / realm-java

Realm is a mobile database: a replacement for SQLite & ORMs
http://realm.io
Apache License 2.0
11.45k stars 1.75k forks source link

FallbackToDestructiveMigration feature #7786

Open Khudoyshukur opened 1 year ago

Khudoyshukur commented 1 year ago

When we are using a Room database, we are allowed to use .fallbackToDestructiveMigration() option. Setting this option, Room tries to execute the migrations we specified. If any error occurs, Room will delete the schema.

How can we achieve this with Realm. .deleteRealmIfMigrationNeeded() is just dropping the database. It just ignores the migration.

Khudoyshukur commented 1 year ago

I found different workarounds for this in StackOverFlow. But I am gonna get the right way of doing it from the developers

cmelchior commented 1 year ago

Hi @Khudoyshukur

We don't have explicit support for it right now, but you could just catch the RealmMigrationNeededException and delete the file in that case, i.e. something like this:

val config = RealmConfiguration.Builder()
  .schemaVersion(1)
  .migration(MyMigration())
  .build()

val realm = try {
    Realm.getInstance(config)
} catch(ex: RealmMigrationNeededException) {
    Realm.deleteRealm(config)
    Realm.open(config)
}