sqlpostgresql

How to create a role in postgress db which supports the CRUD operations but doesn't allow to drop the database and tables with that role


We have an use case where we need to create a user with a role to perform the crud operations but it should not drop the databases with that user.

We have tried the below command and tried other permutations and combinations as well.

-- Replace placeholders with your values
CREATE USER developer WITH PASSWORD 'your_password';

CREATE ROLE developer_role;

GRANT USAGE ON SCHEMA public TO developer;

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO developer_role;

GRANT developer_role TO developer;

REVOKE CREATE, DROP ON ALL TABLES IN SCHEMA public FROM developer;
REVOKE CREATE, DROP ON ALL SCHEMAS IN DATABASE your_database_name FROM developer;

ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO developer_role;
ALTER DEFAULT PRIVILEGES IN DATABASE your_database_name GRANT USAGE ON SCHEMAS TO developer_role;

Thanks in advance, please share your insights

The commands we used are still able to drop the database. Which it shouldn't do.

Suggestion on the command we need to have for this usecase


Solution

  • Aside: Your SQL script looks pretty haphazard, like it was composed from random statements you found somewhere...

    In PostgreSQL, role and user are the same. Any object in PostgreSQL has an owner. The owner is the role that created the object. Only the owner, a member of the owning role or a superuser can drop an object.

    So the only way to achieve what you want is to have the owner of the tables and databases be a different role from the one who performs SELECT, INSERT, UPDATE and CREATE. The owner has to grant that user the respective privileges on the objects.


    Actually, there is another possibility: you can create an event trigger that causes an error whenever a table is dropped. I consider this ugly, and you need a superuser to create an event trigger.