epgsql.erl 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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, execute_batch/3,
  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. -spec execute_batch(connection(), statement() | sql_query(), [ [bind_param()] ]) ->
  268. {[column()], epgsql_cmd_batch:response()}.
  269. execute_batch(C, #statement{columns = Cols} = Statement, Batch) ->
  270. {Cols, epgsql_sock:sync_command(C, epgsql_cmd_batch, {Statement, Batch})};
  271. execute_batch(C, Sql, Batch) ->
  272. case parse(C, Sql) of
  273. {ok, #statement{} = S} ->
  274. execute_batch(C, S, Batch);
  275. Error ->
  276. Error
  277. end.
  278. %% statement/portal functions
  279. -spec describe(connection(), statement()) -> epgsql_cmd_describe_statement:response().
  280. describe(C, #statement{name = Name}) ->
  281. describe(C, statement, Name).
  282. -spec describe(connection(), portal, iodata()) -> epgsql_cmd_describe_portal:response();
  283. (connection(), statement, iodata()) -> epgsql_cmd_describe_statement:response().
  284. describe(C, statement, Name) ->
  285. sync_on_error(
  286. C, epgsql_sock:sync_command(
  287. C, epgsql_cmd_describe_statement, Name));
  288. describe(C, portal, Name) ->
  289. sync_on_error(
  290. C, epgsql_sock:sync_command(
  291. C, epgsql_cmd_describe_portal, Name)).
  292. %% @doc close statement
  293. -spec close(connection(), statement()) -> epgsql_cmd_close:response().
  294. close(C, #statement{name = Name}) ->
  295. close(C, statement, Name).
  296. -spec close(connection(), statement | portal, iodata()) -> epgsql_cmd_close:response().
  297. close(C, Type, Name) ->
  298. epgsql_sock:sync_command(C, epgsql_cmd_close, {Type, Name}).
  299. -spec sync(connection()) -> epgsql_cmd_sync:response().
  300. sync(C) ->
  301. epgsql_sock:sync_command(C, epgsql_cmd_sync, []).
  302. -spec cancel(connection()) -> ok.
  303. cancel(C) ->
  304. epgsql_sock:cancel(C).
  305. %% misc helper functions
  306. -spec with_transaction(connection(), fun((connection()) -> Reply)) ->
  307. Reply | {rollback, any()}
  308. when
  309. Reply :: any().
  310. with_transaction(C, F) ->
  311. with_transaction(C, F, [{reraise, false}]).
  312. %% @doc Execute callback function with connection in a transaction.
  313. %% Transaction will be rolled back in case of exception.
  314. %% Options (proplist or map):
  315. %% - reraise (true): when set to true, exception will be re-thrown, otherwise
  316. %% {rollback, ErrorReason} will be returned
  317. %% - ensure_comitted (false): even when callback returns without exception,
  318. %% check that transaction was comitted by checking CommandComplete status
  319. %% of "COMMIT" command. In case when transaction was rolled back, status will be
  320. %% "rollback" instead of "commit".
  321. %% - begin_opts (""): append extra options to "BEGIN" command (see
  322. %% https://www.postgresql.org/docs/current/static/sql-begin.html)
  323. %% Beware of SQL injections! No escaping is made on begin_opts!
  324. -spec with_transaction(
  325. connection(), fun((connection()) -> Reply), Opts) -> Reply | {rollback, any()} | no_return() when
  326. Reply :: any(),
  327. Opts :: [{reraise, boolean()} |
  328. {ensure_committed, boolean()} |
  329. {begin_opts, iodata()}].
  330. with_transaction(C, F, Opts0) ->
  331. Opts = to_map(Opts0),
  332. Begin = case Opts of
  333. #{begin_opts := BeginOpts} ->
  334. [<<"BEGIN ">> | BeginOpts];
  335. _ -> <<"BEGIN">>
  336. end,
  337. try
  338. {ok, [], []} = squery(C, Begin),
  339. R = F(C),
  340. {ok, [], []} = squery(C, <<"COMMIT">>),
  341. case Opts of
  342. #{ensure_committed := true} ->
  343. {ok, CmdStatus} = get_cmd_status(C),
  344. (commit == CmdStatus) orelse error({ensure_committed_failed, CmdStatus});
  345. _ -> ok
  346. end,
  347. R
  348. catch
  349. ?WITH_STACKTRACE(Type, Reason, Stack)
  350. squery(C, "ROLLBACK"),
  351. case maps:get(reraise, Opts, true) of
  352. true ->
  353. erlang:raise(Type, Reason, Stack);
  354. false ->
  355. {rollback, Reason}
  356. end
  357. end.
  358. sync_on_error(C, Error = {error, _}) ->
  359. ok = sync(C),
  360. Error;
  361. sync_on_error(_C, R) ->
  362. R.
  363. -spec standby_status_update(connection(), lsn(), lsn()) -> ok.
  364. %% @doc sends last flushed and applied WAL positions to the server in a standby status update message via
  365. %% given `Connection'
  366. standby_status_update(Connection, FlushedLSN, AppliedLSN) ->
  367. gen_server:call(Connection, {standby_status_update, FlushedLSN, AppliedLSN}).
  368. handle_x_log_data(Mod, StartLSN, EndLSN, WALRecord, Repl) ->
  369. Mod:handle_x_log_data(StartLSN, EndLSN, WALRecord, Repl).
  370. -type replication_option() ::
  371. {align_lsn, boolean()}. %% Align last applied and flushed LSN with last received LSN
  372. %% after Primary keepalive message with ReplyRequired flag
  373. -type replication_opts() ::
  374. [replication_option()]
  375. | #{align_lsn => boolean()}.
  376. -spec start_replication(connection(), string(), Callback, cb_state(), string(), string(), replication_opts()) ->
  377. Response when
  378. Response :: epgsql_cmd_start_replication:response(),
  379. Callback :: module() | pid().
  380. %% @doc instructs Postgres server to start streaming WAL for logical replication
  381. %% where
  382. %% `Connection' - connection in replication mode
  383. %% `ReplicationSlot' - the name of the replication slot to stream changes from
  384. %% `Callback' - Callback module which should have the callback functions implemented for message processing.
  385. %% or a process which should be able to receive replication messages.
  386. %% `CbInitState' - Callback Module's initial state
  387. %% `WALPosition' - the WAL position XXX/XXX to begin streaming at.
  388. %% "0/0" to let the server determine the start point.
  389. %% `PluginOpts' - optional options passed to the slot's logical decoding plugin.
  390. %% For example: "option_name1 'value1', option_name2 'value2'"
  391. %% `Opts' - options of logical replication
  392. %% returns `ok' otherwise `{error, Reason}'
  393. start_replication(Connection, ReplicationSlot, Callback, CbInitState, WALPosition, PluginOpts, Opts) ->
  394. Command = {ReplicationSlot, Callback, CbInitState, WALPosition, PluginOpts, to_map(Opts)},
  395. epgsql_sock:sync_command(Connection, epgsql_cmd_start_replication, Command).
  396. start_replication(Connection, ReplicationSlot, Callback, CbInitState, WALPosition, PluginOpts) ->
  397. start_replication(Connection, ReplicationSlot, Callback, CbInitState, WALPosition, PluginOpts, []).
  398. start_replication(Connection, ReplicationSlot, Callback, CbInitState, WALPosition) ->
  399. start_replication(Connection, ReplicationSlot, Callback, CbInitState, WALPosition, [], []).
  400. %% @private
  401. -spec to_map([{any(), any()}] | map()) -> map().
  402. to_map(Map) when is_map(Map) ->
  403. Map;
  404. to_map(List) when is_list(List) ->
  405. maps:from_list(List).