Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

Tags:

postgresql

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?

like image 485
sorin Avatar asked Nov 21 '12 16:11

sorin


People also ask

How do I fix Postgres permission denied?

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.

How do I change permissions in PostgreSQL?

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.


1 Answers

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.

like image 99
sorin Avatar answered Oct 24 '22 00:10

sorin