postgresql查看鎖的sql語句

發現一個查看postgresql鎖比較好的sql語句,參考鏈接地址如下

鏈接地址

查看鎖等待sql

witht_wait as(select a.mode,a.locktype,a.database,a.relation,a.page,a.tuple,a.classid,a.granted,a.objid,a.objsubid,a.pid,a.virtualtransaction,a.virtualxid,a.transactionid,a.fastpath,b.state,b.query,b.xact_start,b.query_start,b.usename,b.datname,b.client_addr,b.client_port,b.application_namefrom pg_locks a,pg_stat_activity b where a.pid=b.pid and not a.granted),t_run as(select a.mode,a.locktype,a.database,a.relation,a.page,a.tuple,a.classid,a.granted,a.objid,a.objsubid,a.pid,a.virtualtransaction,a.virtualxid,a.transactionid,a.fastpath,b.state,b.query,b.xact_start,b.query_start,b.usename,b.datname,b.client_addr,b.client_port,b.application_namefrom pg_locks a,pg_stat_activity b where a.pid=b.pid and a.granted),t_overlap as(select r.* from t_wait w join t_run r on(r.locktype is not distinct from w.locktype andr.database is not distinct from w.database andr.relation is not distinct from w.relation andr.page is not distinct from w.page andr.tuple is not distinct from w.tuple andr.virtualxid is not distinct from w.virtualxid andr.transactionid is not distinct from w.transactionid andr.classid is not distinct from w.classid andr.objid is not distinct from w.objid andr.objsubid is not distinct from w.objsubid andr.pid <> w.pid)),t_unionall as(select r.* from t_overlap runion allselect w.* from t_wait w)select locktype,datname,relation::regclass,page,tuple,virtualxid,transactionid::text,classid::regclass,objid,objsubid,string_agg('Pid: '||case when pid is null then 'NULL' else pid::text end||chr(10)||'Lock_Granted: '||case when granted is null then 'NULL' else granted::text end||' , Mode: '||case when mode is null then 'NULL' else mode::text end||' , FastPath: '||case when fastpath is null then 'NULL' else fastpath::text end||' , VirtualTransaction: '||case when virtualtransaction is null then 'NULL' else virtualtransaction::text end||' , Session_State: '||case when state is null then 'NULL' else state::text end||chr(10)||'Username: '||case when usename is null then 'NULL' else usename::text end||' , Database: '||case when datname is null then 'NULL' else datname::text end||' , Client_Addr: '||case when client_addr is null then 'NULL' else client_addr::text end||' , Client_Port: '||case when client_port is null then 'NULL' else client_port::text end||' , Application_Name: '||case when application_name is null then 'NULL' else application_name::text end||chr(10)||'Xact_Start: '||case when xact_start is null then 'NULL' else xact_start::text end||' , Query_Start: '||case when query_start is null then 'NULL' else query_start::text end||' , Xact_Elapse: '||case when (now()-xact_start) is null then 'NULL' else (now()-xact_start)::text end||' , Query_Elapse: '||case when (now()-query_start) is null then 'NULL' else (now()-query_start)::text end||chr(10)||'SQL (Current SQL in Transaction): '||chr(10)||case when query is null then 'NULL' else query::text end,chr(10)||'--------'||chr(10)order by( case modewhen 'INVALID' then 0when 'AccessShareLock' then 1when 'RowShareLock' then 2when 'RowExclusiveLock' then 3when 'ShareUpdateExclusiveLock' then 4when 'ShareLock' then 5when 'ShareRowExclusiveLock' then 6when 'ExclusiveLock' then 7when 'AccessExclusiveLock' then 8else 0end  ) desc,(case when granted then 0 else 1 end)) as lock_conflictfrom t_unionallgroup bylocktype,datname,relation,page,tuple,virtualxid,transactionid::text,classid,objid,objsubid ;

測試如下:

