Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add enum labels using sequelize?

Tags:

sequelize.js

I have a table called characters. Each character has an enum called "state", which can be "sad" or "happy". How do I add a new state "confused" to my column? I tried this migration but it failed:

migration.describeTable('characters').success(function (attributes) {
    migration.changeColumn('characters', 'state',
        {
            type: DataTypes.ENUM,
            values: ['sad', 'happy', 'confused']
        })
        .complete(done);
});

It complained that error: type "enum_characters_state" already exists.

like image 578
stackOverlord Avatar asked May 06 '26 04:05

stackOverlord


2 Answers

Expanding on briangonzalez answer, you will also need a down function to undo the migration:

'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.

like image 145
Edudjr Avatar answered May 09 '26 23:05

Edudjr


With the latest version of Sequelize, you could achieve this by running a query (Postgres assumed):

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.sequelize.query("ALTER TYPE enum_character_state ADD VALUE 'confused';");
  }
};
like image 39
briangonzalez Avatar answered May 09 '26 22:05

briangonzalez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!