epgsql.erl 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. squery/2,
  9. equery/2, equery/3, equery/4,
  10. prepared_query/3,
  11. parse/2, parse/3, parse/4,
  12. describe/2, describe/3,
  13. bind/3, bind/4,
  14. execute/2, execute/3, execute/4,
  15. execute_batch/2,
  16. close/2, close/3,
  17. sync/1,
  18. cancel/1,
  19. update_type_cache/1,
  20. update_type_cache/2,
  21. with_transaction/2,
  22. sync_on_error/2,
  23. standby_status_update/3,
  24. start_replication/5,
  25. start_replication/6]).
  26. -export_type([connection/0, connect_option/0,
  27. connect_error/0, query_error/0,
  28. sql_query/0, bind_param/0, typed_param/0,
  29. squery_row/0, equery_row/0, reply/1]).
  30. -include("epgsql.hrl").
  31. -type sql_query() :: string() | iodata().
  32. -type host() :: inet:ip_address() | inet:hostname().
  33. -type connection() :: pid().
  34. -type connect_option() ::
  35. {database, DBName :: string()} |
  36. {port, PortNum :: inet:port_number()} |
  37. {ssl, IsEnabled :: boolean() | required} |
  38. {ssl_opts, SslOptions :: [ssl:ssl_option()]} | % @see OTP ssl app, ssl_api.hrl
  39. {timeout, TimeoutMs :: timeout()} | % default: 5000 ms
  40. {async, Receiver :: pid()} | % process to receive LISTEN/NOTIFY msgs
  41. {replication, Replication :: string()}. % Pass "database" to connect in replication mode
  42. -type connect_error() :: #error{}.
  43. -type query_error() :: #error{}.
  44. -type bind_param() ::
  45. null
  46. | boolean()
  47. | string()
  48. | binary()
  49. | integer()
  50. | float()
  51. | calendar:date()
  52. | calendar:time() %actualy, `Seconds' may be float()
  53. | calendar:datetime()
  54. | {calendar:time(), Days::non_neg_integer(), Months::non_neg_integer()}
  55. | {list({binary(), binary() | null})} % hstore
  56. | [bind_param()]. %array (maybe nested)
  57. -type typed_param() ::
  58. {epgsql_type(), bind_param()}.
  59. -type squery_row() :: tuple(). % tuple of binary().
  60. -type equery_row() :: tuple(). % tuple of bind_param().
  61. -type ok_reply(RowType) ::
  62. {ok, ColumnsDescription :: [#column{}], RowsValues :: [RowType]} | % select
  63. {ok, Count :: non_neg_integer()} | % update/insert/delete
  64. {ok, Count :: non_neg_integer(), ColumnsDescription :: [#column{}], RowsValues :: [RowType]}. % update/insert/delete + returning
  65. -type error_reply() :: {error, query_error()}.
  66. -type reply(RowType) :: ok_reply(RowType) | error_reply().
  67. -type lsn() :: integer().
  68. -type cb_state() :: term().
  69. %% -- behaviour callbacks --
  70. %% Handles a XLogData Message (StartLSN, EndLSN, WALRecord, CbState).
  71. %% Return: {ok, LastFlushedLSN, LastAppliedLSN, NewCbState}
  72. -callback handle_x_log_data(lsn(), lsn(), binary(), cb_state()) -> {ok, lsn(), lsn(), cb_state()}.
  73. %% -------------
  74. %% -- client interface --
  75. connect(Settings) ->
  76. Host = proplists:get_value(host, Settings, "localhost"),
  77. Username = proplists:get_value(username, Settings, os:getenv("USER")),
  78. Password = proplists:get_value(password, Settings, ""),
  79. connect(Host, Username, Password, Settings).
  80. connect(Host, Opts) ->
  81. connect(Host, os:getenv("USER"), "", Opts).
  82. connect(Host, Username, Opts) ->
  83. connect(Host, Username, "", Opts).
  84. -spec connect(host(), string(), string(), [connect_option()])
  85. -> {ok, Connection :: connection()} | {error, Reason :: connect_error()}.
  86. %% @doc connects to Postgres
  87. %% where
  88. %% `Host' - host to connect to
  89. %% `Username' - username to connect as, defaults to `$USER'
  90. %% `Password' - optional password to authenticate with
  91. %% `Opts' - proplist of extra options
  92. %% returns `{ok, Connection}' otherwise `{error, Reason}'
  93. connect(Host, Username, Password, Opts) ->
  94. {ok, C} = epgsql_sock:start_link(),
  95. connect(C, Host, Username, Password, Opts).
  96. -spec connect(connection(), host(), string(), string(), [connect_option()])
  97. -> {ok, Connection :: connection()} | {error, Reason :: connect_error()}.
  98. connect(C, Host, Username, Password, Opts) ->
  99. %% TODO connect timeout
  100. case gen_server:call(C,
  101. {connect, Host, Username, Password, Opts},
  102. infinity) of
  103. connected ->
  104. case proplists:get_value(replication, Opts, undefined) of
  105. undefined ->
  106. update_type_cache(C),
  107. {ok, C};
  108. _ -> {ok, C} %% do not update update_type_cache if connection is in replication mode
  109. end;
  110. Error = {error, _} ->
  111. Error
  112. end.
  113. -spec update_type_cache(connection()) -> ok.
  114. update_type_cache(C) ->
  115. update_type_cache(C, [<<"hstore">>,<<"geometry">>]).
  116. -spec update_type_cache(connection(), [binary()]) -> ok.
  117. update_type_cache(C, DynamicTypes) ->
  118. Query = "SELECT typname, oid::int4, typarray::int4"
  119. " FROM pg_type"
  120. " WHERE typname = ANY($1::varchar[])",
  121. case equery(C, Query, [DynamicTypes]) of
  122. {ok, _, TypeInfos} ->
  123. ok = gen_server:call(C, {update_type_cache, TypeInfos});
  124. {error, {error, error, _, _,
  125. <<"column \"typarray\" does not exist in pg_type">>, _}} ->
  126. %% Do not fail connect if pg_type table in not in the expected
  127. %% format. Known to happen for Redshift which is based on PG v8.0.2
  128. ok
  129. end.
  130. -spec close(connection()) -> ok.
  131. close(C) ->
  132. epgsql_sock:close(C).
  133. -spec get_parameter(connection(), binary()) -> binary() | undefined.
  134. get_parameter(C, Name) ->
  135. epgsql_sock:get_parameter(C, Name).
  136. -spec set_notice_receiver(connection(), undefined | pid() | atom()) ->
  137. {ok, Previous :: pid() | atom()}.
  138. set_notice_receiver(C, PidOrName) ->
  139. epgsql_sock:set_notice_receiver(C, PidOrName).
  140. -spec squery(connection(), sql_query()) -> reply(squery_row()) | [reply(squery_row())].
  141. %% @doc runs simple `SqlQuery' via given `Connection'
  142. squery(Connection, SqlQuery) ->
  143. gen_server:call(Connection, {squery, SqlQuery}, infinity).
  144. equery(C, Sql) ->
  145. equery(C, Sql, []).
  146. %% TODO add fast_equery command that doesn't need parsed statement
  147. equery(C, Sql, Parameters) ->
  148. case parse(C, "", Sql, []) of
  149. {ok, #statement{types = Types} = S} ->
  150. Typed_Parameters = lists:zip(Types, Parameters),
  151. gen_server:call(C, {equery, S, Typed_Parameters}, infinity);
  152. Error ->
  153. Error
  154. end.
  155. -spec equery(connection(), string(), sql_query(), [bind_param()]) -> reply(equery_row()).
  156. equery(C, Name, Sql, Parameters) ->
  157. case parse(C, Name, Sql, []) of
  158. {ok, #statement{types = Types} = S} ->
  159. Typed_Parameters = lists:zip(Types, Parameters),
  160. gen_server:call(C, {equery, S, Typed_Parameters}, infinity);
  161. Error ->
  162. Error
  163. end.
  164. -spec prepared_query(C::connection(), Name::string(), Parameters::[bind_param()]) -> reply(equery_row()).
  165. prepared_query(C, Name, Parameters) ->
  166. case describe(C, statement, Name) of
  167. {ok, #statement{types = Types} = S} ->
  168. Typed_Parameters = lists:zip(Types, Parameters),
  169. gen_server:call(C, {prepared_query, S, Typed_Parameters}, infinity);
  170. Error ->
  171. Error
  172. end.
  173. %% parse
  174. parse(C, Sql) ->
  175. parse(C, Sql, []).
  176. parse(C, Sql, Types) ->
  177. parse(C, "", Sql, Types).
  178. -spec parse(connection(), iolist(), sql_query(), [epgsql_type()]) ->
  179. {ok, #statement{}} | {error, query_error()}.
  180. parse(C, Name, Sql, Types) ->
  181. sync_on_error(C, gen_server:call(C, {parse, Name, Sql, Types}, infinity)).
  182. %% bind
  183. bind(C, Statement, Parameters) ->
  184. bind(C, Statement, "", Parameters).
  185. -spec bind(connection(), #statement{}, string(), [bind_param()]) ->
  186. ok | {error, query_error()}.
  187. bind(C, Statement, PortalName, Parameters) ->
  188. sync_on_error(
  189. C,
  190. gen_server:call(C, {bind, Statement, PortalName, Parameters}, infinity)).
  191. %% execute
  192. execute(C, S) ->
  193. execute(C, S, "", 0).
  194. execute(C, S, N) ->
  195. execute(C, S, "", N).
  196. -spec execute(connection(), #statement{}, string(), non_neg_integer()) -> Reply
  197. when
  198. Reply :: {ok | partial, [equery_row()]}
  199. | {ok, non_neg_integer()}
  200. | {ok, non_neg_integer(), [equery_row()]}
  201. | {error, query_error()}.
  202. execute(C, S, PortalName, N) ->
  203. gen_server:call(C, {execute, S, PortalName, N}, infinity).
  204. -spec execute_batch(connection(), [{#statement{}, [bind_param()]}]) -> [reply(equery_row())].
  205. execute_batch(C, Batch) ->
  206. gen_server:call(C, {execute_batch, Batch}, infinity).
  207. %% statement/portal functions
  208. describe(C, #statement{name = Name}) ->
  209. describe(C, statement, Name).
  210. describe(C, statement, Name) ->
  211. sync_on_error(C, gen_server:call(C, {describe_statement, Name}, infinity));
  212. %% TODO unknown result format of Describe portal
  213. describe(C, portal, Name) ->
  214. sync_on_error(C, gen_server:call(C, {describe_portal, Name}, infinity)).
  215. close(C, #statement{name = Name}) ->
  216. close(C, statement, Name).
  217. close(C, Type, Name) ->
  218. gen_server:call(C, {close, Type, Name}).
  219. sync(C) ->
  220. gen_server:call(C, sync).
  221. -spec cancel(connection()) -> ok.
  222. cancel(C) ->
  223. epgsql_sock:cancel(C).
  224. %% misc helper functions
  225. -spec with_transaction(connection(), fun((connection()) -> Reply)) ->
  226. Reply | {rollback, any()}
  227. when
  228. Reply :: any().
  229. with_transaction(C, F) ->
  230. try {ok, [], []} = squery(C, "BEGIN"),
  231. R = F(C),
  232. {ok, [], []} = squery(C, "COMMIT"),
  233. R
  234. catch
  235. _:Why ->
  236. squery(C, "ROLLBACK"),
  237. %% TODO hides error stacktrace
  238. {rollback, Why}
  239. end.
  240. sync_on_error(C, Error = {error, _}) ->
  241. ok = sync(C),
  242. Error;
  243. sync_on_error(_C, R) ->
  244. R.
  245. -spec standby_status_update(connection(), lsn(), lsn()) -> ok | error_reply().
  246. %% @doc sends last flushed and applied WAL positions to the server in a standby status update message via given `Connection'
  247. standby_status_update(Connection, FlushedLSN, AppliedLSN) ->
  248. gen_server:call(Connection, {standby_status_update, FlushedLSN, AppliedLSN}).
  249. -spec start_replication(connection(), string(), Callback, cb_state(), string(), string()) -> ok | error_reply() when
  250. Callback :: module() | pid().
  251. %% @doc instructs Postgres server to start streaming WAL for logical replication
  252. %% where
  253. %% `Connection' - connection in replication mode
  254. %% `ReplicationSlot' - the name of the replication slot to stream changes from
  255. %% `Callback' - Callback module which should have the callback functions implemented for message processing.
  256. %% or a process which should be able to receive replication messages.
  257. %% `CbInitState' - Callback Module's initial state
  258. %% `WALPosition' - the WAL position XXX/XXX to begin streaming at.
  259. %% "0/0" to let the server determine the start point.
  260. %% `PluginOpts' - optional options passed to the slot's logical decoding plugin.
  261. %% For example: "option_name1 'value1', option_name2 'value2'"
  262. %% returns `ok' otherwise `{error, Reason}'
  263. start_replication(Connection, ReplicationSlot, Callback, CbInitState, WALPosition, PluginOpts) ->
  264. gen_server:call(Connection, {start_replication, ReplicationSlot, Callback, CbInitState, WALPosition, PluginOpts}).
  265. start_replication(Connection, ReplicationSlot, Callback, CbInitState, WALPosition) ->
  266. start_replication(Connection, ReplicationSlot, Callback, CbInitState, WALPosition, []).