Search code examples
node.jspostgresqlenumssequelize.jssequelize-cli

Sequelize: Change column type to ENUM


I cannot seem to find the proper way to change a column from a String type to an ENUM while persisting the data in that column.

I've also attempted to create a new column with the ENUM type and then copy the data between columns:

// migrations/20160606170538-change-column.js

'use strict';

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.addColumn('time', 'newcolumn', {
      allowNull: true,
      type: Sequelize.ENUM('1-day', '7-day', '1-month', '3-month', '6-month', '1-year')
    }).then(function () {
      return queryInterface.sequelize.query("UPDATE time SET newcolum = oldcolumn");
    });
  },

  down: function (queryInterface, Sequelize) {
  }
};

But I return the following error on migration:

error: column "newcolumn" is of type enum_time_newcolumn but expression is of type character varying]


Solution

  • Postgres doesn't know that the string data in oldcolumn can fit into the enum values - try casting it

    return queryInterface.sequelize.query("UPDATE time SET newcolum = oldcolumn::enum_time_newcolumn");