假设我有两个
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不允许这样做.所以我们不必检查.