Search code examples
iosswiftrealm

Conditionally delete schema instead of migrating


Realm has two approaches to handling schema changes:

  1. Run a migration block, or
  2. Drop the schema

Option 2 is not desired in our case, because we have a lot of data, our schema version is tied to the build number, and we release frequently.

So we use option 1. But some cases, it would be handy to run option 2 instead of migrating if the old schema version is too old. Is this possible?

Use case 1: I want to rename an Object class, but I don't want to risk botching the migration (which is easy to do). I'm fine with dropping the schema for users migrating from the version before the rename, but I don't want to keep on dropping the schema for subsequent migrations.

Use case 2: I've been writing migrations since 2016 (!), but I only really care about running migrations (rather than dropping the schema) for users who update regularly. So I'd like to maintain up to a few months' worth of migrations, and just drop the schema for anyone upgrading from before then.

I could probably hack together a workaround if I could figure out how to access my realm's old schema version before applying the configuration, but it seems like the only space in which Realm lets me see the schema version is in the migration block, and it doesn't seem like it's possible to decide to drop the schema when you're already running a migration.


Solution

  • This doesn't exactly answer the question but may lead to more complete solution.

    If you need to retrieve the schema version of a realm file, here's how to do it (for the default config)

    let x = try! schemaVersionAtURL(Realm.Configuration.defaultConfiguration.fileURL!)
    

    and that documented in the API under Functions: schemaVersionAtURL(_:encryptionKey:)