emqx_utils_sql.erl 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2022-2024 EMQ Technologies Co., Ltd. All Rights Reserved.
  3. %%
  4. %% Licensed under the Apache License, Version 2.0 (the "License");
  5. %% you may not use this file except in compliance with the License.
  6. %% You may obtain a copy of the License at
  7. %%
  8. %% http://www.apache.org/licenses/LICENSE-2.0
  9. %%
  10. %% Unless required by applicable law or agreed to in writing, software
  11. %% distributed under the License is distributed on an "AS IS" BASIS,
  12. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. %% See the License for the specific language governing permissions and
  14. %% limitations under the License.
  15. %%--------------------------------------------------------------------
  16. -module(emqx_utils_sql).
  17. -export([get_statement_type/1]).
  18. -export([parse_insert/1]).
  19. -export([to_sql_value/1]).
  20. -export([to_sql_string/2]).
  21. -export([escape_sql/1]).
  22. -export([escape_cql/1]).
  23. -export([escape_mysql/1]).
  24. -export_type([value/0]).
  25. -type statement_type() :: select | insert | delete | update.
  26. -type value() :: null | binary() | number() | boolean() | [value()].
  27. -define(INSERT_RE_MP_KEY, insert_re_mp).
  28. -define(INSERT_RE_BIN, <<
  29. %% case-insensitive
  30. "(?i)^\\s*",
  31. %% Group-1: insert into, table name and columns (when existed).
  32. %% All space characters suffixed to <TABLE_NAME> will be kept
  33. %% `INSERT INTO <TABLE_NAME> [(<COLUMN>, ..)]`
  34. "(insert\\s+into\\s+[^\\s\\(\\)]+\\s*(?:\\([^\\)]*\\))?)",
  35. %% Keyword: `VALUES`
  36. "\\s*values\\s*",
  37. %% Group-2: literals value(s) or placeholder(s) with round brackets.
  38. %% And the sub-pattern in brackets does not do any capturing
  39. %% `([<VALUE> | <PLACEHOLDER>], ..])`
  40. "(\\((?:[^()]++|(?2))*\\))",
  41. "\\s*$"
  42. >>).
  43. -dialyzer({no_improper_lists, [escape_mysql/4, escape_prepend/4]}).
  44. -on_load(put_insert_mp/0).
  45. put_insert_mp() ->
  46. persistent_term:put({?MODULE, ?INSERT_RE_MP_KEY}, re:compile(?INSERT_RE_BIN)),
  47. ok.
  48. %% The type Copied from stdlib/src/re.erl to compatibility with OTP 26
  49. %% Since `re:mp()` exported after OTP 27
  50. -type mp() :: {re_pattern, _, _, _, _}.
  51. -spec get_insert_mp() -> {ok, mp()}.
  52. get_insert_mp() ->
  53. case persistent_term:get({?MODULE, ?INSERT_RE_MP_KEY}, undefined) of
  54. undefined ->
  55. ok = put_insert_mp(),
  56. get_insert_mp();
  57. {ok, MP} ->
  58. {ok, MP}
  59. end.
  60. -spec get_statement_type(iodata()) -> statement_type() | {error, unknown}.
  61. get_statement_type(Query) ->
  62. KnownTypes = #{
  63. <<"select">> => select,
  64. <<"insert">> => insert,
  65. <<"update">> => update,
  66. <<"delete">> => delete
  67. },
  68. case re:run(Query, <<"^\\s*([a-zA-Z]+)">>, [{capture, all_but_first, binary}]) of
  69. {match, [Token]} ->
  70. maps:get(string:lowercase(Token), KnownTypes, {error, unknown});
  71. _ ->
  72. {error, unknown}
  73. end.
  74. %% @doc Parse an INSERT SQL statement into its INSERT part and the VALUES part.
  75. %% SQL = <<"INSERT INTO \"abc\" (c1, c2, c3) VALUES (${a}, ${b}, ${c.prop})">>
  76. %% {ok, {<<"INSERT INTO \"abc\" (c1, c2, c3)">>, <<"(${a}, ${b}, ${c.prop})">>}}
  77. -spec parse_insert(iodata()) ->
  78. {ok, {_Statement :: binary(), _Rows :: binary()}} | {error, not_insert_sql}.
  79. parse_insert(SQL) ->
  80. {ok, MP} = get_insert_mp(),
  81. case re:run(SQL, MP, [{capture, all_but_first, binary}]) of
  82. {match, [InsertInto, ValuesTemplate]} ->
  83. {ok, {InsertInto, ValuesTemplate}};
  84. nomatch ->
  85. {error, not_insert_sql}
  86. end.
  87. %% @doc Convert an Erlang term to a value that can be used primarily in
  88. %% prepared SQL statements.
  89. -spec to_sql_value(term()) -> value().
  90. to_sql_value(undefined) -> null;
  91. to_sql_value(List) when is_list(List) -> List;
  92. to_sql_value(Bin) when is_binary(Bin) -> Bin;
  93. to_sql_value(Num) when is_number(Num) -> Num;
  94. to_sql_value(Bool) when is_boolean(Bool) -> Bool;
  95. to_sql_value(Atom) when is_atom(Atom) -> atom_to_binary(Atom, utf8);
  96. to_sql_value(Map) when is_map(Map) -> emqx_utils_json:encode(Map).
  97. %% @doc Convert an Erlang term to a string that can be interpolated in literal
  98. %% SQL statements. The value is escaped if necessary.
  99. -spec to_sql_string(term(), Options) -> unicode:chardata() when
  100. Options :: #{
  101. escaping => mysql | sql | cql,
  102. undefined => null | unicode:chardata()
  103. }.
  104. to_sql_string(undefined, #{undefined := Str} = Opts) when Str =/= null ->
  105. to_sql_string(Str, Opts);
  106. to_sql_string(undefined, #{}) ->
  107. <<"NULL">>;
  108. to_sql_string(String, #{escaping := mysql}) when is_binary(String) ->
  109. try
  110. escape_mysql(String)
  111. catch
  112. throw:invalid_utf8 ->
  113. [<<"0x">>, binary:encode_hex(String)]
  114. end;
  115. to_sql_string(Term, #{escaping := mysql}) ->
  116. maybe_escape(Term, fun escape_mysql/1);
  117. to_sql_string(Term, #{escaping := cql}) ->
  118. maybe_escape(Term, fun escape_cql/1);
  119. to_sql_string(Term, #{}) ->
  120. maybe_escape(Term, fun escape_sql/1).
  121. -spec maybe_escape(_Value, fun((binary()) -> iodata())) -> unicode:chardata().
  122. maybe_escape(Str, EscapeFun) when is_binary(Str) ->
  123. EscapeFun(Str);
  124. maybe_escape(Str, EscapeFun) when is_list(Str) ->
  125. case unicode:characters_to_binary(Str) of
  126. Bin when is_binary(Bin) ->
  127. EscapeFun(Bin);
  128. Otherwise ->
  129. error(Otherwise)
  130. end;
  131. maybe_escape(Val, EscapeFun) when is_atom(Val) orelse is_map(Val) ->
  132. EscapeFun(emqx_template:to_string(Val));
  133. maybe_escape(Val, _EscapeFun) ->
  134. emqx_template:to_string(Val).
  135. -spec escape_sql(binary()) -> iodata().
  136. escape_sql(S) ->
  137. % NOTE
  138. % This is a bit misleading: currently, escaping logic in `escape_sql/1` likely
  139. % won't work with pgsql since it does not support C-style escapes by default.
  140. % https://www.postgresql.org/docs/14/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS
  141. ES = binary:replace(S, [<<"\\">>, <<"'">>], <<"\\">>, [global, {insert_replaced, 1}]),
  142. [$', ES, $'].
  143. -spec escape_cql(binary()) -> iodata().
  144. escape_cql(S) ->
  145. ES = binary:replace(S, <<"'">>, <<"'">>, [global, {insert_replaced, 1}]),
  146. [$', ES, $'].
  147. -spec escape_mysql(binary()) -> iodata().
  148. escape_mysql(S0) ->
  149. % https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
  150. [$', escape_mysql(S0, 0, 0, S0), $'].
  151. %% NOTE
  152. %% This thing looks more complicated than needed because it's optimized for as few
  153. %% intermediate memory (re)allocations as possible.
  154. escape_mysql(<<$', Rest/binary>>, I, Run, Src) ->
  155. escape_prepend(I, Run, Src, [<<"\\'">> | escape_mysql(Rest, I + Run + 1, 0, Src)]);
  156. escape_mysql(<<$\\, Rest/binary>>, I, Run, Src) ->
  157. escape_prepend(I, Run, Src, [<<"\\\\">> | escape_mysql(Rest, I + Run + 1, 0, Src)]);
  158. escape_mysql(<<0, Rest/binary>>, I, Run, Src) ->
  159. escape_prepend(I, Run, Src, [<<"\\0">> | escape_mysql(Rest, I + Run + 1, 0, Src)]);
  160. escape_mysql(<<_/utf8, Rest/binary>> = S, I, Run, Src) ->
  161. CWidth = byte_size(S) - byte_size(Rest),
  162. escape_mysql(Rest, I, Run + CWidth, Src);
  163. escape_mysql(<<>>, 0, _, Src) ->
  164. Src;
  165. escape_mysql(<<>>, I, Run, Src) ->
  166. binary:part(Src, I, Run);
  167. escape_mysql(_, _I, _Run, _Src) ->
  168. throw(invalid_utf8).
  169. escape_prepend(_RunI, 0, _Src, Tail) ->
  170. Tail;
  171. escape_prepend(I, Run, Src, Tail) ->
  172. [binary:part(Src, I, Run) | Tail].