如何杀死我所有的postgresql连接?

我试着耙db:下降,但我得到:

ERROR:  database "database_name" is being accessed by other users
DETAIL:  There are 1 other session(s) using the database.

我尝试过关闭我从ps -ef | grep postgres中看到的进程,但这也不起作用:

kill: kill 2358 failed: operation not permitted

当前回答

答案隐藏在上面的一条评论中:brew服务重新启动postgresql

其他回答

可以使用pg_terminate_backend()终止连接。你必须是超级用户才能使用这个功能。这在所有操作系统上都是一样的。

SELECT 
    pg_terminate_backend(pid) 
FROM 
    pg_stat_activity 
WHERE 
    -- don't kill my own connection!
    pid <> pg_backend_pid()
    -- don't kill the connections to other databases
    AND datname = 'database_name'
    ;

在执行这个查询之前,你必须撤销CONNECT权限以避免新的连接:

REVOKE CONNECT ON DATABASE dbname FROM PUBLIC, username;

如果你正在使用Postgres 8.4-9.1,请使用procpid而不是pid

SELECT 
    pg_terminate_backend(procpid) 
FROM 
    pg_stat_activity 
WHERE 
    -- don't kill my own connection!
    procpid <> pg_backend_pid()
    -- don't kill the connections to other databases
    AND datname = 'database_name'
    ;

我在mac上,通过postgress。app使用postgres。我解决了这个问题,只是退出,重新开始应用程序。

我是这样解决的:

在我的Windows8 64位,只是重新启动服务:postgresql-x64-9.5

这似乎适用于PostgreSQL 9.1:

#{Rails.root}/lib/tasks/databases.rake
# monkey patch ActiveRecord to avoid There are n other session(s) using the database.
def drop_database(config)
  case config['adapter']
  when /mysql/
    ActiveRecord::Base.establish_connection(config)
    ActiveRecord::Base.connection.drop_database config['database']
  when /sqlite/
    require 'pathname'
    path = Pathname.new(config['database'])
    file = path.absolute? ? path.to_s : File.join(Rails.root, path)

    FileUtils.rm(file)
  when /postgresql/
    ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
    ActiveRecord::Base.connection.select_all("select * from pg_stat_activity order by procpid;").each do |x|
      if config['database'] == x['datname'] && x['current_query'] =~ /<IDLE>/
        ActiveRecord::Base.connection.execute("select pg_terminate_backend(#{x['procpid']})")
      end
    end
    ActiveRecord::Base.connection.drop_database config['database']
  end
end

从这里和这里的胃肠道谱上提取的。

下面是一个修改后的版本,适用于PostgreSQL 9.1和9.2。

如果你需要断开一个特定用户的会话,这有助于我:

检查当前所有连接:

select * from pg_stat_activity; 

授予你的用户一个角色(不重要):

set role "db_admin";

杀死届:

select pg_terminate_backend(pid)
from pg_stat_activity
where usename = '*** USER NAME TO DISCONNECT ***';