Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize migration queryInterface.removeColum fails to work

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.

like image 469
Aakash Verma Avatar asked Jan 03 '23 20:01

Aakash Verma


1 Answers

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.

like image 73
mrsauravsahu Avatar answered Jan 14 '23 06:01

mrsauravsahu