PostgreSQL 10.0 preview 功能增強 - 更強可靠性, 過去式事務狀態可查(杜絕unknown事務)
標簽
PostgreSQL , 10.0 , 2PC , txid_status , unknown事務
背景
在一些極端情況下,例如當客戶端發出事務提交SQL後,客戶端收到數據庫返回的提交狀態前,如果客戶端崩潰或數據庫異常,導致客戶端不知道事務的最終狀態到底是提交成功還是失敗的。
那麼怎麼解決這個問題呢?
1. 一種方法是走2PC協議,先使用預提交,然後在發出commit 之前的預提交。(因為隻要預提交成功,就可以認為後麵的commit是一定可以成功的),從而來避免unknown的事務問題。
但是2PC引入了性能的問題,因為需要和數據庫交互多次。
2. 10.0引入一個新的功能,查看以往的事務提交狀態。在發生崩潰問題後,應用程序再起來之後,可以通過事務號,查到事務的提交狀態。杜絕unknown的事務。
為了查詢事務狀態,應用程序必須要保留事務號,目前PostgreSQL通過txid_current()可以查詢當前的事務號,結合insert ,update,... returning txid_current(),可以在一次交互中得到這個事務號。從避免因為這個功能引入的增加一次交互。
未來PostgreSQL可能會在驅動層麵解決這個問題,減少業務程序的開發工作量(使用txid_current()獲得事務號)。
Issuing a “multi-statement query”,
e.g. INSERT INTO ...; SELECT txid_current(); if it doesn’t need the result of the prior query;
Combining it with another query,
e.g. INSERT INTO ... RETURNING txid_current();
Using client driver support for batching queries to dispatch the txid_current() query along with other queries without waiting for a reply for each query.
In a future version PostgreSQL may automatically report the transaction ID when it is assigned to make this easier for applications.
例子
SELECT txid_status(BIGINT '63204');
txid_status的參數是xid, 即txid_current()的返回值類型。
注意不是int32, 是int64哦。
patch如下
Add a txid_status function.
author Robert Haas <rhaas@postgresql.org>
Sat, 25 Mar 2017 00:00:53 +0800 (12:00 -0400)
committer Robert Haas <rhaas@postgresql.org>
Sat, 25 Mar 2017 00:00:53 +0800 (12:00 -0400)
commit 857ee8e391ff6654ef9dcc5dd8b658d7709d0a3c
tree 1d0f54ef032aa0a90bcda70e86ee3850167462ad tree | snapshot
parent 42b4b0b2413b9b472aaf2112a3bbfd80a6ab4dc5 commit | diff
Add a txid_status function.
If your connection to the database server is lost while a COMMIT is
in progress, it may be difficult to figure out whether the COMMIT was
successful or not. This function will tell you, provided that you
don't wait too long to ask. It may be useful in other situations,
too.
Craig Ringer, reviewed by Simon Riggs and by me
Discussion: https://postgr.es/m/CAMsr+YHQiWNEi0daCTboS40T+V5s_+dst3PYv_8v2wNVH+Xx4g@mail.gmail.com
這個patch的討論,詳見郵件組,本文末尾URL。
PostgreSQL社區的作風非常嚴謹,一個patch可能在郵件組中討論幾個月甚至幾年,根據大家的意見反複的修正,patch合並到master已經非常成熟,所以PostgreSQL的穩定性也是遠近聞名的。
參考
https://blog.2ndquadrant.com/traceable-commit-postgresql-10/
最後更新:2017-04-21 01:00:33