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

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

Considering alternative solutions

There is an alternative solution to this problem. Consider an example where you are asked to write an application to generate invoice numbers. The tax office might require you to create invoice numbers without gaps and without duplicates. How would you do this? Of course, one solution would be a table lock. However, you can really do better. Here is what you can do to handle the numbering problem we are trying to solve:

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, we introduced a table called t_watermark. It contains just one row. The WITH command 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, which leads to no reads being blocked in the invoice table. Overall, this way is more scalable.

主站蜘蛛池模板: 达拉特旗| 黄龙县| 邵阳市| 夏邑县| 罗甸县| 乌什县| 东丽区| 水富县| 威宁| 尚志市| 花垣县| 尚志市| 全南县| 绥江县| 邓州市| 林州市| 贡觉县| 天祝| 嘉善县| 紫金县| 黑河市| 仪征市| 皮山县| 平远县| 银川市| 三穗县| 昔阳县| 金塔县| 九江县| 兰西县| 开远市| 惠水县| 西峡县| 揭阳市| 北川| 水城县| 望城县| 澄城县| 河源市| 绥江县| 山丹县|