epgsql.erl 17 KB

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