- Mastering PostgreSQL 9.6
- Hans Jurgen Schonig
- 213字
- 2021-07-09 19:57:12
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.
- Project 2007項目管理實用詳解
- Circos Data Visualization How-to
- 深度學習中的圖像分類與對抗技術
- 小型電動機實用設計手冊
- Creo Parametric 1.0中文版從入門到精通
- AI 3.0
- 觸控顯示技術
- 完全掌握AutoCAD 2008中文版:機械篇
- 突破,Objective-C開發(fā)速學手冊
- Mastering Game Development with Unreal Engine 4(Second Edition)
- Microsoft System Center Confi guration Manager
- 啊哈C!思考快你一步
- Photoshop CS5圖像處理入門、進階與提高
- AVR單片機工程師是怎樣煉成的
- ADuC系列ARM器件應用技術