Skip to content

feature: Add to changeColumn the ability to add new ENUM values  #7151

Closed

Description

@diosney

Currently, there is no way in a migration to add new values to ENUMs and we have to fallback to custom and specific SQL to accomplish this.

Activity

  1. Aukhan commented on Jan 26, 2017

    @Aukhan

    I've had to declare the entire ENUM in the migration (up/down). Didn't think about what you're suggesting coz I guess that's how you'd handle it in plain sql.
    Just curious as to what you have in mind ??

  2. diosney commented on Jan 26, 2017

    @diosney
    ContributorAuthor

    This is how I'm doing it now, it is MySQL/MariaDB specific SQL code, so it might now work on Postgres, Oracle or SQlite:

    var warningMessage = 'Executing specific MySQL/MariaDb SQL statements. See `https://github.com/sequelize/sequelize/issues/7151`.';
    
    module.exports = {
      up  : function (queryInterface) {
        console.warn(warningMessage);
        return queryInterface
          .sequelize
          .query('ALTER TABLE ' + tableName + ' MODIFY COLUMN status ENUM(' + wrapInQuotesAndConcat(newReservationItemMetaStatuses) + ');');
      },
      down: function (queryInterface) {
        console.warn(warningMessage);
        return queryInterface
          .sequelize
          .query('ALTER TABLE ' + tableName + ' MODIFY COLUMN status ENUM(' + wrapInQuotesAndConcat(oldReservationItemMetaStatuses) + ');');
      }
    };

    The problem with that code is that is not adapter agnostic, that's why I want to use the changeColumn method to do the alters, in a way like this one:

    module.exports = {
      up  : function (queryInterface) {
        return queryInterface
          .changeColumn(tableName, 'status', {
            values: newValuesArr
          });
      },
      down: function (queryInterface) {
        return queryInterface
          .changeColumn(tableName, 'status', {
            values: oldValuesArr
          });
      }
    };

    which then will generate the specific SQL query for me.

  3. diosney commented on Jan 26, 2017

    @diosney
    ContributorAuthor
  4. Aukhan commented on Jan 26, 2017

    @Aukhan

    Interesting ... this is how I attempted it and worked for me

    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
          });
      }
    };
    
  5. diosney commented on Jan 26, 2017

    @diosney
    ContributorAuthor

    Nice! Worked! First time I use ENUMs like that :)

    Thanks!

  6. petermikitsh commented on Feb 25, 2017

    @petermikitsh

    While @Aukhan's solution works, we are essentially saying the same thing if we write:

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

    I think it's fair to say that this should function identically to @Aukhan's code, but it does not. While the docs say you can only change "default value, allowance of null or the data type", that's all we are doing here, however we have to use the Sequelize interface in a specific way to get the desired output.

  7. jakoandersen commented on Aug 3, 2017

    @jakoandersen

    This does not work for me on PostgreSQL 9.6 with Sequelize [Node: 6.10.3, CLI: 2.7.0, ORM: 3.30.4].
    I get the following error:

    SequelizeDatabaseError: type "enum_processes_status" already exists
    

    With the generated sql:

    'ALTER TABLE "processes" ALTER COLUMN "status" SET NOT NULL;ALTER TABLE "processes" ALTER COLUMN "status" SET DEFAULT \'proposed\';CREATE TYPE "public"."enum_processes_status" AS ENUM(\'proposed\', \'on going\', \'completed\', \'rejected\');ALTER TABLE "processes" ALTER COLUMN "status" TYPE "public"."enum_processes_status" USING ("status"::"public.enum_processes_status");' }

    It looks like it is creating the type, instead of altering it when it already exists.

  8. Aukhan commented on Aug 3, 2017

    @Aukhan

    Hey @jakoandersen
    Unfortunately I'm not so familiar with Postgres, really wish I was though.
    Did you try @petermikitsh solution ?
    I'm thinking maybe the ENUM() function call is triggering the create query in postgres. Somehow it should have IF NOT EXISTS in it.

  9. marneborn commented on Aug 5, 2017

    @marneborn

    @jakoandersen This is what my postgres migration ended up looking like to map an enum.
    I needed to map some values so didn't try using changeColumn.

      up(queryInterface, Sequelize) {
        return queryInterface.sequelize.transaction(async (transaction) => {
    
          // rename the enum
          await queryInterface.sequelize.query(
            `ALTER TYPE enum_my_table_enumcol RENAME TO enum_my_table_enumcol_old`,
            { transaction }
          );
    
          // create the new one
          await queryInterface.sequelize.query(
            `CREATE TYPE enum_my_table_enumcol AS ENUM ('enum1', 'enum2', 'newenum3', 'newenum4', 'enum5')`,
            { transaction }
          );
    
          // change the column to use the new one, mapping data
          await queryInterface.sequelize.query(
            `ALTER TABLE my_table
             ALTER COLUMN enumcol DROP DEFAULT,
             ALTER COLUMN enumcol TYPE enum_my_table_enumcol
               USING (CASE
                 WHEN enumcol='oldenum3' THEN 'newenum3'::text
                 WHEN enumcol='oldenum4' THEN 'newenum4'::text
                 ELSE enumcol::text
               END)::enum_my_table_enumcol,
             ALTER COLUMN enumcol SET DEFAULT 'enum1'
            `, { transaction });
    
          // drop the old enum
          await queryInterface.sequelize.query(
            `DROP TYPE enum_my_table_enumcol_old`,
            { transaction }
          );
        });
      },
    
    
  10. ablankenship10 commented on Aug 28, 2017

    @ablankenship10

    Also getting this error with latest Postgres, Node and SequelizeCLI.

    What exactly needs done to make @Aukhan 's format work as this is what I would expect the syntax to be.

  11. loayg commented on Nov 10, 2017

    @loayg

    @ablankenship10 @jakoandersen @Aukhan @marneborn

    For postgres, here is my workaround

    up: (queryInterface, Sequelize) => {
       return queryInterface.sequelize.query("alter type \"enum_tableName_colName\" rename to \"_enum_tableName_colName\";" +
          "CREATE TYPE \"enum_tableName_colName\" AS ENUM('oldVal1', 'oldVal2', 'oldVal3', 'newVal1', 'newVal2', 'newVal3');" +
          "alter table \"tableName\"  rename column \"colName\" to \"_colName\" ;" +
          "ALTER TABLE \"tableName\" ADD COLUMN \"colName\" \"enum_tableName_colName\" not null default 'newVal1';" +
          "update \"tableName\" set \"colName\"  = \"_colName\"::text::\"enum_tableName_colName\";" +
          "UPDATE \"tableName\" SET \"colName\" = 'newVal1' WHERE \"colName\" = 'oldVal1';" +
          "UPDATE \"tableName\" SET \"colName\" = 'newVal2' WHERE \"colName\" = 'oldVal2';" +
          "UPDATE \"tableName\" SET \"colName\" = 'newVal1' WHERE \"colName\" = 'oldVal3';" +
          "ALTER TABLE \"tableName\" DROP COLUMN \"_colName\"; DROP TYPE \"_enum_tableName_colName\";");
    },
    
    

    You will obviously need to put the proper values for tableName, colName, val1 ..etc

  12. abelosorio commented on Nov 14, 2017

    @abelosorio
  13. abelosorio commented on Jan 10, 2018

    @abelosorio
  14. Aukhan commented on Jan 11, 2018

    @Aukhan

    great work @abelosorio
    just a thought, maybe you could name it like sequelize-replace-enum-postgres

  15. abelosorio commented on Jan 11, 2018

    @abelosorio

    sure @Aukhan, I'll rename it.

  16. flvingdutchman commented on Apr 11, 2018

    @flvingdutchman

    That's how you can alter Enum for a column with existing values in postgress. Values will stay.

    1. Change type to String
    2. Drop Enum
    3. Change type to Enum with new values
      (Unfortunately you can't run this queries inside a transaction block, see: https://www.postgresql.org/docs/9.1/static/sql-altertype.html)
    module.exports = {
    	up: function up(queryInterface, Sequelize) {
    		return queryInterface.changeColumn('MyTable', 'MyColumn', {
    			type: Sequelize.STRING,
    			allowNull: false
    		}).then(() => {
    			const pgEnumDropQuery = queryInterface.QueryGenerator.pgEnumDrop('MyTable', 'MyColumn');
    
    			return queryInterface.sequelize.query(pgEnumDropQuery);
    		}).then(() => {
    			return queryInterface.changeColumn('MyTable', 'MyColumn', {
    				type: Sequelize.ENUM('first', 'second', 'third', 'fourth'),
    				allowNull: false
    			});
    		});
    	},
    	down: function down(queryInterface, Sequelize) {
    		return queryInterface.changeColumn('MyTable', 'MyColumn', {
    			type: Sequelize.STRING,
    			allowNull: false
    		}).then(() => {
    			const pgEnumDropQuery = queryInterface.QueryGenerator.pgEnumDrop('MyTable', 'MyColumn');
    
    			return queryInterface.sequelize.query(pgEnumDropQuery);
    		}).then(() => {
    			return queryInterface.changeColumn('MyTable', 'MyColumn', {
    				type: Sequelize.ENUM('first', 'second'),
    				allowNull: false
    			});
    		});
    	}
    };
    
  17. robcresswell commented on Aug 20, 2018

    @robcresswell

    @Aukhan @abelosorio Am I missing something here? It seems like Postgres supports altering ENUMs just fine since at least 9.1: https://www.postgresql.org/docs/9.1/static/sql-altertype.html ?

  18. Aukhan commented on Aug 21, 2018

    @Aukhan

    @robcresswell at the time of this issue I wasn't much literate with postegres but eventually found opportunity to start using it, the issue here is as @petermikitsh describes that you have to use the sequelize interface in a specific way to achieve it, indeed postgres supports it.

  19. abelosorio commented on Aug 21, 2018

    @abelosorio

    Hi @robcresswell! You are exactly right. With ALTER TYPE you can add values to an ENUM, but you cannot remove values from it.

    Even in the last version (10: https://www.postgresql.org/docs/current/static/sql-altertype.html) removing values from enum is still unsupported.

    Anyway, thanks for this. I'll adjust my package to use ALTER TYPE when the migration only requires to add new values.

  20. lucasalexandre-cc commented on Mar 4, 2021

    @lucasalexandre-cc

    Here is an example of up and down methods that works for me:

    'use strict';
    module.exports = {
      up: (queryInterface, Sequelize) => { 
        return queryInterface.sequelize.query(`ALTER TYPE "enum_name" ADD VALUE 'new_value'`);
      },
    
      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_name'
                )
        `);
      },
    };
    

    Thanks @abelosorio, based on your response I found http://www.michael1e.com/sequelize-enum-migration/ and he give me an example

  21. Amitrochates commented on Feb 4, 2026

    @Amitrochates

    how is this still not officially supported for postgres lol

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions