Skip to content

Instantly share code, notes, and snippets.

@ArseniySavin
Last active January 23, 2025 09:17
Show Gist options
  • Save ArseniySavin/3cbbc0c1ed22c0911273a35f93a26efe to your computer and use it in GitHub Desktop.
Save ArseniySavin/3cbbc0c1ed22c0911273a35f93a26efe to your computer and use it in GitHub Desktop.
The Postgres function drops the attribute value and checks constraint violation if the row contains the attribute value.
ALTER PROCEDURE enum_attr_drop OWNER TO {delete role for pg_enum};
CREATE OR REPLACE PROCEDURE enum_attr_drop(inType varchar, inAttr varchar)
LANGUAGE PLPGSQL
SECURITY DEFINER
AS $$
declare
isBind RECORD;
dQuery varchar;
hasRecord bigint;
errMsg varchar;
begin
if inType is null or inType = '' or inAttr is null or inAttr = '' or then
raise exception query_canceled;
end if;
FOR isBind IN SELECT t.table_schema
, t.table_name
, t.column_name
FROM information_schema.column_udt_usage t
where t.UDT_NAME = inType
LOOP
SELECT format('select count(1) from %s.%s t where t.%s = ''%s'''
, isBind.table_schema
, isBind.table_name
, isBind.column_name
, inAttr) into dQuery;
EXECUTE dQuery INTO hasRecord;
IF hasRecord > 0 THEN
errMsg := 'Relations found "'
|| isBind.table_schema
|| '.'
|| isBind.table_name
|| '.'
|| isBind.column_name
|| '" by type value '
|| inAttr;
raise exception foreign_key_violation;
END IF;
END LOOP;
delete from pg_enum
where enumtypid=inType::regtype
and enumlabel=inAttr;
exception
when no_data_found then
raise exception no_data_found
using hint = 'Not found attribute ' || inAttr || ' in type ' || inType;
when query_canceled then
raise exception query_canceled
using hint = 'Param inType or InAttr is null or empty';
when foreign_key_violation then
raise exception foreign_key_violation
using hint = errMsg;
when invalid_text_representation then
raise exception invalid_text_representation
using hint = 'Attribute ' || inAttr || ' is not found in type ' || inType;
end;
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment