epgsql_sock.erl 30 KB

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