微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

postgresql – 如何获取用户所属的所有角色(包括继承的角色)?

假设我有两个 Postgresql数据库组,“作者”和“编辑”,以及两个用户,“maxwell”和“ernest”.
create role authors;

create role editors;

create user maxwell;

create user ernest;

grant authors to editors; --editors can do what authors can do

grant editors to maxwell; --maxwell is an editor

grant authors to ernest; --ernest is an author

我想编写一个性能函数,它返回maxwell所属的角色列表(最好是它们的oid),如下所示:

create or replace function get_all_roles() returns oid[] ...

它应该返回maxwell,作者和编辑的oids(但不是ernest).

但是,当有继承时,我不确定如何做到这一点.

您可以使用 recursive query查询系统目录,尤其是 pg_auth_members
WITH RECURSIVE cte AS (
   SELECT oid FROM pg_roles WHERE rolname = 'maxwell'

   UNION ALL
   SELECT m.roleid
   FROM   cte
   JOIN   pg_auth_members m ON m.member = cte.oid
)
SELECT oid FROM cte;

BTW,INHERIT是CREATE ROLE认行为,不必拼写出来.

BTW2:循环依赖是不可能的. Postgres不允许这样做.所以我们不必检查.

原文地址:https://www.jb51.cc/postgresql/192356.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