forked from zanfranceschi/rinha-de-backend-2024-q1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.sql
55 lines (50 loc) · 1.64 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
CREATE EXTENSION IF NOT EXISTS plpgsql;
CREATE TABLE accounts (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
credit_limit INTEGER NOT NULL DEFAULT 0,
balance INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE ledgers (
id SERIAL PRIMARY KEY,
amount INTEGER NOT NULL,
kind CHAR(1) NOT NULL,
description VARCHAR(10) NOT NULL,
account_id INTEGER NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_accounts_ledgers_id
FOREIGN KEY (account_id) REFERENCES accounts (id)
);
CREATE OR REPLACE FUNCTION update_balance_function()
RETURNS TRIGGER
LANGUAGE PLPGSQL
AS
$$
BEGIN
IF TG_OP = 'INSERT' AND NEW.kind = 'c' THEN
UPDATE accounts SET balance = balance + NEW.amount WHERE id = NEW.account_id;
ELSIF TG_OP = 'INSERT' AND NEW.kind = 'd' THEN
UPDATE accounts SET balance = balance - NEW.amount WHERE id = NEW.account_id;
ELSIF TG_OP = 'DELETE' AND OLD.kind = 'c' THEN
UPDATE accounts SET balance = balance - OLD.amount WHERE id = OLD.account_id;
ELSIF TG_OP = 'DELETE' AND OLD.kind = 'd' THEN
UPDATE accounts SET balance = balance + OLD.amount WHERE id = OLD.account_id;
END IF;
RETURN NULL;
END; $$;
CREATE TRIGGER update_balance
AFTER INSERT OR DELETE ON ledgers
FOR EACH ROW
EXECUTE FUNCTION update_balance_function();
DO $$
BEGIN
INSERT INTO accounts (name, credit_limit)
VALUES
('o barato sai caro', 1000 * 100),
('zan corp ltda', 800 * 100),
('les cruders', 10000 * 100),
('padaria joia de cocaia', 100000 * 100),
('kid mais', 5000 * 100);
END; $$;