DEV Community

Cover image for NodeJs Sequelize - Update Enum column's default value
Kyle Foo
Kyle Foo

Posted on • Edited on

3

NodeJs Sequelize - Update Enum column's default value

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');
  },
};

Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more