Created
June 4, 2019 02:27
-
-
Save wmathes/0d625276846c254c551f837f49bb234e to your computer and use it in GitHub Desktop.
Postgres: plpgsql drop enum value function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- two functions to add and remove values from an enum. | |
-- reason: there's no easy way of removing a value from an existing enum in postgres. | |
CREATE OR REPLACE FUNCTION utility.enum_add_value(nspname text, typname text, value text) RETURNS void | |
AS $$ | |
BEGIN | |
INSERT INTO pg_enum (enumtypid, enumlabel, enumsortorder) | |
VALUES ( | |
( | |
SELECT oid | |
FROM pg_type | |
WHERE pg_type.typname = enum_add_value.typname | |
AND pg_type.typnamespace = (SELECT oid FROM pg_namespace WHERE pg_namespace.nspname = enum_add_value.nspname) | |
), | |
enum_add_value.value, | |
( SELECT MAX(enumsortorder) + 1 FROM pg_enum WHERE enumtypid IN ( | |
SELECT oid | |
FROM pg_type | |
WHERE pg_type.typname = enum_add_value.typname | |
AND pg_type.typnamespace = (SELECT oid FROM pg_namespace WHERE pg_namespace.nspname = enum_add_value.nspname) | |
) ) | |
); | |
END; | |
$$ | |
LANGUAGE plpgsql; | |
COMMENT ON FUNCTION utility.enum_add_value (text, text, text) IS E'@omit'; | |
----------------------------------------- | |
CREATE OR REPLACE FUNCTION utility.enum_drop_value(nspname text, typname text, value text) RETURNS void | |
AS $$ | |
BEGIN | |
DELETE FROM pg_enum | |
WHERE enumlabel = value | |
AND enumtypid = ( | |
SELECT oid | |
FROM pg_type | |
WHERE pg_type.typname = enum_drop_value.typname | |
AND pg_type.typnamespace = ( | |
SELECT oid FROM pg_namespace WHERE pg_namespace.nspname = enum_drop_value.nspname | |
) | |
); | |
END; | |
$$ | |
LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Assumes there are namespaces in place. Definitely high risk to use, but a lot easier then updating all functions/columns/triggers relying on an enum type already.