簡體   English   中英

PostgreSQL:沒有事務的死鎖

[英]PostgreSQL: deadlock without a transaction

我有一個路由(在節點 JS 應用程序中),它在 PostgreSQL 數據庫(版本 13)中插入和更新一些數據。

在偽代碼中,以下是按順序完成的所有查詢:

select * from x where y=$1;

-- if there is no result
   insert into x (y,z) values ($1,$2) returning *;

-- else if there is a result
   insert into x (y,z) values ($1,$2) returning *; -- values are different
   update x set y=$1 where z=$2 returning *;
   update x set a=$1 where b=$2 returning *;

-- end if

在應用程序的某些實例上,沒有太多流量寫入自己的表,我有很多死鎖。 我不明白為什么因為沒有事務,只有簡單的插入,並且在某些情況下更新。 由於節點 postgres ,我使用准備好的語句(以避免 SQL 注入)。

我以前從未遇到過死鎖(或者我可能沒有注意到它們),所以我不明白為什么會發生這種情況。

出現死鎖的原因可能是什么? 以及如何避免它們?

編輯

來自服務器的日志(我沒有更詳細的日志,因為它在平台即服務上):

2021-04-07T11:55:17+02:00 Process 583773 waits for ShareLock on transaction 2408877; blocked by process 583789.
2021-04-07T11:55:17+02:00 2021-04-07 09:55:17.084 GMT [583789] DETAIL: Process 583789 waits for ShareLock on transaction 2408880; blocked by process 583773.
2021-04-07T11:55:17+02:00 2021-04-07 09:55:17.084 GMT [583789] ERROR: deadlock detected
2021-04-07T11:55:17+02:00 2021-04-07 09:55:17.084 GMT [583789] STATEMENT: update x set user_id=$1, user_properties=$2 where user_id=$3
2021-04-07T11:55:17+02:00 2021-04-07 09:55:17.084 GMT [583789] HINT: See server log for query details.
2021-04-07T11:55:17+02:00 2021-04-07 09:55:17.084 GMT [583789] CONTEXT: while rechecking updated tuple (119,3) in relation "x"
2021-04-07T11:55:17+02:00 Process 583773: update x set user_id=$1, user_properties=$2 where user_id=$3
2021-04-07T11:55:17+02:00 Process 583789: update x set user_id=$1, user_properties=$2 where user_id=$3

在 PostgreSQL 中,所有數據修改都發生在事務中。 哪怕只是單語句的事務,還是有事務的。

日志條目不足以給出明確的答案,但看起來您的更新每次更新不止一行。 如果它們偶爾以不同的順序更新相同的行,它們可能會相互死鎖。 我認為這對於您的日志中的查詢可能很少見,因為我認為他們會根據對同一索引的單值掃描選擇要更新的行,因此通常以相同的順序進行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM