Skip to content

Instantly share code, notes, and snippets.

@qzhuyan
Created March 23, 2021 22:12
Show Gist options
  • Save qzhuyan/d84928e4a802e3a3978666dad2f69e24 to your computer and use it in GitHub Desktop.
Save qzhuyan/d84928e4a802e3a3978666dad2f69e24 to your computer and use it in GitHub Desktop.
#!/usr/bin/env escript
%% -*- erlang -*-
main(["usage"]) ->
io:format("./schema_fix.escript [--dry-run] schema.DAT [add | replace] 'emqx3@127.0.0.1' ~n",
[]);
main(["--dry-run", SchemaFile, Op, NodeStr]) ->
run(true, SchemaFile, Op, NodeStr);
main([SchemaFile, Op, NodeStr]) ->
run(false, SchemaFile, Op, NodeStr);
main(_) ->
main(["usage"]).
run(IsDryrun, SchemaFile, Op, NodeStr) ->
Node = list_to_atom(NodeStr),
{ok, DetsTab} = dets:open_file(SchemaFile),
Old = dets:foldl(fun(Obj,Acc)-> [ Obj| Acc]end, [], DetsTab),
io:format("Old ~p~n", [Old]),
Copies = [ram_copies, disc_copies, disc_only_copies],
New = lists:foldl(fun({schema, Tab, Schema},Acc)->
NewS = lists:filtermap(fun({K,V}) ->
case lists:member(K, Copies) andalso
V =/= [] andalso
not lists:member(Node, V) of
true when Op == "add" ->
{true, {K, [Node | V]}};
true when Op == "replace" ->
{true, {K, [Node]}};
true ->
error(badop);
false ->
true
end
end, Schema),
[{schema, Tab, NewS} | Acc]
end, [], Old),
io:format("New: ~p~n", [New]),
not IsDryrun andalso lists:foreach(fun(O) -> dets:insert(DetsTab,O) end, New),
not IsDryrun andalso dets:sync(DetsTab),
dets:close(DetsTab).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment