epgsql_sock.erl 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. %%% Copyright (C) 2009 - Will Glozer. All rights reserved.
  2. %%% Copyright (C) 2011 - Anton Lebedevich. All rights reserved.
  3. -module(epgsql_sock).
  4. -behavior(gen_server).
  5. -export([start_link/0,
  6. close/1,
  7. get_parameter/2,
  8. cancel/1]).
  9. -export([handle_call/3, handle_cast/2, handle_info/2]).
  10. -export([init/1, code_change/3, terminate/2]).
  11. %% state callbacks
  12. -export([auth/2, initializing/2, on_message/2]).
  13. -include("epgsql.hrl").
  14. -include("epgsql_binary.hrl").
  15. %% Commands defined as per this page:
  16. %% http://www.postgresql.org/docs/9.2/static/protocol-message-formats.html
  17. %% Commands
  18. -define(BIND, $B).
  19. -define(CLOSE, $C).
  20. -define(DESCRIBE, $D).
  21. -define(EXECUTE, $E).
  22. -define(FLUSH, $H).
  23. -define(PASSWORD, $p).
  24. -define(PARSE, $P).
  25. -define(SIMPLEQUERY, $Q).
  26. -define(AUTHENTICATION_REQUEST, $R).
  27. -define(SYNC, $S).
  28. %% Parameters
  29. -define(PREPARED_STATEMENT, $S).
  30. -define(PORTAL, $P).
  31. %% Responses
  32. -define(PARSE_COMPLETE, $1).
  33. -define(BIND_COMPLETE, $2).
  34. -define(CLOSE_COMPLETE, $3).
  35. -define(NOTIFICATION, $A).
  36. -define(COMMAND_COMPLETE, $C).
  37. -define(DATA_ROW, $D).
  38. -define(EMPTY_QUERY, $I).
  39. -define(CANCELLATION_KEY, $K).
  40. -define(NO_DATA, $n).
  41. -define(NOTICE, $N).
  42. -define(PORTAL_SUSPENDED, $s).
  43. -define(PARAMETER_STATUS, $S).
  44. -define(PARAMETER_DESCRIPTION, $t).
  45. -define(ROW_DESCRIPTION, $T).
  46. -define(READY_FOR_QUERY, $Z).
  47. -record(state, {mod,
  48. sock,
  49. data = <<>>,
  50. backend,
  51. handler,
  52. codec,
  53. queue = queue:new(),
  54. async,
  55. parameters = [],
  56. types = [],
  57. columns = [],
  58. rows = [],
  59. results = [],
  60. batch = [],
  61. sync_required,
  62. txstatus}).
  63. %% -- client interface --
  64. start_link() ->
  65. gen_server:start_link(?MODULE, [], []).
  66. close(C) when is_pid(C) ->
  67. catch gen_server:cast(C, stop),
  68. ok.
  69. get_parameter(C, Name) ->
  70. gen_server:call(C, {get_parameter, to_binary(Name)}, infinity).
  71. cancel(S) ->
  72. gen_server:cast(S, cancel).
  73. %% -- gen_server implementation --
  74. init([]) ->
  75. {ok, #state{}}.
  76. handle_call({update_type_cache, TypeInfos}, _From, #state{codec = Codec} = State) ->
  77. Codec2 = epgsql_binary:update_type_cache(TypeInfos, Codec),
  78. {reply, ok, State#state{codec = Codec2}};
  79. handle_call({get_parameter, Name}, _From, State) ->
  80. Value1 = case lists:keysearch(Name, 1, State#state.parameters) of
  81. {value, {Name, Value}} -> Value;
  82. false -> undefined
  83. end,
  84. {reply, {ok, Value1}, State};
  85. handle_call(Command, From, State) ->
  86. #state{queue = Q} = State,
  87. Req = {{call, From}, Command},
  88. command(Command, State#state{queue = queue:in(Req, Q)}).
  89. handle_cast({{Method, From, Ref}, Command} = Req, State)
  90. when ((Method == cast) or (Method == incremental)),
  91. is_pid(From),
  92. is_reference(Ref) ->
  93. #state{queue = Q} = State,
  94. command(Command, State#state{queue = queue:in(Req, Q)});
  95. handle_cast(stop, State) ->
  96. {stop, normal, flush_queue(State, {error, closed})};
  97. handle_cast(cancel, State = #state{backend = {Pid, Key}}) ->
  98. {ok, {Addr, Port}} = inet:peername(State#state.sock),
  99. SockOpts = [{active, false}, {packet, raw}, binary],
  100. %% TODO timeout
  101. {ok, Sock} = gen_tcp:connect(Addr, Port, SockOpts),
  102. Msg = <<16:?int32, 80877102:?int32, Pid:?int32, Key:?int32>>,
  103. ok = gen_tcp:send(Sock, Msg),
  104. gen_tcp:close(Sock),
  105. {noreply, State}.
  106. handle_info({Closed, Sock}, #state{sock = Sock} = State)
  107. when Closed == tcp_closed; Closed == ssl_closed ->
  108. {stop, sock_closed, flush_queue(State, {error, sock_closed})};
  109. handle_info({Error, Sock, Reason}, #state{sock = Sock} = State)
  110. when Error == tcp_error; Error == ssl_error ->
  111. Why = {sock_error, Reason},
  112. {stop, Why, flush_queue(State, {error, Why})};
  113. handle_info({inet_reply, _, ok}, State) ->
  114. {noreply, State};
  115. handle_info({inet_reply, _, Status}, State) ->
  116. {stop, Status, flush_queue(State, {error, Status})};
  117. handle_info({_, Sock, Data2}, #state{data = Data, sock = Sock} = State) ->
  118. loop(State#state{data = <<Data/binary, Data2/binary>>}).
  119. terminate(_Reason, _State) ->
  120. %% TODO send termination msg, close socket ??
  121. ok.
  122. code_change(_OldVsn, State, _Extra) ->
  123. {ok, State}.
  124. %% -- internal functions --
  125. command(Command, State = #state{sync_required = true})
  126. when Command /= sync ->
  127. {noreply, finish(State, {error, sync_required})};
  128. command({connect, Host, Username, Password, Opts}, State) ->
  129. Timeout = proplists:get_value(timeout, Opts, 5000),
  130. Port = proplists:get_value(port, Opts, 5432),
  131. SockOpts = [{active, false}, {packet, raw}, binary, {nodelay, true}, {keepalive, true}],
  132. case gen_tcp:connect(Host, Port, SockOpts, Timeout) of
  133. {ok, Sock} ->
  134. %% Increase the buffer size. Following the recommendation in the inet man page:
  135. %%
  136. %% It is recommended to have val(buffer) >=
  137. %% max(val(sndbuf),val(recbuf)).
  138. {ok, [{recbuf, RecBufSize}, {sndbuf, SndBufSize}]} =
  139. inet:getopts(Sock, [recbuf, sndbuf]),
  140. inet:setopts(Sock, [{buffer, max(RecBufSize, SndBufSize)}]),
  141. State2 = case proplists:get_value(ssl, Opts) of
  142. T when T == true; T == required ->
  143. start_ssl(Sock, T, Opts, State);
  144. _ ->
  145. State#state{mod = gen_tcp, sock = Sock}
  146. end,
  147. Opts2 = ["user", 0, Username, 0],
  148. Opts3 = case proplists:get_value(database, Opts, undefined) of
  149. undefined -> Opts2;
  150. Database -> [Opts2 | ["database", 0, Database, 0]]
  151. end,
  152. send(State2, [<<196608:?int32>>, Opts3, 0]),
  153. Async = proplists:get_value(async, Opts, undefined),
  154. setopts(State2, [{active, true}]),
  155. put(username, Username),
  156. put(password, Password),
  157. {noreply,
  158. State2#state{handler = auth,
  159. async = Async}};
  160. {error, Reason} = Error ->
  161. {stop, Reason, finish(State, Error)}
  162. end;
  163. command({squery, Sql}, State) ->
  164. send(State, ?SIMPLEQUERY, [Sql, 0]),
  165. {noreply, State};
  166. %% TODO add fast_equery command that doesn't need parsed statement,
  167. %% uses default (text) column format,
  168. %% sends Describe after Bind to get RowDescription
  169. command({equery, Statement, Parameters}, #state{codec = Codec} = State) ->
  170. #statement{name = StatementName, columns = Columns} = Statement,
  171. Bin1 = epgsql_wire:encode_parameters(Parameters, Codec),
  172. Bin2 = epgsql_wire:encode_formats(Columns),
  173. send(State, ?BIND, ["", 0, StatementName, 0, Bin1, Bin2]),
  174. send(State, ?EXECUTE, ["", 0, <<0:?int32>>]),
  175. send(State, ?CLOSE, [?PREPARED_STATEMENT, StatementName, 0]),
  176. send(State, ?SYNC, []),
  177. {noreply, State};
  178. command({parse, Name, Sql, Types}, State) ->
  179. Bin = epgsql_wire:encode_types(Types, State#state.codec),
  180. send(State, ?PARSE, [Name, 0, Sql, 0, Bin]),
  181. send(State, ?DESCRIBE, [?PREPARED_STATEMENT, Name, 0]),
  182. send(State, ?FLUSH, []),
  183. {noreply, State};
  184. command({bind, Statement, PortalName, Parameters}, #state{codec = Codec} = State) ->
  185. #statement{name = StatementName, columns = Columns, types = Types} = Statement,
  186. Typed_Parameters = lists:zip(Types, Parameters),
  187. Bin1 = epgsql_wire:encode_parameters(Typed_Parameters, Codec),
  188. Bin2 = epgsql_wire:encode_formats(Columns),
  189. send(State, ?BIND, [PortalName, 0, StatementName, 0, Bin1, Bin2]),
  190. send(State, ?FLUSH, []),
  191. {noreply, State};
  192. command({execute, _Statement, PortalName, MaxRows}, State) ->
  193. send(State, ?EXECUTE, [PortalName, 0, <<MaxRows:?int32>>]),
  194. send(State, ?FLUSH, []),
  195. {noreply, State};
  196. command({execute_batch, Batch}, State) ->
  197. #state{mod = Mod, sock = Sock, codec = Codec} = State,
  198. BindExecute =
  199. lists:map(
  200. fun({Statement, Parameters}) ->
  201. #statement{name = StatementName,
  202. columns = Columns,
  203. types = Types} = Statement,
  204. Typed_Parameters = lists:zip(Types, Parameters),
  205. Bin1 = epgsql_wire:encode_parameters(Typed_Parameters, Codec),
  206. Bin2 = epgsql_wire:encode_formats(Columns),
  207. [epgsql_wire:encode(?BIND, [0, StatementName, 0,
  208. Bin1, Bin2]),
  209. epgsql_wire:encode(?EXECUTE, [0, <<0:?int32>>])]
  210. end,
  211. Batch),
  212. Sync = epgsql_wire:encode(?SYNC, []),
  213. do_send(Mod, Sock, [BindExecute, Sync]),
  214. {noreply, State};
  215. command({describe_statement, Name}, State) ->
  216. send(State, ?DESCRIBE, [?PREPARED_STATEMENT, Name, 0]),
  217. send(State, ?FLUSH, []),
  218. {noreply, State};
  219. command({describe_portal, Name}, State) ->
  220. send(State, ?DESCRIBE, [?PORTAL, Name, 0]),
  221. send(State, ?FLUSH, []),
  222. {noreply, State};
  223. command({close, Type, Name}, State) ->
  224. Type2 = case Type of
  225. statement -> ?PREPARED_STATEMENT;
  226. portal -> ?PORTAL
  227. end,
  228. send(State, ?CLOSE, [Type2, Name, 0]),
  229. send(State, ?FLUSH, []),
  230. {noreply, State};
  231. command(sync, State) ->
  232. send(State, ?SYNC, []),
  233. {noreply, State#state{sync_required = false}}.
  234. start_ssl(S, Flag, Opts, State) ->
  235. ok = gen_tcp:send(S, <<8:?int32, 80877103:?int32>>),
  236. Timeout = proplists:get_value(timeout, Opts, 5000),
  237. {ok, <<Code>>} = gen_tcp:recv(S, 1, Timeout),
  238. case Code of
  239. $S ->
  240. case ssl:connect(S, Opts, Timeout) of
  241. {ok, S2} -> State#state{mod = ssl, sock = S2};
  242. {error, Reason} -> exit({ssl_negotiation_failed, Reason})
  243. end;
  244. $N ->
  245. case Flag of
  246. true -> State;
  247. required -> exit(ssl_not_available)
  248. end
  249. end.
  250. setopts(#state{mod = Mod, sock = Sock}, Opts) ->
  251. case Mod of
  252. gen_tcp -> inet:setopts(Sock, Opts);
  253. ssl -> ssl:setopts(Sock, Opts)
  254. end.
  255. send(#state{mod = Mod, sock = Sock}, Data) ->
  256. do_send(Mod, Sock, epgsql_wire:encode(Data)).
  257. send(#state{mod = Mod, sock = Sock}, Type, Data) ->
  258. do_send(Mod, Sock, epgsql_wire:encode(Type, Data)).
  259. do_send(gen_tcp, Sock, Bin) ->
  260. try erlang:port_command(Sock, Bin) of
  261. true ->
  262. ok
  263. catch
  264. error:_Error ->
  265. {error,einval}
  266. end;
  267. do_send(Mod, Sock, Bin) ->
  268. Mod:send(Sock, Bin).
  269. loop(#state{data = Data, handler = Handler} = State) ->
  270. case epgsql_wire:decode_message(Data) of
  271. {Message, Tail} ->
  272. case ?MODULE:Handler(Message, State#state{data = Tail}) of
  273. {noreply, State2} ->
  274. loop(State2);
  275. R = {stop, _Reason2, _State2} ->
  276. R
  277. end;
  278. _ ->
  279. {noreply, State}
  280. end.
  281. finish(State, Result) ->
  282. finish(State, Result, Result).
  283. finish(State = #state{queue = Q}, Notice, Result) ->
  284. case queue:get(Q) of
  285. {{cast, From, Ref}, _} ->
  286. From ! {self(), Ref, Result};
  287. {{incremental, From, Ref}, _} ->
  288. From ! {self(), Ref, Notice};
  289. {{call, From}, _} ->
  290. gen_server:reply(From, Result)
  291. end,
  292. State#state{queue = queue:drop(Q),
  293. types = [],
  294. columns = [],
  295. rows = [],
  296. results = [],
  297. batch = []}.
  298. add_result(State, Notice, Result) ->
  299. #state{queue = Q, results = Results, batch = Batch} = State,
  300. Results2 = case queue:get(Q) of
  301. {{incremental, From, Ref}, _} ->
  302. From ! {self(), Ref, Notice},
  303. Results;
  304. _ ->
  305. [Result | Results]
  306. end,
  307. Batch2 = case Batch of
  308. [] -> [];
  309. _ -> tl(Batch)
  310. end,
  311. State#state{types = [],
  312. columns = [],
  313. rows = [],
  314. results = Results2,
  315. batch = Batch2}.
  316. add_row(State = #state{queue = Q, rows = Rows}, Data) ->
  317. Rows2 = case queue:get(Q) of
  318. {{incremental, From, Ref}, _} ->
  319. From ! {self(), Ref, {data, Data}},
  320. Rows;
  321. _ ->
  322. [Data | Rows]
  323. end,
  324. State#state{rows = Rows2}.
  325. notify(State = #state{queue = Q}, Notice) ->
  326. case queue:get(Q) of
  327. {{incremental, From, Ref}, _} ->
  328. From ! {self(), Ref, Notice};
  329. _ ->
  330. ignore
  331. end,
  332. State.
  333. notify_async(State = #state{async = Pid}, Msg) ->
  334. case is_pid(Pid) of
  335. true -> Pid ! {epgsql, self(), Msg};
  336. false -> false
  337. end,
  338. State.
  339. command_tag(#state{queue = Q}) ->
  340. {_, Req} = queue:get(Q),
  341. if is_tuple(Req) ->
  342. element(1, Req);
  343. is_atom(Req) ->
  344. Req
  345. end.
  346. get_columns(State) ->
  347. #state{queue = Q, columns = Columns, batch = Batch} = State,
  348. case queue:get(Q) of
  349. {_, {equery, #statement{columns = C}, _}} ->
  350. C;
  351. {_, {execute, #statement{columns = C}, _, _}} ->
  352. C;
  353. {_, {squery, _}} ->
  354. Columns;
  355. {_, {execute_batch, _}} ->
  356. [{#statement{columns = C}, _} | _] = Batch,
  357. C
  358. end.
  359. make_statement(State) ->
  360. #state{queue = Q, types = Types, columns = Columns} = State,
  361. Name = case queue:get(Q) of
  362. {_, {parse, N, _, _}} -> N;
  363. {_, {describe_statement, N}} -> N
  364. end,
  365. #statement{name = Name, types = Types, columns = Columns}.
  366. sync_required(#state{queue = Q} = State) ->
  367. case queue:is_empty(Q) of
  368. false ->
  369. case command_tag(State) of
  370. sync ->
  371. State;
  372. _ ->
  373. sync_required(finish(State, {error, sync_required}))
  374. end;
  375. true ->
  376. State#state{sync_required = true}
  377. end.
  378. flush_queue(#state{queue = Q} = State, Error) ->
  379. case queue:is_empty(Q) of
  380. false ->
  381. flush_queue(finish(State, Error), Error);
  382. true -> State
  383. end.
  384. to_binary(B) when is_binary(B) -> B;
  385. to_binary(L) when is_list(L) -> list_to_binary(L).
  386. hex(Bin) ->
  387. HChar = fun(N) when N < 10 -> $0 + N;
  388. (N) when N < 16 -> $W + N
  389. end,
  390. <<<<(HChar(H)), (HChar(L))>> || <<H:4, L:4>> <= Bin>>.
  391. %% -- backend message handling --
  392. %% AuthenticationOk
  393. auth({?AUTHENTICATION_REQUEST, <<0:?int32>>}, State) ->
  394. {noreply, State#state{handler = initializing}};
  395. %% AuthenticationCleartextPassword
  396. auth({?AUTHENTICATION_REQUEST, <<3:?int32>>}, State) ->
  397. send(State, ?PASSWORD, [get(password), 0]),
  398. {noreply, State};
  399. %% AuthenticationMD5Password
  400. auth({?AUTHENTICATION_REQUEST, <<5:?int32, Salt:4/binary>>}, State) ->
  401. Digest1 = hex(erlang:md5([get(password), get(username)])),
  402. Str = ["md5", hex(erlang:md5([Digest1, Salt])), 0],
  403. send(State, ?PASSWORD, Str),
  404. {noreply, State};
  405. auth({?AUTHENTICATION_REQUEST, <<M:?int32, _/binary>>}, State) ->
  406. Method = case M of
  407. 2 -> kerberosV5;
  408. 4 -> crypt;
  409. 6 -> scm;
  410. 7 -> gss;
  411. 8 -> sspi;
  412. _ -> unknown
  413. end,
  414. State2 = finish(State, {error, {unsupported_auth_method, Method}}),
  415. {stop, normal, State2};
  416. %% ErrorResponse
  417. auth({error, E}, State) ->
  418. Why = case E#error.code of
  419. <<"28000">> -> invalid_authorization_specification;
  420. <<"28P01">> -> invalid_password;
  421. Any -> Any
  422. end,
  423. {stop, normal, finish(State, {error, Why})};
  424. auth(Other, State) ->
  425. on_message(Other, State).
  426. %% BackendKeyData
  427. initializing({?CANCELLATION_KEY, <<Pid:?int32, Key:?int32>>}, State) ->
  428. {noreply, State#state{backend = {Pid, Key}}};
  429. %% ReadyForQuery
  430. initializing({?READY_FOR_QUERY, <<Status:8>>}, State) ->
  431. #state{parameters = Parameters} = State,
  432. erase(username),
  433. erase(password),
  434. %% TODO decode dates to now() format
  435. case lists:keysearch(<<"integer_datetimes">>, 1, Parameters) of
  436. {value, {_, <<"on">>}} -> put(datetime_mod, epgsql_idatetime);
  437. {value, {_, <<"off">>}} -> put(datetime_mod, epgsql_fdatetime)
  438. end,
  439. State2 = finish(State#state{handler = on_message,
  440. txstatus = Status,
  441. codec = epgsql_binary:new_codec([])},
  442. connected),
  443. {noreply, State2};
  444. initializing({error, _} = Error, State) ->
  445. {stop, normal, finish(State, Error)};
  446. initializing(Other, State) ->
  447. on_message(Other, State).
  448. %% ParseComplete
  449. on_message({?PARSE_COMPLETE, <<>>}, State) ->
  450. {noreply, State};
  451. %% ParameterDescription
  452. on_message({?PARAMETER_DESCRIPTION, <<_Count:?int16, Bin/binary>>}, State) ->
  453. Types = [epgsql_binary:oid2type(Oid, State#state.codec) || <<Oid:?int32>> <= Bin],
  454. State2 = notify(State#state{types = Types}, {types, Types}),
  455. {noreply, State2};
  456. %% RowDescription
  457. on_message({?ROW_DESCRIPTION, <<Count:?int16, Bin/binary>>}, State) ->
  458. Columns = epgsql_wire:decode_columns(Count, Bin, State#state.codec),
  459. Columns2 =
  460. case command_tag(State) of
  461. C when C == describe_portal; C == squery ->
  462. Columns;
  463. C when C == parse; C == describe_statement ->
  464. [Col#column{format = epgsql_wire:format(Col#column.type)}
  465. || Col <- Columns]
  466. end,
  467. State2 = State#state{columns = Columns2},
  468. Message = {columns, Columns2},
  469. State3 = case command_tag(State2) of
  470. squery ->
  471. notify(State2, Message);
  472. T when T == parse; T == describe_statement ->
  473. finish(State2, Message, {ok, make_statement(State2)});
  474. describe_portal ->
  475. finish(State2, Message, {ok, Columns})
  476. end,
  477. {noreply, State3};
  478. %% NoData
  479. on_message({?NO_DATA, <<>>}, State) ->
  480. State2 = case command_tag(State) of
  481. C when C == parse; C == describe_statement ->
  482. finish(State, no_data, {ok, make_statement(State)});
  483. describe_portal ->
  484. finish(State, no_data, {ok, []})
  485. end,
  486. {noreply, State2};
  487. %% BindComplete
  488. on_message({?BIND_COMPLETE, <<>>}, State) ->
  489. State2 = case command_tag(State) of
  490. equery ->
  491. %% TODO send Describe as a part of equery, needs text format support
  492. notify(State, {columns, get_columns(State)});
  493. bind ->
  494. finish(State, ok);
  495. execute_batch ->
  496. Batch =
  497. case State#state.batch of
  498. [] ->
  499. {_, {_, B}} = queue:get(State#state.queue),
  500. B;
  501. B -> B
  502. end,
  503. State#state{batch = Batch}
  504. end,
  505. {noreply, State2};
  506. %% CloseComplete
  507. on_message({?CLOSE_COMPLETE, <<>>}, State) ->
  508. State2 = case command_tag(State) of
  509. equery ->
  510. State;
  511. close ->
  512. finish(State, ok)
  513. end,
  514. {noreply, State2};
  515. %% DataRow
  516. on_message({?DATA_ROW, <<_Count:?int16, Bin/binary>>}, State) ->
  517. Data = epgsql_wire:decode_data(get_columns(State), Bin, State#state.codec),
  518. {noreply, add_row(State, Data)};
  519. %% PortalSuspended
  520. on_message({?PORTAL_SUSPENDED, <<>>}, State) ->
  521. State2 = finish(State,
  522. suspended,
  523. {partial, lists:reverse(State#state.rows)}),
  524. {noreply, State2};
  525. %% CommandComplete
  526. on_message({?COMMAND_COMPLETE, Bin}, State) ->
  527. Complete = epgsql_wire:decode_complete(Bin),
  528. Command = command_tag(State),
  529. Notice = {complete, Complete},
  530. Rows = lists:reverse(State#state.rows),
  531. State2 = case {Command, Complete, Rows} of
  532. {execute, {_, Count}, []} ->
  533. finish(State, Notice, {ok, Count});
  534. {execute, {_, Count}, _} ->
  535. finish(State, Notice, {ok, Count, Rows});
  536. {execute, _, _} ->
  537. finish(State, Notice, {ok, Rows});
  538. {execute_batch, {_, Count}, []} ->
  539. add_result(State, Notice, {ok, Count});
  540. {execute_batch, {_, Count}, _} ->
  541. add_result(State, Notice, {ok, Count, Rows});
  542. {execute_batch, _, _} ->
  543. add_result(State, Notice, {ok, Rows});
  544. {C, {_, Count}, []} when C == squery; C == equery ->
  545. add_result(State, Notice, {ok, Count});
  546. {C, {_, Count}, _} when C == squery; C == equery ->
  547. add_result(State, Notice, {ok, Count, get_columns(State), Rows});
  548. {C, _, _} when C == squery; C == equery ->
  549. add_result(State, Notice, {ok, get_columns(State), Rows})
  550. end,
  551. {noreply, State2};
  552. %% EmptyQueryResponse
  553. on_message({?EMPTY_QUERY, _Bin}, State) ->
  554. Notice = {complete, empty},
  555. State2 = case command_tag(State) of
  556. execute ->
  557. finish(State, Notice, {ok, [], []});
  558. C when C == squery; C == equery ->
  559. add_result(State, Notice, {ok, [], []})
  560. end,
  561. {noreply, State2};
  562. %% ReadyForQuery
  563. on_message({?READY_FOR_QUERY, <<Status:8>>}, State) ->
  564. State2 = case command_tag(State) of
  565. squery ->
  566. case State#state.results of
  567. [Result] ->
  568. finish(State, done, Result);
  569. Results ->
  570. finish(State, done, lists:reverse(Results))
  571. end;
  572. execute_batch ->
  573. finish(State, done, lists:reverse(State#state.results));
  574. equery ->
  575. case State#state.results of
  576. [Result] ->
  577. finish(State, done, Result);
  578. [] ->
  579. finish(State, done)
  580. end;
  581. sync ->
  582. finish(State, ok)
  583. end,
  584. {noreply, State2#state{txstatus = Status}};
  585. on_message(Error = {error, _}, State) ->
  586. State2 = case command_tag(State) of
  587. C when C == squery; C == equery; C == execute_batch ->
  588. add_result(State, Error, Error);
  589. _ ->
  590. sync_required(finish(State, Error))
  591. end,
  592. {noreply, State2};
  593. %% NoticeResponse
  594. on_message({?NOTICE, Data}, State) ->
  595. State2 = notify_async(State, {notice, epgsql_wire:decode_error(Data)}),
  596. {noreply, State2};
  597. %% ParameterStatus
  598. on_message({?PARAMETER_STATUS, Data}, State) ->
  599. [Name, Value] = epgsql_wire:decode_strings(Data),
  600. Parameters2 = lists:keystore(Name, 1, State#state.parameters,
  601. {Name, Value}),
  602. {noreply, State#state{parameters = Parameters2}};
  603. %% NotificationResponse
  604. on_message({?NOTIFICATION, <<Pid:?int32, Strings/binary>>}, State) ->
  605. {Channel1, Payload1} = case epgsql_wire:decode_strings(Strings) of
  606. [Channel, Payload] -> {Channel, Payload};
  607. [Channel] -> {Channel, <<>>}
  608. end,
  609. State2 = notify_async(State, {notification, Channel1, Pid, Payload1}),
  610. {noreply, State2}.