//session 1
test=# select * from test123;id |               info
----+----------------------------------1 | 101dc9e8c1d68234176830154b085ac72 | a43bf589b17bba8f38f117fda7a52b0d3 | daf21791ed3a9a45cca9ff1523d9090f4 | 92d9d4badb391f7e75d0c65bb720002e5 | f6a528c82a337412dbeff0a037bbb41b6 | 95e830bfd6789ff3b460f293ab1943e57 | a48251f4dc31eaaa8d9d14310fe7a66c8 | 0abd9628ccdeabe85f63de244019591a9 | 42a01ab80a13b64619d8b6371caf670b10 | 0048a0b3a4da91c05b7997b2f9a48156
(10 行記錄)test=#
test=#
test=#
test=#
test=#
test=# begin;
BEGIN
test=*# delete from test123 where id=1
DELETE 1//session 2,被hang住了test=# begin;
BEGIN
test=*# truncate table test123;

檢測結果:

locktype      | relation
datname       | test
relation      | test123
page          |
tuple         |
virtualxid    |
transactionid |
classid       |
objid         |
objsubid      |
lock_conflict | Pid: 8209                                                                                                                                            +| Lock_Granted: false , Mode: AccessExclusiveLock , FastPath: false , VirtualTransaction: 8/1931 , Session_State: active                               +| Username: sde , Database: test , Client_Addr: 192.168.100.182/32 , Client_Port: 6503 , Application_Name: psql                                        +| Xact_Start: 2025-06-30 10:35:22.978384+08 , Query_Start: 2025-06-30 10:35:32.866765+08 , Xact_Elapse: 00:09:33.288584 , Query_Elapse: 00:09:23.400203+| SQL (Current SQL in Transaction):                                                                                                                    +| truncate table test123;                                                                                                                              +| --------                                                                                                                                             +| Pid: 31733                                                                                                                                           +| Lock_Granted: true , Mode: RowExclusiveLock , FastPath: false , VirtualTransaction: 6/7257 , Session_State: idle in transaction                      +| Username: sde , Database: test , Client_Addr: 192.168.100.182/32 , Client_Port: 13683 , Application_Name: psql                                       +| Xact_Start: 2025-06-30 10:33:56.666653+08 , Query_Start: 2025-06-30 10:34:00.961553+08 , Xact_Elapse: 00:10:59.600315 , Query_Elapse: 00:10:55.305415+| SQL (Current SQL in Transaction):                                                                                                                    +| delete from test123 where id=1;

查看阻塞會話,并生成kill sql

