Postgresql

在 PostgreSQL 中重新分配所有權並刪除舊所有者

  • July 14, 2022

我有一個 PSQL 13.6 數據庫,它最初是由 創建的owner_1,並且隨著時間的推移而被填充。由於外部原因,我現在需要定期更改數據庫的所有者帳戶並刪除舊使用者帳戶。當我嘗試實現這一點時,我被阻止了,因為有些對象依賴於它。

我不想冒險失去manager_role可能存在的或任何級聯依賴項的特權。

我怎樣才能找到並轉移仍然擁有的對象owner_1

你:

  1. 作為postgres使用者:創建owner_1.
CREATE USER owner_1 WITH CREATEDB CREATEROLE ENCRYPTED PASSWORD 'owner_password_1';
  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;
  1. 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 | {}
  1. 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 

你有兩個選擇:

  • 顯式刪除預設權限:
ALTER DEFAULT PRIVILEGES FOR ROLE owner_1 IN SCHEMA public
  REVOKE ALL ON TABLES FROM manager_role;
  • 刪除角色擁有的所有對象和權限:
DROP OWNED BY owner_1;

我找到了一種解決方法,這將導致所需的狀態。

而不是創建owner_role,授予它owner_1,重新分配所有權等。我可以轉換owner_1owner_role這意味著我不再需要放棄owner_1並且仍然可以創建一個新的所有者使用者,然後可以定期更改。

你:

執行上述步驟 1 和 2。

  1. As :在角色owner_1中創建一個新使用者owner_1
CREATE USER owner_2 WITH CREATEDB CREATEROLE ENCRYPTED PASSWORD 'owner_password_2' IN ROLE owner_role;
  1. 作為owner_2:轉換owner_1owner_2
ALTER ROLE owner_1 RENAME TO owner_role;
ALTER ROLE owner_role WITH NOLOGIN;

nowowner_2可用於創建owner_3下次需要更改帳戶時,只要始終( )owner_2執行命令,刪除應該沒有問題。 owner_role``SET ROLE owner_role;``owner_2

引用自:https://dba.stackexchange.com/questions/314379