PG数据库如何新建只读用户

一 新建全局只读账号
以超级用户登录数据库,创建用户。

create user test password 'test' superuser;

设置为只读transaction

alter role test set default_transaction_read_only=true;
image
二 新建单个schema只读账号
以超级用户登录数据库,创建用户。

create user readonly password 'readonly';

设置为只读transaction

alter user readonly set default_transaction_read_only=on;

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

访问postgres数据库的schema
赋给使用schema的权限

grant usage on schema pg_toast to read_only;

添加所有表的只读权限

grant select on all tables in schema pg_toast to read_only;
image
也可以单独给某个表的查询权限

grant select on table tablename to read_only;

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

\c huanyu_fi

如上用户readonly在huanyu_fi数据库public模式的usage权限是默认就有的,只需要添加表的只读权限即可。

grant select on all tables in schema public to read_only;
image
如果是将某个模式下的所有表的只读权限都给了某个用户,当新建表的时候,该用户仍然没有任何权限。则需要手动添加或者修改模式的属性。

alter default privileges in schema public grant select on tables to read_only;
image
这样即使是该模式中新加的表,read_only用户也有只读权限。