-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorder.sql
102 lines (90 loc) · 2.74 KB
/
order.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
100
101
102
-- pgsql
create table orders
(
id bigint not null primary key,
user_id bigint not null,
transaction_id bigint not null,
state varchar(20) not null,
created_at timestamp not null,
expires timestamp not null,
updated_at timestamp not null
);
create table order_items
(
id bigint not null primary key,
order_id bigint not null,
product_id bigint not null,
name varchar(200) not null,
image text not null,
price decimal(10, 2) not null,
qty int not null,
foreign key (order_id) references orders (id)
);
create or replace function confirm_order(_transaction_id bigint, _updated_at timestamp)
returns bool
as
$func$
declare
__state varchar(20);
__expires timestamp;
begin
select state, expires into __state, __expires from orders where transaction_id = _transaction_id for update;
if __state <> 'Pending' or __expires < _updated_at then
return false;
end if;
update orders set state = 'Confirmed', updated_at = _updated_at where transaction_id = _transaction_id;
return true;
end;
$func$ language plpgsql;
create or replace function cancel_order(_transaction_id bigint, _updated_at timestamp)
returns bool
as
$func$
declare
__state varchar(20);
__expires timestamp;
begin
select state, expires
into __state, __expires
from orders
where transaction_id = _transaction_id for update;
if __state <> 'Pending' or __expires < _updated_at then
return false;
end if;
update orders set state = 'Canceled', updated_at = _updated_at where transaction_id = _transaction_id;
return true;
end;
$func$ language plpgsql;
create or replace function notify_order_state()
returns trigger
as
$func$
declare
__json text;
begin
if (tg_op = 'INSERT') then
__json = json_build_object(
'id', new.transaction_id,
'state', new.state,
'beginTime', new.created_at,
'expires', new.expires
) #>> '{}';
elseif (tg_op = 'UPDATE') then
__json = json_build_object(
'id', old.transaction_id,
'state', new.state,
'beginTime', old.created_at,
'expires', old.expires
) #>> '{}';
end if;
if (__json is not null) then
perform pg_notify('transaction_channel', __json);
end if;
return null;
end;
$func$ language plpgsql;
create trigger state_trigger
after insert or update
on orders
for each row
execute function notify_order_state();