emqx_utils_sql.erl 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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([escape_snowflake/1]).
  25. -export_type([value/0]).
  26. -type statement_type() :: select | insert | delete | update.
  27. -type value() :: null | binary() | number() | boolean() | [value()].
  28. %% The type Copied from stdlib/src/re.erl to compatibility with OTP 26
  29. %% Since `re:mp()` exported after OTP 27
  30. -type mp() :: {re_pattern, _, _, _, _}.
  31. -define(INSERT_RE_MP_KEY, {?MODULE, insert_re_mp}).
  32. -define(INSERT_RE_BIN, <<
  33. %% case-insensitive
  34. "(?i)^\\s*",
  35. %% Group-1: insert into, table name and columns (when existed).
  36. %% All space characters suffixed to <TABLE_NAME> will be kept
  37. %% `INSERT INTO <TABLE_NAME> [(<COLUMN>, ..)]`
  38. "(insert\\s+into\\s+[^\\s\\(\\)]+\\s*(?:\\([^\\)]*\\))?)",
  39. %% Keyword: `VALUES`
  40. "\\s*values\\s*",
  41. %% Group-2: literals value(s) or placeholder(s) with round brackets.
  42. %% And the sub-pattern in brackets does not do any capturing
  43. %% `([<VALUE> | <PLACEHOLDER>], ..])`
  44. "(\\((?:[^()]++|(?2))*\\))",
  45. "\\s*$"
  46. >>).
  47. -define(HEX_RE_MP_KEY, {?MODULE, hex_re_mp}).
  48. -define(HEX_RE_BIN, <<"^[0-9a-fA-F]+$">>).
  49. -dialyzer({no_improper_lists, [escape_mysql/4, escape_prepend/4]}).
  50. -on_load(on_load/0).
  51. on_load() ->
  52. ok = put_insert_mp(),
  53. ok = put_hex_re_mp().
  54. put_insert_mp() ->
  55. persistent_term:put(?INSERT_RE_MP_KEY, re:compile(?INSERT_RE_BIN)),
  56. ok.
  57. -spec get_insert_mp() -> {ok, mp()}.
  58. get_insert_mp() ->
  59. case persistent_term:get(?INSERT_RE_MP_KEY, undefined) of
  60. undefined ->
  61. ok = put_insert_mp(),
  62. get_insert_mp();
  63. {ok, MP} ->
  64. {ok, MP}
  65. end.
  66. put_hex_re_mp() ->
  67. persistent_term:put(?HEX_RE_MP_KEY, re:compile(?HEX_RE_BIN)),
  68. ok.
  69. -spec get_hex_re_mp() -> {ok, mp()}.
  70. get_hex_re_mp() ->
  71. case persistent_term:get(?HEX_RE_MP_KEY, undefined) of
  72. undefined ->
  73. ok = put_hex_re_mp(),
  74. get_hex_re_mp();
  75. {ok, MP} ->
  76. {ok, MP}
  77. end.
  78. -spec get_statement_type(iodata()) -> statement_type() | {error, unknown}.
  79. get_statement_type(Query) ->
  80. KnownTypes = #{
  81. <<"select">> => select,
  82. <<"insert">> => insert,
  83. <<"update">> => update,
  84. <<"delete">> => delete
  85. },
  86. case re:run(Query, <<"^\\s*([a-zA-Z]+)">>, [{capture, all_but_first, binary}]) of
  87. {match, [Token]} ->
  88. maps:get(string:lowercase(Token), KnownTypes, {error, unknown});
  89. _ ->
  90. {error, unknown}
  91. end.
  92. %% @doc Parse an INSERT SQL statement into its INSERT part and the VALUES part.
  93. %% SQL = <<"INSERT INTO \"abc\" (c1, c2, c3) VALUES (${a}, ${b}, ${c.prop})">>
  94. %% {ok, {<<"INSERT INTO \"abc\" (c1, c2, c3)">>, <<"(${a}, ${b}, ${c.prop})">>}}
  95. -spec parse_insert(iodata()) ->
  96. {ok, {_Statement :: binary(), _Rows :: binary()}} | {error, not_insert_sql}.
  97. parse_insert(SQL) ->
  98. {ok, MP} = get_insert_mp(),
  99. case re:run(SQL, MP, [{capture, all_but_first, binary}]) of
  100. {match, [InsertInto, ValuesTemplate]} ->
  101. {ok, {InsertInto, ValuesTemplate}};
  102. nomatch ->
  103. {error, not_insert_sql}
  104. end.
  105. %% @doc Convert an Erlang term to a value that can be used primarily in
  106. %% prepared SQL statements.
  107. -spec to_sql_value(term()) -> value().
  108. to_sql_value(undefined) -> null;
  109. to_sql_value(List) when is_list(List) -> List;
  110. to_sql_value(Bin) when is_binary(Bin) -> Bin;
  111. to_sql_value(Num) when is_number(Num) -> Num;
  112. to_sql_value(Bool) when is_boolean(Bool) -> Bool;
  113. to_sql_value(Atom) when is_atom(Atom) -> atom_to_binary(Atom, utf8);
  114. to_sql_value(Map) when is_map(Map) -> emqx_utils_json:encode(Map).
  115. %% @doc Convert an Erlang term to a string that can be interpolated in literal
  116. %% SQL statements. The value is escaped if necessary.
  117. -spec to_sql_string(term(), Options) -> unicode:chardata() when
  118. Options :: #{
  119. escaping => mysql | sql | cql | sqlserver,
  120. undefined => null | unicode:chardata()
  121. }.
  122. to_sql_string(undefined, #{undefined := Str} = Opts) when Str =/= null ->
  123. to_sql_string(Str, Opts);
  124. to_sql_string(undefined, #{}) ->
  125. <<"NULL">>;
  126. to_sql_string(String, #{escaping := mysql}) when is_binary(String) ->
  127. try
  128. escape_mysql(String)
  129. catch
  130. throw:invalid_utf8 ->
  131. [<<"0x">>, binary:encode_hex(String)]
  132. end;
  133. to_sql_string(Term, #{escaping := mysql}) ->
  134. maybe_escape(Term, fun escape_mysql/1);
  135. to_sql_string(Term, #{escaping := cql}) ->
  136. maybe_escape(Term, fun escape_cql/1);
  137. to_sql_string(Term, #{escaping := sqlserver}) ->
  138. maybe_escape(Term, fun escape_sqlserver/1);
  139. to_sql_string(Term, #{}) ->
  140. maybe_escape(Term, fun escape_sql/1).
  141. -spec maybe_escape(_Value, fun((binary()) -> iodata())) -> unicode:chardata().
  142. maybe_escape(Str, EscapeFun) when is_binary(Str) ->
  143. EscapeFun(Str);
  144. maybe_escape(Str, EscapeFun) when is_list(Str) ->
  145. case unicode:characters_to_binary(Str) of
  146. Bin when is_binary(Bin) ->
  147. EscapeFun(Bin);
  148. Otherwise ->
  149. error(Otherwise)
  150. end;
  151. maybe_escape(Val, EscapeFun) when is_atom(Val) orelse is_map(Val) ->
  152. EscapeFun(emqx_template:to_string(Val));
  153. maybe_escape(Val, _EscapeFun) ->
  154. emqx_template:to_string(Val).
  155. -spec escape_sql(binary()) -> iodata().
  156. escape_sql(S) ->
  157. % NOTE
  158. % This is a bit misleading: currently, escaping logic in `escape_sql/1` likely
  159. % won't work with pgsql since it does not support C-style escapes by default.
  160. % https://www.postgresql.org/docs/14/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS
  161. ES = binary:replace(S, [<<"\\">>, <<"'">>], <<"\\">>, [global, {insert_replaced, 1}]),
  162. [$', ES, $'].
  163. -spec escape_cql(binary()) -> iodata().
  164. escape_cql(S) ->
  165. ES = binary:replace(S, <<"'">>, <<"'">>, [global, {insert_replaced, 1}]),
  166. [$', ES, $'].
  167. -spec escape_mysql(binary()) -> iodata().
  168. escape_mysql(S0) ->
  169. % https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
  170. [$', escape_mysql(S0, 0, 0, S0), $'].
  171. -spec escape_snowflake(binary()) -> iodata().
  172. escape_snowflake(S) ->
  173. ES = binary:replace(S, <<"\"">>, <<"\"">>, [global, {insert_replaced, 1}]),
  174. [$", ES, $"].
  175. escape_sqlserver(<<"0x", Rest/binary>> = S) ->
  176. {ok, MP} = get_hex_re_mp(),
  177. case re:run(Rest, MP, []) of
  178. {match, _} ->
  179. [S];
  180. _ ->
  181. escape_sql(S)
  182. end;
  183. escape_sqlserver(S) ->
  184. escape_sql(S).
  185. %% NOTE
  186. %% This thing looks more complicated than needed because it's optimized for as few
  187. %% intermediate memory (re)allocations as possible.
  188. escape_mysql(<<$', Rest/binary>>, I, Run, Src) ->
  189. escape_prepend(I, Run, Src, [<<"\\'">> | escape_mysql(Rest, I + Run + 1, 0, Src)]);
  190. escape_mysql(<<$\\, Rest/binary>>, I, Run, Src) ->
  191. escape_prepend(I, Run, Src, [<<"\\\\">> | escape_mysql(Rest, I + Run + 1, 0, Src)]);
  192. escape_mysql(<<0, Rest/binary>>, I, Run, Src) ->
  193. escape_prepend(I, Run, Src, [<<"\\0">> | escape_mysql(Rest, I + Run + 1, 0, Src)]);
  194. escape_mysql(<<_/utf8, Rest/binary>> = S, I, Run, Src) ->
  195. CWidth = byte_size(S) - byte_size(Rest),
  196. escape_mysql(Rest, I, Run + CWidth, Src);
  197. escape_mysql(<<>>, 0, _, Src) ->
  198. Src;
  199. escape_mysql(<<>>, I, Run, Src) ->
  200. binary:part(Src, I, Run);
  201. escape_mysql(_, _I, _Run, _Src) ->
  202. throw(invalid_utf8).
  203. escape_prepend(_RunI, 0, _Src, Tail) ->
  204. Tail;
  205. escape_prepend(I, Run, Src, Tail) ->
  206. [binary:part(Src, I, Run) | Tail].