GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;
The readonly user can connect, see the tables but when it tries to do a simple select it gets:
ERROR: permission denied for relation mytable SQL state: 42501
This is happening on PostgreSQL 9.1
What I did wrong?
Grant privileges to a new user We resolve this permission denied error using the command. GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO new_user; The new_user was then able to read data from the table. Similarly, we can also resolve the permission denied error by setting DEFAULT privileges to the user.
First, connect to your database cluster as the admin user, doadmin , by passing the cluster's connection string to psql . This brings you into the interactive shell for PostgreSQL, which changes your command prompt to defaultdb=> . From here, connect to the database that you want to modify the user's privileges on.
Here is the complete solution for PostgreSQL 9+, updated recently.
CREATE USER readonly WITH ENCRYPTED PASSWORD 'readonly'; GRANT USAGE ON SCHEMA public to readonly; ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly; -- repeat code below for each database: GRANT CONNECT ON DATABASE foo to readonly; \c foo ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly; --- this grants privileges on new tables generated in new database "foo" GRANT USAGE ON SCHEMA public to readonly; GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO readonly; GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;
Thanks to https://jamie.curle.io/creating-a-read-only-user-in-postgres/ for several important aspects
If anyone find shorter code, and preferably one that is able to perform this for all existing databases, extra kudos.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With