sequelize icon indicating copy to clipboard operation
sequelize copied to clipboard

Migration on ENUM with postgres dialect: type already exists

Open ghost opened this issue 12 years ago • 34 comments

Deleting previously existing ENUM column and re-creating it but with a different ENUM results in:

Executing (default): ALTER TABLE "Trackers" DROP COLUMN "type";
Executing (default): CREATE TYPE "enum_Trackers_type" AS ENUM('image', 'javascript', 'snippet'); ALTER TABLE "Trackers" ADD COLUMN "type" "enum_Trackers_type";
Possibly unhandled SequelizeDatabaseError: error: type "enum_Trackers_type" already exists

ghost avatar Nov 10 '14 05:11 ghost

That's a postgres issue. Dropping an enum column does not drop the enum itself (since an enum might be used in several tables as I understand it)

janmeier avatar Nov 10 '14 06:11 janmeier

@janmeier: Any idea how to correctly edit enum values through migration then?

ghost avatar Nov 10 '14 20:11 ghost

Using raw query meanwhile, unless someone comes up with a better suggestion.

ghost avatar Nov 14 '14 06:11 ghost

@kytwb

Any idea how to correctly edit enum values through migration then?

I was able to modify an ENUM by:

  1. Modifying the array assigned to the values property of the configuration object passed as the second argument to sequelize.define to include a new value
  2. Create a migration in which the up simply calls ModelNameHere.sync()

That generated the SQL statements required to modify the ENUM-type to match what I'd expressed in JavaScript code.

Erin

laser avatar Jan 09 '15 19:01 laser

@laser Tried what you said, it does work when you add only one new value at a time.

Executing (default): ALTER TYPE "enum_warehouses_type" ADD VALUE 'postmaster' BEFORE 'amazon'
Executing (default): ALTER TYPE "enum_warehouses_type" ADD VALUE 'amazon' AFTER 'postmaster'
Possibly unhandled SequelizeDatabaseError: "amazon" is not an existing enum label

With amazon and postmaster being the two new values here.

ghost avatar Mar 22 '15 16:03 ghost

I am facing the same issue. I was able to bypass it with using raw query

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.sequelize.query("CREATE TYPE \"enum_users_sellerAccountType\" AS ENUM(\'sa\', \'sm\'); ALTER TABLE \"users\" ADD COLUMN \"sellerAccountType\" \"enum_users_sellerAccountType\";");
  },

  down: function (queryInterface, Sequelize) {
    return queryInterface.sequelize.query("DROP TYPE \"enum_users_sellerAccountType\"; ALTER TABLE \"users\" DROP COLUMN \"sellerAccountType\";");
  }
};

Is it a bug in sequelize, that causes enum migration to fail?

Victor08 avatar Feb 06 '16 18:02 Victor08

Facing same issue. To add to the problem, sequelize only allows changing default value, allowance of null or the data type. If you want to change some other attribute of a column, you will have to find a hack for it.

delveintechnolabs avatar Mar 12 '16 08:03 delveintechnolabs

Heads up that if you decide to do raw queries like @Victor08 points out above, the down migration should drop the column first so that nothing depends on the data type, like this:

 down: function (queryInterface, Sequelize) {
    return queryInterface.sequelize.query("ALTER TABLE \"users\" DROP COLUMN \"userType\"; DROP TYPE \"enum_users_userType\";");
  }

thealmightygrant avatar Oct 04 '16 21:10 thealmightygrant

We have QueryInterface.dropAllEnums(), I think we should add a simple dropEnum() method.

felixfbecker avatar Oct 05 '16 08:10 felixfbecker

@felixfbecker is there an update on the dropEnum() method? This would really be very handy. What is the context of QueryInterface.dropAllEnums()? Is it the whole database or maybe a table?

kgalli avatar Feb 21 '17 10:02 kgalli

No, there is no update. Can't answer your second question.

felixfbecker avatar Feb 21 '17 10:02 felixfbecker

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂

stale[bot] avatar Jun 29 '17 11:06 stale[bot]

This is still an issue

markelog avatar Jul 18 '17 13:07 markelog

This is how I solved it, not the best way but it allows adding a new field with an existing enum without it throwing an error.

queryInterface.addColumn(
            'Users',
            'language', {
                type: Sequelize.ENUM('nl', 'en'),
                allowNull: false,
                defaultValue: 'nl'
            }).then(function (response) {
                console.log(response);
                done();
            }).catch(function (err) {
                return queryInterface.sequelize.query(`ALTER TABLE "Users" ADD COLUMN "language" "public"."enum_Users_language" NOT NULL DEFAULT 'nl';`)
                    .then(function (response) {
                        console.log(response);
                        done();
                    }).catch(function (err) {
                        done();
                    });
            });

mariano-aguero avatar Sep 08 '17 17:09 mariano-aguero

finally got it working:

'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.sequelize.query("ALTER TYPE enum_type_name ADD VALUE 'new_value'");
  },

  down: (queryInterface, Sequelize) => {
    var query = 'DELETE FROM pg_enum ' +
      'WHERE enumlabel = \'new_value\' ' +
      'AND enumtypid = ( SELECT oid FROM pg_type WHERE typname = \'enum_type_name\')';
    return queryInterface.sequelize.query(query);
  }
};

change enum_type_name and new_value to fit your needs.

Edudjr avatar Sep 15 '17 17:09 Edudjr

Any plans for adding QueryInterface.dropEnum() method?

JustBlackBird avatar Sep 25 '17 20:09 JustBlackBird

@Edudjr that almost worked for me, but I had to make an ever so slight change to your up function:

up: (queryInterface, Sequelize) => {
    return queryInterface.sequelize.query(`ALTER TYPE "enum_type_name" ADD VALUE 'new_value'`);
}

As you can see, I had to wrap my enum name in double quotes; for whatever reason, that's how Sequelize created my enum, so without the double quotes I got a "type does not exist" error. I'm not sure if this is a standard for Sequelize, but I figured I'd post my findings here in case anyone else ran into a similar issue. Also note that due to the use of both single and double quotes, I wrapped the query in tick marks since I'm using a new enough version of Node that supports template strings, thereby avoiding the need to escape any strings.

And for the down function, I made similar changes for readability:

down: (queryInterface, Sequelize) => {
    return queryInterface.sequelize.query(`
        DELETE 
        FROM
            pg_enum
        WHERE
            enumlabel = 'new_value' AND
            enumtypid = (
                SELECT
                    oid
                FROM
                    pg_type
                WHERE
                    typname = 'enum_type_name'
            )
    `);
}

Strangely enough, enum_type_name here in the pg_type table did not have double quotes in its actual value, unlike the type that was created.

ajmueller avatar Oct 20 '17 02:10 ajmueller

See my comment https://github.com/sequelize/sequelize/issues/7151#issuecomment-344246084.

I've written a function to entirely replace the ENUM. It works inside a transaction and supports default value.

Hope you find it helpul.

abelosorio avatar Nov 14 '17 12:11 abelosorio

I asked this on SO here and this is something sweet and simple that seems to be doing it

down: (queryInterface, Sequelize) => queryInterface.removeColumn('TableName', 'ColumnName') .then(() => queryInterface.sequelize.query('DROP TYPE "enum_TableName_ColumnName";')); };

theSuiGenerisAakash avatar Feb 13 '18 19:02 theSuiGenerisAakash

The best way to modify enum values is to queryInterface.changeColumn:

module.exports = {
  up  : function (queryInterface, Sequelize) {
    return queryInterface
      .changeColumn(tableName, 'status', {
        type: Sequelize.ENUM('a', 'b', 'c', 'd'),
        allowNull: false
      });
  },
  down: function (queryInterface, Sequelize) {
    return queryInterface
      .changeColumn(tableName, 'status', {
        type: Sequelize.ENUM('a', 'b', 'c'),
        allowNull: false
      });
  }
};

tomprogers avatar Jun 05 '18 20:06 tomprogers