pgsql_sock.erl 22 KB

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