zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

PostgreSQL数据库创建只读用户总结

数据库postgresql 总结 创建 用户 只读
2023-09-27 14:26:06 时间

 

好久没有弄,有点忘了,今天有客户问这个问题,发现几个SQL还解决不了,于是总结一下:

 

--以超级用户登录数据库,创建用户:

postgres=# create user test_read_only password 'test_read_only';

CREATE ROLE

 

--设置为只读的transaction:

postgres=# alter user test_read_only set default_transaction_read_only=on;

ALTER ROLE

 

--默认在postgres数据库的public模式下的对象是可以访问的:

--如果要访问别的schema的表,则需要两步:

 

--首先要有使用schema的权限:

postgres=# grant usage on schema test to test_read_only;

 

--然后加所有表的只读权限:

postgres=# grant select on all tables in schema public to test_read_only;

GRANT

 

--如果不想给所有表的查询权限,则单独给某个表的查询权限:

postgres=# grant select on table test to test_read_only;

GRANT

 

--如果要在别的数据库访问,则先要用postgres(超级用户登录),然后\c到对应的数据库,执行下面的命令,将对应的schema的表查询权限给这个用户:

postgres=# \c test

You are now connected to database "test" as user "postgres".

 

--test数据库的public模式的usage权限是默认就有的,只需要添加表的只读权限即可:

test=# grant select on all tables in schema public to test_read_only;

GRANT

 

--如果是将某个模式下的所有表的只读权限都给了某个用户,当新建表的时候,该用户仍然没有任何权限,这时,需要手动添加,或者修改模式的属性:

test=# alter default privileges in schema public grant select on tables to test_read_only;

ALTER DEFAULT PRIVILEGES

 

--这样即使是该模式中新加的表,test_read_only用户都有只读权限。