Remove constraints in sequelize migration

为君一笑 提交于 2019-12-06 19:30:01

问题


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

回答1:


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

queryInterface.removeConstraint(tableName, constraintName)

Documentation is here.




回答2:


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;
}



回答3:


Sequelize has removeConstraint() method if you want to remove the constraint. So you can have use something like this:

return queryInterface.removeConstraint('users', 'users_userId_key', {})

where users is my Table Name and users_userId_key is index or constraint name which is generally of the form attributename_unique_key if you have unique constraint which you wanna remove(say).




回答4:


If you want to remove the index you should use:

down: function (migration, DataTypes) {
    return migration.removeIndex('Users', 'myAttribute_unique_idx');
}

The return is used to use promise style instead of callbacks. This is recommended by sequelize.

It would also be good to handle the creation of the index on your own as descripted here: http://sequelize.readthedocs.org/en/latest/docs/migrations/#addindextablename-attributes-options



来源:https://stackoverflow.com/questions/29518786/remove-constraints-in-sequelize-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!