Skip to content

Instantly share code, notes, and snippets.

@JulienBreux
Forked from oinopion/read-access.sql
Last active February 18, 2020 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JulienBreux/f251b7db3ef9f83606bcac93ca90083f to your computer and use it in GitHub Desktop.
Save JulienBreux/f251b7db3ef9f83606bcac93ca90083f to your computer and use it in GitHub Desktop.
How to create read only user in PostgreSQL
-- Create a group
CREATE ROLE readaccess;
-- Grant access to existing tables
GRANT CONNECT ON DATABASE _database_name_ TO readaccess;
GRANT USAGE ON SCHEMA public TO readaccess;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readaccess;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO readaccess;
-- Grant access to future tables
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readaccess;
-- Create a final user with password
CREATE USER readonly WITH ENCRYPTED PASSWORD '_secret_' NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE NOREPLICATION VALID UNTIL 'infinity';
GRANT readaccess TO readonly;
-- Create a final user with password
CREATE USER readonly WITH ENCRYPTED PASSWORD '_secret_' NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE NOREPLICATION VALID UNTIL 'infinity';
-- Grant access to existing tables
GRANT CONNECT ON DATABASE _database_name_ TO readonly;
GRANT USAGE ON SCHEMA public TO readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO readonly;
-- Grant access to future tables
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment