PostgreSQL DBA(138) - PG 13(Drop database force)

在PG 12或以下版本,删除数据库时如存在连接则无法删除,PG 13提供了force选项,可终止相关连接直接删除数据库。

PG 12
创建数据库并连接

[pg12@localhost ~]$ createdb dropdb
[pg12@localhost ~]$ 
[pg12@localhost ~]$ psql -d dropdb
Expanded display is used automatically.
psql (12.1)
Type "help" for help.
[local:/run/pg12]:5120 pg12@dropdb=#

删除数据库,一直在等待,超时后提示

[pg12@localhost ~]$ psql
Expanded display is used automatically.
psql (12.1)
Type "help" for help.
[local:/run/pg12]:5120 pg12@testdb=# drop database dropdb;
ERROR:  database "dropdb" is being accessed by other users
DETAIL:  There is 1 other session using the database.

PG 13
创建数据库并连接

[pg13@localhost ~]$ createdb dropdb
[pg13@localhost ~]$ psql -d dropdb
Expanded display is used automatically.
psql (13devel)
Type "help" for help.
[local:/run/pg13]:5130 pg13@dropdb=#

删除数据库,提示无法删除数据库

[pg13@localhost ~]$ psql
Expanded display is used automatically.
psql (13devel)
Type "help" for help.
[local:/run/pg13]:5130 pg13@masterdb=# drop database dropdb;
ERROR:  database "dropdb" is being accessed by other users
DETAIL:  There is 1 other session using the database.
[local:/run/pg13]:5130 pg13@masterdb=#

使用force选项删除

[local:/run/pg13]:5130 pg13@masterdb=# drop database dropdb with(force);
DROP DATABASE
[local:/run/pg13]:5130 pg13@masterdb=#

回到连接dropdb数据库的session,该session已被drop

[local:/run/pg13]:5130 pg13@dropdb=# select 1;
FATAL:  terminating connection due to administrator command
server closed the connection unexpectedly
    This probably means the server terminated abnormally
    before or while processing the request.
The connection to the server was lost. Attempting reset: Failed.
: @!>?

参考资料
Waiting for PostgreSQL 13 – Introduce the ‘force’ option for the Drop Database command.

请使用浏览器的分享功能分享到微信等