4

I created a migration file to add a column as an up and then delete it under down.

Here's the migration file code:

module.exports = {
  up: (queryInterface, Sequelize) =>
    queryInterface.addColumn('Books', 'Rating', {
      allowNull: false,
      type: Sequelize.ENUM('like', 'dislike'),
    }),

  down: (queryInterface, Sequelize) => {
    queryInterface.removeColumn('Books', 'Rating');
  },
};

When I ran it for the first time using db:migrate, it successfully added the column but when I did a db:migrate:undo:all and then ran the migrations again, it threw me an error sqying

======= 20180211100937-AddedRatingIntoBooks: migrating 
======= 2018-02-11 15:42:46.076 IST 
[64531] ERROR:  type "enum_Books_Rating" already exists 2018-02-11 15:42:46.076 IST 
[64531] STATEMENT:  CREATE TYPE "public"."enum_Books_Rating" AS ENUM('like', 'dislike');
ALTER TABLE "public"."Boo ks" ADD COLUMN "Rating" "public"."enum_Books_Rating";

    ERROR: type "enum_Books_Rating" already exists

The issue is still live here.

Aakash Verma
  • 3,705
  • 5
  • 29
  • 66

1 Answers1

8

Sequelize creates TYPES for each of the enum you define, which you can find here

The name of the ENUM type is the concatenation of "enum", the table name, and the column name in snake casing. (enum_Books_Rating here)

To create migrations for ENUM, you have to modify your down function like so:

module.exports = {
  up: (queryInterface, Sequelize) =>
    queryInterface.addColumn('Books', 'Rating', {
      allowNull: false,
      type: Sequelize.ENUM('like', 'dislike')
  }),

  down: (queryInterface, Sequelize) =>  
    queryInterface.removeColumn('Books', 'Rating')
      .then(() => queryInterface.sequelize.query('DROP TYPE "enum_Books_Rating";'));
  };

Hope this helps.

mrsauravsahu
  • 2,046
  • 2
  • 15
  • 21
  • Just a note - If the error exists before one uses this code, he or she needs to go execute `DROP TYPE enum_tableName_attributeName` at the database first before he runs any kind of up or down migrations. – Aakash Verma Feb 17 '18 at 21:00