Search code examples
migrationsequelize.js

Sequelize - Rename column with index & constraint


I want create migration with Sequelize to rename column with camelCase to have a database with column in snake_case.

I use Sequelize to create migration and use migration.

module.exports = {
  up: function(queryInterface, Sequelize) {
      return queryInterface.renameColumn('my_some_table', 'totoId', 'toto_id');
  },

  down: function(queryInterface, Sequelize) {
      //
  }
};

But... I have a unique constraint on this column (totoId) and name column, named my_some_table_name_totoId_uindex, and I also have an index on this column (totoId).

How I can force renaming column who have a unique constraint and one index?


Solution

  • You have to drop all the constraints, rename the column and then add the constraints back. With a single constraint on totoId it would look something like this:

    // 1) drop constraint
    queryInterface.removeConstraint('my_some_table', 'my_constraint');
    
    // 2) rename column
    queryInterface.renameColumn('my_some_table', 'totoId', 'toto_id');
    
    // 3) add constraint back
    queryInterface.addConstraint('my_some_table', ['toto_id'], {
        type: 'unique',
        name: 'my_constraint'
    });
    

    Remember that migrations should be atomic operations. So you should create 3 migrations in that order. Or even better, as @Santilli pointed out in the comments, you could create a transaction. This will prevent from any change to be applied if one of the queries fails:

    return queryInterface.sequelize.transaction(async (transaction) => {
      await queryInterface.removeConstraint("my_some_table", "my_constraint", {
        transaction,
      });
      await queryInterface.renameColumn("my_some_table", "totoId", "toto_id", {
        transaction,
      });
      await queryInterface.addConstraint("my_some_table", ["toto_id"], {
        type: "unique",
        name: "my_constraint",
        transaction,
      });
    });
    

    Also, remember to create a transaction to revert the changes in the down function.