Last active
March 9, 2021 21:11
-
-
Save kljensen/2a1af7a1f414a6c5ebc61913f7b26af2 to your computer and use it in GitHub Desktop.
Postgresql command to drop a role after removing all privileges in a loop
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
/* This function loops over all schemas and drops a role's | |
privileges in those schemas and then drops the role. Call | |
it like `SELECT drop_role('foo');` where 'foo' is the role | |
you want to drop. Would be nice to have exception handling | |
😎😜 | |
Inspiration: | |
https://stackoverflow.com/questions/3023583/how-to-quickly-drop-a-user-with-existing-privileges | |
*/ | |
DROP FUNCTION IF EXISTS drop_role; | |
CREATE OR REPLACE FUNCTION drop_role(role_name TEXT) RETURNS void AS | |
$$ | |
DECLARE | |
t record; | |
BEGIN | |
FOR t IN | |
SELECT DISTINCT(schema_name) | |
FROM information_schema.schemata | |
where schema_name not in ('pg_catalog', 'information_schema') | |
LOOP | |
EXECUTE format('REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA %I FROM %I', t.schema_name, role_name); | |
EXECUTE format('REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA %I FROM %I', t.schema_name, role_name); | |
EXECUTE format('REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA %I FROM %I', t.schema_name, role_name); | |
EXECUTE format('REVOKE ALL PRIVILEGES ON SCHEMA %I FROM %I', t.schema_name, role_name); | |
END LOOP; | |
EXECUTE format('DROP ROLE %I', role_name); | |
END; | |
$$ LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment