forked from zanfranceschi/rinha-de-backend-2024-q1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.sql
96 lines (77 loc) · 2.34 KB
/
script.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
ALTER SYSTEM SET max_connections = 180;
CREATE TABLE public.Cliente (
Id smallint NOT NULL,
Total int NOT NULL,
Limite int NOT NULL,
Versao int NOT NULL,
CONSTRAINT "uq_Cliente_id" PRIMARY KEY (Id)
);
CREATE TABLE public.Transacao (
Id int NOT NULL GENERATED BY DEFAULT AS IDENTITY( INCREMENT BY 1 MINVALUE 1 MAXVALUE 100000 START 1 CACHE 1 NO CYCLE),
Valor int NOT NULL,
Descricao varchar(10) NOT NULL,
Tipo varchar(1) NOT NULL,
CriadoEm timestamptz NOT NULL,
ClienteId smallint NOT NULL,
CONSTRAINT fk_transacao_cliente_id FOREIGN KEY (ClienteId) REFERENCES public.Cliente(Id),
CONSTRAINT "uq_transacao_id" PRIMARY KEY (Id)
);
INSERT INTO public.Cliente (Id, Total, Limite, Versao)
VALUES (1, 0, 100000, 0);
INSERT INTO public.Cliente (Id, Total, Limite, Versao)
VALUES (2, 0, 80000, 0);
INSERT INTO public.Cliente (Id, Total, Limite, Versao)
VALUES (3, 0, 1000000, 0);
INSERT INTO public.Cliente (Id, Total, Limite, Versao)
VALUES (4, 0, 10000000, 0);
INSERT INTO public.Cliente (Id, Total, Limite, Versao)
VALUES (5, 0, 500000, 0);
-- Functions
CREATE OR REPLACE FUNCTION creditar(
ClienteId int4,
Valor INT,
Descricao varchar(10)
)
RETURNS TABLE(
LinhaAfetada BOOLEAN,
_limite INT,
_total INT
)
LANGUAGE plpgsql AS
$func$
DECLARE
updated_limite INT;
updated_saldo INT;
BEGIN
UPDATE public.Cliente SET Total = Total + Valor WHERE Id = ClienteId
RETURNING Limite, Total INTO updated_limite, updated_saldo;
INSERT INTO public.Transacao (ClienteId, Valor, Descricao, Tipo, CriadoEm) VALUES (ClienteId, Valor, Descricao, 'c', NOW());
RETURN QUERY SELECT true, updated_limite, updated_saldo;
END;
$func$;
CREATE OR REPLACE FUNCTION debitar(
ClienteId int4,
Valor INT,
Descricao varchar(10)
)
RETURNS TABLE(
LinhaAfetada BOOLEAN,
_limite INT,
_total INT
)
LANGUAGE plpgsql AS
$func$
DECLARE
updated_limite INT;
updated_saldo INT;
BEGIN
update public.Cliente SET Total = Total - @Valor WHERE Id = @ClienteId AND ((Total - @Valor) >= -Limite)
RETURNING Limite, Total INTO updated_limite, updated_saldo;
IF FOUND THEN
INSERT INTO public.Transacao (ClienteId, Valor, Descricao, Tipo, CriadoEm) VALUES (ClienteId, Valor, Descricao, 'd', NOW());
RETURN QUERY SELECT true, updated_limite, updated_saldo;
ELSE
RETURN QUERY SELECT false, 0, 0;
END IF;
END;
$func$;