-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
65 lines (54 loc) · 1.61 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import express from 'express';
import { Pool, PoolClient } from 'pg';
const app = express();
const pool = new Pool({
user: 'admin',
password: 'admin',
host: 'localhost',
port: 5432,
database: 'db-transaction'
});
const buyOptimisticLockIn = async (connect: PoolClient) => {
const data = await connect.query('SELECT amount,version FROM stock where id = 1')
const { amount, version } = data?.rows?.find(Boolean) || {};
if (!amount || amount <= 0) {
console.log('nothing to buy');
return
}
try {
await pool.query('BEGIN')
await connect.query('UPDATE stock SET amount = amount - 1, version = version + 1 WHERE id =1 AND version=' + version)
await pool.query('COMMIT')
} catch (error) {
await pool.query('ROLLBACK')
}
}
const buyPessimisticLockIn = async (connect: PoolClient) => {
const data = await connect.query('SELECT amount FROM stock where id = 1 FOR UPDATE')
const amount = data?.rows?.find(Boolean)?.amount;
if (!amount || amount <= 0) {
console.log('nothing to buy');
return
}
try {
await pool.query('BEGIN')
await pool.query('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE READ')
await connect.query('UPDATE stock SET amount = amount - 1 WHERE id =1')
await pool.query('COMMIT')
} catch (error) {
await pool.query('ROLLBACK')
}
}
(async () => {
const connect = await pool.connect()
await connect.query(`CREATE TABLE IF NOT EXISTS stock
(
id integer PRIMARY KEY,
amount integer,
version integer
)`)
app.listen(5000, () => {
console.log('Server is running on port 5000');
});
await buyOptimisticLockIn(connect)
})()