|
| 1 | +-module(rafter_backend_ets). |
| 2 | + |
| 3 | +-behaviour(rafter_backend). |
| 4 | + |
| 5 | +%% rafter_backend callbacks |
| 6 | +-export([init/1, stop/1, read/2, write/2]). |
| 7 | + |
| 8 | +-record(state, {peer :: atom() | {atom(), atom()}}). |
| 9 | + |
| 10 | +init(Peer) -> |
| 11 | + State = #state{peer=Peer}, |
| 12 | + NewState = stop(State), |
| 13 | + ets:new(rafter_backend_ets, [set, named_table, public]), |
| 14 | + ets:new(rafter_backend_ets_tables, [set, named_table, public]), |
| 15 | + NewState. |
| 16 | + |
| 17 | +stop(State) -> |
| 18 | + catch ets:delete(rafter_backend_ets), |
| 19 | + catch ets:delete(rafter_backend_ets_tables), |
| 20 | + State. |
| 21 | + |
| 22 | +read({get, Table, Key}, State) -> |
| 23 | + Val = try |
| 24 | + case ets:lookup(Table, Key) of |
| 25 | + [{Key, Value}] -> |
| 26 | + {ok, Value}; |
| 27 | + [] -> |
| 28 | + {ok, not_found} |
| 29 | + end |
| 30 | + catch _:E -> |
| 31 | + {error, E} |
| 32 | + end, |
| 33 | + {Val, State}; |
| 34 | + |
| 35 | +read(list_tables, State) -> |
| 36 | + {{ok, [Table || {Table} <- ets:tab2list(rafter_backend_ets_tables)]}, |
| 37 | + State}; |
| 38 | + |
| 39 | +read({list_keys, Table}, State) -> |
| 40 | + Val = try |
| 41 | + list_keys(Table) |
| 42 | + catch _:E -> |
| 43 | + {error, E} |
| 44 | + end, |
| 45 | + {Val, State}. |
| 46 | + |
| 47 | +write({new, Name}, State) -> |
| 48 | + Val = try |
| 49 | + ets:new((Name), [ordered_set, named_table, public]), |
| 50 | + ets:insert(rafter_backend_ets_tables, {Name}), |
| 51 | + {ok, Name} |
| 52 | + catch _:E -> |
| 53 | + {error, E} |
| 54 | + end, |
| 55 | + {Val, State}; |
| 56 | + |
| 57 | +write({put, Table, Key, Value}, State) -> |
| 58 | + Val = try |
| 59 | + ets:insert(Table, {Key, Value}), |
| 60 | + {ok, Value} |
| 61 | + catch _:E -> |
| 62 | + {error, E} |
| 63 | + end, |
| 64 | + {Val, State}; |
| 65 | + |
| 66 | +write({delete, Table}, State) -> |
| 67 | + Val = |
| 68 | + try |
| 69 | + ets:delete(Table), |
| 70 | + ets:delete(rafter_backend_ets_tables, Table), |
| 71 | + {ok, true} |
| 72 | + catch _:E -> |
| 73 | + {error, E} |
| 74 | + end, |
| 75 | + {Val, State}; |
| 76 | + |
| 77 | + |
| 78 | +write({delete, Table, Key}, State) -> |
| 79 | + Val = try |
| 80 | + {ok, ets:delete(Table, Key)} |
| 81 | + catch _:E -> |
| 82 | + {error, E} |
| 83 | + end, |
| 84 | + {Val, State}. |
| 85 | + |
| 86 | +list_keys(Table) -> |
| 87 | + list_keys(ets:first(Table), Table, []). |
| 88 | + |
| 89 | +list_keys('$end_of_table', _Table, Keys) -> |
| 90 | + {ok, Keys}; |
| 91 | +list_keys(Key, Table, Keys) -> |
| 92 | + list_keys(ets:next(Table, Key), Table, [Key | Keys]). |
0 commit comments