PostgreSQL 实现快速删除一个用户
一、具体方法
一般情况下直接执行 drop role xxx; 就可以把这个用户删除。但是很多时候会因为用户有依赖而报错。
二、权限依赖
postgres=# create role test with login;
CREATE ROLEpostgres=# grant all on database postgres to test;GRANTpostgres=# drop role test;ERROR: role "test" cannot be dropped because some objects depend on itDETAIL: privileges for database postgres可以看出,因为我们把数据库postgres 的权限赋予了test 用户,所以直接删除的时候会报错。面对这种情况,我们需要先将role 的权限所有的权限全部revoke 掉,如下:
postgres=# revoke all on database postgres from test;
REVOKEpostgres=# drop role test;DROP ROLE注意:需要把该用户在所有数据库具有权限的所有数据库对象的(表,视图,SEQUENCE)权限全部回收,才能删除该用户。
三、对象依赖
postgres=# create role test with login;
CREATE ROLEpostgres=# \c - testYou are now connected to database "postgres" as user "test".postgres=> create table test (id int);CREATE TABLEpostgres=# \c - postgresYou are now connected to database "postgres" as user "postgres".postgres=# drop role test;ERROR: role "test" cannot be dropped because some objects depend on itDETAIL: owner of table test可以看出,因为test 用户是test 表的owner,所以删除的时候报错owner of table test。如果不需要保留该对象,则需要先把该依赖对象删除。如果需要保留该对象,则应该在删除之前先把owner 赋予别人,如下:
postgres=# alter table test OWNER TO postgres;
ALTER TABLEpostgres=# drop role test;DROP ROLE注意:需要把该用户在所有数据库具有owner 权限的所有数据库对象(表,视图,SEQUENCE)删除或者执行alter xx owner to,才能删除该用户。
四、更改数据库角色拥有的数据库对象的所有权
1、如果不保留owner 的数据库对象
postgres=# REASSIGN OWNED BY test TO postgres;
REASSIGN OWNEDpostgres=# DROP OWNED BY test;DROP OWNEDpostgres=# drop role test;DROP ROLE2、如果保留owner 的数据库对象
postgres=# REASSIGN OWNED BY test TO postgres;
REASSIGN OWNEDpostgres=# drop role test;DROP ROLE注意:REASSIGN OWNED 需要执行者所属的role (或者子集)必须包含test 和postgres 或者是superuser。另外必须所有涉及到的数据库上都执行该以上语句才能删除用户。
知识分享,需人人参与,看完请点赞留言,共同讨论进步

浙公网安备 33010602011771号