PostgreSQL中role是权限的集合,没有区分用户和角色的概念,”CREATE USER” 为 “CREATE ROLE” 的别名,这两个命令几乎是完全相同的,唯一的区别是”CREATE USER” 命令创建的用户默认带有LOGIN属性,而”CREATE ROLE” 命令创建的用户默认不带LOGIN属性(CREATE USER is equivalent to CREATE ROLE except that CREATE USER assumes LOGIN by default, while CREATE ROLE does not)
为了方便用role的方式管理用户, 而不是每新建一个用户就授予权限一次.
准备
收回PUBLIC用户组对模式public的所有权限, 并创建测试用表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
jintao@jintao-ThinkPad-L490:~$ psql psql (14devel) Type "help" for help.
只对table, sequence, function 做了处理, 如type, procedure等类似
1 2 3 4 5 6 7 8 9 10 11 12 13 14
mydb=# create role readonly; CREATE ROLE mydb=# grant SELECT on ALL tables in schema public to readonly ; -- 赋予readonly对public模式下当前存在的表可读 GRANT mydb=# grant EXECUTE on ALL functions in schema public to readonly ; -- 赋予readonly对public模式下当前函数可执行 GRANT mydb=# grant SELECT on ALL sequences in schema public to readonly ; -- 赋予readonly对public模式下当前序列的可读 GRANT mydb=# alter default privileges for role postgres in schema public grant select on tables to readonly; -- 赋予readonly对public模式下之后对postgres用户新建的表可读 ALTER DEFAULT PRIVILEGES mydb=# alter default privileges for role postgres in schema public grant execute on functions to readonly; -- 赋予readonly对public模式下之后对postgres用户新建的函数可执行 ALTER DEFAULT PRIVILEGES mydb=# alter default privileges for role postgres in schema public grant select on sequences to readonly; - 赋予readonly对public模式下之后对postgres用户新建的序列可读 ALTER DEFAULT PRIVILEGES
创建读写角色
只对table, sequence, function 做了处理, 如type, procedure等类似
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
mydb=# grant all on SCHEMA public to readwrite ; -- 赋予readwrite对public模式下当前存在的表可读写 GRANT mydb=# grant ALL on ALL tables in schema public to readwrite ; GRANT mydb=# grant ALL on ALL sequences in schema public to readwrite ; GRANT mydb=# grant ALL on ALL functions in schema public to readwrite ; GRANT mydb=# alter default privileges for role postgres in schema public grant all on tables to readwrite; ALTER DEFAULT PRIVILEGES mydb=# alter default privileges for role postgres in schema public grant all on sequences to readwrite; ALTER DEFAULT PRIVILEGES mydb=# alter default privileges for role postgres in schema public grant all on functions to readwrite; ALTER DEFAULT PRIVILEGES