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

Considering alternative solutions

However, 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. But 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 1
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.

主站蜘蛛池模板: 九寨沟县| 芜湖县| 兴化市| 平南县| 栾川县| 军事| 元朗区| 滁州市| 吴桥县| 安陆市| 潼南县| 宁都县| 格尔木市| 桃江县| 林周县| 滦南县| 芜湖县| 扎赉特旗| 平远县| 安阳县| 安阳县| 德化县| 泰州市| 房山区| 昭苏县| 蛟河市| 德惠市| 鄂伦春自治旗| 建水县| 额敏县| 灵台县| 定边县| 腾冲县| 济阳县| 奉化市| 杂多县| 枝江市| 永嘉县| 华坪县| 庆安县| 雷州市|