Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 an unique constraint on this column (totoId) and name column, named my_some_table_name_totoId_uindex, and I have too an index on this column (totoId).

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

like image 642
pirmax Avatar asked Dec 11 '17 14:12

pirmax


1 Answers

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.

like image 153
Omar Avatar answered Sep 20 '22 12:09

Omar