我有一个 PSQL 13.6 数据库,它最初是由 创建的owner_1
,并且随着时间的推移而被填充。由于外部原因,我现在需要定期更改数据库的所有者帐户并删除旧用户帐户。当我尝试实现这一点时,我被阻止了,因为有些对象依赖于它。
我不想冒险失去manager_role
可能存在的或任何级联依赖项的特权。
我怎样才能找到并转移仍然拥有的对象owner_1
?
MWE:
- 作为
postgres
用户:创建owner_1
.
CREATE USER owner_1 WITH CREATEDB CREATEROLE ENCRYPTED PASSWORD 'owner_password_1';
- As
owner_1
:设置数据库和对象。
CREATE DATABASE test_db;
\c test_db
CREATE ROLE manager_role;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE ON TABLES TO manager_role;
CREATE USER manager_1 WITH ENCRYPTED PASSWORD 'manager_password_1' IN ROLE manager_role;
- As
owner_1
:创建一个owner_role
,转移所有权,并在该角色中创建新用户。
CREATE ROLE owner_role WITH NOLOGIN NOSUPERUSER INHERIT CREATEDB CREATEROLE NOREPLICATION;
GRANT USAGE, CREATE ON SCHEMA public TO owner_role;
GRANT owner_role TO "owner_1";
REASSIGN OWNED BY owner_1 TO owner_role;
CREATE USER owner_2 WITH CREATEDB CREATEROLE ENCRYPTED PASSWORD 'owner_password_2' IN ROLE owner_role;
您现在应该拥有这些用户定义
\du
List of roles
Role name | Attributes | Member of
--------------+------------------------------------------------------------+----------------
manager_1 | | {manager_role}
manager_role | Cannot login | {}
owner_1 | Create role, Create DB | {owner_role}
owner_2 | Create role, Create DB | {owner_role}
owner_role | Create role, Create DB, Cannot login | {}
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
- As
owner_2
:删除旧用户。
DROP USER owner_1;
最后一个命令将失败并出现错误:
ERROR: role "owner_1" cannot be dropped because some objects depend on it
DETAIL: owner of default privileges on new relations belonging to role owner_1 in schema public
编辑DROP OWNED BY owner_1;
从用户
执行owner_2
失败并出现错误:
test_db=> DROP OWNED BY owner_1;
ERROR: permission denied to drop objects
你有两个选择:
显式删除默认权限:
删除角色拥有的所有对象和权限:
我找到了一种解决方法,这将导致所需的状态。
而不是创建
owner_role
,授予它owner_1
,重新分配所有权等。我可以转换owner_1
成owner_role
这意味着我不再需要放弃owner_1
并且仍然可以创建一个新的所有者用户,然后可以定期更改。MWE:
执行上述步骤 1 和 2。
owner_1
中创建一个新用户owner_1
owner_2
:转换owner_1
为owner_2
now
owner_2
可用于创建owner_3
下次需要更改帐户时,只要始终以( )owner_2
运行命令,删除应该没有问题。owner_role
SET ROLE owner_role;
owner_2