-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessage_store.erl
79 lines (65 loc) · 1.95 KB
/
message_store.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
67
68
69
70
71
72
73
74
75
76
77
78
-module(message_store).
-include_lib("stdlib/include/qlc.hrl").
-define(SERVER, message_store).
-compile(export_all).
-record(chat_message,
{addressee, body, created_on}).
save_message(Addressee, Body) ->
global:send(?SERVER, {save_msg, Addressee, Body}).
find_messages(Addressee) ->
global:send(?SERVER, {get_messages, Addressee, self()}),
receive
{ok, Messages} ->
Messages
end.
start() ->
server_util:start(?SERVER, {message_store, run, [true]}).
stop() ->
server_util:stop(?SERVER).
run(FirstTime) ->
if
FirstTime == true ->
init_store(),
run(false);
true ->
receive
{save_msg, Addressee, Body} ->
store_message(Addressee, Body),
run(FirstTime);
{find_msgs, Addressee, Pid} ->
Messages = get_messages(Addressee),
Pid ! {ok, Messages},
run(FirstTime);
shutdown ->
mnesia:stop(),
io:format("Shutting down...~n")
end
end.
delete_messages(Messages) ->
F = fun() ->
lists:foreach( fun(Msg) -> mnesea:delete_object(Msg) end, Messages) end,
mnesia:transaction(F).
get_messages(Addressee) ->
F = fun() ->
Query = qlc:q([M#chat_message.body || M <- mnesia:table(chat_message),
M#chat_message.addressee =:= Addressee]),
Results = qlc:e(Query),
delete_messages(Results),
Results end,
mnesia:transaction(F).
store_message(Addressee, Body) ->
F = fun() ->
{_, CreatedOn, _} = erlang:now(),
mnesia:write(#chat_message{addressee=Addressee, body=Body, created_on=CreatedOn}) end,
mnesia:transaction(F).
init_store() ->
mnesia:create_schema([node()]),
mnesia:start(),
try
mnesia:table_info(chat_message, type)
catch
exit: _ ->
mnesia:create_table(chat_message, [{attributes, record_info(fields, chat_message)},
{type, bag},
{disc_copies, [node()]}])
end.