How to delete an enum type value in postgres?

前端 未结 9 2016
没有蜡笔的小新
没有蜡笔的小新 2020-12-04 08:02

How do I delete an enum type value that I created in postgresql?

create type admin_level1 as enum(\'classifier\', \'moderator\', \'god\');

相关标签:
9条回答
  • 2020-12-04 08:46

    if your dataset is not so big you can dump with --column-inserts edit the dump with a text editor, remove the value and re-import the dump

    0 讨论(0)
  • 2020-12-04 08:48

    If you want delete item of enum type, you must operate on system table of PostgreSQL.

    With this command, you can display all the items enum type.

    SELECT * FROM pg_enum;

    Then check that searched the value is unique. To increase the uniqueness during the removal of rekoru must be passed 'enumtypid' in addition to 'enumlabel'.

    This command removes the entry in enum type, where 'unique' is your value.

    DELETE FROM pg_enum en WHERE en.enumtypid=124 AND en.enumlabel='unique';

    NOTE The example that I described must be used, when by chance we add new value to enum type, and yet we have not used it anywhere in database.

    0 讨论(0)
  • 2020-12-04 08:49

    You delete (drop) enum types like any other type, with DROP TYPE:

    DROP TYPE admin_level1;
    

    Is it possible you're actually asking about how to remove an individual value from an enum type? If so, you can't. It's not supported:

    Although enum types are primarily intended for static sets of values, there is support for adding new values to an existing enum type, and for renaming values (see ALTER TYPE). Existing values cannot be removed from an enum type, nor can the sort ordering of such values be changed, short of dropping and re-creating the enum type.

    You must create a new type without the value, convert all existing uses of the old type to use the new type, then drop the old type.

    E.g.

    CREATE TYPE admin_level1 AS ENUM ('classifier', 'moderator');
    
    CREATE TABLE blah (
        user_id integer primary key,
        power admin_level1 not null
    );
    
    INSERT INTO blah(user_id, power) VALUES (1, 'moderator'), (10, 'classifier');
    
    ALTER TYPE admin_level1 ADD VALUE 'god';
    
    INSERT INTO blah(user_id, power) VALUES (42, 'god');
    
    -- .... oops, maybe that was a bad idea
    
    CREATE TYPE admin_level1_new AS ENUM ('classifier', 'moderator');
    
    -- Remove values that won't be compatible with new definition
    -- You don't have to delete, you might update instead
    DELETE FROM blah WHERE power = 'god';
    
    -- Convert to new type, casting via text representation
    ALTER TABLE blah 
      ALTER COLUMN power TYPE admin_level1_new 
        USING (power::text::admin_level1_new);
    
    -- and swap the types
    DROP TYPE admin_level1;
    
    ALTER TYPE admin_level1_new RENAME TO admin_level1;
    
    0 讨论(0)
提交回复
热议问题