Isolation Level

上次介紹到 Lock 的特性,主要是要了解資料庫對於資料保護的基本方法,在實務上的運用是要利用 Isolation Level 來做資料存取權限的設定。一般而言,Isolation Level 可以分成四個階層,層級高的功能會涵蓋層級低的功能。

層級 名稱 說明
0 read uncommitted 允許讀取尚在作用中的 transaction 異動過的資料,也就是當資料正在被其他 transaction 異動時,也可以讀取該資料。
1 read committed 只能讀取不在 transaction 中異動的資料,也就是當資料正在被其他 transaction 異動時,就不可以讀取該資料。
2 repeatable read 在同一個 transaction 中,同樣的 SQL 語法都會得到同樣的結果,也就是當資料被讀取後,其他的 transaction ,不可以 update 或 delete 該資料。
3 serialized read 在同一個 transaction 中,同樣的 SQL 語法都會得到同樣的結果,也就是當資料被讀取後,其他的 transaction ,不可以 insert、update 或 delete 該資料。

Isolation Level 0 ( read uncommitted )

T1 事件說明 T2
begin transaction T1、T2 兩個 transaction 同時啟動 begin transaction
Update employee Set salary = salary * 1.05 T1 正在做調薪的動作  
  T2 讀取 empid 為 A01 的薪資資料 Select salary From employee Where empid = 'A01'
  T2 處理結束 commit transaction
commit/ rollback transaction T1 處理過程正常 ( commit ),處理過程中有問題,回復到未處理的狀態 ( rollback )  

當 T2 以 read uncommitted 的方式讀取資料時,所取得的薪資資料,會因為 T1 以 rollback 的方式結束,而取得錯誤的資料。

Isolation Level 1 ( read committed )

T3 事件說明 T4
begin transaction T3、T4 兩個 transaction 同時啟動 begin transaction
Update employee Set salary = salary * 1.05 T3 正在做調薪的動作  
  T4 讀取 empid 為 A01 的薪資資料 Select salary From employee Where empid = 'A01'
commit/ rollback transaction T4 處理過程正常 ( commit ),處理過程中有問題,回復到未處理的狀態 ( rollback )  
  T4 處理結束 commit transaction

當 T3 以 read committed 的方式讀取資料時,T4 會等到 T3 執行完成 ( commit/ rollback ),再讀取該筆資料,萬一 T4 等太久就會發生 Time Out 的現象。

Isolation Level 2 ( repeatable read )

T5 事件說明 T6
begin transaction T5、T6 兩個 transaction 同時啟動 begin transaction
Select sum ( salary ) From emp T5 計算所有的薪資總和  
  T6 更新 empid 為 A01 的薪資 Update emp Set salary = salary * 1.10 Where empid = 'A01'
  T6 處理結束 commit transaction
Select sum ( salary ) From emp    
commit transaction T5 處理結束  

這裡要特別注意的是,T5 重複讀取相同的資料,但是在處理的過程中,T6 更新了部分的資料,將導致 T5 無法取得相同的資料。

為避免這個問題, T5 在讀取資料時應該採用 Isolation Level 2 的方式,禁止使用 update、delete  的指令,纔可以達到所需要的效果。

Isolation Level 3 ( serialized read )

T7 事件說明 T8
begin transaction T7、T8 兩個 transaction 同時啟動 begin transaction
Select sum ( salary ) From emp T7 計算所有的薪資總和  
  T8 新增一筆 emp 資料 Insert Into emp ( ... ) Values ( ... )
  T8 處理結束 commit transaction
Select sum ( salary ) From emp    
commit transaction T7 處理結束  

T7 延續 Isolation Level 2 所產生的問題,當 T8 insert 新的資料進來時,將導致 T7 無法取得相同的資料。

為避免這個問題, T7 在讀取資料時應該採用 Isolation Level 3 的方式,除了禁止使用 update、delete  的指令,同時也禁止使用 insert 的指令,纔可以達到所需要的效果。

至於要使用哪一種 Isolation Level,必須視實際上的需要做設定,沒有絕對的處理方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章