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
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.
As of 2017 with Sequelize 4.4.2, we can remove constraints with queryInterface API:
queryInterface.removeConstraint(tableName, constraintName)
Documentation is here.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With