Adding a new value to an existing ENUM Type

前端 未结 18 1317
春和景丽
春和景丽 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:22

    Updating pg_enum works, as does the intermediary column trick highlighted above. One can also use USING magic to change the column's type directly:

    CREATE TYPE test AS enum('a', 'b');
    CREATE TABLE foo (bar test);
    INSERT INTO foo VALUES ('a'), ('b');
    
    ALTER TABLE foo ALTER COLUMN bar TYPE varchar;
    
    DROP TYPE test;
    CREATE TYPE test as enum('a', 'b', 'c');
    
    ALTER TABLE foo ALTER COLUMN bar TYPE test
    USING CASE
    WHEN bar = ANY (enum_range(null::test)::varchar[])
    THEN bar::test
    WHEN bar = ANY ('{convert, these, values}'::varchar[])
    THEN 'c'::test
    ELSE NULL
    END;
    

    As long as you've no functions that explicitly require or return that enum, you're good. (pgsql will complain when you drop the type if there are.)

    Also, note that PG9.1 is introducing an ALTER TYPE statement, which will work on enums:

    http://developer.postgresql.org/pgdocs/postgres/release-9-1-alpha.html

提交回复
热议问题