Skip to content

Commit

Permalink
some new exmple
Browse files Browse the repository at this point in the history
  • Loading branch information
hpyhacking committed Jul 25, 2011
1 parent ae4775b commit e1a6788
Show file tree
Hide file tree
Showing 8 changed files with 9,570 additions and 0 deletions.
Binary file added chapter_10/UsrTabFile
Binary file not shown.
8 changes: 8 additions & 0 deletions chapter_10/usr.hrl
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
%%% File: usr.hrl
%%% Description: Include file for user db

-record(usr, {msisdn,
id,
status = enabled,
plan,
services = []}).
72 changes: 72 additions & 0 deletions chapter_10/usr_db.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
%%% File: usr_db.erl
%%% Description: Database API for subscriber DB

-module(usr_db).
-include("usr.hrl").
-export([create_tables/1, close_tables/0]).
-export([add_usr/1, update_usr/1]).
-export([lookup_id/1, lookup_msisdn/1]).
-export([restore_backup/0]).

create_tables(FileName) ->
ets:new(usrRam, [named_table, {keypos, #usr.msisdn}]),
ets:new(usrIndex, [named_table]),
dets:open_file(usrDisk, [{file, FileName}, {keypos, #usr.msisdn}]).

close_tables() ->
ets:delete(usrRam),
ets:delete(usrIndex),
dets:close(usrDisk).

add_usr(#usr{msisdn=PhoneNo, id=CustId} = Usr) ->
ets:insert(usrIndex, {CustId, PhoneNo}),
update_usr(Usr).

update_usr(Usr) ->
ets:insert(usrRam, Usr),
dets:insert(usrDisk, Usr),
ok.

lookup_id(CustId) ->
case get_index(CustId) of
{ok, PhoneNo} -> lookup_msisdn(PhoneNo);
{error, instance} -> {error, instance}
end.

lookup_msisdn(PhoneNo) ->
case ets:lookup(usrRam, PhoneNo) of
[Usr] -> {ok, Usr};
[] -> {error, instance}
end.

get_index(CustId) ->
case ets:lookup(usrIndex, CustId) of
[{CustId, PhoneNo}] -> {ok, PhoneNo};
[] -> {error, instance}
end.

restore_backup() ->
Insert = fun(#usr{msisdn=PhoneNo, id=Id} = Usr) ->
ets:insert(usrRam, Usr),
ets:insert(usrIndex, {Id, PhoneNo}),
continue
end,
dets:traverse(usrDisk, Insert).

delete_disabled() ->
ets:safe_fixtable(usrRam, true),
catch loop_delete_disabled(ets:first(usrRam)),
ets:safe_fixtable(usrRam, false),
ok.

loop_delete_disabled('$end_of_table') ->
ok;

loop_delete_disabled(PhoneNo) ->
case ets:lookup(usrRam, PhoneNo) of
[usr{status=disabled, id=CustId}] ->
delete_usr(PhoneNo, CustId);
_ ->
ok
end,
loop_delete_disabled(ets:next(usrRam, PhoneNo)).
5 changes: 5 additions & 0 deletions chapter_11/dist.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-module(dist).
-export([t/1]).

t(From) ->
From ! node().
Loading

0 comments on commit e1a6788

Please sign in to comment.