Adding a new value to an existing ENUM Type

前端 未结 18 1322
春和景丽
春和景丽 2020-12-04 04:52

I have a table column that uses an enum type. I wish to update that enum type to have an additional possible value. I don\'t want to delete any exi

18条回答
  •  执念已碎
    2020-12-04 05:31

    As discussed above, ALTER command cannot be written inside a transaction. The suggested way is to insert into the pg_enum table directly, by retrieving the typelem from pg_type table and calculating the next enumsortorder number;

    Following is the code that I use. (Checks if duplicate value exists before inserting (constraint between enumtypid and enumlabel name)

    INSERT INTO pg_enum (enumtypid, enumlabel, enumsortorder)
        SELECT typelem,
        'NEW_ENUM_VALUE',
        (SELECT MAX(enumsortorder) + 1 
            FROM pg_enum e
            JOIN pg_type p
            ON p.typelem = e.enumtypid
            WHERE p.typname = '_mytypename'
        )
        FROM pg_type p
        WHERE p.typname = '_mytypename'
        AND NOT EXISTS (
            SELECT * FROM 
            pg_enum e
            JOIN pg_type p
            ON p.typelem = e.enumtypid
            WHERE e.enumlabel = 'NEW_ENUM_VALUE'
            AND p.typname = '_mytypename'
        )
    

    Note that your type name is prepended with an underscore in the pg_type table. Also, the typname needs to be all lowercase in the where clause.

    Now this can be written safely into your db migrate script.

提交回复
热议问题