forked from zanfranceschi/rinha-de-backend-2024-q1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.sql
105 lines (95 loc) · 2 KB
/
init.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
103
104
105
SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
SET default_tablespace = '';
CREATE UNLOGGED TABLE customers (
id SERIAL PRIMARY KEY,
saldo INTEGER NOT NULL,
limite INTEGER NOT NULL
);
CREATE UNLOGGED TABLE transacoes (
id SERIAL PRIMARY KEY,
customerId INTEGER NOT NULL,
valor INTEGER NOT NULL,
tipo CHAR(1) NOT NULL,
descricao VARCHAR(10) NOT NULL,
realizada_em TIMESTAMP NOT NULL DEFAULT NOW(),
CONSTRAINT fk_cliente_transacao_id
FOREIGN KEY (customerId) REFERENCES customers(id)
);
CREATE INDEX ix_transacao_idcliente ON transacoes
(
customerId ASC
);
DO $$
BEGIN
INSERT INTO customers (limite, saldo)
VALUES
(100000, 0),
(80000, 0),
(1000000, 0),
(10000000, 0),
(500000, 0);
END;
$$;
CREATE OR REPLACE FUNCTION debit(
customerId INT,
valor INT,
descricao VARCHAR(10))
RETURNS TABLE (saldoFinal INT, error BOOL)
LANGUAGE plpgsql
AS $$
DECLARE
limiteAtual int;
saldoAtual int;
BEGIN
PERFORM pg_advisory_xact_lock(customerId);
SELECT
c.limite,
c.saldo
INTO
limiteAtual,
saldoAtual
FROM customers c
WHERE c.id = customerId;
IF saldoAtual - valor < limiteAtual * -1 THEN
RETURN QUERY
SELECT
saldo,
TRUE -- saldo insuficiente
FROM customers
WHERE id = customerId;
ELSE
INSERT INTO transacoes
VALUES(DEFAULT, customerId, valor, 'd', descricao, DEFAULT);
RETURN QUERY
UPDATE customers
SET saldo = saldo - valor
WHERE id = customerId
RETURNING saldo, FALSE;
END IF;
END;
$$;
CREATE OR REPLACE FUNCTION credit(
customerId INT,
valor INT,
descricao VARCHAR(10))
RETURNS TABLE (saldoFinal INT)
LANGUAGE plpgsql
AS $$
BEGIN
PERFORM pg_advisory_xact_lock(customerId);
INSERT INTO transacoes
VALUES(DEFAULT, customerId, valor, 'c', descricao, DEFAULT);
RETURN QUERY
UPDATE customers
SET saldo = saldo + valor
WHERE id = customerId
RETURNING saldo;
END;
$$;