-
Notifications
You must be signed in to change notification settings - Fork 923
/
Copy pathinit.sql
99 lines (82 loc) · 2.32 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
BEGIN;
CREATE UNLOGGED TABLE IF NOT EXISTS CLIENTS (
ID SERIAL PRIMARY KEY,
ACCOUNT_LIMIT INTEGER NOT NULL DEFAULT 0,
BALANCE INTEGER NOT NULL DEFAULT 0
);
CREATE UNLOGGED TABLE IF NOT EXISTS TRANSACTIONS (
ID SERIAL PRIMARY KEY,
CLIENT_ID INTEGER NOT NULL,
VALUE INTEGER NOT NULL,
TYPE VARCHAR(1) NOT NULL,
DESCRIPTION VARCHAR(10) NOT NULL,
CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IDX_TRANSACTIONS ON TRANSACTIONS (ID DESC);
CREATE INDEX IDX_TRANSACTIONS_CLIENT_ID ON TRANSACTIONS (CLIENT_ID);
INSERT INTO CLIENTS (ACCOUNT_LIMIT, BALANCE) VALUES (100000, 0);
INSERT INTO CLIENTS (ACCOUNT_LIMIT, BALANCE) VALUES (80000, 0);
INSERT INTO CLIENTS (ACCOUNT_LIMIT, BALANCE) VALUES (1000000, 0);
INSERT INTO CLIENTS (ACCOUNT_LIMIT, BALANCE) VALUES (10000000, 0);
INSERT INTO CLIENTS (ACCOUNT_LIMIT, BALANCE) VALUES (500000, 0);
CREATE OR REPLACE FUNCTION CREATE_TRANSACTION(
ID_CLIENT INT,
T_VALUE INT,
T_TYPE CHAR,
T_DESC VARCHAR(10)
)
RETURNS TABLE (B INT, L INT) AS $$
DECLARE
CLIENT_BALANCE INTEGER;
CLIENT_LIMIT INTEGER;
BEGIN
SELECT C.BALANCE, C.ACCOUNT_LIMIT
INTO CLIENT_BALANCE, CLIENT_LIMIT
FROM CLIENTS C
WHERE ID = ID_CLIENT FOR UPDATE;
IF NOT FOUND THEN
RAISE EXCEPTION 'CLIENT_NOT_FOUND';
END IF;
IF T_TYPE = 'd' THEN
IF (CLIENT_BALANCE - T_VALUE) < (CLIENT_LIMIT * -1) THEN
RAISE EXCEPTION 'LOW_LIMIT';
END IF;
UPDATE CLIENTS
SET BALANCE = BALANCE - T_VALUE
WHERE ID = ID_CLIENT;
ELSE
UPDATE CLIENTS
SET BALANCE = BALANCE + T_VALUE
WHERE ID = ID_CLIENT;
END IF;
INSERT INTO TRANSACTIONS (TYPE, VALUE, DESCRIPTION, CLIENT_ID)
VALUES (T_TYPE, T_VALUE, T_DESC, ID_CLIENT);
RETURN QUERY SELECT BALANCE, ACCOUNT_LIMIT
FROM CLIENTS WHERE ID = ID_CLIENT;
END $$
LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION GET_BALANCE(CID INTEGER)
RETURNS TABLE (
ACCOUNT_LIMIT INTEGER,
BALANCE INTEGER,
VALUE INTEGER,
TYPE CHAR,
DESCRIPTION VARCHAR(10),
CREATED_AT TEXT
) AS $$
BEGIN
RETURN QUERY SELECT
C.ACCOUNT_LIMIT
, C.BALANCE
, T.VALUE
, T.TYPE::CHAR
, T.DESCRIPTION
, T.CREATED_AT::TEXT
FROM CLIENTS C
LEFT JOIN TRANSACTIONS T ON T.CLIENT_ID = C.ID
WHERE C.ID = CID
ORDER BY T.ID DESC
LIMIT 10;
END $$
LANGUAGE PLPGSQL;
COMMIT;