终止 postgresql 会话/连接

发布于 2024-10-18 20:32:39 字数 340 浏览 3 评论 0原文

如何终止所有 postgresql 连接?

我正在尝试 rake db:drop 但我得到:

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

How can I kill all my postgresql connections?

I'm trying a rake db:drop but I get:

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

I've tried shutting down the processes I see from a ps -ef | grep postgres but this doesn't work either:

kill: kill 2358 failed: operation not permitted

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(25

痴梦一场 2024-10-25 20:32:39

您可以使用 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'
    ;

在执行此查询之前,您必须REVOKE 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'
    ;

You can use pg_terminate_backend() to kill a connection. You have to be superuser to use this function. This works on all operating systems the same.

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'
    ;

Before executing this query, you have to REVOKE the CONNECT privileges to avoid new connections:

REVOKE CONNECT ON DATABASE dbname FROM PUBLIC, username;

If you're using Postgres 8.4-9.1 use procpid instead of 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'
    ;
岁月无声 2024-10-25 20:32:39

也许只需重新启动 postgres => sudo 服务 postgresql 重新启动

Maybe just restart postgres => sudo service postgresql restart

夏夜暖风 2024-10-25 20:32:39

有关运行过程的所有信息:

SELECT *, pg_terminate_backend(pid)
FROM pg_stat_activity 
WHERE pid <> pg_backend_pid()
AND datname = 'my_database_name';

With all infos about the running process:

SELECT *, pg_terminate_backend(pid)
FROM pg_stat_activity 
WHERE pid <> pg_backend_pid()
AND datname = 'my_database_name';
青衫儰鉨ミ守葔 2024-10-25 20:32:39

MacOS,如果 postgresqlbrew 一起安装:

brew services restart postgresql

来源:终止 postgresql 会话/连接

MacOS, if postgresql was installed with brew:

brew services restart postgresql

Source: Kill a postgresql session/connection

为人所爱 2024-10-25 20:32:39

更简单、更新的方法是:

  1. 使用 ps -ef | grep postgres 查找连接 #
  2. sudo Kill -9 "#" 该连接

注意:可能有相同的 PID。杀死一个人就等于杀死所有人。

Easier and more updated way is:

  1. Use ps -ef | grep postgres to find the connection #
  2. sudo kill -9 "#" of the connection

Note: There may be identical PID. Killing one kills all.

昔日梦未散 2024-10-25 20:32:39

OSX、Postgres 9.2(使用自制程序安装)

$ launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
$ pg_ctl restart -D /usr/local/var/postgres
$ launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

如果您的数据目录在其他地方,您可以通过检查 ps aux | 的输出来找出它在哪里。 grep postgres

OSX, Postgres 9.2 (installed with homebrew)

$ launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
$ pg_ctl restart -D /usr/local/var/postgres
$ launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

If your datadir is elsewhere you can find out where it is by examining the output of ps aux | grep postgres

记忆里有你的影子 2024-10-25 20:32:39

如果您需要断开特定用户的会话,这对我有帮助:

检查所有当前连接:

select * from pg_stat_activity; 

向您的用户授予角色(不重要):

set role "db_admin";

终止会话:

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

If you need to disconnect sessions of a particular user, this helped me:

Check all current connections:

select * from pg_stat_activity; 

Grant a role to your user (not important):

set role "db_admin";

Kill sessions:

select pg_terminate_backend(pid)
from pg_stat_activity
where usename = '*** USER NAME TO DISCONNECT ***';
﹎☆浅夏丿初晴 2024-10-25 20:32:39
SELECT 
pg_terminate_backend(pid) 
FROM 
pg_stat_activity 
WHERE
pid <> pg_backend_pid()
-- no need to kill connections to other databases
AND datname = current_database();
-- use current_database by opening right query tool
SELECT 
pg_terminate_backend(pid) 
FROM 
pg_stat_activity 
WHERE
pid <> pg_backend_pid()
-- no need to kill connections to other databases
AND datname = current_database();
-- use current_database by opening right query tool
坚持沉默 2024-10-25 20:32:39

这似乎适用于 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。

This seems to be working for 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

Lifted from gists found here and here.

Here's a modified version that works for both PostgreSQL 9.1 and 9.2.

还不是爱你 2024-10-25 20:32:39

MacOS,如果postgresql是用brew:

brew services restart postgresql

UBUNTU安装的,

首先检查这个(杀死后台运行的服务器)

sudo kill -9 $(lsof -i :3000 -t)

如​​果没有找到pid那么你只需要重新启动
提到的 Postgresql 服务命令如下:

sudo service postgresql restart

MacOS, if postgresql was installed with brew:

brew services restart postgresql

UBUNTU,

firstly check with this (kill server which is running in background)

sudo kill -9 $(lsof -i :3000 -t)

if you didn't find pid Then you just need to restart
Postgresql service by command which is mention are as under:

sudo service postgresql restart
很酷又爱笑 2024-10-25 20:32:39

我使用以下 rake 任务来覆盖 Rails drop_database 方法。

lib/database.rake

require 'active_record/connection_adapters/postgresql_adapter'
module ActiveRecord
  module ConnectionAdapters
    class PostgreSQLAdapter < AbstractAdapter
      def drop_database(name)
        raise "Nah, I won't drop the production database" if Rails.env.production?
        execute <<-SQL
          UPDATE pg_catalog.pg_database
          SET datallowconn=false WHERE datname='#{name}'
        SQL

        execute <<-SQL
          SELECT pg_terminate_backend(pg_stat_activity.pid)
          FROM pg_stat_activity
          WHERE pg_stat_activity.datname = '#{name}';
        SQL
        execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}"
      end
    end
  end
