Skip to content

Instantly share code, notes, and snippets.

@isqad
Created March 25, 2013 06:17
Show Gist options
  • Save isqad/5235226 to your computer and use it in GitHub Desktop.
Save isqad/5235226 to your computer and use it in GitHub Desktop.
Simple database
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Database base on list set %
% Andrew N. Shalaev %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-module(db).
-export([start/0, stop/0, read/1, write/2, delete/1]).
-export([init/0]).
% process loop
loop(Db) ->
receive
{write, From, Key, Value} ->
NewDb = write_db(Key, Value, Db),
From ! {ok, NewDb},
loop(NewDb);
{read, From, Key} ->
From ! read_db(Key, Db),
loop(Db);
{delete, From, Key} ->
NewDb = delete_db(Key, Db),
From ! {ok, NewDb},
loop(NewDb);
{stop, From} ->
From ! {ok, Db};
_ ->
loop(Db)
end.
init() ->
Db = [],
loop(Db).
%%%%%%%%%%%%%%%%%%%%
% Client functions %
%%%%%%%%%%%%%%%%%%%%
% start process
start() ->
register(my_db, spawn(?MODULE, init, [])).
% stop process
stop() ->
my_db ! {stop, self()},
receive
{ok, Db} ->
io:format("~w~n", [Db])
end.
% write to Database
write(Key, Value) ->
my_db ! {write, self(), Key, Value},
receive
{ok, Db} ->
io:format("~w~n", [Db])
end.
% read from Database
read(Key) ->
my_db ! {read, self(), Key},
receive
{ok, Value} ->
io:format("~w~n", [Value]);
{error, _} ->
io:format("~w~n", [error])
end.
% delete by key
delete(Key) ->
my_db ! {delete, self(), Key},
receive
{ok, Db} ->
io:format("~w~n", [Db])
end.
%%%%%%%%%%%%%%%%%%%%
% Server functions %
%%%%%%%%%%%%%%%%%%%%
% Create
% Update
write_db(Key, Value, Db) ->
case read_db(Key, Db) of
{error, instance} -> [{Key, Value}|Db];
{ok, _} -> [{Key, Value}|delete_db(Key, Db)]
end.
% Read
read_db(_, []) ->
{error, instance};
read_db(Key, [{Key, Value}|_]) ->
{ok, Value};
read_db(Key, [_ | T]) ->
read_db(Key, T).
% Delete
delete_db(Key, Db) ->
delete_acc(Key, Db, []).
delete_acc(_, [], L) ->
L;
delete_acc(Key, [{Key,_}|T], L) ->
L ++ T;
delete_acc(Key, [H|T], L) ->
delete_acc(Key, T, L ++ [H]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment