官术网_书友最值得收藏!

  • Mastering PostgreSQL 12
  • Hans Jürgen Sch?nig
  • 311字
  • 2021-08-20 10:00:22

Understanding transaction isolation levels

Up until now, you have seen how to handle locking, as well as some basic concurrency. In this section, you will learn about transaction isolation. To me, this is one of the most neglected topics in modern software development. Only a small fraction of software developers are actually aware of this issue, which in turn leads to mind-boggling bugs.

Here is an example of what can happen:

 

Most users would actually expect the first transaction to always return 300, regardless of the second transaction. However, this isn't true. By default, PostgreSQL runs in the READ COMMITTED transaction isolation mode. This means that every statement inside a transaction will get a new snapshot of the data, which will be constant throughout the query.

A SQL statement will operate on the same snapshot and will ignore changes by concurrent transactions while it is running.

If you want to avoid this, you can use TRANSACTION ISOLATION LEVEL REPEATABLE READ. In this transaction isolation level, a transaction will use the same snapshot through the entire transaction. Here's what will happen:

 

As we've outlined, the first transaction will freeze its snapshot of the data and provide us with constant results throughout the entire transaction. This feature is especially important if you want to run reports. The first and last page of a report should always be consistent and operate on the same data. Therefore, the repeatable read is key to consistent reports.

Note that isolation-related errors won't always pop up instantly. Sometimes, trouble is noticed years after an application has been moved to production.

Repeatable read is not more expensive than read committed. There is no need to worry about performance penalties. For normal online transaction processing ( OLTP), read committed has various advantages because changes can be seen much earlier and the odds of unexpected errors are usually lower.
主站蜘蛛池模板: 郯城县| 谷城县| 大悟县| 苗栗市| 奈曼旗| 乌鲁木齐县| 宜丰县| 宁乡县| 庆云县| 大化| 永胜县| 财经| 株洲市| 宁强县| 海盐县| 永仁县| 寿宁县| 四子王旗| 庆阳市| 宝兴县| 望奎县| 海兴县| 资中县| 孝义市| 巴塘县| 九龙城区| 大方县| 乌鲁木齐县| 鹰潭市| 开封县| 金昌市| 甘肃省| 碌曲县| 秦安县| 光泽县| 沂水县| 安丘市| 得荣县| 习水县| 嘉鱼县| 威信县|