forked from zanfranceschi/rinha-de-backend-2024-q1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.sql
50 lines (41 loc) · 1.27 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
-- create clientes table
CREATE UNLOGGED TABLE IF NOT EXISTS clientes (
id SMALLINT PRIMARY KEY NOT NULL,
limite INTEGER NOT NULL,
saldo INTEGER NOT NULL,
ultimas_transacoes JSONB not null default '[]'::jsonb,
CONSTRAINT limite_minimo CHECK (saldo > limite)
);
-- insert clientes
INSERT INTO clientes (id, limite, saldo)
VALUES
(1, -100000, 0),
(2, -80000, 0),
(3, -1000000, 0),
(4, -10000000, 0),
(5, -500000, 0),
(9999, -10000000, 0);
-- add_transaction function
CREATE OR REPLACE FUNCTION add_transaction(client_id INTEGER, transaction JSONB)
RETURNS JSONB AS $$
DECLARE
novosaldo INTEGER;
cliente RECORD;
BEGIN
IF transaction ->> 'tipo' = 'c' THEN
novosaldo := (transaction ->> 'valor')::INTEGER;
ELSIF transaction ->> 'tipo' = 'd' THEN
novosaldo := -(transaction ->> 'valor')::INTEGER;
END IF;
UPDATE clientes
SET
saldo = saldo + novosaldo,
ultimas_transacoes = jsonb_path_query_array(jsonb_insert(ultimas_transacoes,'{0}', transaction), '$[0 to 9]')
WHERE id = client_id
RETURNING * INTO cliente;
IF NOT FOUND THEN
RAISE EXCEPTION 'cliente_not_found';
END IF;
RETURN jsonb_build_object('limite', ABS(cliente.limite), 'saldo', cliente.saldo);
END;
$$ LANGUAGE plpgsql;