当会话或请求不再存在时,停止(长时间)在 PostgreSQL 中运行 SQL 查询?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3508627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stop (long) running SQL query in PostgreSQL when session or requests no longer exist?
提问by Kenny Shen
I'm not sure where to start on addressing this issue but if I have a AJAX web application that sends requests to the server and runs long queries on the database (postgresql in my case), is there a way to stop or kill the queries if while still running, the user refreshes the page or closes the session...etc?
我不确定从哪里开始解决这个问题,但是如果我有一个 AJAX Web 应用程序向服务器发送请求并在数据库上运行长查询(在我的例子中是 postgresql),有没有办法停止或终止查询如果仍在运行时,用户刷新页面或关闭会话...等?
回答by Frank Heikens
To stop the query:
要停止查询:
SELECT pg_cancel_backend(procpid);
To kill the database connection:
要终止数据库连接:
SELECT pg_terminate_backend(procpid);
To get an overview of the current transactions, to get the proced id's:
要获得当前交易的概览,要获取过程 ID:
SELECT * FROM pg_stat_activity;
http://www.postgresql.org/docs/current/interactive/functions-admin.html
http://www.postgresql.org/docs/current/interactive/functions-admin.html
回答by Tigra
Considering your psql configured to run and connect to current dev database this one liner comes handy in development when testing complicated queries which can hung, just kills whatever runs:
考虑到您的 psql 配置为运行并连接到当前的开发数据库,当测试可能挂起的复杂查询时,这个 liner 在开发中很方便,只会杀死任何运行:
If not configured properly - add flags for user/password/database
如果配置不正确 - 为用户/密码/数据库添加标志
psql -c "SELECT procpid FROM pg_stat_activity;" -t | xargs -n1 -I {} psql -c "SELECT pg_cancel_backend({})"
psql -c "SELECT procpid FROM pg_stat_activity;" -t | xargs -n1 -I {} psql -c "SELECT pg_cancel_backend({})"