PostgreSQL
 SQL >> Base de Dados >  >> RDS >> PostgreSQL

Removendo um valor de um tipo enum do PostgreSQL

Você remove tipos enum como qualquer outro tipo, com DROP TYPE:

DROP TYPE admin_level1;

Mas talvez você esteja realmente perguntando como remover um único valor de um tipo enum? Se for isso, você não pode — não é suportado:

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.

Você deve criar um novo tipo sem aquele valor, migrar todos os usos existentes para o novo tipo e então remover o antigo. Por exemplo:

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 the new definition -- (you could update instead of delete) DELETE FROM blah WHERE power = 'god'; -- Convert to the new type, casting via the 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;