- 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.
- Internet接入·網(wǎng)絡(luò)安全
- 大數(shù)據(jù)管理系統(tǒng)
- 平面設(shè)計(jì)初步
- 21天學(xué)通PHP
- Getting Started with MariaDB
- CorelDRAW X4中文版平面設(shè)計(jì)50例
- Visual Basic從初學(xué)到精通
- 樂高創(chuàng)意機(jī)器人教程(中級(jí) 下冊(cè) 10~16歲) (青少年iCAN+創(chuàng)新創(chuàng)意實(shí)踐指導(dǎo)叢書)
- 80x86/Pentium微型計(jì)算機(jī)原理及應(yīng)用
- 視覺檢測(cè)技術(shù)及智能計(jì)算
- RPA(機(jī)器人流程自動(dòng)化)快速入門:基于Blue Prism
- INSTANT Autodesk Revit 2013 Customization with .NET How-to
- Lightning Fast Animation in Element 3D
- 所羅門的密碼
- 從零開始學(xué)Java Web開發(fā)