forked from zanfranceschi/rinha-de-backend-2024-q1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.sql
75 lines (63 loc) · 1.8 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
-- 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);
-- get_client function
CREATE OR REPLACE FUNCTION get_client(p_client_id SMALLINT)
RETURNS JSONB AS $$
DECLARE
saldo_result JSONB;
BEGIN
SELECT jsonb_build_object(
'saldo', jsonb_build_object(
'total', c.saldo,
'data_extrato', current_timestamp,
'limite', ABS(c.limite)
),
'ultimas_transacoes', c.ultimas_transacoes
)
INTO saldo_result
FROM clientes c
WHERE c.id = p_client_id;
IF NOT FOUND THEN
RAISE EXCEPTION 'cliente_not_found';
END IF;
RETURN saldo_result;
END;
$$ LANGUAGE plpgsql;
-- 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;