-
Notifications
You must be signed in to change notification settings - Fork 923
/
Copy pathddl.sql
103 lines (88 loc) · 2.53 KB
/
ddl.sql
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
SET timezone = 'America/Sao_Paulo';
CREATE SCHEMA IF NOT EXISTS rinha;
CREATE TABLE rinha.users
(
id SERIAL PRIMARY KEY,
limit_in_cents INTEGER NOT NULL,
initial_balance INTEGER NOT NULL DEFAULT 0
);
INSERT INTO rinha.users (id, limit_in_cents, initial_balance)
VALUES (DEFAULT, 1000 * 100, 0),
(DEFAULT, 800 * 100, 0),
(DEFAULT, 10000 * 100, 0),
(DEFAULT, 100000 * 100, 0),
(DEFAULT, 5000 * 100, 0);
CREATE UNLOGGED TABLE rinha.history
(
id SERIAL PRIMARY KEY,
user_id SMALLINT NOT NULL,
value INTEGER NOT NULL,
type CHAR(1) NOT NULL,
description VARCHAR(10) NOT NULL,
do_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
ALTER TABLE
rinha.history
SET
(autovacuum_enabled = false);
CREATE INDEX idx_history ON rinha.history (user_id);
CREATE OR REPLACE FUNCTION rinha.credit(
user_id_tx SMALLINT,
value_tx INT,
description_tx VARCHAR(10))
RETURNS TABLE
(
new_balance INT,
success BOOL,
current_limit INT
)
LANGUAGE plpgsql
AS
$$
BEGIN
PERFORM pg_advisory_xact_lock(user_id_tx);
INSERT INTO rinha.history VALUES (DEFAULT, user_id_tx, value_tx, 'c', description_tx);
RETURN QUERY
UPDATE rinha.users
SET initial_balance = initial_balance + value_tx
WHERE id = user_id_tx
RETURNING initial_balance, TRUE, limit_in_cents;
END;
$$;
CREATE OR REPLACE FUNCTION rinha.debit(
user_id_tx SMALLINT,
value_tx INT,
description_tx VARCHAR(10))
RETURNS TABLE
(
new_balance INT,
success BOOL,
current_limit INT
)
LANGUAGE plpgsql
AS
$$
DECLARE
current_balance int;
current_limit_value int;
BEGIN
PERFORM pg_advisory_xact_lock(user_id_tx);
SELECT limit_in_cents,
initial_balance
INTO
current_limit_value,
current_balance
FROM rinha.users
WHERE id = user_id_tx;
IF current_balance - value_tx >= current_limit_value * -1 THEN
INSERT INTO rinha.history VALUES (DEFAULT, user_id_tx, value_tx, 'd', description_tx);
RETURN QUERY
UPDATE rinha.users
SET initial_balance = initial_balance - value_tx
WHERE id = user_id_tx
RETURNING initial_balance, TRUE, limit_in_cents;
ELSE
RETURN QUERY SELECT current_balance, FALSE, current_limit_value;
END IF;
END;
$$;