Intend to modify a Enum column's default value? we can modify it without losing the original data. Here's an use case when original enum value for size column is small, we're changing it to big.
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
// Create a new enum type, make sure its name isn't the same as current column's enum type
await queryInterface.sequelize.query(`
CREATE TYPE enum_new_size AS ENUM ('big', 'medium', 'small');
`);
// Add a new temp column with the enum type, setting the new default value as 'big'
await queryInterface.addColumn('Shirts', 'sizeTemp', {
type: 'enum_new_size',
allowNull: false,
defaultValue: 'big',
});
// Copy over the old data to new column and cast to Enum values
await queryInterface.sequelize.query(`
UPDATE "Shirts"
SET "sizeTemp" = CASE
WHEN "size" = 'small' THEN CAST('small' AS enum_new_size)
WHEN "size" = 'medium' THEN CAST('medium' AS enum_new_size)
WHEN "size" = 'big' THEN CAST('big' AS enum_new_size)
ELSE CAST('big' AS enum_new_size)
END;
`);
// Remove the old column
await queryInterface.removeColumn('Shirts', 'size');
// Rename the temporary column
await queryInterface.renameColumn(
'Shirts',
'sizeTemp',
'size',
);
},
async down(queryInterface, Sequelize) {
/**
* Add reverting commands here.
*/
await queryInterface.removeColumn('Shirts', 'sizeTemp');
},
};
Top comments (0)