Search code examples
node.jsloopbackjsloopback4

How to do database migrations in LoopBack 4


When the application is in the production stage and it's needed to do changes in tables, I guess doing automigrate is out of the question since it deletes all the data of the tables being changed. Doing autoupdate would be appropriate, but I'm concerned about scalability. Is it safe to rely on autoupdate on a product in the production stage? One advantage of Rails-like migrations is keeping a record of changes to ensure that every instance or environment of the database will be in the exact same schema. Is there any well-developed way to achieve this in LoopBack?

Not only because of this but if it's needed to normalize data during a column change, how would it be done in LoopBack? I didn't see support for this kind of migration.


Solution

  • Hello from the LoopBack team 👋

    Doing autoupdate would be appropriate, but I'm concerned about scalability. Is it safe to rely on autoupdate on a product in the production stage? One advantage of Rails-like migrations is keeping a record of changes to ensure that every instance or environment of the database will be in the exact same schema. Is there any well-developed way to achieve this in LoopBack?

    You are right that running auto-magic database migration (as the one provided by autoupdate) on live production data is risky. We are discussing a more robust framework in the GitHub issue loopback-next#487, feel free to join the effort! One of the community members mentioned a 3rd-party package loopback4-migration, you may want to check it out.

    Not only because of this but if it's needed to normalize data during a column change, how would it be done in LoopBack? I didn't see support for this kind of migration.

    I am afraid the current automigrate/autoupdate design does not support custom data transformations as part of database migration. A possible option is to overwrite app.migrateSchema to run additional database command before or after the automated migration is executed.

    class MyApplication extends RepositoryMixin(RestApplication) {
     async migrateSchema(options: SchemaMigrationOptions = {}): Promise<void> {
       // add code to normalize data before column definitions are changed
       await super.migrateSchema(options);
       // add code to normalize data after column definitions were changed
      }
    }