PostgreSQL 实现快速删除一个用户

时间:2021-05-24

背景

在多租户场景或者其他场景下,很多时候需要主动清理一些用户,本文将介绍PostgreSQL 下如何快速删除一个用户(role)。

具体方法

一般情况下直接执行 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,才能删除该用户。

更牛逼的方法

如果不保留owner 的数据库对象

postgres=# REASSIGN OWNED BY test TO postgres;REASSIGN OWNEDpostgres=# DROP OWNED BY test;DROP OWNEDpostgres=# drop role test;DROP ROLE

如果保留owner 的数据库对象

postgres=# REASSIGN OWNED BY test TO postgres;REASSIGN OWNEDpostgres=# drop role test;DROP ROLE

注意:REASSIGN OWNED 需要执行者所属的role (或者子集)必须包含test 和postgres 或者是superuser。另外必须所有涉及到的数据库上都执行该以上语句才能删除用户。

补充:PostgreSQL数据库创建/删除

方法1 - 系统命令

sudo su - postgres #切换到postgres用户(系统用户)createdb weichen #创建数据库psql #直接访问数据库(默认进入本地postgres数据库)\l --查看数据库列表:q --退出列表页面\q --退出客户端dropdb weichen #删除数据库

方法2 - psql命令行

sudo -u postgres psql #登录客户端create database weichen; --创建数据库create database sz owner postgres; --创建数据库select oid,datname from pg_database; --查看数据库列表drop database weichen; --删除数据库drop database sz; --删除数据库

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章