Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop and create ENUM with sequelize correctly?

How to correctly drop and then recreate ENUM type with sequelize for Postgres in migrations? For example this migration doesn't drop enum_Users_status enum... so any attempts to recreate/change status values after they have been once created fail.

module.exports = {
    up: function (queryInterface, DataTypes) {
        queryInterface.createTable('Users', {
            //...
            status: {
                type: DataTypes.ENUM,
                values: [
                    'online',
                    'offline',
                ],
                defaultValue: 'online'
            }
            //...
        })
    },

    down: function (queryInterface) {
        queryInterface.dropTable('Users')
    },
}

Eventually i did manage to delete the enum type inside down, but then up migration (which is supposed to create this status enum from scratch) fails, saying something like public.enum_Users_status enum type doesn't exist..

like image 396
ZenDD Avatar asked Aug 01 '17 12:08

ZenDD


People also ask

How do I create an enum Sequelize?

Sequelize provides the ENUM data type that you can use to create and interact with SQL tables that has ENUM as its column type. To use the ENUM type, you need to use either Sequelize. ENUM or DataTypes. ENUM as the type of your model attribute.

How do I remove a column from Sequelize?

To add or delete columns in Sequelize CLI, we can use the sequelize migration:create command to create a migration file. Then we call addColumn to add a column and removeColumn to remove a column in the migration file.

How do I set default value in Sequelize migration?

When you create a Sequelize model, you can add the default value for your model by adding the defaultValue option to the column(s) definition. The defaultValue option will be used by Sequelize to define default value(s) for your SQL column(s) when you create a table using Sequelize.


1 Answers

If you want to change/edit type enum without losing data. here is my migration code. hopefully it helps.

queryInterface.changeColumn(
  'table_name',
  'Column_name',
  {
    type: Sequelize.TEXT,
  },
),
queryInterface.sequelize.query('drop type enum_tableName_columnName;')
.then(() => queryInterface.changeColumn(
  'table_name',
  'column_name',
  {
    type: Sequelize.ENUM('value1','value2'),
  },
)),
like image 125
shakir ullah Avatar answered Sep 22 '22 13:09

shakir ullah