-
Notifications
You must be signed in to change notification settings - Fork 923
/
Copy pathscript.sql
55 lines (47 loc) · 1.46 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
-- Coloque scripts iniciais aqui
CREATE UNLOGGED TABLE clientes (
id SMALLINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
limite INTEGER,
saldo INTEGER DEFAULT 0
);
CREATE INDEX idx_client_id ON clientes USING HASH(id);
ALTER TABLE clientes ADD CONSTRAINT balance_within_limit CHECK (saldo > -limite);
CREATE UNLOGGED TABLE transacoes (
id INT GENERATED BY DEFAULT AS IDENTITY,
user_id SMALLINT,
valor INTEGER,
tipo VARCHAR(1),
descricao VARCHAR(10),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_transaction_id_desc ON transacoes (id DESC);
CREATE INDEX idx_transaction_user_id ON transacoes USING HASH(user_id);
-- Função para atualizar o saldo do usuário
CREATE OR REPLACE FUNCTION updateUserBalance(userId SMALLINT, transactionValue INTEGER)
RETURNS TABLE (newBalance INTEGER, limit_res INTEGER)
AS $$
DECLARE
balance INTEGER;
newBalance INTEGER;
limit_res INTEGER;
BEGIN
SELECT saldo, limite INTO balance, limit_res FROM clientes WHERE id = userId FOR UPDATE;
IF NOT FOUND THEN
RAISE EXCEPTION 'user not found on postgres';
END IF;
SELECT transactionValue + balance INTO newBalance;
UPDATE clientes SET saldo = newBalance WHERE id = userId;
RETURN QUERY SELECT newBalance, limit_res;
END;
$$ LANGUAGE plpgsql;
DO $$
BEGIN
INSERT INTO clientes (limite)
VALUES
(1000 * 100),
(800 * 100),
(10000 * 100),
(100000 * 100),
(5000 * 100);
END;
$$