Skip to content

Commit b2ac101

Browse files
committed
Issue #186: Delete node related records when node is deleted
1 parent 18f126f commit b2ac101

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/lorawan_db_guard.erl

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ start_link() ->
1818
gen_server:start_link(?MODULE, [], []).
1919

2020
init([]) ->
21+
{ok, _} = mnesia:subscribe({table, links, simple}),
2122
{ok, _} = timer:send_interval(3600*1000, trim_tables),
2223
{ok, undefined}.
2324

@@ -27,9 +28,14 @@ handle_call(_Request, _From, State) ->
2728
handle_cast(_Msg, State) ->
2829
{noreply, State}.
2930

31+
handle_info({mnesia_table_event, {delete, {Tab, Key}, _Id}}, State) ->
32+
handle_delete(Tab, Key),
33+
{noreply, State};
3034
handle_info(trim_tables, State) ->
3135
[trim_rxframes(R) || R <- mnesia:dirty_all_keys(links)],
3236
[mnesia:dirty_delete(events, E) || E <- expired_events()],
37+
{noreply, State};
38+
handle_info(_Other, State) ->
3339
{noreply, State}.
3440

3541
terminate(_Reason, _State) ->
@@ -38,6 +44,21 @@ terminate(_Reason, _State) ->
3844
code_change(_OldVsn, State, _Extra) ->
3945
{ok, State}.
4046

47+
handle_delete(links, DevAddr) ->
48+
lager:debug("Node ~p deleted", [lorawan_mac:binary_to_hex(DevAddr)]),
49+
% delete linked records
50+
ok = mnesia:dirty_delete(pending, DevAddr),
51+
delete_matched(rxframes, #rxframe{frid='$1', devaddr=DevAddr, _='_'}),
52+
delete_matched(txframes, #txframe{frid='$1', devaddr=DevAddr, _='_'});
53+
handle_delete(_Other, _Any) ->
54+
ok.
55+
56+
delete_matched(Table, Record) ->
57+
lists:foreach(
58+
fun(Id) ->
59+
ok = mnesia:dirty_delete(Table, Id)
60+
end,
61+
mnesia:dirty_select(Table, [{Record, [], ['$1']}])).
4162

4263
trim_rxframes(DevAddr) ->
4364
{ok, Count} = application:get_env(lorawan_server, retained_rxframes),

0 commit comments

Comments
 (0)