楊育晟(Peter Yang)

嗨, 我叫育晟, 部落格文章主題包含了程式設計、財務金融及投資...等等,內容多是記錄一些學習的過程和心得,任何想法都歡迎留言一起討論。



Email: ycy.tai@gmail.com
LinkedIn: Peter Yang
Github: ycytai

Postgres Uncommitted Transactions 處理紀錄

發生了什麼事

發現 drop table 的 query 會直接卡住,無法成功執行。

排查過程

  1. 找出未完成的 query

    SELECT pid, usename, application_name, query, state
    FROM pg_stat_activity
    WHERE pid <> pg_backend_pid()
    AND state = 'idle in transaction'
    

    問了一下 chatgpt 關於 idleidle in transaction 的解釋

    idle: This state indicates that the session is currently not executing any query and is waiting for a new client command to arrive.

    idle in transaction: This state indicates that the session is currently in a transaction but is not executing any query. It's waiting for the client to issue a new command or to commit or rollback the transaction.

  2. 找出了前一步驟結果中 query 和我想砍掉 table 有關的 pid,然後用下面的 query kill,但仍然沒用。

    SELECT pg_terminate_backend(pid)
    FROM pg_stat_activity
    
  3. 有鑒於找不到是哪個 uncommitted 的 transaction 影響到我要做的事,索性全砍了。

    DO $$
    DECLARE
        rec RECORD;
    BEGIN
        FOR rec IN
            SELECT pid
            FROM pg_stat_activity
            WHERE state = 'idle in transaction'
            AND pid <> pg_backend_pid()
        LOOP
            PERFORM pg_terminate_backend(rec.pid);
        END LOOP;
    END $$;
    
  4. 再次執行 drop table 就成功了,終於。

Tags:
# postgres
# database
# data
# backend