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

  • 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.

主站蜘蛛池模板: 新源县| 峡江县| 白水县| 防城港市| 乐业县| 包头市| 平谷区| 大同市| 兴仁县| 绥江县| 淮安市| 康保县| 枣强县| 宝丰县| 固镇县| 望江县| 利辛县| 博客| 宁安市| 铜鼓县| 云和县| 武汉市| 泰安市| 邵阳县| 通城县| 镇雄县| 冕宁县| 达尔| 仪征市| 左权县| 桃园县| 台东市| 凤庆县| 衡东县| 石狮市| 朝阳县| 乌拉特后旗| 呼图壁县| 堆龙德庆县| 瓮安县| 绍兴县|