Skip to content

Commit

Permalink
Fix nested_put and nested_get
Browse files Browse the repository at this point in the history
  • Loading branch information
terry-xiaoyu committed May 31, 2019
1 parent 5f2238d commit 64776ae
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
4 changes: 2 additions & 2 deletions src/emqx_rule_runtime.erl
Expand Up @@ -154,7 +154,7 @@ select_and_transform(['*'|More], Input, Output) ->
select_and_transform(More, Input, maps:merge(Output, Input));
select_and_transform([{as, Field, Alias}|More], Input, Output) ->
Val = eval(Field, Input),
select_and_transform(More, Input, nested_put(Alias, Val, Output));
select_and_transform(More, Input, nested_put(emqx_rule_utils:atom_key(Alias), Val, Output));
select_and_transform([Field|More], Input, Output) ->
Val = eval(Field, Input),
Alias = alias(Field, Val),
Expand Down Expand Up @@ -214,7 +214,7 @@ take_action(#action_instance{id = Id}, Selected, Envs) ->
Apply(Selected, Envs).

eval({var, Var}, Input) -> %% nested
nested_get(Var, Input);
nested_get(emqx_rule_utils:atom_key(Var), Input);
eval({const, Val}, _Input) ->
Val;
eval({payload, Attr}, Input) when is_binary(Attr) ->
Expand Down
13 changes: 8 additions & 5 deletions src/emqx_rule_utils.erl
Expand Up @@ -71,13 +71,16 @@ preproc_sql(Sql, ReplaceWith) ->
{match, PlaceHolders} ->
{repalce_with(Sql, ReplaceWith),
fun(Data) ->
[maps:get(atom_key(Key), Data, undefined)
|| Key <- [var(hd(PH)) || PH <- PlaceHolders]]
get_phld(Data, PlaceHolders)
end};
nomatch ->
{Sql, fun(_) -> [] end}
end.

get_phld(Data, PlaceHolders) ->
[maps:get(atom_key(Key), Data, undefined)
|| Key <- [var(hd(PH)) || PH <- PlaceHolders]].

repalce_with(Tmpl, '?') ->
re:replace(Tmpl, ?EX_PLACE_HOLDER, "?", [{return, binary}, global]);
repalce_with(Tmpl, '$n') ->
Expand All @@ -94,9 +97,9 @@ repalce_with(Tmpl, '$n') ->

atom_key(Key) when is_atom(Key) ->
Key;
atom_key(Key) when is_list(Key) ->
try list_to_existing_atom(Key)
catch error:badarg -> error({invalid_key, Key})
atom_key(Keys = [Key | SubKeys]) when is_binary(Key) -> %% nested keys
try [binary_to_existing_atom(Key, utf8) | SubKeys]
catch error:badarg -> error({invalid_key, Keys})
end;
atom_key(Key) when is_binary(Key) ->
try binary_to_existing_atom(Key, utf8)
Expand Down

0 comments on commit 64776ae

Please sign in to comment.