Skip to content

Commit

Permalink
Support preprocess SQL with place holders
Browse files Browse the repository at this point in the history
  • Loading branch information
tigercl authored and terry-xiaoyu committed May 31, 2019
1 parent 3265ffe commit b00fad4
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion src/emqx_rule_utils.erl
Expand Up @@ -16,7 +16,9 @@

%% preprocess and process tempalte string with place holders
-export([ preproc_tmpl/1
, proc_tmpl/2]).
, proc_tmpl/2
, preproc_sql/1
, preproc_sql/2]).

%% type converting
-export([ str/1
Expand All @@ -31,6 +33,10 @@

-type(tmpl_token() :: list({var, fun()} | {str, binary()})).

-type(prepare_statement() :: binary()).

-type(prepare_params() :: fun((binary()) -> list())).

%% preprocess template string with place holders
-spec(preproc_tmpl(binary()) -> tmpl_token()).
preproc_tmpl(Str) ->
Expand All @@ -54,6 +60,38 @@ proc_tmpl(Tokens, Data) ->
({var, GetVal}) -> GetVal(Data)
end, Tokens)).

%% preprocess SQL with place holders
-spec(preproc_sql(Sql::binary()) -> {prepare_statement(), prepare_params()}).
preproc_sql(Sql) ->
preproc_sql(Sql, '?').

-spec(preproc_sql(Sql::binary(), '?' | '$n') -> {prepare_statement(), prepare_params()}).
preproc_sql(Sql, ReplaceWith) ->
case re:run(Sql, ?EX_PLACE_HOLDER, [{capture, all_but_first, binary}, global]) of
{match, PlaceHolders} ->
NewSql =
case ReplaceWith of
'?' ->
re:replace(Sql, ?EX_PLACE_HOLDER, "?", [{return, binary}, global]);
'$n' ->
Parts = re:split(Sql, ?EX_PLACE_HOLDER, [{return,binary}, trim, group]),
{Sql1, _} =
lists:foldl(fun([Tkn, _Phld], {Acc, Seq}) ->
Seq1 = erlang:integer_to_binary(Seq),
{<<Acc/binary, Tkn/binary, "$", Seq1/binary>>, Seq + 1};
([Tkn], {Acc, Seq}) ->
{<<Acc/binary, Tkn/binary>>, Seq}
end, {<<>>, 1}, Parts),
binary_to_list(Sql1)
end,
{NewSql, fun(Data) ->
[maps:get(atom_key(Key), Data, undefined)
|| Key <- [var(hd(PH)) || PH <- PlaceHolders]]
end};
nomatch ->
{Sql, []}
end.

atom_key(Key) when is_atom(Key) ->
Key;
atom_key(Key) when is_list(Key) ->
Expand Down

0 comments on commit b00fad4

Please sign in to comment.