Created
March 19, 2025 23:12
-
-
Save ImIOImI/42d9ee6d5aff9ece24d037a2109717ac to your computer and use it in GitHub Desktop.
Add all the permissions you can on every schema in a DB
This file contains hidden or 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
DO $$ | |
DECLARE | |
target_user text := '<replace me>'; | |
r record; | |
current_db text := current_database(); | |
BEGIN | |
-- Grant CONNECT on the current database. | |
EXECUTE format('GRANT CONNECT ON DATABASE %I TO %I', current_db, target_user); | |
-- Loop over non‑system schemas and grant privileges on each schema and its objects. | |
FOR r IN | |
SELECT schema_name | |
FROM information_schema.schemata | |
WHERE schema_name NOT IN ('pg_catalog', 'information_schema') | |
LOOP | |
RAISE NOTICE 'Granting privileges on schema: %', r.schema_name; | |
EXECUTE format('GRANT USAGE ON SCHEMA %I TO %I', r.schema_name, target_user); | |
EXECUTE format('GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA %I TO %I', r.schema_name, target_user); | |
EXECUTE format('GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA %I TO %I', r.schema_name, target_user); | |
EXECUTE format('GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA %I TO %I', r.schema_name, target_user); | |
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT ALL ON TABLES TO %I', r.schema_name, target_user); | |
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT ALL ON SEQUENCES TO %I', r.schema_name, target_user); | |
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT EXECUTE ON FUNCTIONS TO %I', r.schema_name, target_user); | |
END LOOP; | |
END | |
$$; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment