# 22.3. Role Membership

It is frequently convenient to group users together to ease management of privileges: that way, privileges can be granted to, or revoked from, a group as a whole. In PostgreSQL this is done by creating a role that represents the group, and then grantingmembershipin the group role to individual user roles.

To set up a group role, first create the role:

CREATE ROLE name;

Typically a role being used as a group would not have theLOGINattribute, though you can set it if you wish.

Once the group role exists, you can add and remove members using theGRANTandREVOKEcommands:

GRANT group_role TO role1, ... ;
REVOKE group_role FROM role1, ... ;

You can grant membership to other group roles, too (since there isn't really any distinction between group roles and non-group roles). The database will not let you set up circular membership loops. Also, it is not permitted to grant membership in a role toPUBLIC.

The members of a group role can use the privileges of the role in two ways. First, every member of a group can explicitly doSET ROLEto temporarily “become” the group role. In this state, the database session has access to the privileges of the group role rather than the original login role, and any database objects created are considered owned by the group role not the login role. Second, member roles that have theINHERITattribute automatically have use of the privileges of roles of which they are members, including any privileges inherited by those roles. As an example, suppose we have done:

CREATE ROLE joe LOGIN INHERIT;
CREATE ROLE admin NOINHERIT;
CREATE ROLE wheel NOINHERIT;
GRANT admin TO joe;
GRANT wheel TO admin;

Immediately after connecting as rolejoe, a database session will have use of privileges granted directly to加上授予的任何特权行政, 因为“继承”行政的特权。但是,授予的特权车轮不可用,因为即使是间接的成员车轮, 成员资格是通过行政其中有非继承属性。后:

SET ROLE admin;

会话将只能使用授予给行政,而不是那些授予.后:

SET ROLE wheel;

会话将只能使用授予给车轮,而不是授予任何一方的或者行政.可以通过以下任何方式恢复原始特权状态:

SET ROLE joe;
SET ROLE NONE;
RESET ROLE;

# 笔记

设定角色命令始终允许选择原始登录角色直接或间接所属的任何角色。因此,在上面的例子中,没有必要变成行政在成为之前车轮.

# 笔记

在 SQL 标准中,用户和角色有明显的区别,用户不会自动继承权限,而角色会自动继承。这种行为可以在 PostgreSQL 中通过赋予被用作 SQL 角色的角色继承属性,同时赋予被用作 SQL 用户的角色非继承属性。但是,PostgreSQL 默认给所有角色继承属性,用于向后兼容 8.1 之前的版本,在该版本中,用户始终可以使用授予他们所属的组的权限。

角色属性登录,超级用户,创建数据库, 和创造者可以认为是特殊权限,但它们永远不会像数据库对象的普通权限那样被继承。你必须实际上设定角色到具有这些属性之一的特定角色,以便使用该属性。继续上面的例子,我们可能会选择授予创建数据库创造者行政角色。然后一个会话连接为角色不会立即拥有这些特权,只有在做之后设置角色管理员.

要销毁组角色,请使用删除角色

DROP ROLE name;

组角色中的任何成员资格都会被自动撤销(但成员角色不会受到其他影响)。