end

编辑:这适用于 Postgresql 9.2+

I use the following rake task to override the Rails drop_database method.

lib/database.rake

require 'active_record/connection_adapters/postgresql_adapter'
module ActiveRecord
  module ConnectionAdapters
    class PostgreSQLAdapter < AbstractAdapter
      def drop_database(name)
        raise "Nah, I won't drop the production database" if Rails.env.production?
        execute <<-SQL
          UPDATE pg_catalog.pg_database
          SET datallowconn=false WHERE datname='#{name}'
        SQL

        execute <<-SQL
          SELECT pg_terminate_backend(pg_stat_activity.pid)
          FROM pg_stat_activity
          WHERE pg_stat_activity.datname = '#{name}';
        SQL
        execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}"
      end
    end
  end
end

Edit: This is for Postgresql 9.2+

那伤。 2024-10-25 20:32:39

我遇到了这个问题,问题是 Navicat 连接到了我本地的 Postgres 数据库。一旦我断开 Navicat 的连接,问题就消失了。

编辑:

此外,作为绝对的最后手段,您可以备份数据,然后运行此命令:

sudo kill -15 `ps -u postgres -o pid`

...这将杀死postgres 用户正在访问的所有内容。避免在生产计算机上执行此操作,但在开发环境中应该不会有问题。在此之后尝试重新启动 PostgreSQL 之前,确保每个 postgres 进程确实终止是至关重要的。

编辑2:

由于 这篇 unix.SE 帖子,我已从 kill -9 更改为kill -15

I had this issue and the problem was that Navicat was connected to my local Postgres db. Once I disconnected Navicat the problem disappeared.

EDIT:

Also, as an absolute last resort you can back up your data then run this command:

sudo kill -15 `ps -u postgres -o pid`

... which will kill everything that the postgres user is accessing. Avoid doing this on a production machine but you shouldn't have a problem with a development environment. It is vital that you ensure every postgres process has really terminated before attempting to restart PostgreSQL after this.

EDIT 2:

Due to this unix.SE post I've changed from kill -9 to kill -15.

所谓喜欢 2024-10-25 20:32:39

我这样解决了:

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

I'VE SOLVED THIS WAY:

In my Windows8 64 bit, just restarting the service: postgresql-x64-9.5

离鸿 2024-10-25 20:32:39

在 PG 管理中,您可以断开服务器连接(右键单击服务器)&所有会话将在重新启动时断开连接