with recursive 
tmp_lock as (select distinct--w.mode w_mode,w.page w_page,--w.tuple w_tuple,w.xact_start w_xact_start,w.query_start w_query_start,--now()-w.query_start w_locktime,w.query w_queryw.pid as id,--w_pid,r.pid as parentid--r_pid,--r.locktype,r.mode r_mode,r.usename r_user,r.datname r_db,--r.relation::regclass,--r.page r_page,r.tuple r_tuple,r.xact_start r_xact_start,--r.query_start r_query_start,--now()-r.query_start r_locktime,r.query r_query,from (select a.mode,a.locktype,a.database,a.relation,a.page,a.tuple,a.classid,a.objid,a.objsubid,a.pid,a.virtualtransaction,a.virtualxid,a.transactionid,b.query as query,b.xact_start,b.query_start,b.usename,b.datnamefrom pg_locks a,pg_stat_activity bwhere a.pid=b.pidand not a.granted) w,(select a.mode,a.locktype,a.database,a.relation,a.page,a.tuple,a.classid,a.objid,a.objsubid,a.pid,a.virtualtransaction,a.virtualxid,a.transactionid,b.query as query,b.xact_start,b.query_start,b.usename,b.datnamefrom pg_locks a,pg_stat_activity b -- select pg_typeof(pid) from pg_stat_activitywhere a.pid=b.pidand a.granted) rwhere 1=1and r.locktype is not distinct from w.locktypeand r.database is not distinct from w.databaseand r.relation is not distinct from w.relationand r.page is not distinct from w.pageand r.tuple is not distinct from w.tupleand r.classid is not distinct from w.classidand r.objid is not distinct from w.objidand r.objsubid is not distinct from w.objsubidand r.transactionid is not distinct from w.transactionidand r.pid <> w.pid),
tmp0 as (select *from tmp_lock tlunion allselect t1.parentid,0::int4from tmp_lock t1where 1=1and t1.parentid not in (select id from tmp_lock)),
tmp3 (pathid,depth,id,parentid) as (SELECT array[id]::text[] as pathid,1 as depth,id,parentidFROM tmp0where 1=1 and parentid=0unionSELECT t0.pathid||array[t1.id]::text[] as pathid,t0.depth+1 as depth,t1.id,t1.parentidFROM tmp0 t1, tmp3 t0where 1=1 and t1.parentid=t0.id
)
select distinct'/'||array_to_string(a0.pathid,'/') as pathid,a0.depth,a0.id,a0.parentid,lpad(a0.id::text, 2*a0.depth-1+length(a0.id::text),' ') as tree_id,--'select pg_cancel_backend('||a0.id|| ');' as cancel_pid,--'select pg_terminate_backend('||a0.id|| ');' as term_pid,case when a0.depth =1 then 'select pg_terminate_backend('|| a0.id || ');' else null end  as term_pid,case when a0.depth =1 then 'select cancel_backend('|| a0.id || ');' else null end  as cancel_pid,a2.datname,a2.usename,a2.application_name,a2.client_addr,a2.wait_event_type,a2.wait_event,a2.state--,a2.backend_start,a2.xact_start,a2.query_start
from tmp3 a0
left outer join (select distinct '/'||id||'/' as prefix_id,idfrom tmp0where 1=1 ) a1
on position( a1.prefix_id in '/'||array_to_string(a0.pathid,'/')||'/' ) >0
left outer join pg_stat_activity a2 -- select * from pg_stat_activity
on a0.id = a2.pid
order by '/'||array_to_string(a0.pathid,'/'),a0.depth;

查詢結果如下:

-[ RECORD 1 ]----+------------------------------------
pathid           | /31733
depth            | 1
id               | 31733
parentid         | 0
tree_id          |  31733
term_pid         | select pg_terminate_backend(31733);
cancel_pid       | select cancel_backend(31733);
datname          | test
usename          | sde
application_name | psql
client_addr      | 192.168.100.182
wait_event_type  | Client
wait_event       | ClientRead
state            | idle in transaction
-[ RECORD 2 ]----+------------------------------------
pathid           | /31733/8209
depth            | 2
id               | 8209
parentid         | 31733
tree_id          |    8209
term_pid         |
cancel_pid       |
datname          | test
usename          | sde
application_name | psql
client_addr      | 192.168.100.182
wait_event_type  | Lock
wait_event       | relation
state            | active

查詢超過60s的sql

selectpg_stat_activity.datname,pg_stat_activity.pid,pg_stat_activity.query,pg_stat_activity.client_addr,clock_timestamp() - pg_stat_activity.query_start
frompg_stat_activity pg_stat_activity
where(pg_stat_activity.state = any (array['active'::text,'idle in transaction'::text]))and (clock_timestamp() - pg_stat_activity.query_start) > '00:00:60'::interval
order by(clock_timestamp() - pg_stat_activity.query_start) desc;

結果如下:

-[ RECORD 1 ]--------------------------------
datname     | test
pid         | 31733
query       | delete from test123 where id=1;
client_addr | 192.168.100.182
?column?    | 00:21:25.624592
-[ RECORD 2 ]--------------------------------
datname     | test
pid         | 8209
query       | truncate table test123;
client_addr | 192.168.100.182
?column?    | 00:19:53.719401

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/86937.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/86937.shtml
英文地址,請注明出處:http://en.pswp.cn/web/86937.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

JSON 格式詳解

JSON 格式詳解 隨著互聯網的發展和各種 Web 應用程序的普及&#xff0c;數據交換已經成為了我們日常開發中的重要環節。而在各種數據交換格式中&#xff0c;JSON&#xff08;JavaScript Object Notation&#xff09;作為一種輕量級的數據交換格式&#xff0c;以其簡潔、易于閱…

原型設計Axure RP網盤資源下載與安裝教程共享

對于初學者來說&#xff0c;我們熟悉一下其定義&#xff1a;?Axure RP是一款常用的快速原型設計工具?&#xff0c;主要用于創建應用軟件或Web網站的線框圖、流程圖、原型和規格說明文檔&#xff0c;廣泛應用于產品經理、UI/UX設計師等專業領域。?? 主要用戶群體&#xff1…

iframe嵌套 redirect中轉頁面 route跳轉

需求是項目A要使用iframe內嵌項目B的頁面&#xff0c; 由于需要嵌套的頁面很多&#xff0c;每個頁面路徑和參數又各不相同&#xff0c; 所以我們在項目B里做了一個中轉頁面&#xff0c;這樣就能自己掌控項目A傳遞過來的東西了&#xff1b; routes.js 增加一個菜單&#xff1a;…

IP數據報 封裝成 MAC幀 ( 目的MAC地址6B 源MAC地址6B 類型2B 數據部分 FCS校驗和4B )

將 IP 數據報&#xff08;Internet Protocol Datagram&#xff09;封裝成 MAC 幀 需要在數據鏈路層添加適當的頭部信息&#xff0c;以便在局域網內進行傳輸。這個過程涉及將網絡層&#xff08;IP 層&#xff09;的數據通過數據鏈路層&#xff08;MAC 層&#xff09;封裝成適合物…

Note2.4 機器學習:Batch Normalization Introduction

Batch Normalization&#xff08;批標準化&#xff0c;BN&#xff09;通過標準化數據的操作&#xff0c;使得損失函數的優化地形&#xff08;optimization landscape&#xff09;更加平滑&#xff0c;從而達到更好地訓練效果。BN常用于卷積神經網絡&#xff08;CNN&#xff09;…

IDEA在AI時代的智能編程實踐:從工蜂到通義靈碼的效能躍遷??

引言? 在騰訊云工作期間&#xff0c;我曾使用?工蜂的AI代碼補全功能&#xff0c;結合IntelliJ IDEA&#xff08;以下簡稱IDEA&#xff09;極大提升了開發效率。如今離開騰訊云&#xff0c;面對外部開發環境&#xff0c;如何繼續利用AI提升編碼效率&#xff1f;本文將系統梳理…

MySQL 慢查詢日志詳解

慢查詢日志&#xff08;Slow Query Log&#xff09;是 MySQL 提供的一種核心性能優化工具&#xff0c;用于記錄執行時間超過指定閾值的 SQL 語句。通過分析這些日志&#xff0c;可以定位數據庫性能瓶頸&#xff0c;優化低效查詢&#xff0c;提升系統整體效率。 一、慢查詢日志的…

UV安裝Python指南總結

UV安裝Python指南總結 UV是一個Python包管理工具,它可以幫助我們安裝和管理Python版本。以下是關于UV安裝Python的主要功能和用法總結。 基本使用 安裝最新版Python uv python install注意&#xff1a;UV使用Astral的python-build-standalone項目提供的Python發行版,而不是…

運維基礎-MYSQL數據庫-筆記

序 欠10年前自己的一份筆記&#xff0c;獻給今后的自己。 數據庫介紹 數據的時代 涉及的數據量大數據不隨程序的結束而消失數據被多個應用程序共享大數據 數據庫的發展史 萌芽階段&#xff1a;文件系統 使用磁盤文件來存儲數據初級階段&#xff1a;第一代數據庫 出現了網狀…

從GPTs到Real智能體:目前常見的幾種創建智能體方式

文章目錄 智能體的三個發展階段低階智能體(面向過程) VS 高階智能體(面向目標)主流智能體創建平臺實踐基礎型平臺cherry-studio豆包訊飛星火騰訊元器 高階智能體開發體系cline開發套件Coze平臺Dify開源框架Manus突破性方案 技術演進趨勢總結 智能體的三個發展階段 當前智能體技…

WPF 實現自定義數字輸入彈窗

1.前端代碼實現 <Grid><Grid.RowDefinitions><RowDefinition Height"100" /><RowDefinition Height"*" /></Grid.RowDefinitions><BorderGrid.Row"0"BorderBrush"WhiteSmoke"BorderThickness"0…

基于yolo海洋垃圾物品識別系統flask

查看完整項目包點擊文末名片 項目簡介 本項目 基于YOLO的海洋垃圾物品識別系統 旨在利用深度學習中的YOLO&#xff08;You Only Look Once&#xff09;模型&#xff0c;實現對海洋垃圾的自動識別與分類。通過構建一個基于Flask的Web應用&#xff0c;用戶可以方便地上傳圖片&…

從數據到決策:UI前端如何利用數字孿生技術提升管理效率?

hello寶子們...我們是艾斯視覺擅長ui設計、前端開發、數字孿生、大數據、三維建模、三維動畫10年經驗!希望我的分享能幫助到您!如需幫助可以評論關注私信我們一起探討!致敬感謝感恩! 在數字化轉型的深水區&#xff0c;企業管理者正面臨數據過載與決策滯后的雙重挑戰 ——IDC 研…

Spring Boot高并發 鎖的使用方法

Spring Boot高并發 鎖的使用方法 在高并發場景中&#xff08;比如電商秒殺、搶票系統、轉賬交易&#xff09;&#xff0c;多個線程/用戶會同時操作同一共享資源&#xff08;如庫存、賬戶余額、訂單號&#xff09;。如果不做控制&#xff0c;會導致數據錯誤&#xff08;如庫存超…

二十九:Dynamic Prompts插件動態提示詞講解

引言:可變化提示詞,隨機抽取不固定 使用方式一:{提示詞1|提示詞2|。。。。}------從提示詞種隨機抽取生成 方式二:{25::提示詞1|75::提示詞2}------數字為每個提示詞的占比,相當于權重 方式三:{2$$提示詞1|提示詞2|提示詞3|提示詞4|。。。}從中選區2個搭配生成(可以換 比…

vscode 改注釋的顏色,默認是灰色的,想改成紅色

修改VScode編輯器默認注釋的顏色_databricks代碼中怎么設置讓注釋是灰色的-CSDN博客 //改變注釋顏色"editor.tokenColorCustomizations": {"comments": "#009933" // 注釋}, //如果后面還加內容&#xff0c;記得塊末用逗號隔開我自己用的vscdoe.…

chili3d筆記22 正交投影3d重建筆記3 面構建

雙視圖重建3d solid import { FaceNode } from "chili"; import {IDocument,IEdge,Logger,ShapeNode,XYZ } from "chili-core"; import { Graph } from "graphlib"; function pointToString(point: XYZ): string {return ${point.x.toFixed(0)}-…

Kotlin 協程使用與通信

一、協程基礎使用 1. 協程的三種創建方式 (1) launch - 啟動后臺作業 val job CoroutineScope(Dispatchers.IO).launch {// 后臺操作delay(1000)println("任務完成 ${Thread.currentThread().name}")// 輸出&#xff1a;任務完成 DefaultDispatcher-worker-1 } j…

Ubuntu服務器(公網)- Ubuntu客戶端(內網)的FRP內網穿透配置教程

以下是為Ubuntu服務器&#xff08;公網&#xff09;- Ubuntu客戶端&#xff08;內網&#xff09;的FRP內網穿透配置教程&#xff0c;基于最新版本&#xff08;2025年6月&#xff0c;使用frp_0.61.1_linux_amd64&#xff09;整理&#xff1a; 一、服務端配置&#xff08;公網Ubu…

什么是哈希函數(SHA-256)

SHA-256 是區塊鏈系統中最核心的加密基礎之一&#xff0c;尤其是在比特幣、以太坊、文件存證等場景中扮演“指紋識別器”的角色。下面是對它的詳細講解&#xff0c;包括原理、特點、用途和代碼示例。 &#x1f4cc; 一、什么是 SHA-256&#xff1f; SHA-256 是一種密碼學哈希函…