D Deshmane
D Deshmane

Reputation: 1265

Migrations with SequelizeJS and CLI

Currently I have started working on NODE JS where I am using the SEQUELIZE ORM. The Sequelize does support the migrations using sequelize-cli, but the documentation does not explain every details around how it should be used of migrations. I want to know if following are possible using Sequelize CLI. The following points are important considering the PROD deployment

  1. Auto generate migration file by looking at model
  2. Auto generate migration file based new changes made to model
  3. Generate the SQL script of migration so that we can run this on PROD
  4. Environment specific migrations(Dev,Stage,Prod

I have gone through the documentation but it does not explian any of the point mentioned above. Please help me with this, I

Upvotes: 1

Views: 1492

Answers (1)

joshua.paling
joshua.paling

Reputation: 13952

The idea with using migrations is that they are the king of your database. They are the only thing that changes your database schema, and the only way you should be changing your database schema is by simply running the migrations.

In answer to your questions:

1. Auto generate migration file by looking at model

Don't. Manually generate a migration. If you're changing the columns of a particular table, generate the migration first, then modify the corresponding model next. Migrations are king of the database. Models come second.

2. Auto generate migration file based new changes made to model

Don't. Same as above.

3. Generate the SQL script of migration so that we can run this on PROD

Don't. You should just be able to run the migrations themselves directly on production, connecting to the production database, just the same as you'd run them in dev, with sequelize db:migrate. Your deployment script should automatically run sequelize db:migrate on the production database every time you push new code to production.

4. Environment specific migrations(Dev,Stage,Prod)

Definitely don't. Every migration should run in every environment. Your database should have the same schema regardless of the environment.

Update: Here's an example migartion that works (both running up and down) to add a new boolean column:

'use strict';

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.addColumn(
      'my_table',
      'my_new_column',
      {
        type: Sequelize.BOOLEAN,
      }
    )
  },

  down: function (queryInterface, Sequelize) {
    return queryInterface.removeColumn('my_table', 'my_new_column')
  }
};

Upvotes: 4

Related Questions