realm / realm-js

Realm is a mobile database: an alternative to SQLite & key-value stores
https://realm.io
Apache License 2.0
5.62k stars 558 forks source link

What is best practice to migration? #6241

Closed devethan closed 2 months ago

devethan commented 6 months ago

Problem

Hi, I'd like to know what is YOUR the best practice to write codes for migration statement.

I've manageed to that like below codes,

export const CURRENT_REALM_SCHEMA_VERSION = 6;

export function onMigration( oldRealm: Realm, newRealm: Realm ) {
   if( oldRealm.schemaVersion < CURRENT_REALM_SCHEMA_VERSION ) {
      switch( oldRealm.schemaVersion ) {
         case 0:
            // do
         case 1:
            // do
         case 2:
            // do
         ...
         case 5:
            // do
            break;
         default:
            throw new Error('Cannot match schemaVersion for this migration')
      }
   }
}

If the user install the version which has schemaVersion 2 and then update to the version has schemaVersion 6, the migration statement will executed from case 2 to 5.

Solution

No response

Alternatives

No response

How important is this improvement for you?

Feature would mainly be used with

kneth commented 6 months ago

In most cases, schema migration can happen automatically. At least if you have simple schema changes, and you don't need to change any objects.

In your case, I would change the code to

export const CURRENT_REALM_SCHEMA_VERSION = 6;

export function onMigration( oldRealm: Realm, newRealm: Realm ) {
  const oldSchemaVersion = oldRealm.schemaVersion;
  const migration = [
    () => { /* do */ },
    () => { /* do */ },
  ];
  for (let ver = oldSchemaVersion; ver < CURRENT_REALM_SCHEMA_VERSION; ver++) {
    migration[ver]();
  }
};

Documentation on how to change an object model might be useful.

ansarizafar commented 6 months ago

@kneth Could you please explain/list schema changes that require migration and what are the schema changes that trigger automatic migration?

nirinchev commented 2 months ago

The topic of migrations is covered in our docs. If you have questions or suggestions for additional content there, you can use the "Rate this page" widget and explain your request.