forked from zanfranceschi/rinha-de-backend-2024-q1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.sql
85 lines (74 loc) · 2.26 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
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
DO
$$
BEGIN
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
SET default_tablespace = '';
SET default_table_access_method = heap;
create table public.users
(
id bigserial primary key,
name varchar(255),
"limit" bigint,
balance bigint
);
create table public.transaction
(
id bigserial primary key,
created_at timestamp,
value bigint,
description varchar(10),
user_id bigint
);
-- Inserção de valores iniciais na tabela clientes
INSERT INTO users (id, balance, "limit") VALUES (1, 0, -100000);
INSERT INTO users (id, balance, "limit") VALUES (2, 0, -80000);
INSERT INTO users (id, balance, "limit") VALUES (3, 0, -1000000);
INSERT INTO users (id, balance, "limit") VALUES (4, 0, -10000000);
INSERT INTO users (id, balance, "limit") VALUES (5, 0, -500000);
END
$$;
CREATE OR REPLACE FUNCTION createtransaction(
IN idUser integer,
IN value integer,
IN description varchar(10)
) RETURNS RECORD AS
$$
DECLARE
userfound users%rowtype;
ret RECORD;
BEGIN
SELECT *
FROM users
INTO userfound
WHERE
id = idUser;
IF not found THEN
--raise notice'Id user % not found.', idUser;
select -1 into ret;
RETURN ret;
END IF;
--raise notice'transaction by user %.', idUser;
INSERT INTO transaction (value, description, created_at, user_id)
VALUES (value, description, now() at time zone 'utc', idUser);
UPDATE users
SET balance = balance + value
WHERE id = idUser
AND (value > 0 OR balance + value >= "limit")
RETURNING balance, "limit"
INTO ret;
raise notice 'Ret: %', ret;
IF ret."limit" is NULL THEN
--raise notice'Id user % not found.', idUser;
select -2 into ret;
END IF;
RETURN ret;
END;
$$ LANGUAGE plpgsql;