-
Notifications
You must be signed in to change notification settings - Fork 923
/
Copy pathscript_psql.sql
99 lines (80 loc) · 2.49 KB
/
script_psql.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
CREATE TABLE IF NOT EXISTS clientes
(
id int not null Primary key,
limite int not null default 0,
saldo int not null default 0
);
insert into clientes (id, limite, saldo) values(1, 100000, 0);
insert into clientes (id, limite, saldo) values(2, 80000, 0);
insert into clientes (id, limite, saldo) values(3, 1000000, 0);
insert into clientes (id, limite, saldo) values(4, 10000000, 0);
insert into clientes (id, limite, saldo) values(5, 500000, 0);
CREATE UNLOGGED TABLE IF NOT EXISTS transacoes
(
id varchar(100) not null,
id_cliente INT NOT NULL,
valor INT NOT NULL,
tipo VARCHAR(1) NOT NULL,
descricao VARCHAR(100) NOT NULL,
ultimo_saldo INT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL
);
ALTER TABLE transacoes SET (autovacuum_enabled = false);
--
-- credito
--
CREATE OR REPLACE FUNCTION func_credito(
pid VARCHAR(30),
pid_cliente INT,
pvalor INT,
pdescricao VARCHAR(10),
pcreated_at TIMESTAMPTZ
)
RETURNS TABLE (saldo_atual INT, limite_atual INT)
LANGUAGE plpgsql
AS $$
DECLARE
var_saldo INT;
BEGIN
LOCK TABLE clientes, transacoes IN ACCESS EXCLUSIVE MODE;
INSERT INTO transacoes (id, id_cliente, valor, tipo, descricao, ultimo_saldo, created_at)
VALUES (pid, pid_cliente, pvalor, 'c', pdescricao, var_saldo, pcreated_at);
RETURN QUERY
UPDATE clientes SET saldo = saldo + pvalor WHERE id = pid_cliente
RETURNING saldo, limite;
END;
$$;
--
-- debito
--
CREATE OR REPLACE FUNCTION func_debito(
pid VARCHAR(30),
pid_cliente INT,
pvalor INT,
pdescricao VARCHAR(10),
pcreated_at TIMESTAMPTZ
)
RETURNS TABLE (saldo_atual INT, limite_atual INT)
LANGUAGE plpgsql
AS $$
DECLARE
var_saldo INT;
var_limite INT;
BEGIN
LOCK TABLE clientes, transacoes IN ACCESS EXCLUSIVE MODE;
SELECT c.saldo, c.limite
INTO var_saldo, var_limite
FROM clientes c
WHERE c.id = pid_cliente;
IF (var_saldo - pvalor >= -var_limite) THEN
INSERT INTO transacoes (id, id_cliente, valor, tipo, descricao, ultimo_saldo, created_at)
VALUES (pid, pid_cliente, pvalor, 'd', pdescricao, var_saldo, pcreated_at);
UPDATE clientes SET saldo = var_saldo WHERE id = pid_cliente;
RETURN QUERY
UPDATE clientes SET saldo = saldo - pvalor WHERE id = pid_cliente
RETURNING saldo, limite;
ELSE
RAISE EXCEPTION '[001] Cliente não tem limite para a operação';
END IF;
END;
$$;