- Mastering PostgreSQL 10
- Hans Jürgen Sch?nig
- 211字
- 2021-06-30 19:03:50
Considering alternative solutions
There is an alternative solution to the problem. Consider the following example: you are asked to write an application generating invoice numbers. The tax office might require you to create invoice numbers without gaps and without duplicates. How would you do it? Of course, one solution would be a table lock. However, you can really do better. Here is what I would do:
test=# CREATE TABLE t_invoice (id int PRIMARY KEY);
CREATE TABLE
test=# CREATE TABLE t_watermark (id int); CREATE TABLE
test=# INSERT INTO t_watermark VALUES (0); INSERT 0
test=# WITH x AS (UPDATE t_watermark SET id = id + 1 RETURNING *) INSERT INTO t_invoice SELECT * FROM x RETURNING *;
id
----
1
(1 row)
In this case, I introduced a table called t_watermark. It contains just one row. The WITH will be executed first. The row will be locked and incremented, and the new value will be returned. Only one person can do this at a time. The value returned by the CTE is then used in the invoice table. It is guaranteed to be unique. The beauty is that there is only a simple row lock on the watermark table; no reads will be blocked in the invoice table. Overall, this way is more scalable.
- 走入IBM小型機(jī)世界
- PIC單片機(jī)C語(yǔ)言非常入門與視頻演練
- 大數(shù)據(jù)安全與隱私保護(hù)
- 水晶石精粹:3ds max & ZBrush三維數(shù)字靜幀藝術(shù)
- 悟透AutoCAD 2009完全自學(xué)手冊(cè)
- 分析力!專業(yè)Excel的制作與分析實(shí)用法則
- 中國(guó)戰(zhàn)略性新興產(chǎn)業(yè)研究與發(fā)展·智能制造裝備
- Applied Data Visualization with R and ggplot2
- 人工智能:語(yǔ)言智能處理
- 網(wǎng)絡(luò)服務(wù)器搭建與管理
- 經(jīng)典Java EE企業(yè)應(yīng)用實(shí)戰(zhàn)
- 手機(jī)游戲策劃設(shè)計(jì)
- Getting Started with Tableau 2018.x
- ROS Robotics By Example(Second Edition)
- Flink內(nèi)核原理與實(shí)現(xiàn)