How to delete an enum type value in postgres?

前端 未结 9 2034
没有蜡笔的小新
没有蜡笔的小新 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:38

    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.

    1. Rename your type.

      ALTER TYPE my_type RENAME TO my_type_old;
      
    2. 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 $$;
      
    3. 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 $$;
      
    4. Delete the old type.

      DROP TYPE my_type_old;
      

提交回复
热议问题