顯示具有 PostgreSQL 標籤的文章。 顯示所有文章
顯示具有 PostgreSQL 標籤的文章。 顯示所有文章

2019年1月14日 星期一

PostgreSQL 的索引:B-tree

開這篇之前,其實本來是想要了解 PostgreSQL 10 裡實現索引的原理,畢竟在了解原理的情況下,比較容易想像在什麼情況下索引能夠具有優勢、什麼情況索引幫不上忙。不過花了一段時間搜尋…也不能說沒有找到,但沒有找到我想要的類型。所以這篇雖然標題在講 PostgreSQL 的 B-tree 索引,但實際上會先紀錄的是一般關聯式資料庫以 B-tree 做索引時的狀況。如果想參考看看我找到的其他在談 PostgreSQL B-tree 原理的文章,可以看看 [1-5]。

這篇當中實際會紀錄到的東西,有很大一部份並非來自 PostgreSQL 的官方文件,因此這並不一定完全就是 PostgreSQL 實現的方法,嚴格來說其實這個標題並不是太合適。不過理想上….應該不會差太多….吧!此外這篇文章紀錄的事項,除了我個人的觀點以外,有許多部份是來自 USE THE INDEX, LUKE! [7] 這個網站的解說。因此如果想要有條理地細讀,推薦可以直接去閱讀這個網站的內容。

然後呢,理想上我是想要依序了解所有 PostgreSQL 的索引結構,並分別做點紀錄。所以它有可能會是個系列文,這篇作為系列文的第一篇就會參雜一些奇怪的廢話了。但…也不保證真的會寫出來就是,以前有編號的系列文絕大多數都虎頭蛇尾了 Orz,所以這次索性不編號了。

2019年1月2日 星期三

idle in transaction

在 PostgreSQL 中,如果因為某些因素必須要關閉部份的 transaction,需要判斷一個 transaction 是否可以被安全地關閉。這時可以從 pg_stat_activity 裡面觀察 transaction 的狀態,主要觀察的對象是兩個參數:backend_xidbackend_xmin。比較詳細的描述可以參考 [1]。

2018年12月29日 星期六

PostgreSQL 在 READ_COMMITTED 模式的特性

在閱讀官方文件時,雖然官方文件是寫得挺詳細的,但有種很像是把程式邏輯攤出來解釋的感覺,有時候需要稍微思考一下才能把前後的描述合併起來理解。

non-repeatable read 和 phantom read

在 PostgreSQL 的文件中,描述到 SQL 標準對於錯誤的描述,分別有以下的敘述在描述 non-repeatable read 和 phantom read:

nonrepeatable read
A transaction re-reads data it has previously read and finds that data has been modified by another transaction (that committed since the initial read).

phantom read
A transaction re-executes a query returning a set of rows that satisfy a search condition and finds that the set of rows satisfying the condition has changed due to another recently-committed transaction.

本來對於兩者的差別感覺不是非常明顯,因此查了一下。看了 wikipedia 的描述以後,發現其實也蠻好懂的:

A non-repeatable read occurs, when during the course of a transaction, a row is retrieved twice and the values within the row differ between reads.

A phantom read occurs when, in the course of a transaction, two identical queries are executed, and the collection of rows returned by the second query is different from the first.

也就是說,當在交易中連續讀取兩次的時候,non-repeatable read 指的是讀取到的資料列的內容不一樣,而 phantom read 指的是讀取到的資料列不一樣,例如第一次讀到 #1、#2、#3,第二次讀到 #1、#4,每個資料列的內容都一樣,但符合條件的資料列們不同。(這段描述總覺得好難用中文寫 XD)

參考資料
  1. What is the difference between Non-Repeatable Read and Phantom Read?
  2. Wikipedia: Isolation (database systems)