PostgreSQL:访问另一个用户拥有的表

时间:2017-05-22 20:26:37

标签: postgresql access roles owner

我在同一模式的postgreSql中创建了两个来自超级用户的角色。

1)read_only_with_create_view
2)read_write

然后我从每个角色创建了两个用户。 (read_only_with_create_view_user和read_write)

现在,read_write_user无法访问read_only_with_create_view_user创建的任何新视图,因为视图的所有者是不同的(read_only_with_create_view_user)。

那么read_write_user访问所有新视图的方式是什么?

基本上我想要实现的是一个用户创建的所有内容都应该可供其他用户访问。

我遵循的步骤:

CREATE ROLE read_only_role WITH
NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE NOREPLICATION VALID UNTIL 'infinity';

GRANT CONNECT ON DATABASE mydb to read_only_role;
GRANT USAGE,CREATE ON SCHEMA myschema TO read_only_role;
GRANT SELECT ON ALL TABLES IN SCHEMA myschema TO read_only_role;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA myschema TO read_only_role;

CREATE USER read_only_with_create_view_user
WITH PASSWORD '*****'
in ROLE read_only_role;

-- Now created new views using this role. That means read_only_with_create_view_user is owner of those views.

-- Creating new read-write role. 

CREATE ROLE rw_role WITH
NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE NOREPLICATION VALID UNTIL 'infinity' IN ROLE read_only_role;

GRANT CONNECT ON DATABASE mydb to rw_role;

GRANT USAGE ON SCHEMA myschema TO crn_rw_role_qa;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA myschema TO rw_role;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA myschema TO rw_role;

CREATE USER read_write_user
WITH PASSWORD '*****'
in role rw_role;

So after login with read_write_user when I try to access new views created by read_only_with_create_view_user, I get below error


ERROR:  permission denied for relation view_name
********** Error **********

ERROR: permission denied for relation view_name
SQL state: 42501

谢谢,
人士Himanshu

1 个答案:

答案 0 :(得分:1)

您可以将角色设置为其他角色的成员:

GRANT read_only_with_create_view_user TO read_write_user; 

更多信息here

<小时/> 的修改

它永远不会像你期望的那样工作。查看您当前的用户架构:

enter image description here

角色read_write_user将无法访问read_only_with_create_view_user拥有的对象,因为两者之间没有任何关系。要使其工作,您必须将对象所有权重新分配给&#34;鞋帮&#34;级别角色:read_only_role(因为每个人都是这个角色的成员)。

您可以执行以下操作之一:

--Connected as read_only_with_create_view_user
CREATE VIEW my_view AS SELECT 1;

--Assign ownership to top-level role
ALTER VIEW my_view OWNER TO read_only_role;

或者您可能更喜欢这种方法:

--Connected as read_only_with_create_view_user
--Change current user to read_only_role
SET role = read_only_role;

--Create a view...
CREATE VIEW my_view AS SELECT 1;

--Turn back to read_only_with_create_view_user
RESET role;

当然,您也可以直接向该对象授予权限。

CREATE VIEW my_view_2 AS SELECT 1;
GRANT SELECT ON my_view_2 TO read_write_user

如果您希望一次完成所有操作,只需一个命令即可将read_only_with_create_view_user拥有的对象的所有权重新分配给您的顶级角色:

REASSIGN OWNED BY read_only_with_create_view_user TO read_only_role;