a tomato

トマトが大好きです

データベースに接続中のセッションを強制切断する方法

データベースに関する設定を行う時に、接続中のユーザがいると操作が正常に行えない場合があります。 そんな場合の対処です。

f:id:kzdev:20170921125812p:plain

前提

Software Version
PostgreSQL 9.6.1

手順

postgres=# alter database xxxxdb rename to xxxxdb_org;
ERROR:  database "xxxxdb" is being accessed by other users
DETAIL:  There are 2 other sessions using the database.

この場合、接続中のユーザセッションを強制的に切断後に再実行します。
まずは、接続中のユーザのpidを以下のコマンドで求めます。

postgres=# SELECT pid FROM pg_stat_activity where pid <> pg_backend_pid();
  pid  
-------
 15725
 16586
(2 rows)

参考 PostgreSQL: Documentation: 9.6: System Administration Functions

上記のように2ユーザいるので、それぞれのpidを強制切断します。

SELECT pg_terminate_backend(15725);
 pg_terminate_backend 
----------------------
 t
(1 row)

SELECT pg_terminate_backend(16586);
 pg_terminate_backend 
----------------------
 t
(1 row)

これで再実行します。

postgres=# alter database xxxxdb rename to xxxxdb_org;
postgres=#