Should Sequelize migrations update model files?
Asked Answered
R

1

17

Are Sequelize migrations supposed to keep your model files in line with your database?

I used the sequelize cli to bootstrap a simple project and create a model node_modules/.bin/sequelize model:generate --name User --attributes email:string. I migrated this with no issue.

Then I created the following migration file to add a notNull constraint to the user email attribute.

updateEmail migration

const models = require("../models")

module.exports = {
  up: (queryInterface, Sequelize) => {
      return queryInterface.changeColumn(models.User.tableName, 'email',{
        type: Sequelize.STRING,
        allowNull: false,
      });
    },

  down: (queryInterface, Sequelize) => {
      return queryInterface.changeColumn(models.User.tableName, 'email',{
        type: Sequelize.STRING,
      });
    },
};

The database schema updated to add the constraint but the model file did not. Is there a way to automatically update the model files as you make migrations?

Renie answered 7/3, 2018 at 20:56 Comment(0)
H
25

Is there a way to automatically update the model files as you make migrations?

Unfortunately, no. There is no level of synchronization between sequelize models and migration except for their initial creation from sequelize model:create. However, the workflow suggested in this question is that updates should propagate from migrations to models. This confuses me slightly, as typically the migrations are to be auto-generated from changes to the models, not necessarily vice-versa.

There have been on-going open issues tracking these features that you may find helpful to subscribe to:

Community Suggestions/Solutions:

Refer to https://mcmap.net/q/167772/-how-to-auto-generate-migrations-with-sequelize-cli-from-sequelize-models As suggested, a workaround is to re-create models using sequelize-cli when introducing simple changes. However, there are clear limitations to this methodology as many configurations are not possible to define from the cli such as associations.

Additionally, an npm package sequelize-auto-migrations does exist that does provide support for generating migrations, however it doesn't seem to be an overly active project.

Conclusion:

Should Sequelize migrations update model files?

Sequelize/sequelize-cli does not yet support this feature.

Should an ORMs create tools to auto generate migrations? Yes, this is desired functionality as otherwise the developers are forced to violate principles such as DRY and manage the same logic in different files.

Hyperkinesia answered 12/4, 2018 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.