Home > 零敲碎打 > PostgreSQL创建ReadOnly只读用户

PostgreSQL创建ReadOnly只读用户

PostgreSQL可以通过schema和table级别对数据表进行只读控制
一般会使用PostgreSQL创建只读用户,然后给予相应的只读权限方式实现

通过使用

-- 创建readonly_user用户,密码为readonly_password
CREATE USER readonly_user WITH encrypted password 'readonly_password';
-- 设置readonly_user用户为只读事务
ALTER USER readonly_user SET default_transaction_read_only=ON;
-- 授予usage权限给到readonly_user用户
GRANT usage ON schema "public" TO readonly_user;
-- 将默认"public"schema下新建表的读取权限授予给readonly_user
ALTER DEFAULT privileges IN schema "public" GRANT SELECT ON TABLES TO readonly_user;
-- 授予select权限给到readonly_user用户
GRANT SELECT ON ALL TABLES IN schema "public" TO readonly_user;
GRANT SELECT ON ALL sequences IN schema "public" TO readonly_user;
-- 允许readonly_user用户连接到指定数据库
GRANT CONNECT ON DATABASE splrp_dev TO readonly_user;

注意:
已有的数据表进行readonly设置,可以通过

-- 授予usage权限给到readonly_user用户
GRANT usage ON schema "public" TO readonly_user;
-- 授予select权限给到readonly_user用户
GRANT SELECT ON ALL TABLES IN schema "public" TO readonly_user;
GRANT SELECT ON ALL sequences IN schema "public" TO readonly_user;

对于将来创建的新表,则需要通过

-- 将默认"public"schema下新建表的读取权限授予给readonly_user
ALTER DEFAULT privileges IN schema "public" GRANT SELECT ON TABLES TO readonly_user;

可以讲以后创建的table也赋予readonly_user只读权限。

Categories: 零敲碎打 Tags: ,
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.