postgreSQL:如何使用 ROLE 允许完全访问给定角色的所有用户部分(例如,在访问 table 之前不使用 SET ROLE)

postgreSQL: How to use ROLE to allow full access to all users part of a given role (without using SET ROLE prior accessing a table for instance)

我带着 SQL 服务器背景来到 postgreSQL 并且天真地将相同的概念应用到 postgreSQL 以允许不同的用户共享 'by default' 数据库中的一些对象。

这是我所做的:

CREATE DATABASE testdb;
CREATE ROLE testdb_role_full INHERIT;
GRANT ALL PRIVILEGES ON DATABASE testdb TO testdb_role_full;

CREATE USER user1 INHERIT; 
GRANT testdb_role_full TO user1;

CREATE USER user2 INHERIT; 
GRANT testdb_role_full TO user2;

完成后,我使用 user1 创建了一个 table t1。 然后,我以 user2 的身份尝试读取 t1 table 并收到 "permission denied error"... :-(

看了文档,好像得先发出一个SET ROLE testdb_role_full才能充当testdb_role_full.

然而,这并不是我真正想要的。我不想让用户知道这一点。

所以我的问题是:

有什么方法可以实现吗?

非常感谢, 何塞

您已授予对数据库的某些权限,但这并不意味着任何具有 testdb_role_full 角色的用户都将拥有对该数据库内所有对象的所有权限。引用自the documentation

When an object is created, it is assigned an owner. The owner is normally the role that executed the creation statement. For most kinds of objects, the initial state is that only the owner (or a superuser) can do anything with the object. To allow other roles to use it, privileges must be granted.

所以在 user1 创建了 table t1 之后,他是所有者并且只有他有权限。他需要 运行

GRANT ALL PRIVILEGES ON TABLE t1 TO testdb_role_full;

然后 user2 也可以访问它(无需切换任何角色 - 只有当角色具有 NOINHERIT 属性时才有必要)。


如果您不希望用户每次在数据库中创建新对象时都必须执行 GRANT,您可以 alter the default privileges 每次创建对象时都会应用user2:

ALTER DEFAULT PRIVILEGES FOR user2
  GRANT ALL PRIVILEGES ON TABLES TO testdb_role_full;

注意这些仅指定初始值,如果 user2 想阻止其他人看到它们,他可以撤销对他的 table 的特权。