clewiston
clewiston

Reputation: 53

How to removeConstraint defaultValue in Sequelize

I'm trying to write a migration in Sequelize and want to remove the defaultValue constraint. What is the proper syntax? I've tried both of the following:

return queryInterface.removeConstraint('Table', 'table_columnName_default')
return queryInterface.removeConstraint('Table', 'columnName_default')

Upvotes: 0

Views: 6109

Answers (4)

cdauth
cdauth

Reputation: 7597

For me defaultValue: null was not working, as it was trying to set the default value to NULL rather than removing it.

What worked for me was supplying the whole column definition, but without a defaultValue:

await queryInterface.changeColumn('Table', 'columnName', {
    type: DataTypes.TEXT // or whatever is your data type
});

Upvotes: 1

Nben
Nben

Reputation: 332

you should know the data type. for e.g. STRING:

const { DataTypes } = require('sequelize');

return queryInterface.changeColumn('Table', 'attributeName', {
    defaultValue: null,
    type: DataTypes.STRING
});

you can also use queryInterface from the model definition (or pass the model/query interface) to make it generic for any column with default value:

function dropDefaults(queryInterface, model) {
  const defaultValues = Object.keys(model._defaultValues);
  for (const column of defaultValues) {
    model.queryInterface.changeColumn(model.tableName, column, {
      defaultValue: null,
      type: model.fieldRawAttributesMap[column].type,
    });
  }
}

Upvotes: 0

pwerth
pwerth

Reputation: 210

You can also use a raw query:

return queryInterface.sequelize.query(`ALTER TABLE table ALTER COLUMN column DROP DEFAULT;`)

Upvotes: 0

Rahul Sharma
Rahul Sharma

Reputation: 1431

Can you please try to use

return queryInterface.changeColumn('Table', 'attributeName', {
    defaultValue: null,
    allowNull: true,
});

http://docs.sequelizejs.com/class/lib/query-interface.js~QueryInterface.html#instance-method-changeColumn

Upvotes: 7

Related Questions