epgsql.erl 16 KB

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