-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_server.erl
54 lines (48 loc) · 1.37 KB
/
db_server.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
-module(db_server).
-export([start/0, stop/1, start/1, stop/0]).
-import(db_persistence, [read/1, save/2]).
-import(db_operation, [select/2, add/2]).
serve_add(DB, NewRow) ->
try add(DB, NewRow) of
NewDB -> {ok, NewDB}
catch
throw:Reason -> {{error, Reason}, DB};
error:function_clause -> {{error, "Not a triple"}, DB}
end.
serve_select(DB, Filters) ->
try select(DB, Filters) of
Result -> Result
catch
throw:Reason -> {error, Reason};
error:function_clause -> {error, "Invalid filters"}
end.
serve(DB) ->
receive
{SenderPID, {add, Row}} ->
{Response, NewDB} = serve_add(DB, Row),
SenderPID ! Response,
serve(NewDB);
{SenderPID, {select, Filters}} ->
Response = serve_select(DB, Filters),
SenderPID ! Response,
serve(DB);
{'EXIT', _, {stop, OutFile}} ->
ok = save(DB, OutFile)
end.
stop(OutFile) ->
case whereis(dbms) of
undefined -> throw("DBMS not started");
Pid -> exit(Pid, {stop, OutFile})
end.
stop() ->
stop(none).
init(InitialDB) ->
process_flag(trap_exit, true),
serve(InitialDB).
start(none) ->
register(dbms, spawn(fun() -> init([]) end));
start(InFile) ->
InitialDB = read(InFile),
register(dbms, spawn(fun() -> init(InitialDB) end)).
start() ->
start(none).