-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy_db_distrib.erl
66 lines (55 loc) · 1.25 KB
/
my_db_distrib.erl
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
-module(my_db_distrib).
-export([start/0,stop/0,write/2,delete/1,read/1,match/1]).
-export([code_upgrade/0]).
-export([init/0]).
start() ->
register(db_server, spawn(my_db, init, [])).
init() ->
DB = db:new(),
loop(DB).
stop() ->
call(destroy).
write(Key, Element) ->
call({write, Key, Element}).
delete(Key) ->
call({delete, Key}).
read(Key) ->
call({read, Key}).
match(Element) ->
call({match, Element}).
call(Msg) ->
db_server ! {request, self(), Msg},
receive
{reply, Reply} ->
Reply
end.
reply(Pid, Msg) ->
Pid ! {reply, Msg}.
loop(DB) ->
receive
{request, Pid, upgrade} ->
NewDB = db:code_upgrade(DB),
reply(Pid, ok),
loop(NewDB);
{request, Pid, destroy} ->
db:destory(DB),
reply(Pid, ok);
{request, Pid, {write, Key, Element}} ->
NewDB = db:write(Key, Element, DB),
reply(Pid, ok),
loop(NewDB);
{request, Pid, {delete, Key}} ->
NewDB = db:delete(Key, DB),
reply(Pid, ok),
loop(NewDB);
{request, Pid, {read, Key}} ->
Reply = db:read(Key, DB),
reply(Pid, Reply),
loop(DB);
{request, Pid, {match, Element}} ->
Reply = db:match(Element, DB),
reply(Pid, Reply),
loop(DB)
end.
code_upgrade() ->
call(upgrade).