Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove constraints in sequelize migration

I'm adding a unique constraint in a migration via the migrations.changeColumn function.

Adding the constraint works, but since you need to provide a “backwards migration“, removing it the same way does not. It doesn't give any errors when migrating backwards, but again applying the forward migration results in Possibly unhandled SequelizeDatabaseError: relation "myAttribute_unique_idx" already exists.

(The used database is postgres)

module.exports = {
  up: function (migration, DataTypes, done) {
    migration.changeColumn(
      'Users',
      'myAttribute',
      {
        type: DataTypes.STRING,
        unique: true                 // ADDING constraint works
      }
    ).done(done);
  },

  down: function (migration, DataTypes, done) {
    migration.changeColumn(
      'Users',
      'myAttribute',
      {
        type: DataTypes.STRING,
        unique: false                // REMOVING does not
      }
    ).done(done);
  }
};

I also tried using removeIndex

migration.removeIndex('Users', 'myAttribute_unique_idx').done(done);

But it gives the following error when reverting the migration:

Possibly unhandled SequelizeDatabaseError: cannot drop index "myAttribute_unique_idx" because constraint myAttribute_unique_idx on table "Users" requires it
like image 909
soerface Avatar asked Apr 08 '15 15:04

soerface


People also ask

How do I get rid of Sequelize migration?

Undoing Migrations​ You can use db:migrate:undo , this command will revert most the recent migration. You can revert back to the initial state by undoing all migrations with the db:migrate:undo:all command. You can also revert back to a specific migration by passing its name with the --to option.


2 Answers

As of 2017 with Sequelize 4.4.2, we can remove constraints with queryInterface API:

queryInterface.removeConstraint(tableName, constraintName)

Documentation is here.

like image 160
Tim Givois Avatar answered Sep 16 '22 20:09

Tim Givois


Unfortunately sequelize doesn't have a builtin migration method to remove constraint. That is why before removing key you need to make a raw query.

down: function (migration, DataTypes) {
  migration.sequelize.query(
    'ALTER TABLE Users DROP CONSTRAINT myAttribute_unique_idx;'
  );
  migration.removeIndex('Users', 'myAttribute_unique_idx');

  return;
}
like image 38
ezpn Avatar answered Sep 17 '22 20:09

ezpn