In PG admin you can disconnect your server (right click on the server) & all sessions will be disconnected at restart

三生路 2024-10-25 20:32:39

首先,找到要关闭的查询/连接的 PID(请参阅 如何列出 PostgreSQL 上的活动连接?

mydb=> select pid, application_name, state, query from pg_stat_activity where application_name = 'myapp';
 pid  | application_name | state | query 
------+------------------+-------+-------
 1234 | myapp            | idle  | 
 5678 | myapp            | idle  | 
(2 rows)

然后,像这样关闭与您选择的 PID 的连接

mydb=> SELECT pg_terminate_backend(1234);

First, locate the PID of the query/connection you want to close (see How to list active connections on PostgreSQL?)

mydb=> select pid, application_name, state, query from pg_stat_activity where application_name = 'myapp';
 pid  | application_name | state | query 
------+------------------+-------+-------
 1234 | myapp            | idle  | 
 5678 | myapp            | idle  | 
(2 rows)

Then, closing the connection with the PID you picked like this

mydb=> SELECT pg_terminate_backend(1234);
缪败 2024-10-25 20:32:39

只是想指出,如果其他后台进程正在使用数据库,哈里斯的答案可能不起作用,在我的情况下,它是延迟的作业,我这样做了:

script/delayed_job stop

只有这样我才能删除/重置数据库。

Just wanted to point out that Haris's Answer might not work if some other background process is using the database, in my case it was delayed jobs, I did:

script/delayed_job stop

And only then I was able to drop/reset the database.

一身仙ぐ女味 2024-10-25 20:32:39

退出 postgres 并重新启动它。很简单,但每次都对我有用,而其他 cli 命令有时却不起作用。

Quit postgres and restart it. Simple, but works every time for me, where other cli commands sometimes don't.

风蛊 2024-10-25 20:32:39

没有必要丢弃它。只需删除并重新创建公共架构即可。在大多数情况下,这具有完全相同的效果。

namespace :db do

desc 'Clear the database'
task :clear_db => :environment do |t,args|
  ActiveRecord::Base.establish_connection
  ActiveRecord::Base.connection.tables.each do |table|
    next if table == 'schema_migrations'
    ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
  end
end

desc 'Delete all tables (but not the database)'
task :drop_schema => :environment do |t,args|
  ActiveRecord::Base.establish_connection
  ActiveRecord::Base.connection.execute("DROP SCHEMA public CASCADE")
  ActiveRecord::Base.connection.execute("CREATE SCHEMA public")
  ActiveRecord::Base.connection.execute("GRANT ALL ON SCHEMA public TO postgres")
  ActiveRecord::Base.connection.execute("GRANT ALL ON SCHEMA public TO public")
  ActiveRecord::Base.connection.execute("COMMENT ON SCHEMA public IS 'standard public schema'")
end

desc 'Recreate the database and seed'
task :redo_db => :environment do |t,args|
  # Executes the dependencies, but only once
  Rake::Task["db:drop_schema"].invoke
  Rake::Task["db:migrate"].invoke
  Rake::Task["db:migrate:status"].invoke 
  Rake::Task["db:structure:dump"].invoke
  Rake::Task["db:seed"].invoke
end

end

There is no need to drop it. Just delete and recreate the public schema. In most cases this have exactly the same effect.

namespace :db do

desc 'Clear the database'
task :clear_db => :environment do |t,args|
  ActiveRecord::Base.establish_connection
  ActiveRecord::Base.connection.tables.each do |table|
    next if table == 'schema_migrations'
    ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
  end
end

desc 'Delete all tables (but not the database)'
task :drop_schema => :environment do |t,args|
  ActiveRecord::Base.establish_connection
  ActiveRecord::Base.connection.execute("DROP SCHEMA public CASCADE")
  ActiveRecord::Base.connection.execute("CREATE SCHEMA public")
  ActiveRecord::Base.connection.execute("GRANT ALL ON SCHEMA public TO postgres")
  ActiveRecord::Base.connection.execute("GRANT ALL ON SCHEMA public TO public")
  ActiveRecord::Base.connection.execute("COMMENT ON SCHEMA public IS 'standard public schema'")
end

desc 'Recreate the database and seed'
task :redo_db => :environment do |t,args|
  # Executes the dependencies, but only once
  Rake::Task["db:drop_schema"].invoke
  Rake::Task["db:migrate"].invoke
  Rake::Task["db:migrate:status"].invoke 
  Rake::Task["db:structure:dump"].invoke
  Rake::Task["db:seed"].invoke
end

end
ぇ气 2024-10-25 20:32:39

远程场景。但是,如果您尝试在 Rails 应用程序中运行测试,并且会收到类似

“ActiveRecord::StatementInvalid: PG::ObjectInUse: ERROR: 数据库“myapp_test”正在被其他用户访问” 的信息
详细信息:还有 1 个其他会话正在使用该数据库。”

确保在运行测试之前关闭 pgAdmin 或任何其他 postgres GUI 工具。

Remote scenario. But if you're trying to run tests in a rails app, and you get something like

"ActiveRecord::StatementInvalid: PG::ObjectInUse: ERROR: database "myapp_test" is being accessed by other users
DETAIL: There is 1 other session using the database."

Make sure you close pgAdmin or any other postgres GUI tools before running tests.

青衫负雪 2024-10-25 20:32:39

案例:
无法执行查询:

DROP TABLE dbo.t_tabelname

解决方案:
一个。显示查询状态活动如下:

SELECT * FROM pg_stat_activity  ;

b.查找“查询”列包含的行:

'DROP TABLE dbo.t_tabelname'

c.在同一行中,获取“PID”列

example : 16409

d 的值。执行这些脚本:

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

Case :
Fail to execute the query :

DROP TABLE dbo.t_tabelname

Solution :
a. Display query Status Activity as follow :

SELECT * FROM pg_stat_activity  ;

b. Find row where 'Query' column has contains :

'DROP TABLE dbo.t_tabelname'

c. In the same row, get value of 'PID' Column

example : 16409

d. Execute these scripts :

SELECT 
    pg_terminate_backend(25263) 
FROM 
    pg_stat_activity 
WHERE 
    -- don't kill my own connection!
    25263 <> pg_backend_pid()
    -- don't kill the connections to other databases
    AND datname = 'database_name'
    ;
岁月流歌 2024-10-25 20:32:39

我使用的是 Mac,通过 Postgres.app 使用 postgres。我解决了这个问题,只是退出并重新启动应用程序。

I'm on a mac and I use postgres via Postgres.app. I solved this problem just quitting and starting again the app.

一枫情书 2024-10-25 20:32:39

打开 PGadmin 看看是否有任何查询页面打开,关闭所有查询页面并断开 PostgresSQL 服务器并再次连接并尝试删除/删除选项。这对我有帮助。

Open PGadmin see if there is any query page open, close all query page and disconnect the PostgresSQL server and Connect it again and try delete/drop option.This helped me.

め可乐爱微笑 2024-10-25 20:32:39

上面的答案之一无疑给了我在 Windows 中解决这个问题的想法。

从 Windows 打开服务,找到 Postgres 服务并重新启动它。

Definitely one of the answers above gave me the idea for solving it in Windows.

Open the Services from Windows, locate the Postgres service and restart it.

没有伤那来痛 2024-10-25 20:32:39

对我来说,做了以下工作:

sudo gitlab-ctl stop
sudo gitlab-ctl start gitaly
sudo gitlab-rake gitlab:setup [type yes and let it finish]
sudo gitlab-ctl start

我正在使用:
gitlab_edition:“gitlab-ce”
gitlab_版本:'12.4.0-ce.0.el7'

For me worked the following:

sudo gitlab-ctl stop
sudo gitlab-ctl start gitaly
sudo gitlab-rake gitlab:setup [type yes and let it finish]
sudo gitlab-ctl start

I am using:
gitlab_edition: "gitlab-ce"
gitlab_version: '12.4.0-ce.0.el7'

毁我热情 2024-10-25 20:32:39

答案隐藏在上面的评论之一中:brew services restart postgresql

the answer is hidden in one of the comments above: brew services restart postgresql

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文