epgsql.erl 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. %%% @doc Synchronous interface.
  2. %%%
  3. %%% All functions block (with infinite timeout) until full result is available.
  4. %%% @end
  5. %%% Copyright (C) 2008 - Will Glozer. All rights reserved.
  6. %%% Copyright (C) 2011 - Anton Lebedevich. All rights reserved.
  7. -module(epgsql).
  8. -export([connect/1, connect/2, connect/3, connect/4, connect/5,
  9. close/1,
  10. get_parameter/2,
  11. set_notice_receiver/2,
  12. get_cmd_status/1,
  13. squery/2,
  14. equery/2, equery/3, equery/4,
  15. prepared_query/3,
  16. parse/2, parse/3, parse/4,
  17. describe/2, describe/3,
  18. bind/3, bind/4,
  19. execute/2, execute/3, execute/4,
  20. execute_batch/2, execute_batch/3,
  21. close/2, close/3,
  22. sync/1,
  23. cancel/1,
  24. update_type_cache/1,
  25. update_type_cache/2,
  26. with_transaction/2,
  27. with_transaction/3,
  28. sync_on_error/2,
  29. copy_from_stdin/2,
  30. copy_from_stdin/3,
  31. copy_send_rows/3,
  32. copy_done/1,
  33. standby_status_update/3,
  34. start_replication/5,
  35. start_replication/6,
  36. start_replication/7,
  37. to_map/1]).
  38. -export([handle_x_log_data/5]). % private
  39. -export_type([connection/0, connect_option/0, connect_opts/0,
  40. connect_error/0, query_error/0, sql_query/0, column/0,
  41. type_name/0, epgsql_type/0, statement/0,
  42. transaction_option/0, transaction_opts/0]).
  43. %% Deprecated types
  44. -export_type([bind_param/0, typed_param/0,
  45. squery_row/0, equery_row/0, reply/1,
  46. pg_time/0, pg_date/0, pg_datetime/0, pg_interval/0]).
  47. -include("epgsql.hrl").
  48. -ifdef(OTP_RELEASE).
  49. -type ssl_options() :: [ssl:tls_client_option()].
  50. -else.
  51. -type ssl_options() :: list().
  52. -endif.
  53. -type sql_query() :: iodata(). % SQL query text
  54. -type host() :: inet:ip_address() | inet:hostname().
  55. -type password() :: string() | iodata() | fun( () -> iodata() ).
  56. -type connection() :: pid().
  57. -type connect_option() ::
  58. {host, host()} |
  59. {username, string()} |
  60. {password, password()} |
  61. {database, DBName :: string()} |
  62. {port, PortNum :: inet:port_number()} |
  63. {ssl, IsEnabled :: boolean() | required} |
  64. {ssl_opts, SslOptions :: ssl_options()} | % see OTP ssl app documentation
  65. {tcp_opts, TcpOptions :: [gen_tcp:option()]} | % see OTP gen_tcp module documentation
  66. {timeout, TimeoutMs :: timeout()} | % connect timeout, default: 5000 ms
  67. {async, Receiver :: pid() | atom()} | % process to receive LISTEN/NOTIFY msgs
  68. {codecs, Codecs :: [{epgsql_codec:codec_mod(), any()}]} |
  69. {nulls, Nulls :: [any(), ...]} | % terms to be used as NULL
  70. {replication, Replication :: string()} | % Pass "database" to connect in replication mode
  71. {application_name, ApplicationName :: string()}.
  72. -type connect_opts() ::
  73. [connect_option()]
  74. | #{host => host(),
  75. username => string(),
  76. password => password(),
  77. database => string(),
  78. port => inet:port_number(),
  79. ssl => boolean() | required,
  80. ssl_opts => ssl_options(),
  81. tcp_opts => [gen_tcp:option()],
  82. timeout => timeout(),
  83. async => pid() | atom(),
  84. codecs => [{epgsql_codec:codec_mod(), any()}],
  85. nulls => [any(), ...],
  86. replication => string(),
  87. application_name => string()
  88. }.
  89. -type transaction_option() ::
  90. {reraise, boolean()} |
  91. {ensure_committed, boolean()} |
  92. {begin_opts, iodata()}.
  93. -type transaction_opts() ::
  94. [transaction_option()]
  95. | #{reraise => boolean(),
  96. ensure_committed => boolean(),
  97. begin_opts => iodata()
  98. }.
  99. -type connect_error() :: epgsql_cmd_connect:connect_error().
  100. -type query_error() :: #error{}. % Error report generated by server
  101. -type type_name() :: atom().
  102. -type epgsql_type() :: type_name()
  103. | {array, type_name()}
  104. | {unknown_oid, integer()}.
  105. %% Deprecated
  106. -type pg_date() :: epgsql_codec_datetime:pg_date().
  107. -type pg_time() :: epgsql_codec_datetime:pg_time().
  108. -type pg_datetime() :: epgsql_codec_datetime:pg_datetime().
  109. -type pg_interval() :: epgsql_codec_datetime:pg_interval().
  110. -type bind_param() :: any().
  111. %% Value to be bound to placeholder (`$1', `$2' etc)
  112. -type typed_param() :: {epgsql_type(), bind_param()}.
  113. -type column() :: #column{}.
  114. -type statement() :: #statement{}.
  115. -type squery_row() :: tuple(). % tuple of binary().
  116. -type equery_row() :: tuple(). % tuple of any().
  117. -type ok_reply(RowType) ::
  118. %% select
  119. {ok, ColumnsDescription :: [column()], RowsValues :: [RowType]} |
  120. %% update/insert/delete
  121. {ok, Count :: non_neg_integer()} |
  122. %% update/insert/delete + returning
  123. {ok, Count :: non_neg_integer(), ColumnsDescription :: [column()], RowsValues :: [RowType]}.
  124. -type error_reply() :: {error, query_error()}.
  125. -type reply(RowType) :: ok_reply(RowType) | error_reply().
  126. -type lsn() :: integer().
  127. -type cb_state() :: term().
  128. %% See https://github.com/erlang/rebar3/pull/1773
  129. -ifndef(OTP_RELEASE). % pre-OTP21
  130. -define(WITH_STACKTRACE(T, R, S), T:R -> S = erlang:get_stacktrace(), ).
  131. -else.
  132. -define(WITH_STACKTRACE(T, R, S), T:R:S ->).
  133. -endif.
  134. %% -- behaviour callbacks --
  135. %% Handles a XLogData Message (StartLSN, EndLSN, WALRecord, CbState).
  136. %% Return: {ok, LastFlushedLSN, LastAppliedLSN, NewCbState}
  137. -callback handle_x_log_data(lsn(), lsn(), binary(), cb_state()) -> {ok, lsn(), lsn(), cb_state()}.
  138. %% -------------
  139. %% -- client interface --
  140. %% @doc connects to the server and performs all the necessary handshakes
  141. -spec connect(connect_opts())
  142. -> {ok, Connection :: connection()} | {error, Reason :: connect_error()}.
  143. connect(Opts) ->
  144. {ok, C} = epgsql_sock:start_link(),
  145. call_connect(C, Opts).
  146. connect(Host, Opts) ->
  147. connect(Host, os:getenv("USER"), "", Opts).
  148. connect(Host, Username, Opts) ->
  149. connect(Host, Username, "", Opts).
  150. -spec connect(host(), string(), password(), connect_opts())
  151. -> {ok, Connection :: connection()} | {error, Reason :: connect_error()}.
  152. %% @doc connects to the server and performs all the necessary handshakes (legacy interface)
  153. %% @param Host host to connect to
  154. %% @param Username username to connect as, defaults to `$USER'
  155. %% @param Password optional password to authenticate with
  156. %% @param Opts proplist or map of extra options
  157. %% @returns `{ok, Connection}' otherwise `{error, Reason}'
  158. %% @see connect/1
  159. connect(Host, Username, Password, Opts) ->
  160. {ok, C} = epgsql_sock:start_link(),
  161. connect(C, Host, Username, Password, Opts).
  162. -spec connect(connection(), host(), string(), password(), connect_opts())
  163. -> {ok, Connection :: connection()} | {error, Reason :: connect_error()}.
  164. connect(C, Host, Username, Password, Opts) ->
  165. Opts1 = maps:merge(to_map(Opts),
  166. #{host => Host,
  167. username => Username,
  168. password => Password}),
  169. call_connect(C, Opts1).
  170. -spec call_connect(connection(), connect_opts())
  171. -> {ok, Connection :: connection()} | {error, Reason :: connect_error()}.
  172. call_connect(C, Opts) ->
  173. Opts1 = epgsql_cmd_connect:opts_hide_password(to_map(Opts)),
  174. case epgsql_sock:sync_command(
  175. C, epgsql_cmd_connect, Opts1) of
  176. connected ->
  177. %% If following call fails for you, try to add {codecs, []} connect option
  178. {ok, _} = maybe_update_typecache(C, Opts1),
  179. {ok, C};
  180. Error = {error, _} ->
  181. Error
  182. end.
  183. maybe_update_typecache(C, Opts) ->
  184. maybe_update_typecache(C, maps:get(replication, Opts, undefined), maps:get(codecs, Opts, undefined)).
  185. maybe_update_typecache(C, undefined, undefined) ->
  186. %% TODO: don't execute 'update_type_cache' when `codecs` is undefined.
  187. %% This will break backward compatibility
  188. update_type_cache(C);
  189. maybe_update_typecache(C, undefined, [_ | _] = Codecs) ->
  190. update_type_cache(C, Codecs);
  191. maybe_update_typecache(_, _, _) ->
  192. {ok, []}.
  193. update_type_cache(C) ->
  194. update_type_cache(C, [{epgsql_codec_hstore, []},
  195. {epgsql_codec_postgis, []}]).
  196. -spec update_type_cache(connection(), [{epgsql_codec:codec_mod(), Opts :: any()}]) ->
  197. epgsql_cmd_update_type_cache:response() | {error, empty}.
  198. update_type_cache(_C, []) ->
  199. {error, empty};
  200. update_type_cache(C, Codecs) ->
  201. %% {error, #error{severity = error,
  202. %% message = <<"column \"typarray\" does not exist in pg_type">>}}
  203. %% Do not fail connect if pg_type table in not in the expected
  204. %% format. Known to happen for Redshift which is based on PG v8.0.2
  205. epgsql_sock:sync_command(C, epgsql_cmd_update_type_cache, Codecs).
  206. %% @doc close connection
  207. -spec close(connection()) -> ok.
  208. close(C) ->
  209. epgsql_sock:close(C).
  210. -spec get_parameter(connection(), binary()) -> binary() | undefined.
  211. get_parameter(C, Name) ->
  212. epgsql_sock:get_parameter(C, Name).
  213. -spec set_notice_receiver(connection(), undefined | pid() | atom()) ->
  214. {ok, Previous :: pid() | atom()}.
  215. set_notice_receiver(C, PidOrName) ->
  216. epgsql_sock:set_notice_receiver(C, PidOrName).
  217. %% @doc Returns last command status message.
  218. %% If multiple queries were executed using {@link squery/2}, separated by semicolon,
  219. %% only the last query's status will be available.
  220. %% See [https://www.postgresql.org/docs/current/static/libpq-exec.html#LIBPQ-PQCMDSTATUS]
  221. -spec get_cmd_status(connection()) -> {ok, Status}
  222. when
  223. Status :: undefined | atom() | {atom(), integer()}.
  224. get_cmd_status(C) ->
  225. epgsql_sock:get_cmd_status(C).
  226. -spec squery(connection(), sql_query()) -> epgsql_cmd_squery:response() | epgsql_sock:error().
  227. %% @doc runs simple `SqlQuery' via given `Connection'
  228. %% @see epgsql_cmd_squery
  229. squery(Connection, SqlQuery) ->
  230. epgsql_sock:sync_command(Connection, epgsql_cmd_squery, SqlQuery).
  231. equery(C, Sql) ->
  232. equery(C, Sql, []).
  233. -spec equery(connection(), sql_query(), [bind_param()]) ->
  234. epgsql_cmd_equery:response() | epgsql_sock:error().
  235. equery(C, Sql, Parameters) ->
  236. equery(C, "", Sql, Parameters).
  237. %% @doc Executes extended query
  238. %% @end
  239. %% @see epgsql_cmd_equery
  240. %% @end
  241. %% TODO add fast_equery command that doesn't need parsed statement
  242. -spec equery(connection(), string(), sql_query(), [bind_param()]) ->
  243. epgsql_cmd_equery:response() | epgsql_sock:error().
  244. equery(C, Name, Sql, Parameters) ->
  245. case parse(C, Name, Sql, []) of
  246. {ok, #statement{types = Types} = S} ->
  247. TypedParameters = lists:zip(Types, Parameters),
  248. epgsql_sock:sync_command(C, epgsql_cmd_equery, {S, TypedParameters});
  249. Error ->
  250. Error
  251. end.
  252. %% @doc Similar to {@link equery/3}, but uses prepared statement that can be reused multiple times.
  253. %% @see epgsql_cmd_prepared_query
  254. -spec prepared_query(C::connection(), string() | statement(), Parameters::[bind_param()]) ->
  255. epgsql_cmd_prepared_query:response().
  256. prepared_query(C, #statement{types = Types} = S, Parameters) ->
  257. TypedParameters = lists:zip(Types, Parameters),
  258. epgsql_sock:sync_command(C, epgsql_cmd_prepared_query, {S, TypedParameters});
  259. prepared_query(C, Name, Parameters) when is_list(Name) ->
  260. case describe(C, statement, Name) of
  261. {ok, #statement{} = S} ->
  262. prepared_query(C, S, Parameters);
  263. Error ->
  264. Error
  265. end.
  266. %% parse
  267. parse(C, Sql) ->
  268. parse(C, Sql, []).
  269. parse(C, Sql, Types) ->
  270. parse(C, "", Sql, Types).
  271. -spec parse(connection(), iolist(), sql_query(), [epgsql_type()]) ->
  272. epgsql_cmd_parse:response().
  273. parse(C, Name, Sql, Types) ->
  274. sync_on_error(
  275. C, epgsql_sock:sync_command(
  276. C, epgsql_cmd_parse, {Name, Sql, Types})).
  277. %% bind
  278. bind(C, Statement, Parameters) ->
  279. bind(C, Statement, "", Parameters).
  280. -spec bind(connection(), statement(), string(), [bind_param()]) ->
  281. epgsql_cmd_bind:response().
  282. bind(C, Statement, PortalName, Parameters) ->
  283. sync_on_error(
  284. C,
  285. epgsql_sock:sync_command(
  286. C, epgsql_cmd_bind, {Statement, PortalName, Parameters})).
  287. %% execute
  288. execute(C, S) ->
  289. execute(C, S, "", 0).
  290. execute(C, S, N) ->
  291. execute(C, S, "", N).
  292. -spec execute(connection(), statement(), string(), non_neg_integer()) -> Reply when
  293. Reply :: epgsql_cmd_execute:response().
  294. execute(C, S, PortalName, N) ->
  295. epgsql_sock:sync_command(C, epgsql_cmd_execute, {S, PortalName, N}).
  296. %% @doc Executes batch of `{statement(), [bind_param()]}' extended queries
  297. %% @see epgsql_cmd_batch
  298. -spec execute_batch(connection(), [{statement(), [bind_param()]}]) ->
  299. epgsql_cmd_batch:response().
  300. execute_batch(C, Batch) ->
  301. epgsql_sock:sync_command(C, epgsql_cmd_batch, Batch).
  302. %% @doc Executes same statement() extended query with each parameter list of a `Batch'
  303. %% @see epgsql_cmd_batch
  304. -spec execute_batch(connection(), statement() | sql_query(), [ [bind_param()] ]) ->
  305. {[column()], epgsql_cmd_batch:response()}.
  306. execute_batch(C, #statement{columns = Cols} = Statement, Batch) ->
  307. {Cols, epgsql_sock:sync_command(C, epgsql_cmd_batch, {Statement, Batch})};
  308. execute_batch(C, Sql, Batch) ->
  309. case parse(C, Sql) of
  310. {ok, #statement{} = S} ->
  311. execute_batch(C, S, Batch);
  312. Error ->
  313. Error
  314. end.
  315. %% statement/portal functions
  316. -spec describe(connection(), statement()) -> epgsql_cmd_describe_statement:response().
  317. describe(C, #statement{name = Name}) ->
  318. describe(C, statement, Name).
  319. -spec describe(connection(), portal, iodata()) -> epgsql_cmd_describe_portal:response();
  320. (connection(), statement, iodata()) -> epgsql_cmd_describe_statement:response().
  321. describe(C, statement, Name) ->
  322. sync_on_error(
  323. C, epgsql_sock:sync_command(
  324. C, epgsql_cmd_describe_statement, Name));
  325. describe(C, portal, Name) ->
  326. sync_on_error(
  327. C, epgsql_sock:sync_command(
  328. C, epgsql_cmd_describe_portal, Name)).
  329. %% @doc close statement
  330. -spec close(connection(), statement()) -> epgsql_cmd_close:response().
  331. close(C, #statement{name = Name}) ->
  332. close(C, statement, Name).
  333. %% @doc close statement or portal
  334. -spec close(connection(), statement | portal, iodata()) -> epgsql_cmd_close:response().
  335. close(C, Type, Name) ->
  336. epgsql_sock:sync_command(C, epgsql_cmd_close, {Type, Name}).
  337. -spec sync(connection()) -> epgsql_cmd_sync:response().
  338. sync(C) ->
  339. epgsql_sock:sync_command(C, epgsql_cmd_sync, []).
  340. %% @doc cancel currently executing command
  341. -spec cancel(connection()) -> ok.
  342. cancel(C) ->
  343. epgsql_sock:cancel(C).
  344. %% misc helper functions
  345. -spec with_transaction(connection(), fun((connection()) -> Reply)) ->
  346. Reply | {rollback, any()}
  347. when
  348. Reply :: any().
  349. with_transaction(C, F) ->
  350. with_transaction(C, F, [{reraise, false}]).
  351. %% @doc Execute callback function with connection in a transaction.
  352. %% Transaction will be rolled back in case of exception.
  353. %% Options (proplist or map):
  354. %% <dl>
  355. %% <dt>reraise</dt>
  356. %% <dd>when set to true, exception will be re-thrown, otherwise
  357. %% `{rollback, ErrorReason}' will be returned. Default: `true'</dd>
  358. %% <dt>ensure_comitted</dt>
  359. %% <dd>even when callback returns without exception,
  360. %% check that transaction was comitted by checking CommandComplete status
  361. %% of "COMMIT" command. In case when transaction was rolled back, status will be
  362. %% "rollback" instead of "commit". Default: `false'</dd>
  363. %% <dt>begin_opts</dt>
  364. %% <dd>append extra options to "BEGIN" command (see
  365. %% https://www.postgresql.org/docs/current/static/sql-begin.html)
  366. %% Beware of SQL injections! No escaping is made on begin_opts! Default: `""'</dd>
  367. %% </dl>
  368. -spec with_transaction(
  369. connection(), fun((connection()) -> Reply), transaction_opts()) -> Reply | {rollback, any()} | no_return() when
  370. Reply :: any().
  371. with_transaction(C, F, Opts0) ->
  372. Opts = to_map(Opts0),
  373. Begin = case Opts of
  374. #{begin_opts := BeginOpts} ->
  375. [<<"BEGIN ">> | BeginOpts];
  376. _ -> <<"BEGIN">>
  377. end,
  378. try
  379. {ok, [], []} = squery(C, Begin),
  380. R = F(C),
  381. {ok, [], []} = squery(C, <<"COMMIT">>),
  382. case Opts of
  383. #{ensure_committed := true} ->
  384. {ok, CmdStatus} = get_cmd_status(C),
  385. (commit == CmdStatus) orelse error({ensure_committed_failed, CmdStatus});
  386. _ -> ok
  387. end,
  388. R
  389. catch
  390. ?WITH_STACKTRACE(Type, Reason, Stack)
  391. squery(C, "ROLLBACK"),
  392. case maps:get(reraise, Opts, true) of
  393. true ->
  394. erlang:raise(Type, Reason, Stack);
  395. false ->
  396. {rollback, Reason}
  397. end
  398. end.
  399. sync_on_error(C, Error = {error, _}) ->
  400. ok = sync(C),
  401. Error;
  402. sync_on_error(_C, R) ->
  403. R.
  404. %% @equiv copy_from_stdin(C, SQL, text)
  405. copy_from_stdin(C, SQL) ->
  406. copy_from_stdin(C, SQL, text).
  407. %% @doc Switches epgsql into COPY-mode
  408. %%
  409. %% When `Format' is `text', Erlang IO-protocol should be used to transfer "raw" COPY data to the
  410. %% server (see, eg, `io:put_chars/2' and `file:write/2' etc).
  411. %%
  412. %% When `Format' is `{binary, Types}', {@link copy_send_rows/3} should be used instead.
  413. %%
  414. %% In case COPY-payload is invalid, asynchronous message of the form
  415. %% `{epgsql, connection(), {error, epgsql:query_error()}}' (similar to asynchronous notification,
  416. %% see {@link set_notice_receiver/2}) will be sent to the process that called `copy_from_stdin'
  417. %% and all the subsequent IO-protocol requests will return error.
  418. %% It's important to not call `copy_done' if such error is detected!
  419. %%
  420. %% @param SQL have to be `COPY ... FROM STDIN ...' statement
  421. %% @param Format data transfer format specification: `text' or `{binary, epgsql_type()}'. Have to
  422. %% match `WHERE (FORMAT ???)' from SQL (`text' for `text'/`csv' OR `{binary, ..}' for `binary').
  423. %% @returns in case of success, `{ok, [text | binary]}' tuple is returned. List describes the expected
  424. %% payload format for each column of input. In current implementation all the atoms in a list
  425. %% will be the same and will match the atom in `Format' parameter. It may change in the future
  426. %% if PostgreSQL will introduce alternative payload formats.
  427. -spec copy_from_stdin(connection(), sql_query(), text | {binary, [epgsql_type()]}) ->
  428. epgsql_cmd_copy_from_stdin:response().
  429. copy_from_stdin(C, SQL, Format) ->
  430. epgsql_sock:sync_command(C, epgsql_cmd_copy_from_stdin, {SQL, self(), Format}).
  431. %% @doc Send a batch of rows to `COPY .. FROM STDIN WITH (FORMAT binary)' in Erlang format
  432. %%
  433. %% Erlang values will be converted to postgres types same way as parameters of, eg, {@link equery/3}
  434. %% using data type specification from 3rd argument of {@link copy_from_stdin/3} (number of columns in
  435. %% each element of `Rows' should match the number of elements in `{binary, Types}').
  436. %% @param Rows might be a list of tuples or list of lists. List of lists is slightly more efficient.
  437. -spec copy_send_rows(connection(), [tuple() | [bind_param()]], timeout()) -> ok | {error, ErrReason} when
  438. ErrReason :: not_in_copy_mode | not_binary_format | query_error().
  439. copy_send_rows(C, Rows, Timeout) ->
  440. epgsql_sock:copy_send_rows(C, Rows, Timeout).
  441. %% @doc Tells server that the transfer of COPY data is done
  442. %%
  443. %% Stops copy-mode and returns the number of inserted rows.
  444. -spec copy_done(connection()) -> epgsql_cmd_copy_done:response().
  445. copy_done(C) ->
  446. epgsql_sock:sync_command(C, epgsql_cmd_copy_done, []).
  447. -spec standby_status_update(connection(), lsn(), lsn()) -> ok.
  448. %% @doc sends last flushed and applied WAL positions to the server in a standby status update message via
  449. %% given `Connection'
  450. standby_status_update(Connection, FlushedLSN, AppliedLSN) ->
  451. epgsql_sock:standby_status_update(Connection, FlushedLSN, AppliedLSN).
  452. handle_x_log_data(Mod, StartLSN, EndLSN, WALRecord, Repl) ->
  453. Mod:handle_x_log_data(StartLSN, EndLSN, WALRecord, Repl).
  454. -type replication_option() ::
  455. {align_lsn, boolean()}. %% Align last applied and flushed LSN with last received LSN
  456. %% after Primary keepalive message with ReplyRequired flag
  457. -type replication_opts() ::
  458. [replication_option()]
  459. | #{align_lsn => boolean()}.
  460. -spec start_replication(connection(), string(), Callback, cb_state(), string(), string(), replication_opts()) ->
  461. Response when
  462. Response :: epgsql_cmd_start_replication:response(),
  463. Callback :: module() | pid().
  464. %% @doc instructs Postgres server to start streaming WAL for logical replication
  465. %% @param Connection connection in replication mode
  466. %% @param ReplicationSlot the name of the replication slot to stream changes from
  467. %% @param Callback Callback module which should have the callback functions implemented for message processing.
  468. %% or a process which should be able to receive replication messages.
  469. %% @param CbInitState Callback Module's initial state
  470. %% @param WALPosition the WAL position XXX/XXX to begin streaming at.
  471. %% "0/0" to let the server determine the start point.
  472. %% @param PluginOpts optional options passed to the slot's logical decoding plugin.
  473. %% For example: "option_name1 'value1', option_name2 'value2'"
  474. %% @param Opts options of logical replication
  475. %% @returns `ok' otherwise `{error, Reason}'
  476. start_replication(Connection, ReplicationSlot, Callback, CbInitState, WALPosition, PluginOpts, Opts) ->
  477. Command = {ReplicationSlot, Callback, CbInitState, WALPosition, PluginOpts, to_map(Opts)},
  478. epgsql_sock:sync_command(Connection, epgsql_cmd_start_replication, Command).
  479. start_replication(Connection, ReplicationSlot, Callback, CbInitState, WALPosition, PluginOpts) ->
  480. start_replication(Connection, ReplicationSlot, Callback, CbInitState, WALPosition, PluginOpts, []).
  481. start_replication(Connection, ReplicationSlot, Callback, CbInitState, WALPosition) ->
  482. start_replication(Connection, ReplicationSlot, Callback, CbInitState, WALPosition, [], []).
  483. %% @private
  484. -spec to_map([{any(), any()}] | map()) -> map().
  485. to_map(Map) when is_map(Map) ->
  486. Map;
  487. to_map(List) when is_list(List) ->
  488. maps:from_list(List).