DEV Community

Dmitry Romanoff
Dmitry Romanoff

Posted on

How to create read-only user in PostgreSQL DB?

How to create read-only user in PostgreSQL DB?

CREATE ROLE postgres_my_ro_group;

GRANT USAGE ON SCHEMA public TO postgres_my_ro_group;

GRANT SELECT ON ALL TABLES IN SCHEMA public TO postgres_my_ro_group;

GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO postgres_my_ro_group;

ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO postgres_my_ro_group;

CREATE USER my_dbuser_readonly WITH PASSWORD '***************';

GRANT postgres_my_ro_group TO my_dbuser_readonly;

--- To grant connect to specific DB:

GRANT CONNECT ON DATABASE cloud_usage TO my_dbuser_readonly;

--- To grant connect to all DBs on this DB instance:

SELECT format('GRANT CONNECT ON DATABASE %I TO my_dbuser_readonly;', datname) FROM pg_database; \gexec

--- Repeat code below for each database

\c foo
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO my_dbuser_readonly; --- this grants privileges on new tables generated in new database "foo"
GRANT USAGE ON SCHEMA public to my_dbuser_readonly;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO my_dbuser_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO my_dbuser_readonly;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)