emqx_postgresql.erl 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2020-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_postgresql).
  17. -include("emqx_postgresql.hrl").
  18. -include_lib("emqx_connector/include/emqx_connector.hrl").
  19. -include_lib("typerefl/include/types.hrl").
  20. -include_lib("emqx/include/logger.hrl").
  21. -include_lib("hocon/include/hoconsc.hrl").
  22. -include_lib("epgsql/include/epgsql.hrl").
  23. -include_lib("snabbkaffe/include/snabbkaffe.hrl").
  24. -export([roots/0, fields/1, namespace/0]).
  25. -behaviour(emqx_resource).
  26. %% callbacks of behaviour emqx_resource
  27. -export([
  28. resource_type/0,
  29. callback_mode/0,
  30. on_start/2,
  31. on_stop/2,
  32. on_query/3,
  33. on_batch_query/3,
  34. on_get_status/2,
  35. on_add_channel/4,
  36. on_remove_channel/3,
  37. on_get_channels/1,
  38. on_get_channel_status/3,
  39. on_format_query_result/1
  40. ]).
  41. -export([connect/1]).
  42. -export([
  43. query/3,
  44. prepared_query/3,
  45. execute_batch/3
  46. ]).
  47. -export([disable_prepared_statements/0]).
  48. %% for ecpool workers usage
  49. -export([do_get_status/1, prepare_sql_to_conn/2]).
  50. -define(PGSQL_HOST_OPTIONS, #{
  51. default_port => ?PGSQL_DEFAULT_PORT
  52. }).
  53. -type connector_resource_id() :: binary().
  54. -type action_resource_id() :: binary().
  55. -type template() :: {unicode:chardata(), emqx_template_sql:row_template()}.
  56. -type state() ::
  57. #{
  58. pool_name := binary(),
  59. query_templates := #{binary() => template()},
  60. prepares := disabled | #{binary() => epgsql:statement()} | {error, _}
  61. }.
  62. %% FIXME: add `{error, sync_required}' to `epgsql:execute_batch'
  63. %% We want to be able to call sync if any message from the backend leaves the driver in an
  64. %% inconsistent state needing sync.
  65. -dialyzer({nowarn_function, [execute_batch/3]}).
  66. %%=====================================================================
  67. namespace() -> postgres.
  68. roots() ->
  69. [{config, #{type => hoconsc:ref(?MODULE, config)}}].
  70. fields(config) ->
  71. [
  72. {server, server()},
  73. disable_prepared_statements()
  74. ] ++
  75. adjust_fields(emqx_connector_schema_lib:relational_db_fields()) ++
  76. emqx_connector_schema_lib:ssl_fields() ++
  77. emqx_connector_schema_lib:prepare_statement_fields().
  78. server() ->
  79. Meta = #{desc => ?DESC("server")},
  80. emqx_schema:servers_sc(Meta, ?PGSQL_HOST_OPTIONS).
  81. disable_prepared_statements() ->
  82. {disable_prepared_statements,
  83. hoconsc:mk(
  84. boolean(),
  85. #{
  86. default => false,
  87. required => false,
  88. desc => ?DESC("disable_prepared_statements")
  89. }
  90. )}.
  91. adjust_fields(Fields) ->
  92. lists:map(
  93. fun
  94. ({username, Sc}) ->
  95. %% to please dialyzer...
  96. Override = #{type => hocon_schema:field_schema(Sc, type), required => true},
  97. {username, hocon_schema:override(Sc, Override)};
  98. (Field) ->
  99. Field
  100. end,
  101. Fields
  102. ).
  103. %% ===================================================================
  104. resource_type() -> postgresql.
  105. callback_mode() -> always_sync.
  106. -spec on_start(binary(), hocon:config()) -> {ok, state()} | {error, _}.
  107. on_start(
  108. InstId,
  109. #{
  110. server := Server,
  111. disable_prepared_statements := DisablePreparedStatements,
  112. database := DB,
  113. username := User,
  114. pool_size := PoolSize,
  115. ssl := SSL
  116. } = Config
  117. ) ->
  118. #{hostname := Host, port := Port} = emqx_schema:parse_server(Server, ?PGSQL_HOST_OPTIONS),
  119. ?SLOG(info, #{
  120. msg => "starting_postgresql_connector",
  121. connector => InstId,
  122. config => emqx_utils:redact(Config)
  123. }),
  124. SslOpts =
  125. case maps:get(enable, SSL) of
  126. true ->
  127. [
  128. %% note: this is converted to `required' in
  129. %% `conn_opts/2', and there's a boolean guard
  130. %% there; if this is set to `required' here,
  131. %% that'll require changing `conn_opts/2''s guard.
  132. {ssl, true},
  133. {ssl_opts, emqx_tls_lib:to_client_opts(SSL)}
  134. ];
  135. false ->
  136. [{ssl, false}]
  137. end,
  138. Options = [
  139. {host, Host},
  140. {port, Port},
  141. {username, User},
  142. {password, maps:get(password, Config, emqx_secret:wrap(""))},
  143. {database, DB},
  144. {auto_reconnect, ?AUTO_RECONNECT_INTERVAL},
  145. {pool_size, PoolSize}
  146. ],
  147. State1 = parse_sql_template(Config, <<"send_message">>),
  148. State2 = State1#{installed_channels => #{}},
  149. case emqx_resource_pool:start(InstId, ?MODULE, Options ++ SslOpts) of
  150. ok ->
  151. Prepares =
  152. case DisablePreparedStatements of
  153. true -> disabled;
  154. false -> #{}
  155. end,
  156. {ok, init_prepare(State2#{pool_name => InstId, prepares => Prepares})};
  157. {error, Reason} ->
  158. ?tp(
  159. pgsql_connector_start_failed,
  160. #{error => Reason}
  161. ),
  162. {error, Reason}
  163. end.
  164. on_stop(InstId, State) ->
  165. ?SLOG(info, #{
  166. msg => "stopping_postgresql_connector",
  167. connector => InstId
  168. }),
  169. close_connections(State),
  170. Res = emqx_resource_pool:stop(InstId),
  171. ?tp(postgres_stopped, #{instance_id => InstId}),
  172. Res.
  173. close_connections(#{pool_name := PoolName} = _State) ->
  174. WorkerPids = [Worker || {_WorkerName, Worker} <- ecpool:workers(PoolName)],
  175. close_connections_with_worker_pids(WorkerPids),
  176. ok.
  177. close_connections_with_worker_pids([WorkerPid | Rest]) ->
  178. %% We ignore errors since any error probably means that the
  179. %% connection is closed already.
  180. try ecpool_worker:client(WorkerPid) of
  181. {ok, Conn} ->
  182. _ = epgsql:close(Conn),
  183. close_connections_with_worker_pids(Rest);
  184. _ ->
  185. close_connections_with_worker_pids(Rest)
  186. catch
  187. _:_ ->
  188. close_connections_with_worker_pids(Rest)
  189. end;
  190. close_connections_with_worker_pids([]) ->
  191. ok.
  192. on_add_channel(
  193. _InstId,
  194. #{
  195. installed_channels := InstalledChannels
  196. } = OldState,
  197. ChannelId,
  198. ChannelConfig
  199. ) ->
  200. %% The following will throw an exception if the bridge producers fails to start
  201. {ok, ChannelState} = create_channel_state(ChannelId, OldState, ChannelConfig),
  202. case ChannelState of
  203. #{prepares := {error, Reason}} ->
  204. {error, {unhealthy_target, Reason}};
  205. _ ->
  206. NewInstalledChannels = maps:put(ChannelId, ChannelState, InstalledChannels),
  207. %% Update state
  208. NewState = OldState#{installed_channels => NewInstalledChannels},
  209. {ok, NewState}
  210. end.
  211. create_channel_state(
  212. ChannelId,
  213. #{
  214. pool_name := PoolName,
  215. prepares := Prepares
  216. } = _ConnectorState,
  217. #{parameters := Parameters} = _ChannelConfig
  218. ) ->
  219. State1 = parse_sql_template(Parameters, ChannelId),
  220. {ok,
  221. init_prepare(State1#{
  222. pool_name => PoolName,
  223. prepares => Prepares,
  224. prepare_statement => #{}
  225. })}.
  226. on_remove_channel(
  227. _InstId,
  228. #{
  229. installed_channels := InstalledChannels
  230. } = OldState,
  231. ChannelId
  232. ) ->
  233. %% Close prepared statements
  234. ok = close_prepared_statement(ChannelId, OldState),
  235. NewInstalledChannels = maps:remove(ChannelId, InstalledChannels),
  236. %% Update state
  237. NewState = OldState#{installed_channels => NewInstalledChannels},
  238. {ok, NewState}.
  239. close_prepared_statement(_ChannelId, #{prepares := disabled}) ->
  240. ok;
  241. close_prepared_statement(ChannelId, #{pool_name := PoolName} = State) ->
  242. WorkerPids = [Worker || {_WorkerName, Worker} <- ecpool:workers(PoolName)],
  243. close_prepared_statement(WorkerPids, ChannelId, State),
  244. ok.
  245. close_prepared_statement([WorkerPid | Rest], ChannelId, State) ->
  246. %% We ignore errors since any error probably means that the
  247. %% prepared statement doesn't exist. If it exists when we try
  248. %% to insert one with the same name, we will try to remove it
  249. %% again anyway.
  250. try ecpool_worker:client(WorkerPid) of
  251. {ok, Conn} ->
  252. Statement = get_templated_statement(ChannelId, State),
  253. _ = epgsql:close(Conn, Statement),
  254. close_prepared_statement(Rest, ChannelId, State);
  255. _ ->
  256. close_prepared_statement(Rest, ChannelId, State)
  257. catch
  258. _:_ ->
  259. close_prepared_statement(Rest, ChannelId, State)
  260. end;
  261. close_prepared_statement([], _ChannelId, _State) ->
  262. ok.
  263. on_get_channel_status(
  264. _ResId,
  265. ChannelId,
  266. #{
  267. pool_name := PoolName,
  268. installed_channels := Channels
  269. } = _State
  270. ) ->
  271. ChannelState = maps:get(ChannelId, Channels),
  272. case
  273. do_check_channel_sql(
  274. PoolName,
  275. ChannelId,
  276. ChannelState
  277. )
  278. of
  279. ok ->
  280. connected;
  281. {error, undefined_table} ->
  282. {error, {unhealthy_target, <<"Table does not exist">>}}
  283. end.
  284. do_check_channel_sql(
  285. PoolName,
  286. ChannelId,
  287. #{query_templates := ChannelQueryTemplates} = _ChannelState
  288. ) ->
  289. {SQL, _RowTemplate} = maps:get(ChannelId, ChannelQueryTemplates),
  290. WorkerPids = [Worker || {_WorkerName, Worker} <- ecpool:workers(PoolName)],
  291. validate_table_existence(WorkerPids, SQL).
  292. on_get_channels(ResId) ->
  293. emqx_bridge_v2:get_channels_for_connector(ResId).
  294. -spec on_query
  295. %% Called from authn and authz modules
  296. (connector_resource_id(), {prepared_query, binary(), [term()]}, state()) ->
  297. {ok, _} | {error, term()};
  298. %% Called from bridges
  299. (connector_resource_id(), {action_resource_id(), map()}, state()) ->
  300. {ok, _} | {error, term()}.
  301. on_query(InstId, {TypeOrKey, NameOrMap}, State) ->
  302. on_query(InstId, {TypeOrKey, NameOrMap, []}, State);
  303. on_query(
  304. InstId,
  305. {TypeOrKey, NameOrMap, Params},
  306. #{pool_name := PoolName} = State
  307. ) ->
  308. ?SLOG(debug, #{
  309. msg => "postgresql_connector_received_sql_query",
  310. connector => InstId,
  311. type => TypeOrKey,
  312. sql => NameOrMap,
  313. state => State
  314. }),
  315. {QueryType, NameOrSQL2, Data} = proc_sql_params(TypeOrKey, NameOrMap, Params, State),
  316. emqx_trace:rendered_action_template(
  317. TypeOrKey,
  318. #{
  319. statement_type => QueryType,
  320. statement_or_name => NameOrSQL2,
  321. data => Data
  322. }
  323. ),
  324. Res = on_sql_query(InstId, PoolName, QueryType, NameOrSQL2, Data),
  325. ?tp(postgres_bridge_connector_on_query_return, #{instance_id => InstId, result => Res}),
  326. handle_result(Res).
  327. on_batch_query(
  328. InstId,
  329. [{Key, _} = Request | _] = BatchReq,
  330. #{pool_name := PoolName} = State
  331. ) ->
  332. BinKey = to_bin(Key),
  333. case get_template(BinKey, State) of
  334. undefined ->
  335. Log = #{
  336. connector => InstId,
  337. first_request => Request,
  338. state => State,
  339. msg => "batch prepare not implemented"
  340. },
  341. ?SLOG(error, Log),
  342. {error, {unrecoverable_error, batch_prepare_not_implemented}};
  343. {_Statement, RowTemplate} ->
  344. StatementTemplate = get_templated_statement(BinKey, State),
  345. Rows = [render_prepare_sql_row(RowTemplate, Data) || {_Key, Data} <- BatchReq],
  346. emqx_trace:rendered_action_template(
  347. Key,
  348. #{
  349. statement_type => execute_batch,
  350. statement_or_name => StatementTemplate,
  351. data => Rows
  352. }
  353. ),
  354. case on_sql_query(InstId, PoolName, execute_batch, StatementTemplate, Rows) of
  355. {error, _Error} = Result ->
  356. handle_result(Result);
  357. {_Column, Results} ->
  358. handle_batch_result(Results, 0)
  359. end
  360. end;
  361. on_batch_query(InstId, BatchReq, State) ->
  362. ?SLOG(error, #{
  363. connector => InstId,
  364. request => BatchReq,
  365. state => State,
  366. msg => "invalid request"
  367. }),
  368. {error, {unrecoverable_error, invalid_request}}.
  369. proc_sql_params(ActionResId, #{} = Map, [], State) when is_binary(ActionResId) ->
  370. %% When this connector is called from actions/bridges.
  371. DisablePreparedStatements = prepared_statements_disabled(State),
  372. {ExprTemplate, RowTemplate} = get_template(ActionResId, State),
  373. Rendered = render_prepare_sql_row(RowTemplate, Map),
  374. case DisablePreparedStatements of
  375. true ->
  376. {query, ExprTemplate, Rendered};
  377. false ->
  378. {prepared_query, ActionResId, Rendered}
  379. end;
  380. proc_sql_params(prepared_query, ConnResId, Params, State) ->
  381. %% When this connector is called from authn/authz modules
  382. DisablePreparedStatements = prepared_statements_disabled(State),
  383. case DisablePreparedStatements of
  384. true ->
  385. #{query_templates := #{ConnResId := {ExprTemplate, _VarsTemplate}}} = State,
  386. {query, ExprTemplate, Params};
  387. false ->
  388. %% Connector resource id itself is the prepared statement name
  389. {prepared_query, ConnResId, Params}
  390. end;
  391. proc_sql_params(QueryType, SQL, Params, _State) when
  392. is_atom(QueryType) andalso
  393. (is_binary(SQL) orelse is_list(SQL)) andalso
  394. is_list(Params)
  395. ->
  396. %% When called to do ad-hoc commands/queries.
  397. {QueryType, SQL, Params}.
  398. prepared_statements_disabled(State) ->
  399. maps:get(prepares, State, #{}) =:= disabled.
  400. get_template(Key, #{installed_channels := Channels} = _State) when is_map_key(Key, Channels) ->
  401. BinKey = to_bin(Key),
  402. ChannelState = maps:get(BinKey, Channels),
  403. ChannelQueryTemplates = maps:get(query_templates, ChannelState),
  404. maps:get(BinKey, ChannelQueryTemplates);
  405. get_template(Key, #{query_templates := Templates}) ->
  406. BinKey = to_bin(Key),
  407. maps:get(BinKey, Templates, undefined).
  408. get_templated_statement(Key, #{installed_channels := Channels} = _State) when
  409. is_map_key(Key, Channels)
  410. ->
  411. BinKey = to_bin(Key),
  412. ChannelState = maps:get(BinKey, Channels),
  413. case ChannelState of
  414. #{prepares := disabled, query_templates := #{BinKey := {ExprTemplate, _}}} ->
  415. ExprTemplate;
  416. #{prepares := #{BinKey := ExprTemplate}} ->
  417. ExprTemplate
  418. end;
  419. get_templated_statement(Key, #{prepares := PrepStatements}) ->
  420. BinKey = to_bin(Key),
  421. maps:get(BinKey, PrepStatements).
  422. on_sql_query(InstId, PoolName, Type, NameOrSQL, Data) ->
  423. try ecpool:pick_and_do(PoolName, {?MODULE, Type, [NameOrSQL, Data]}, no_handover) of
  424. {error, Reason} ->
  425. ?tp(
  426. pgsql_connector_query_return,
  427. #{error => Reason}
  428. ),
  429. TranslatedError = translate_to_log_context(Reason),
  430. ?SLOG(
  431. error,
  432. maps:merge(
  433. #{
  434. msg => "postgresql_connector_do_sql_query_failed",
  435. connector => InstId,
  436. type => Type,
  437. sql => NameOrSQL
  438. },
  439. TranslatedError
  440. )
  441. ),
  442. case Reason of
  443. sync_required ->
  444. {error, {recoverable_error, Reason}};
  445. ecpool_empty ->
  446. {error, {recoverable_error, Reason}};
  447. {error, error, _, undefined_table, _, _} ->
  448. {error, {unrecoverable_error, export_error(TranslatedError)}};
  449. _ ->
  450. {error, export_error(TranslatedError)}
  451. end;
  452. Result ->
  453. ?tp(
  454. pgsql_connector_query_return,
  455. #{result => Result}
  456. ),
  457. Result
  458. catch
  459. error:function_clause:Stacktrace ->
  460. ?SLOG(error, #{
  461. msg => "postgresql_connector_do_sql_query_failed",
  462. connector => InstId,
  463. type => Type,
  464. sql => NameOrSQL,
  465. reason => function_clause,
  466. stacktrace => Stacktrace
  467. }),
  468. {error, {unrecoverable_error, invalid_request}}
  469. end.
  470. on_get_status(_InstId, #{pool_name := PoolName} = State) ->
  471. case emqx_resource_pool:health_check_workers(PoolName, fun ?MODULE:do_get_status/1) of
  472. true ->
  473. case do_check_prepares(State) of
  474. ok ->
  475. connected;
  476. {ok, NState} ->
  477. %% return new state with prepared statements
  478. {connected, NState};
  479. {error, undefined_table} ->
  480. %% return new state indicating that we are connected but the target table is not created
  481. {disconnected, State, unhealthy_target};
  482. {error, _Reason} ->
  483. %% do not log error, it is logged in prepare_sql_to_conn
  484. connecting
  485. end;
  486. false ->
  487. connecting
  488. end.
  489. do_get_status(Conn) ->
  490. ok == element(1, epgsql:squery(Conn, "SELECT count(1) AS T")).
  491. do_check_prepares(
  492. #{
  493. pool_name := PoolName,
  494. query_templates := #{<<"send_message">> := {SQL, _RowTemplate}}
  495. }
  496. ) ->
  497. WorkerPids = [Worker || {_WorkerName, Worker} <- ecpool:workers(PoolName)],
  498. case validate_table_existence(WorkerPids, SQL) of
  499. ok ->
  500. ok;
  501. {error, Reason} ->
  502. {error, Reason}
  503. end;
  504. do_check_prepares(#{prepares := disabled}) ->
  505. ok;
  506. do_check_prepares(#{prepares := Prepares}) when is_map(Prepares) ->
  507. ok;
  508. do_check_prepares(#{prepares := {error, _}} = State) ->
  509. %% retry to prepare
  510. case prepare_sql(State) of
  511. {ok, PrepStatements} ->
  512. %% remove the error
  513. {ok, State#{prepares := PrepStatements}};
  514. {error, Reason} ->
  515. {error, Reason}
  516. end.
  517. -spec validate_table_existence([pid()], binary()) -> ok | {error, undefined_table}.
  518. validate_table_existence([WorkerPid | Rest], SQL) ->
  519. try ecpool_worker:client(WorkerPid) of
  520. {ok, Conn} ->
  521. case epgsql:parse2(Conn, "", SQL, []) of
  522. {error, {_, _, _, undefined_table, _, _}} ->
  523. {error, undefined_table};
  524. Res when is_tuple(Res) andalso ok == element(1, Res) ->
  525. ok;
  526. Res ->
  527. ?tp(postgres_connector_bad_parse2, #{result => Res}),
  528. validate_table_existence(Rest, SQL)
  529. end;
  530. _ ->
  531. validate_table_existence(Rest, SQL)
  532. catch
  533. exit:{noproc, _} ->
  534. validate_table_existence(Rest, SQL)
  535. end;
  536. validate_table_existence([], _SQL) ->
  537. %% All workers either replied an unexpected error; we will retry
  538. %% on the next health check.
  539. ok.
  540. %% ===================================================================
  541. connect(Opts) ->
  542. Host = proplists:get_value(host, Opts),
  543. Username = proplists:get_value(username, Opts),
  544. %% TODO: teach `epgsql` to accept 0-arity closures as passwords.
  545. Password = emqx_secret:unwrap(proplists:get_value(password, Opts)),
  546. case epgsql:connect(Host, Username, Password, conn_opts(Opts)) of
  547. {ok, _Conn} = Ok ->
  548. Ok;
  549. {error, Reason} ->
  550. {error, Reason}
  551. end.
  552. query(Conn, SQL, Params) ->
  553. case epgsql:equery(Conn, SQL, Params) of
  554. {error, sync_required} = Res ->
  555. ok = epgsql:sync(Conn),
  556. Res;
  557. Res ->
  558. Res
  559. end.
  560. prepared_query(Conn, Name, Params) ->
  561. case epgsql:prepared_query2(Conn, Name, Params) of
  562. {error, sync_required} = Res ->
  563. ok = epgsql:sync(Conn),
  564. Res;
  565. Res ->
  566. Res
  567. end.
  568. execute_batch(Conn, Statement, Params) ->
  569. case epgsql:execute_batch(Conn, Statement, Params) of
  570. {error, sync_required} = Res ->
  571. ok = epgsql:sync(Conn),
  572. Res;
  573. Res ->
  574. Res
  575. end.
  576. conn_opts(Opts) ->
  577. conn_opts(Opts, []).
  578. conn_opts([], Acc) ->
  579. Acc;
  580. conn_opts([Opt = {database, _} | Opts], Acc) ->
  581. conn_opts(Opts, [Opt | Acc]);
  582. conn_opts([{ssl, Bool} | Opts], Acc) when is_boolean(Bool) ->
  583. Flag =
  584. case Bool of
  585. true -> required;
  586. false -> false
  587. end,
  588. conn_opts(Opts, [{ssl, Flag} | Acc]);
  589. conn_opts([Opt = {port, _} | Opts], Acc) ->
  590. conn_opts(Opts, [Opt | Acc]);
  591. conn_opts([Opt = {timeout, _} | Opts], Acc) ->
  592. conn_opts(Opts, [Opt | Acc]);
  593. conn_opts([Opt = {ssl_opts, _} | Opts], Acc) ->
  594. conn_opts(Opts, [Opt | Acc]);
  595. conn_opts([_Opt | Opts], Acc) ->
  596. conn_opts(Opts, Acc).
  597. parse_sql_template(Config, SQLID) ->
  598. Queries =
  599. case Config of
  600. #{prepare_statement := Qs} ->
  601. Qs;
  602. #{sql := Query} ->
  603. #{SQLID => Query};
  604. #{} ->
  605. #{}
  606. end,
  607. Templates = maps:fold(fun parse_sql_template/3, #{}, Queries),
  608. #{query_templates => Templates}.
  609. parse_sql_template(Key, Query, Acc) ->
  610. Template = emqx_template_sql:parse_prepstmt(Query, #{parameters => '$n'}),
  611. Acc#{Key => Template}.
  612. render_prepare_sql_row(RowTemplate, Data) ->
  613. % NOTE: ignoring errors here, missing variables will be replaced with `null`.
  614. {Row, _Errors} = emqx_template_sql:render_prepstmt(RowTemplate, {emqx_jsonish, Data}),
  615. Row.
  616. init_prepare(State = #{prepares := disabled}) ->
  617. State;
  618. init_prepare(State = #{query_templates := Templates}) when map_size(Templates) == 0 ->
  619. State;
  620. init_prepare(State = #{}) ->
  621. case prepare_sql(State) of
  622. {ok, PrepStatements} ->
  623. State#{prepares => PrepStatements};
  624. Error ->
  625. TranslatedError = translate_to_log_context(Error),
  626. ?SLOG(
  627. error,
  628. maps:merge(
  629. #{msg => <<"postgresql_init_prepare_statement_failed">>},
  630. TranslatedError
  631. )
  632. ),
  633. %% mark the prepares failed
  634. State#{prepares => {error, export_error(TranslatedError)}}
  635. end.
  636. prepare_sql(#{query_templates := Templates, pool_name := PoolName}) ->
  637. prepare_sql(maps:to_list(Templates), PoolName).
  638. prepare_sql(Templates, PoolName) ->
  639. case do_prepare_sql(Templates, PoolName) of
  640. {ok, _Sts} = Ok ->
  641. %% prepare for reconnect
  642. ecpool:add_reconnect_callback(PoolName, {?MODULE, prepare_sql_to_conn, [Templates]}),
  643. Ok;
  644. Error ->
  645. Error
  646. end.
  647. do_prepare_sql(Templates, PoolName) ->
  648. do_prepare_sql(ecpool:workers(PoolName), Templates, #{}).
  649. do_prepare_sql([{_Name, Worker} | Rest], Templates, _LastSts) ->
  650. {ok, Conn} = ecpool_worker:client(Worker),
  651. case prepare_sql_to_conn(Conn, Templates) of
  652. {ok, Sts} ->
  653. do_prepare_sql(Rest, Templates, Sts);
  654. Error ->
  655. Error
  656. end;
  657. do_prepare_sql([], _Prepares, LastSts) ->
  658. {ok, LastSts}.
  659. prepare_sql_to_conn(Conn, Prepares) ->
  660. prepare_sql_to_conn(Conn, Prepares, #{}, 0).
  661. prepare_sql_to_conn(Conn, [], Statements, _Attempts) when is_pid(Conn) ->
  662. {ok, Statements};
  663. prepare_sql_to_conn(Conn, [{_Key, _} | _Rest], _Statements, _MaxAttempts = 2) when is_pid(Conn) ->
  664. failed_to_remove_prev_prepared_statement_error();
  665. prepare_sql_to_conn(
  666. Conn, [{Key, {SQL, _RowTemplate}} | Rest] = ToPrepare, Statements, Attempts
  667. ) when is_pid(Conn) ->
  668. LogMeta = #{msg => "postgresql_prepare_statement", name => Key, sql => SQL},
  669. ?SLOG(info, LogMeta),
  670. case epgsql:parse2(Conn, Key, SQL, []) of
  671. {ok, Statement} ->
  672. prepare_sql_to_conn(Conn, Rest, Statements#{Key => Statement}, 0);
  673. {error, #error{severity = error, codename = undefined_table} = Error} ->
  674. %% Target table is not created
  675. ?tp(pgsql_undefined_table, #{}),
  676. LogMsg =
  677. maps:merge(
  678. LogMeta#{msg => "postgresql_parse_failed"},
  679. translate_to_log_context(Error)
  680. ),
  681. ?SLOG(error, LogMsg),
  682. {error, undefined_table};
  683. {error, #error{severity = error, codename = duplicate_prepared_statement}} = Error ->
  684. ?tp(pgsql_prepared_statement_exists, #{}),
  685. LogMsg =
  686. maps:merge(
  687. LogMeta#{
  688. msg => "postgresql_prepared_statment_with_same_name_already_exists",
  689. explain => <<
  690. "A prepared statement with the same name already "
  691. "exists in the driver. Will attempt to remove the "
  692. "previous prepared statement with the name and then "
  693. "try again."
  694. >>
  695. },
  696. translate_to_log_context(Error)
  697. ),
  698. ?SLOG(warning, LogMsg),
  699. case epgsql:close(Conn, statement, Key) of
  700. ok ->
  701. ?SLOG(info, #{msg => "pqsql_closed_statement_successfully"}),
  702. prepare_sql_to_conn(Conn, ToPrepare, Statements, Attempts + 1);
  703. {error, CloseError} ->
  704. ?SLOG(error, #{msg => "pqsql_close_statement_failed", cause => CloseError}),
  705. failed_to_remove_prev_prepared_statement_error()
  706. end;
  707. {error, Error} ->
  708. TranslatedError = translate_to_log_context(Error),
  709. LogMsg =
  710. maps:merge(
  711. LogMeta#{msg => "postgresql_parse_failed"},
  712. TranslatedError
  713. ),
  714. ?SLOG(error, LogMsg),
  715. {error, export_error(TranslatedError)}
  716. end.
  717. failed_to_remove_prev_prepared_statement_error() ->
  718. Msg =
  719. ("A previous prepared statement for the action already exists "
  720. "but cannot be closed. Please, try to disable and then enable "
  721. "the connector to resolve this issue."),
  722. {error, unicode:characters_to_binary(Msg)}.
  723. to_bin(Bin) when is_binary(Bin) ->
  724. Bin;
  725. to_bin(Atom) when is_atom(Atom) ->
  726. erlang:atom_to_binary(Atom).
  727. handle_result({error, {recoverable_error, _Error}} = Res) ->
  728. Res;
  729. handle_result({error, {unrecoverable_error, _Error}} = Res) ->
  730. Res;
  731. handle_result({error, disconnected}) ->
  732. {error, {recoverable_error, disconnected}};
  733. handle_result({error, Error}) ->
  734. TranslatedError = translate_to_log_context(Error),
  735. {error, {unrecoverable_error, export_error(TranslatedError)}};
  736. handle_result(Res) ->
  737. Res.
  738. on_format_query_result({ok, Cnt}) when is_integer(Cnt) ->
  739. #{result => ok, affected_rows => Cnt};
  740. on_format_query_result(Res) ->
  741. Res.
  742. handle_batch_result([{ok, Count} | Rest], Acc) ->
  743. handle_batch_result(Rest, Acc + Count);
  744. handle_batch_result([{error, Error} | _Rest], _Acc) ->
  745. TranslatedError = translate_to_log_context(Error),
  746. {error, {unrecoverable_error, export_error(TranslatedError)}};
  747. handle_batch_result([], Acc) ->
  748. ?tp("postgres_success_batch_result", #{row_count => Acc}),
  749. {ok, Acc}.
  750. translate_to_log_context({error, Reason}) ->
  751. translate_to_log_context(Reason);
  752. translate_to_log_context(#error{} = Reason) ->
  753. #error{
  754. severity = Severity,
  755. code = Code,
  756. codename = Codename,
  757. message = Message,
  758. extra = Extra
  759. } = Reason,
  760. #{
  761. driver_severity => Severity,
  762. driver_error_codename => Codename,
  763. driver_error_code => Code,
  764. driver_error_message => emqx_logger_textfmt:try_format_unicode(Message),
  765. driver_error_extra => Extra
  766. };
  767. translate_to_log_context(Reason) ->
  768. #{reason => Reason}.
  769. export_error(#{
  770. driver_severity := Severity,
  771. driver_error_codename := Codename,
  772. driver_error_code := Code
  773. }) ->
  774. %% Extra information has already been logged.
  775. #{
  776. error_code => Code,
  777. error_codename => Codename,
  778. severity => Severity
  779. };
  780. export_error(#{reason := Reason}) ->
  781. Reason;
  782. export_error(Error) ->
  783. Error.