创建一个 PostgreSQL 只读用户

常规流程

正常的思路是创建一个用户,再挨个将 database、schema、table 的权限授权给用户。

# To create a new user in PostgreSQL
CREATE USER username WITH PASSWORD 'password';
# GRANT the CONNECT access
GRANT CONNECT ON DATABASE database_name TO username;
# Then GRANT USAGE on schema
GRANT USAGE ON SCHEMA schema_name TO username;
# Grant SELECT for a specific table
GRANT SELECT ON table_name TO username;
GRANT SELECT ON ALL TABLES IN SCHEMA schema_name TO username;
# If you want to grant access to the new table in the future automatically, you have to alter default
ALTER DEFAULT PRIVILEGES IN SCHEMA schema_name
GRANT SELECT ON TABLES TO username;

但是操作比较繁琐,容易出错。可以采用创建一个超级用户取消事务插入权限的方式来替换。

超级用户流程

A simple way is Create a user with superuser privileges and read only permission.

# Login psql as postgres or other superuser.
# Create the new superuser role and set it to read only :
CREATE USER backupadmn WITH PASSWORD 'pwd' SUPERUSER ;
ALTER USER backupadmn set default_transaction_read_only = on;

参考

Infee Fang
Infee Fang
互联网二手搬砖工