PostgreSQL Grant Privileges To a Role

Hi all,

If you have lots of user and table/schema on your database you can not give permission per table but you can follow this steps. It's gonna be manual process but sometimes you can not give whole privileges on entire schema in your databases to users/roles. So, in that case you should generate your scripts.

GRANT SELECT ON ALL TABLES IN SCHEMA schema_name TO your_role;
GRANT USAGE ON SCHEMA schema_name TO your_role;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA schema_name TO
your_role;


If you don't want to give all privileges and make specific for users also you can generate a sql script for whole schema for user or your all users like;

Generate GRANT script for granting privileges whole schemas for a role;
SELECT DISTINCT 'GRANT SELECT ON ALL TABLES IN SCHEMA '|| schemaname || 'TO user_role;' FROM pg_stat_user_tables;

Generate USAGE script for whole schemas;
SELECT DISTINCT 'GRANT USAGE ON SCHEMA '|| schemaname || 'TO user_role;' FROM pg_stat_user_tables;

You may want to executing privileges on whole functions;
SELECT DISTINCT 'GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA '|| schemaname || 'TO user_role;' FROM pg_stat_user_tables;

Or you can type script bellow for functions, it's gonna be fine.

SELECT DISTINCT 'GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA '|| schemaname ||' TO '|| rolname || ';' from pg_stat_user_tables, pg_roles;

Other way, you prefer to grant all privileges based on database, so you can use bellow script;

GRANT ALL PRIVILEGES ON DATABASE databasename TO your_role;


Loves,

Comments

Popular posts from this blog

PostgreSQL Foreign Data Wrappers

PostgreSQL High Availability - Patroni 2

pg_ctl: command not found