Postgres 9.3: Sharelock issue with simple INSERT

落爺英雄遲暮 提交于 2019-12-05 04:49:15

It looks like you're in this situation:

  1. The table to INSERT into has a primary key (or unique index(es) of any sort).
  2. Several INSERTs into that table are performed within one transaction (as opposed to committing immediately after each one)
  3. The rows to insert come in random order (with regard to the primary key)
  4. The rows are inserted in concurrent transactions.

This situation creates the following opportunity for deadlock:

Assuming there are two sessions, that each started a transaction.

  1. Session #1: insert row with PK 'A'
  2. Session #2: insert row with PK 'B'
  3. Session #1: try to insert row with PK 'B' => Session #1 is put to wait until Session #2 commits or rollbacks
  4. Session #2: try to insert row with PK 'A' => Session #2 is put to wait for Session #1.

Shortly thereafter, the deadlock detector gets aware that both sessions are now waiting for each other, and terminates one of them with a fatal deadlock detected error.

If you're in this scenario, the simplest solution is to COMMIT after a new entry is inserted, before attempting to insert any new row into the table.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!