epgsql.erl 19 KB

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