pgsql_sock.erl 22 KB

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