I usually use databases and rarely have authorized operations, but recently there was a scene where it was necessary to set which databases, tables and sequences can only be operated by a certain user. Let me share my experience, I use PostgreSQL database.
Empowerment Command Syntax
The grant commands in PostgreSQL are GRANT and REVOKE.
The GRANT command is used to grant certain permissions (such as SELECT, INSERT, UPDATE, DELETE, etc.) to a certain user or user group on an object (such as tables, views, functions, etc.).
grammar:
GRANT privilege [, ...] ON object TO {user | group | PUBLIC} [, ...] [WITH GRANT OPTION];
Among them, privilege is a kind of permission, object is an object, which can be a table, view, function, etc., user or group is the user or user group to be granted permission, and PUBLIC means all users.
For example, authorized user zhangsan performs SELECT and INSERT operations on table test:
GRANT SELECT, INSERT ON test TO zhangsan;
The REVOKE command is used to revoke certain permissions of a user or user group on an object.
grammar:
REVOKE privilege [, ...] ON object FROM {user | group | PUBLIC} [, ...] [CASCADE | RESTRICT];
Among them, the meanings of privilege, object, user or group, and PUBLIC are the same as those of the GRANT command.
For example, cancel the SELECT permission of user zhangsan on table test:
REVOKE SELECT ON test FROM zhangsan;
It should be noted that only superusers have the authority to grant and revoke permissions.
combat
view all users
SELECT * FROM pg_user;
Create a user and set a password
CREATE USER zhangsan WITH PASSWORD '123456';
delete users
DROP USER zhangsan;
create database
CREATE DATABASE test;
delete database
DROP DATABASE IF EXISTS test;
Remove the user's privileges on the "test" database
REVOKE ALL privileges ON DATABASE "test" FROM zhangsan;
Give the user permission to operate the "test" database
GRANT CONNECT, CREATE, TEMPORARY ON DATABASE "test" TO zhangsan;
Give the user permission to operate tables in the "test" database
GRANT SELECT, INSERT, UPDATE, DELETE
ON ALL TABLES IN SCHEMA PUBLIC
TO zhangsan;
Grants the user the privilege to operate on sequences in the "test" database
Permission Definitions for Sequences
It can be seen in the official document that all permissions of the sequence are rwU, corresponding to SELECT, UPDATE, USAGE respectively;
For sequences, the SELECT privilege allows the use of the currval function
For sequences, the UPDATE privilege allows the use of the nextval and setval functions
For sequences, the USAGE privilege allows the use of the currval and nextval functions
If you need to have the permission to modify the sequence, you can directly grant ALL, as follows
GRANT SELECT, UPDATE, USAGE ON ALL SEQUENCES IN SCHEME PUBLIC TO zhangsan;
If you just use the sequence and don't need to modify it, you can empower USAGE
GRANT USAGE ON ALL SEQUENCES IN SCHEME PUBLIC TO zhangsan;