How do I delete an enum type value that I created in postgresql?
create type admin_level1 as enum(\'classifier\', \'moderator\', \'god\');
The programmatic way to do this is as follows. The same general steps as given
in https://stackoverflow.com/a/47305844/629272 are appropriate, but those are
more manual than made sense for my purposes (writing an alembic down migration). my_type
, my_type_old
, and value_to_delete
, should, of course, be changed as appropriate.
Rename your type.
ALTER TYPE my_type RENAME TO my_type_old;
Create a new type with the values from your old type, excluding the one you want to delete.
DO $$
BEGIN
EXECUTE format(
'CREATE TYPE my_type AS ENUM (%s)',
(
SELECT string_agg(quote_literal(value), ',')
FROM unnest(enum_range(NULL::my_type_old)) value
WHERE value <> 'value_to_delete'
)
);
END $$;
Change all existing columns which use the old type to use the new one.
DO $$
DECLARE
column_data record;
table_name varchar(255);
column_name varchar(255);
BEGIN
FOR column_data IN
SELECT cols.table_name, cols.column_name
FROM information_schema.columns cols
WHERE udt_name = 'my_type_old'
LOOP
table_name := column_data.table_name;
column_name := column_data.column_name;
EXECUTE format(
'
ALTER TABLE %s
ALTER COLUMN %s
TYPE my_type
USING %s::text::my_type;
',
table_name, column_name, column_name
);
END LOOP;
END $$;
Delete the old type.
DROP TYPE my_type_old;