epgsql_sock.erl 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. %%% @doc GenServer holding all the connection state (including socket).
  2. %%%
  3. %%% See [https://www.postgresql.org/docs/current/static/protocol-flow.html]
  4. %%%
  5. %%% Commands in PostgreSQL protocol are pipelined: you don't have to wait for
  6. %%% reply to be able to send next command.
  7. %%% Commands are processed (and responses to them are generated) in FIFO order.
  8. %%% eg, if you execute 2 SimpleQuery: #1 and #2, first you get all response
  9. %%% packets for #1 and then all for #2:
  10. %%% ```
  11. %%% > SQuery #1
  12. %%% > SQuery #2
  13. %%% < RowDescription #1
  14. %%% < DataRow #1.1
  15. %%% < ...
  16. %%% < DataRow #1.N
  17. %%% < CommandComplete #1
  18. %%% < RowDescription #2
  19. %%% < DataRow #2.1
  20. %%% < ...
  21. %%% < DataRow #2.N
  22. %%% < CommandComplete #2
  23. %%% '''
  24. %%% `epgsql_sock' is capable of utilizing the pipelining feature - as soon as
  25. %%% it receives a new command, it sends it to the server immediately and then
  26. %%% it puts command's callbacks and state into internal queue of all the commands
  27. %%% which were sent to the server and waiting for response. So it knows in which
  28. %%% order it should call each pipelined command's `handle_message' callback.
  29. %%% But it can be easily broken if high-level command is poorly implemented or
  30. %%% some conflicting low-level commands (such as `parse', `bind', `execute') are
  31. %%% executed in a wrong order. In this case server and epgsql states become out of
  32. %%% sync and {@link epgsql_cmd_sync} have to be executed in order to recover.
  33. %%% @see epgsql_cmd_connect. epgsql_cmd_connect for network connection and authentication setup
  34. %%% @end
  35. %%% Copyright (C) 2009 - Will Glozer. All rights reserved.
  36. %%% Copyright (C) 2011 - Anton Lebedevich. All rights reserved.
  37. -module(epgsql_sock).
  38. -behavior(gen_server).
  39. -export([start_link/0,
  40. close/1,
  41. sync_command/3,
  42. async_command/4,
  43. get_parameter/2,
  44. set_notice_receiver/2,
  45. get_cmd_status/1,
  46. cancel/1]).
  47. -export([handle_call/3, handle_cast/2, handle_info/2]).
  48. -export([init/1, code_change/3, terminate/2]).
  49. %% loop callback
  50. -export([on_message/3, on_replication/3, on_copy_from_stdin/3]).
  51. %% Comand's APIs
  52. -export([set_net_socket/3, init_replication_state/1, set_attr/3, get_codec/1,
  53. get_rows/1, get_results/1, notify/2, send/2, send/3, send_multi/2,
  54. get_parameter_internal/2,
  55. get_subproto_state/1, set_packet_handler/2]).
  56. -export_type([transport/0, pg_sock/0, error/0]).
  57. -include("epgsql.hrl").
  58. -include("protocol.hrl").
  59. -include("epgsql_replication.hrl").
  60. -include("epgsql_copy.hrl").
  61. -type transport() :: {call, any()}
  62. | {cast, pid(), reference()}
  63. | {incremental, pid(), reference()}.
  64. -type tcp_socket() :: port(). %gen_tcp:socket() isn't exported prior to erl 18
  65. -type repl_state() :: #repl{}.
  66. -type copy_state() :: #copy{}.
  67. -type error() :: {error, sync_required | closed | sock_closed | sock_error}.
  68. -record(state, {mod :: gen_tcp | ssl | undefined,
  69. sock :: tcp_socket() | ssl:sslsocket() | undefined,
  70. data = <<>>,
  71. backend :: {Pid :: integer(), Key :: integer()} | undefined,
  72. handler = on_message :: on_message | on_replication | on_copy_from_stdin | undefined,
  73. codec :: epgsql_binary:codec() | undefined,
  74. queue = queue:new() :: queue:queue({epgsql_command:command(), any(), transport()}),
  75. current_cmd :: epgsql_command:command() | undefined,
  76. current_cmd_state :: any() | undefined,
  77. current_cmd_transport :: transport() | undefined,
  78. async :: undefined | atom() | pid(),
  79. parameters = [] :: [{Key :: binary(), Value :: binary()}],
  80. rows = [] :: [tuple()],
  81. results = [],
  82. sync_required :: boolean() | undefined,
  83. txstatus :: byte() | undefined, % $I | $T | $E,
  84. complete_status :: atom() | {atom(), integer()} | undefined,
  85. subproto_state :: repl_state() | copy_state() | undefined,
  86. connect_opts :: epgsql:connect_opts() | undefined}).
  87. -opaque pg_sock() :: #state{}.
  88. %% -- client interface --
  89. start_link() ->
  90. gen_server:start_link(?MODULE, [], []).
  91. close(C) when is_pid(C) ->
  92. catch gen_server:cast(C, stop),
  93. ok.
  94. -spec sync_command(epgsql:connection(), epgsql_command:command(), any()) -> any().
  95. sync_command(C, Command, Args) ->
  96. gen_server:call(C, {command, Command, Args}, infinity).
  97. -spec async_command(epgsql:connection(), cast | incremental,
  98. epgsql_command:command(), any()) -> reference().
  99. async_command(C, Transport, Command, Args) ->
  100. Ref = make_ref(),
  101. Pid = self(),
  102. ok = gen_server:cast(C, {{Transport, Pid, Ref}, Command, Args}),
  103. Ref.
  104. get_parameter(C, Name) ->
  105. gen_server:call(C, {get_parameter, to_binary(Name)}, infinity).
  106. set_notice_receiver(C, PidOrName) when is_pid(PidOrName);
  107. is_atom(PidOrName) ->
  108. gen_server:call(C, {set_async_receiver, PidOrName}, infinity).
  109. get_cmd_status(C) ->
  110. gen_server:call(C, get_cmd_status, infinity).
  111. cancel(S) ->
  112. gen_server:cast(S, cancel).
  113. %% -- command APIs --
  114. %% send()
  115. %% send_many()
  116. -spec set_net_socket(gen_tcp | ssl, tcp_socket() | ssl:sslsocket(), pg_sock()) -> pg_sock().
  117. set_net_socket(Mod, Socket, State) ->
  118. State1 = State#state{mod = Mod, sock = Socket},
  119. setopts(State1, [{active, true}]),
  120. State1.
  121. -spec init_replication_state(pg_sock()) -> pg_sock().
  122. init_replication_state(State) ->
  123. State#state{subproto_state = #repl{}}.
  124. -spec set_attr(atom(), any(), pg_sock()) -> pg_sock().
  125. set_attr(backend, {_Pid, _Key} = Backend, State) ->
  126. State#state{backend = Backend};
  127. set_attr(async, Async, State) ->
  128. State#state{async = Async};
  129. set_attr(txstatus, Status, State) ->
  130. State#state{txstatus = Status};
  131. set_attr(codec, Codec, State) ->
  132. State#state{codec = Codec};
  133. set_attr(sync_required, Value, State) ->
  134. State#state{sync_required = Value};
  135. set_attr(subproto_state, Value, State) ->
  136. State#state{subproto_state = Value};
  137. set_attr(connect_opts, ConnectOpts, State) ->
  138. State#state{connect_opts = ConnectOpts}.
  139. %% XXX: be careful!
  140. -spec set_packet_handler(atom(), pg_sock()) -> pg_sock().
  141. set_packet_handler(Handler, State) ->
  142. State#state{handler = Handler}.
  143. -spec get_codec(pg_sock()) -> epgsql_binary:codec().
  144. get_codec(#state{codec = Codec}) ->
  145. Codec.
  146. -spec get_subproto_state(pg_sock()) -> repl_state() | copy_state() | undefined.
  147. get_subproto_state(#state{subproto_state = SubState}) ->
  148. SubState.
  149. -spec get_rows(pg_sock()) -> [tuple()].
  150. get_rows(#state{rows = Rows}) ->
  151. lists:reverse(Rows).
  152. -spec get_results(pg_sock()) -> [any()].
  153. get_results(#state{results = Results}) ->
  154. lists:reverse(Results).
  155. -spec get_parameter_internal(binary(), pg_sock()) -> binary() | undefined.
  156. get_parameter_internal(Name, #state{parameters = Parameters}) ->
  157. case lists:keysearch(Name, 1, Parameters) of
  158. {value, {Name, Value}} -> Value;
  159. false -> undefined
  160. end.
  161. %% -- gen_server implementation --
  162. init([]) ->
  163. {ok, #state{}}.
  164. handle_call({command, Command, Args}, From, State) ->
  165. Transport = {call, From},
  166. command_new(Transport, Command, Args, State);
  167. handle_call({get_parameter, Name}, _From, State) ->
  168. {reply, {ok, get_parameter_internal(Name, State)}, State};
  169. handle_call({set_async_receiver, PidOrName}, _From, #state{async = Previous} = State) ->
  170. {reply, {ok, Previous}, State#state{async = PidOrName}};
  171. handle_call(get_cmd_status, _From, #state{complete_status = Status} = State) ->
  172. {reply, {ok, Status}, State};
  173. handle_call({standby_status_update, FlushedLSN, AppliedLSN}, _From,
  174. #state{handler = on_replication,
  175. subproto_state = #repl{last_received_lsn = ReceivedLSN} = Repl} = State) ->
  176. send(State, ?COPY_DATA, epgsql_wire:encode_standby_status_update(ReceivedLSN, FlushedLSN, AppliedLSN)),
  177. Repl1 = Repl#repl{last_flushed_lsn = FlushedLSN,
  178. last_applied_lsn = AppliedLSN},
  179. {reply, ok, State#state{subproto_state = Repl1}}.
  180. handle_cast({{Method, From, Ref} = Transport, Command, Args}, State)
  181. when ((Method == cast) or (Method == incremental)),
  182. is_pid(From),
  183. is_reference(Ref) ->
  184. command_new(Transport, Command, Args, State);
  185. handle_cast(stop, State) ->
  186. send(State, ?TERMINATE, []),
  187. {stop, normal, flush_queue(State, {error, closed})};
  188. handle_cast(cancel, State = #state{backend = {Pid, Key},
  189. connect_opts = ConnectOpts,
  190. mod = Mode}) ->
  191. SockOpts = [{active, false}, {packet, raw}, binary],
  192. Msg = <<16:?int32, 80877102:?int32, Pid:?int32, Key:?int32>>,
  193. case epgsql_cmd_connect:open_socket(SockOpts, ConnectOpts) of
  194. {ok, Mode, Sock} ->
  195. ok = apply(Mode, send, [Sock, Msg]),
  196. apply(Mode, close, [Sock]);
  197. {error, _Reason} ->
  198. noop
  199. end,
  200. {noreply, State}.
  201. handle_info({DataTag, Sock, Data2}, #state{data = Data, sock = Sock} = State)
  202. when DataTag == tcp; DataTag == ssl ->
  203. loop(State#state{data = <<Data/binary, Data2/binary>>});
  204. handle_info({Closed, Sock}, #state{sock = Sock} = State)
  205. when Closed == tcp_closed; Closed == ssl_closed ->
  206. {stop, sock_closed, flush_queue(State#state{sock = undefined}, {error, sock_closed})};
  207. handle_info({Error, Sock, Reason}, #state{sock = Sock} = State)
  208. when Error == tcp_error; Error == ssl_error ->
  209. Why = {sock_error, Reason},
  210. {stop, Why, flush_queue(State, {error, Why})};
  211. handle_info({inet_reply, _, ok}, State) ->
  212. {noreply, State};
  213. handle_info({inet_reply, _, Status}, State) ->
  214. {stop, Status, flush_queue(State, {error, Status})};
  215. handle_info({io_request, From, ReplyAs, Request}, State) ->
  216. Response = handle_io_request(Request, State),
  217. io_reply(Response, From, ReplyAs),
  218. {noreply, State}.
  219. terminate(_Reason, #state{sock = undefined}) -> ok;
  220. terminate(_Reason, #state{mod = gen_tcp, sock = Sock}) -> gen_tcp:close(Sock);
  221. terminate(_Reason, #state{mod = ssl, sock = Sock}) -> ssl:close(Sock).
  222. code_change(_OldVsn, State, _Extra) ->
  223. {ok, State}.
  224. %% -- internal functions --
  225. -spec command_new(transport(), epgsql_command:command(), any(), pg_sock()) ->
  226. Result when
  227. Result :: {noreply, pg_sock()}
  228. | {stop, Reason :: any(), pg_sock()}.
  229. command_new(Transport, Command, Args, State) ->
  230. CmdState = epgsql_command:init(Command, Args),
  231. command_exec(Transport, Command, CmdState, State).
  232. -spec command_exec(transport(), epgsql_command:command(), any(), pg_sock()) ->
  233. Result when
  234. Result :: {noreply, pg_sock()}
  235. | {stop, Reason :: any(), pg_sock()}.
  236. command_exec(Transport, Command, _, State = #state{sync_required = true})
  237. when Command /= epgsql_cmd_sync ->
  238. {noreply,
  239. finish(State#state{current_cmd = Command,
  240. current_cmd_transport = Transport},
  241. {error, sync_required})};
  242. command_exec(Transport, Command, CmdState, State) ->
  243. case epgsql_command:execute(Command, State, CmdState) of
  244. {ok, State1, CmdState1} ->
  245. {noreply, command_enqueue(Transport, Command, CmdState1, State1)};
  246. {send, PktType, PktData, State1, CmdState1} ->
  247. ok = send(State1, PktType, PktData),
  248. {noreply, command_enqueue(Transport, Command, CmdState1, State1)};
  249. {send_multi, Packets, State1, CmdState1} when is_list(Packets) ->
  250. ok = send_multi(State1, Packets),
  251. {noreply, command_enqueue(Transport, Command, CmdState1, State1)};
  252. {stop, StopReason, Response, State1} ->
  253. reply(Transport, Response, Response),
  254. {stop, StopReason, State1}
  255. end.
  256. -spec command_enqueue(transport(), epgsql_command:command(), epgsql_command:state(), pg_sock()) -> pg_sock().
  257. command_enqueue(Transport, Command, CmdState, #state{current_cmd = undefined} = State) ->
  258. State#state{current_cmd = Command,
  259. current_cmd_state = CmdState,
  260. current_cmd_transport = Transport,
  261. complete_status = undefined};
  262. command_enqueue(Transport, Command, CmdState, #state{queue = Q} = State) ->
  263. State#state{queue = queue:in({Command, CmdState, Transport}, Q),
  264. complete_status = undefined}.
  265. -spec command_handle_message(byte(), binary() | epgsql:query_error(), pg_sock()) ->
  266. {noreply, pg_sock()}
  267. | {stop, any(), pg_sock()}.
  268. command_handle_message(Msg, Payload,
  269. #state{current_cmd = Command,
  270. current_cmd_state = CmdState} = State) ->
  271. case epgsql_command:handle_message(Command, Msg, Payload, State, CmdState) of
  272. {add_row, Row, State1, CmdState1} ->
  273. {noreply, add_row(State1#state{current_cmd_state = CmdState1}, Row)};
  274. {add_result, Result, Notice, State1, CmdState1} ->
  275. {noreply,
  276. add_result(State1#state{current_cmd_state = CmdState1},
  277. Notice, Result)};
  278. {finish, Result, Notice, State1} ->
  279. {noreply, finish(State1, Notice, Result)};
  280. {noaction, State1} ->
  281. {noreply, State1};
  282. {noaction, State1, CmdState1} ->
  283. {noreply, State1#state{current_cmd_state = CmdState1}};
  284. {requeue, State1, CmdState1} ->
  285. Transport = State1#state.current_cmd_transport,
  286. command_exec(Transport, Command, CmdState1,
  287. State1#state{current_cmd = undefined});
  288. {stop, Reason, Response, State1} ->
  289. {stop, Reason, finish(State1, Response)};
  290. {sync_required, Why} ->
  291. %% Protocol error. Finish and flush all pending commands.
  292. {noreply, sync_required(finish(State#state{sync_required = true}, Why))};
  293. unknown ->
  294. {stop, {error, {unexpected_message, Msg, Command, CmdState}}, State}
  295. end.
  296. command_next(#state{current_cmd = PrevCmd,
  297. queue = Q} = State) when PrevCmd =/= undefined ->
  298. case queue:out(Q) of
  299. {empty, _} ->
  300. State#state{current_cmd = undefined,
  301. current_cmd_state = undefined,
  302. current_cmd_transport = undefined,
  303. rows = [],
  304. results = []};
  305. {{value, {Command, CmdState, Transport}}, Q1} ->
  306. State#state{current_cmd = Command,
  307. current_cmd_state = CmdState,
  308. current_cmd_transport = Transport,
  309. queue = Q1,
  310. rows = [],
  311. results = []}
  312. end.
  313. setopts(#state{mod = Mod, sock = Sock}, Opts) ->
  314. case Mod of
  315. gen_tcp -> inet:setopts(Sock, Opts);
  316. ssl -> ssl:setopts(Sock, Opts)
  317. end.
  318. %% This one only used in connection initiation to send client's
  319. %% `StartupMessage' and `SSLRequest' packets
  320. -spec send(pg_sock(), iodata()) -> ok | {error, any()}.
  321. send(#state{mod = Mod, sock = Sock}, Data) ->
  322. do_send(Mod, Sock, epgsql_wire:encode_command(Data)).
  323. -spec send(pg_sock(), epgsql_wire:packet_type(), iodata()) -> ok | {error, any()}.
  324. send(#state{mod = Mod, sock = Sock}, Type, Data) ->
  325. do_send(Mod, Sock, epgsql_wire:encode_command(Type, Data)).
  326. -spec send_multi(pg_sock(), [{epgsql_wire:packet_type(), iodata()}]) -> ok | {error, any()}.
  327. send_multi(#state{mod = Mod, sock = Sock}, List) ->
  328. do_send(Mod, Sock, lists:map(fun({Type, Data}) ->
  329. epgsql_wire:encode_command(Type, Data)
  330. end, List)).
  331. do_send(gen_tcp, Sock, Bin) ->
  332. %% Why not gen_tcp:send/2?
  333. %% See https://github.com/rabbitmq/rabbitmq-common/blob/v3.7.4/src/rabbit_writer.erl#L367-L384
  334. %% Because of that we also have `handle_info({inet_reply, ...`
  335. try erlang:port_command(Sock, Bin) of
  336. true ->
  337. ok
  338. catch
  339. error:_Error ->
  340. {error, einval}
  341. end;
  342. do_send(ssl, Sock, Bin) ->
  343. ssl:send(Sock, Bin).
  344. loop(#state{data = Data, handler = Handler, subproto_state = Repl} = State) ->
  345. case epgsql_wire:decode_message(Data) of
  346. {Type, Payload, Tail} ->
  347. case ?MODULE:Handler(Type, Payload, State#state{data = Tail}) of
  348. {noreply, State2} ->
  349. loop(State2);
  350. R = {stop, _Reason2, _State2} ->
  351. R
  352. end;
  353. _ ->
  354. %% in replication mode send feedback after each batch of messages
  355. case Handler == on_replication
  356. andalso (Repl =/= undefined)
  357. andalso (Repl#repl.feedback_required) of
  358. true ->
  359. #repl{last_received_lsn = LastReceivedLSN,
  360. last_flushed_lsn = LastFlushedLSN,
  361. last_applied_lsn = LastAppliedLSN} = Repl,
  362. send(State, ?COPY_DATA, epgsql_wire:encode_standby_status_update(
  363. LastReceivedLSN, LastFlushedLSN, LastAppliedLSN)),
  364. {noreply, State#state{subproto_state = Repl#repl{feedback_required = false}}};
  365. _ ->
  366. {noreply, State}
  367. end
  368. end.
  369. finish(State, Result) ->
  370. finish(State, Result, Result).
  371. finish(State = #state{current_cmd_transport = Transport}, Notice, Result) ->
  372. reply(Transport, Notice, Result),
  373. command_next(State).
  374. reply({cast, From, Ref}, _, Result) ->
  375. From ! {self(), Ref, Result};
  376. reply({incremental, From, Ref}, Notice, _) ->
  377. From ! {self(), Ref, Notice};
  378. reply({call, From}, _, Result) ->
  379. gen_server:reply(From, Result).
  380. add_result(#state{results = Results, current_cmd_transport = Transport} = State, Notice, Result) ->
  381. Results2 = case Transport of
  382. {incremental, From, Ref} ->
  383. From ! {self(), Ref, Notice},
  384. Results;
  385. _ ->
  386. [Result | Results]
  387. end,
  388. State#state{rows = [],
  389. results = Results2}.
  390. add_row(#state{rows = Rows, current_cmd_transport = Transport} = State, Data) ->
  391. Rows2 = case Transport of
  392. {incremental, From, Ref} ->
  393. From ! {self(), Ref, {data, Data}},
  394. Rows;
  395. _ ->
  396. [Data | Rows]
  397. end,
  398. State#state{rows = Rows2}.
  399. notify(#state{current_cmd_transport = {incremental, From, Ref}} = State, Notice) ->
  400. From ! {self(), Ref, Notice},
  401. State;
  402. notify(State, _) ->
  403. State.
  404. %% Send asynchronous messages (notice / notification)
  405. notify_async(#state{async = undefined}, _) ->
  406. false;
  407. notify_async(#state{async = PidOrName}, Msg) ->
  408. try PidOrName ! {epgsql, self(), Msg} of
  409. _ -> true
  410. catch error:badarg ->
  411. %% no process registered under this name
  412. false
  413. end.
  414. sync_required(#state{current_cmd = epgsql_cmd_sync} = State) ->
  415. State;
  416. sync_required(#state{current_cmd = undefined} = State) ->
  417. State#state{sync_required = true};
  418. sync_required(State) ->
  419. sync_required(finish(State, {error, sync_required})).
  420. flush_queue(#state{current_cmd = undefined} = State, _) ->
  421. State;
  422. flush_queue(State, Error) ->
  423. flush_queue(finish(State, Error), Error).
  424. %% @doc Handler for IO protocol version of COPY FROM STDIN
  425. %%
  426. %% COPY FROM STDIN is implemented as Erlang
  427. %% <a href="https://erlang.org/doc/apps/stdlib/io_protocol.html">io protocol</a>.
  428. handle_io_request(_, #state{handler = Handler}) when Handler =/= on_copy_from_stdin ->
  429. %% Received IO request when `epgsql_cmd_copy_from_stdin' haven't yet been called or it was
  430. %% terminated with error and already sent `ReadyForQuery'
  431. {error, not_in_copy_mode};
  432. handle_io_request(_, #state{subproto_state = #copy{last_error = Err}}) when Err =/= undefined ->
  433. {error, Err};
  434. handle_io_request({put_chars, Encoding, Chars}, State) ->
  435. send(State, ?COPY_DATA, encode_chars(Encoding, Chars));
  436. handle_io_request({put_chars, Encoding, Mod, Fun, Args}, State) ->
  437. try apply(Mod, Fun, Args) of
  438. Chars when is_binary(Chars);
  439. is_list(Chars) ->
  440. handle_io_request({put_chars, Encoding, Chars}, State);
  441. Other ->
  442. {error, {fun_return_not_characters, Other}}
  443. catch T:R:S ->
  444. {error, {fun_exception, {T, R, S}}}
  445. end;
  446. handle_io_request({setopts, _}, _State) ->
  447. {error, request};
  448. handle_io_request(getopts, _State) ->
  449. {error, request};
  450. handle_io_request({requests, Requests}, State) ->
  451. try_requests(Requests, State, ok).
  452. try_requests([Req | Requests], State, _) ->
  453. case handle_io_request(Req, State) of
  454. {error, _} = Err ->
  455. Err;
  456. Other ->
  457. try_requests(Requests, State, Other)
  458. end;
  459. try_requests([], _, LastRes) ->
  460. LastRes.
  461. io_reply(Result, From, ReplyAs) ->
  462. From ! {io_reply, ReplyAs, Result}.
  463. encode_chars(_, Bin) when is_binary(Bin) ->
  464. Bin;
  465. encode_chars(unicode, Chars) when is_list(Chars) ->
  466. unicode:characters_to_binary(Chars);
  467. encode_chars(latin1, Chars) when is_list(Chars) ->
  468. unicode:characters_to_binary(Chars, latin1).
  469. to_binary(B) when is_binary(B) -> B;
  470. to_binary(L) when is_list(L) -> list_to_binary(L).
  471. %% -- backend message handling --
  472. %% CommandComplete
  473. on_message(?COMMAND_COMPLETE = Msg, Bin, State) ->
  474. Complete = epgsql_wire:decode_complete(Bin),
  475. command_handle_message(Msg, Bin, State#state{complete_status = Complete});
  476. %% ReadyForQuery
  477. on_message(?READY_FOR_QUERY = Msg, <<Status:8>> = Bin, State) ->
  478. command_handle_message(Msg, Bin, State#state{txstatus = Status});
  479. %% Error
  480. on_message(?ERROR = Msg, Err, #state{current_cmd = CurrentCmd} = State) ->
  481. Reason = epgsql_wire:decode_error(Err),
  482. case CurrentCmd of
  483. undefined ->
  484. %% Message generated by server asynchronously
  485. {stop, {shutdown, Reason}, State};
  486. _ ->
  487. command_handle_message(Msg, Reason, State)
  488. end;
  489. %% NoticeResponse
  490. on_message(?NOTICE, Data, State) ->
  491. notify_async(State, {notice, epgsql_wire:decode_error(Data)}),
  492. {noreply, State};
  493. %% ParameterStatus
  494. on_message(?PARAMETER_STATUS, Data, State) ->
  495. [Name, Value] = epgsql_wire:decode_strings(Data),
  496. Parameters2 = lists:keystore(Name, 1, State#state.parameters,
  497. {Name, Value}),
  498. {noreply, State#state{parameters = Parameters2}};
  499. %% NotificationResponse
  500. on_message(?NOTIFICATION, <<Pid:?int32, Strings/binary>>, State) ->
  501. {Channel1, Payload1} = case epgsql_wire:decode_strings(Strings) of
  502. [Channel, Payload] -> {Channel, Payload};
  503. [Channel] -> {Channel, <<>>}
  504. end,
  505. notify_async(State, {notification, Channel1, Pid, Payload1}),
  506. {noreply, State};
  507. %% ParseComplete
  508. %% ParameterDescription
  509. %% RowDescription
  510. %% NoData
  511. %% BindComplete
  512. %% CloseComplete
  513. %% DataRow
  514. %% PortalSuspended
  515. %% EmptyQueryResponse
  516. %% CopyData
  517. %% CopyBothResponse
  518. on_message(Msg, Payload, State) ->
  519. command_handle_message(Msg, Payload, State).
  520. %% @doc Handle "copy subprotocol" for COPY .. FROM STDIN
  521. %%
  522. %% Activated by `epgsql_cmd_copy_from_stdin', deactivated by `epgsql_cmd_copy_done' or error
  523. on_copy_from_stdin(?READY_FOR_QUERY, <<Status:8>>,
  524. #state{subproto_state = #copy{last_error = Err,
  525. initiator = Pid}} = State) when Err =/= undefined ->
  526. %% Reporting error from here and not from ?ERROR so it's easier to be in sync state
  527. Pid ! {epgsql, self(), {error, Err}},
  528. {noreply, State#state{subproto_state = undefined,
  529. handler = on_message,
  530. txstatus = Status}};
  531. on_copy_from_stdin(?ERROR, Err, #state{subproto_state = SubState} = State) ->
  532. Reason = epgsql_wire:decode_error(Err),
  533. {noreply, State#state{subproto_state = SubState#copy{last_error = Reason}}};
  534. on_copy_from_stdin(M, Data, Sock) when M == ?NOTICE;
  535. M == ?NOTIFICATION;
  536. M == ?PARAMETER_STATUS ->
  537. on_message(M, Data, Sock).
  538. %% CopyData for Replication mode
  539. on_replication(?COPY_DATA, <<?PRIMARY_KEEPALIVE_MESSAGE:8, LSN:?int64, _Timestamp:?int64, ReplyRequired:8>>,
  540. #state{subproto_state = #repl{last_flushed_lsn = LastFlushedLSN,
  541. last_applied_lsn = LastAppliedLSN,
  542. align_lsn = AlignLsn} = Repl} = State) ->
  543. Repl1 =
  544. case ReplyRequired of
  545. 1 when AlignLsn ->
  546. send(State, ?COPY_DATA,
  547. epgsql_wire:encode_standby_status_update(LSN, LSN, LSN)),
  548. Repl#repl{feedback_required = false,
  549. last_received_lsn = LSN, last_applied_lsn = LSN, last_flushed_lsn = LSN};
  550. 1 when not AlignLsn ->
  551. send(State, ?COPY_DATA,
  552. epgsql_wire:encode_standby_status_update(LSN, LastFlushedLSN, LastAppliedLSN)),
  553. Repl#repl{feedback_required = false,
  554. last_received_lsn = LSN};
  555. _ ->
  556. Repl#repl{feedback_required = true,
  557. last_received_lsn = LSN}
  558. end,
  559. {noreply, State#state{subproto_state = Repl1}};
  560. %% CopyData for Replication mode
  561. on_replication(?COPY_DATA, <<?X_LOG_DATA, StartLSN:?int64, EndLSN:?int64,
  562. _Timestamp:?int64, WALRecord/binary>>,
  563. #state{subproto_state = Repl} = State) ->
  564. Repl1 = handle_xlog_data(StartLSN, EndLSN, WALRecord, Repl),
  565. {noreply, State#state{subproto_state = Repl1}};
  566. on_replication(?ERROR, Err, State) ->
  567. Reason = epgsql_wire:decode_error(Err),
  568. {stop, {error, Reason}, State};
  569. on_replication(M, Data, Sock) when M == ?NOTICE;
  570. M == ?NOTIFICATION;
  571. M == ?PARAMETER_STATUS ->
  572. on_message(M, Data, Sock).
  573. handle_xlog_data(StartLSN, EndLSN, WALRecord, #repl{cbmodule = undefined,
  574. receiver = Receiver} = Repl) ->
  575. %% with async messages
  576. Receiver ! {epgsql, self(), {x_log_data, StartLSN, EndLSN, WALRecord}},
  577. Repl#repl{feedback_required = true,
  578. last_received_lsn = EndLSN};
  579. handle_xlog_data(StartLSN, EndLSN, WALRecord,
  580. #repl{cbmodule = CbModule, cbstate = CbState, receiver = undefined} = Repl) ->
  581. %% with callback method
  582. {ok, LastFlushedLSN, LastAppliedLSN, NewCbState} =
  583. epgsql:handle_x_log_data(CbModule, StartLSN, EndLSN, WALRecord, CbState),
  584. Repl#repl{feedback_required = true,
  585. last_received_lsn = EndLSN,
  586. last_flushed_lsn = LastFlushedLSN,
  587. last_applied_lsn = LastAppliedLSN,
  588. cbstate = NewCbState}.