pgsql_connection.erl 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. %%% Copyright (C) 2008 - Will Glozer. All rights reserved.
  2. -module(pgsql_connection).
  3. -behavior(gen_fsm).
  4. -export([start_link/0, stop/1, connect/5, get_parameter/2]).
  5. -export([squery/2, equery/3]).
  6. -export([parse/4, bind/4, execute/4, describe/3]).
  7. -export([close/3, sync/1]).
  8. -export([init/1, handle_event/3, handle_sync_event/4]).
  9. -export([handle_info/3, terminate/3, code_change/4]).
  10. -export([read/3]).
  11. -export([startup/3, auth/2, initializing/2, ready/2, ready/3]).
  12. -export([querying/2, parsing/2, binding/2, describing/2]).
  13. -export([executing/2, closing/2, synchronizing/2]).
  14. -include("pgsql.hrl").
  15. -record(state, {
  16. reader,
  17. sock,
  18. parameters = [],
  19. reply,
  20. reply_to,
  21. backend,
  22. statement,
  23. txstatus}).
  24. -define(int16, 1/big-signed-unit:16).
  25. -define(int32, 1/big-signed-unit:32).
  26. %% -- client interface --
  27. start_link() ->
  28. gen_fsm:start_link(?MODULE, [], []).
  29. stop(C) ->
  30. gen_fsm:send_all_state_event(C, stop).
  31. connect(C, Host, Username, Password, Opts) ->
  32. gen_fsm:sync_send_event(C, {connect, Host, Username, Password, Opts}).
  33. get_parameter(C, Name) ->
  34. gen_fsm:sync_send_event(C, {get_parameter, to_binary(Name)}).
  35. squery(C, Sql) ->
  36. gen_fsm:sync_send_event(C, {squery, Sql}).
  37. equery(C, Statement, Parameters) ->
  38. gen_fsm:sync_send_event(C, {equery, Statement, Parameters}).
  39. parse(C, Name, Sql, Types) ->
  40. gen_fsm:sync_send_event(C, {parse, Name, Sql, Types}).
  41. bind(C, Statement, PortalName, Parameters) ->
  42. gen_fsm:sync_send_event(C, {bind, Statement, PortalName, Parameters}).
  43. execute(C, Statement, PortalName, MaxRows) ->
  44. gen_fsm:sync_send_event(C, {execute, Statement, PortalName, MaxRows}).
  45. describe(C, Type, Name) ->
  46. gen_fsm:sync_send_event(C, {describe, Type, Name}).
  47. close(C, Type, Name) ->
  48. gen_fsm:sync_send_event(C, {close, Type, Name}).
  49. sync(C) ->
  50. gen_fsm:sync_send_event(C, sync).
  51. %% -- gen_fsm implementation --
  52. init([]) ->
  53. process_flag(trap_exit, true),
  54. {ok, startup, #state{}}.
  55. handle_event({notice, Notice}, State_Name, State) ->
  56. notify(State, {notice, Notice}),
  57. {next_state, State_Name, State};
  58. handle_event({parameter_status, Name, Value}, State_Name, State) ->
  59. Parameters2 = lists:keystore(Name, 1, State#state.parameters, {Name, Value}),
  60. {next_state, State_Name, State#state{parameters = Parameters2}};
  61. handle_event(stop, _State_Name, State) ->
  62. {stop, normal, State};
  63. handle_event(Event, _State_Name, State) ->
  64. {stop, {unsupported_event, Event}, State}.
  65. handle_sync_event(Event, _From, _State_Name, State) ->
  66. {stop, {unsupported_sync_event, Event}, State}.
  67. handle_info({'EXIT', Pid, Reason}, _State_Name, State = #state{reader = Pid}) ->
  68. {stop, Reason, State};
  69. handle_info(Info, _State_Name, State) ->
  70. {stop, {unsupported_info, Info}, State}.
  71. terminate(_Reason, _State_Name, State = #state{sock = Sock})
  72. when Sock =/= undefined ->
  73. send(State, $X, []),
  74. gen_tcp:close(Sock);
  75. terminate(_Reason, _State_Name, _State) ->
  76. ok.
  77. code_change(_Old_Vsn, State_Name, State, _Extra) ->
  78. {ok, State_Name, State}.
  79. %% -- states --
  80. startup({connect, Host, Username, Password, Opts}, From, State) ->
  81. Port = proplists:get_value(port, Opts, 5432),
  82. Sock_Opts = [{active, false}, {packet, raw}, binary],
  83. case gen_tcp:connect(Host, Port, Sock_Opts) of
  84. {ok, Sock} ->
  85. Reader = spawn_link(?MODULE, read, [self(), Sock, <<>>]),
  86. Opts2 = ["user", 0, Username, 0],
  87. case proplists:get_value(database, Opts, undefined) of
  88. undefined -> Opts3 = Opts2;
  89. Database -> Opts3 = [Opts2 | ["database", 0, Database, 0]]
  90. end,
  91. put(username, Username),
  92. put(password, Password),
  93. State2 = State#state{reader = Reader,
  94. sock = Sock,
  95. reply_to = From},
  96. send(State2, [<<196608:32>>, Opts3, 0]),
  97. {next_state, auth, State2};
  98. Error ->
  99. {stop, normal, Error, State}
  100. end.
  101. %% AuthenticationOk
  102. auth({$R, <<0:?int32>>}, State) ->
  103. {next_state, initializing, State};
  104. %% AuthenticationCleartextPassword
  105. auth({$R, <<3:?int32>>}, State) ->
  106. send(State, $p, [get(password), 0]),
  107. {next_state, auth, State};
  108. %% AuthenticationMD5Password
  109. auth({$R, <<5:?int32, Salt:4/binary>>}, State) ->
  110. Digest1 = hex(erlang:md5([get(password), get(username)])),
  111. Str = ["md5", hex(erlang:md5([Digest1, Salt])), 0],
  112. send(State, $p, Str),
  113. {next_state, auth, State};
  114. auth({$R, <<M:?int32, _/binary>>}, State) ->
  115. case M of
  116. 2 -> Method = kerberosV5;
  117. 4 -> Method = crypt;
  118. 6 -> Method = scm;
  119. 7 -> Method = gss;
  120. 8 -> Method = sspi;
  121. _ -> Method = unknown
  122. end,
  123. Error = {error, {unsupported_auth_method, Method}},
  124. gen_fsm:reply(State#state.reply_to, Error),
  125. {stop, normal, State};
  126. %% ErrorResponse
  127. auth({$E, Bin}, State) ->
  128. Error = decode_error(Bin),
  129. case Error#error.code of
  130. <<"28000">> -> Why = invalid_authorization_specification;
  131. Any -> Why = Any
  132. end,
  133. gen_fsm:reply(State#state.reply_to, {error, Why}),
  134. {stop, normal, State}.
  135. %% BackendKeyData
  136. initializing({$K, <<Pid:?int32, Key:?int32>>}, State) ->
  137. State2 = State#state{backend = {Pid, Key}},
  138. {next_state, initializing, State2};
  139. %% ErrorResponse
  140. initializing({$E, Bin}, State) ->
  141. Error = decode_error(Bin),
  142. case Error#error.code of
  143. <<"28000">> -> Why = invalid_authorization_specification;
  144. Any -> Why = Any
  145. end,
  146. gen_fsm:reply(State#state.reply_to, {error, Why}),
  147. {stop, normal, State};
  148. %% ReadyForQuery
  149. initializing({$Z, <<Status:8>>}, State) ->
  150. erase(username),
  151. erase(password),
  152. gen_fsm:reply(State#state.reply_to, {ok, self()}),
  153. {next_state, ready, State#state{txstatus = Status}}.
  154. ready(_Msg, State) ->
  155. {next_state, ready, State}.
  156. %% execute simple query
  157. ready({squery, Sql}, From, State) ->
  158. send(State, $Q, [Sql, 0]),
  159. State2 = State#state{statement = #statement{}, reply_to = From},
  160. {reply, ok, querying, State2};
  161. %% execute extended query
  162. ready({equery, Statement, Parameters}, From, State) ->
  163. #statement{name = StatementName, columns = Columns} = Statement,
  164. Bin1 = encode_parameters(Parameters),
  165. Bin2 = encode_formats(Columns),
  166. send(State, $B, ["", 0, StatementName, 0, Bin1, Bin2]),
  167. send(State, $E, ["", 0, <<0:?int32>>]),
  168. send(State, $C, [$S, "", 0]),
  169. send(State, $S, []),
  170. State2 = State#state{statement = Statement, reply_to = From},
  171. {reply, ok, querying, State2};
  172. ready({get_parameter, Name}, _From, State) ->
  173. case lists:keysearch(Name, 1, State#state.parameters) of
  174. {value, {Name, Value}} -> Value;
  175. false -> Value = undefined
  176. end,
  177. {reply, {ok, Value}, ready, State};
  178. ready({parse, Name, Sql, Types}, From, State) ->
  179. Bin = encode_types(Types),
  180. send(State, $P, [Name, 0, Sql, 0, Bin]),
  181. send(State, $D, [$S, Name, 0]),
  182. send(State, $H, []),
  183. S = #statement{name = Name},
  184. {next_state, parsing, State#state{statement = S, reply_to = From}};
  185. ready({bind, Statement, PortalName, Parameters}, From, State) ->
  186. #statement{name = StatementName, columns = Columns, types = Types} = Statement,
  187. Typed_Parameters = lists:zip(Types, Parameters),
  188. Bin1 = encode_parameters(Typed_Parameters),
  189. Bin2 = encode_formats(Columns),
  190. send(State, $B, [PortalName, 0, StatementName, 0, Bin1, Bin2]),
  191. send(State, $H, []),
  192. {next_state, binding, State#state{statement = Statement, reply_to = From}};
  193. ready({execute, Statement, PortalName, MaxRows}, From, State) ->
  194. send(State, $E, [PortalName, 0, <<MaxRows:?int32>>]),
  195. send(State, $H, []),
  196. {reply, ok, executing, State#state{statement = Statement, reply_to = From}};
  197. ready({describe, Type, Name}, From, State) ->
  198. case Type of
  199. statement -> Type2 = $S;
  200. portal -> Type2 = $P
  201. end,
  202. send(State, $D, [Type2, Name, 0]),
  203. send(State, $H, []),
  204. {next_state, describing, State#state{reply_to = From}};
  205. ready({close, Type, Name}, From, State) ->
  206. case Type of
  207. statement -> Type2 = $S;
  208. portal -> Type2 = $P
  209. end,
  210. send(State, $C, [Type2, Name, 0]),
  211. send(State, $H, []),
  212. {next_state, closing, State#state{reply_to = From}};
  213. ready(sync, From, State) ->
  214. send(State, $S, []),
  215. {next_state, synchronizing, State#state{reply = ok, reply_to = From}}.
  216. %% BindComplete
  217. querying({$2, <<>>}, State) ->
  218. #state{statement = #statement{columns = Columns}} = State,
  219. notify(State, {columns, Columns}),
  220. {next_state, querying, State};
  221. %% CloseComplete
  222. querying({$3, <<>>}, State) ->
  223. {next_state, querying, State};
  224. %% RowDescription
  225. querying({$T, <<Count:?int16, Bin/binary>>}, State) ->
  226. Columns = decode_columns(Count, Bin),
  227. S2 = (State#state.statement)#statement{columns = Columns},
  228. notify(State, {columns, Columns}),
  229. {next_state, querying, State#state{statement = S2}};
  230. %% DataRow
  231. querying({$D, <<_Count:?int16, Bin/binary>>}, State) ->
  232. #state{statement = #statement{columns = Columns}} = State,
  233. Data = decode_data(Columns, Bin),
  234. notify(State, {data, Data}),
  235. {next_state, querying, State};
  236. %% CommandComplete
  237. querying({$C, Bin}, State) ->
  238. Complete = decode_complete(Bin),
  239. notify(State, {complete, Complete}),
  240. {next_state, querying, State};
  241. %% EmptyQueryResponse
  242. querying({$I, _Bin}, State) ->
  243. notify(State, {complete, empty}),
  244. {next_state, querying, State};
  245. %% ErrorResponse
  246. querying({$E, Bin}, State) ->
  247. Error = decode_error(Bin),
  248. notify(State, {error, Error}),
  249. {next_state, querying, State};
  250. %% ReadyForQuery
  251. querying({$Z, <<_Status:8>>}, State) ->
  252. notify(State, done),
  253. {next_state, ready, State#state{reply_to = undefined}}.
  254. %% ParseComplete
  255. parsing({$1, <<>>}, State) ->
  256. {next_state, describing, State};
  257. %% ErrorResponse
  258. parsing({$E, Bin}, State) ->
  259. Reply = {error, decode_error(Bin)},
  260. send(State, $S, []),
  261. {next_state, parsing, State#state{reply = Reply}};
  262. %% ReadyForQuery
  263. parsing({$Z, <<Status:8>>}, State) ->
  264. #state{reply = Reply, reply_to = Reply_To} = State,
  265. gen_fsm:reply(Reply_To, Reply),
  266. {next_state, ready, State#state{reply = undefined, txstatus = Status}}.
  267. %% BindComplete
  268. binding({$2, <<>>}, State) ->
  269. gen_fsm:reply(State#state.reply_to, ok),
  270. {next_state, ready, State};
  271. %% ErrorResponse
  272. binding({$E, Bin}, State) ->
  273. Reply = {error, decode_error(Bin)},
  274. send(State, $S, []),
  275. {next_state, binding, State#state{reply = Reply}};
  276. %% ReadyForQuery
  277. binding({$Z, <<Status:8>>}, State) ->
  278. #state{reply = Reply, reply_to = Reply_To} = State,
  279. gen_fsm:reply(Reply_To, Reply),
  280. {next_state, ready, State#state{reply = undefined, txstatus = Status}}.
  281. %% ParameterDescription
  282. describing({$t, <<_Count:?int16, Bin/binary>>}, State) ->
  283. Types = [pgsql_types:oid2type(Oid) || <<Oid:?int32>> <= Bin],
  284. S2 = (State#state.statement)#statement{types = Types},
  285. {next_state, describing, State#state{statement = S2}};
  286. %% RowDescription
  287. describing({$T, <<Count:?int16, Bin/binary>>}, State) ->
  288. Columns = decode_columns(Count, Bin),
  289. Columns2 = [C#column{format = format(C#column.type)} || C <- Columns],
  290. S2 = (State#state.statement)#statement{columns = Columns2},
  291. gen_fsm:reply(State#state.reply_to, {ok, S2}),
  292. {next_state, ready, State};
  293. %% NoData
  294. describing({$n, <<>>}, State) ->
  295. S2 = (State#state.statement)#statement{columns = []},
  296. gen_fsm:reply(State#state.reply_to, {ok, S2}),
  297. {next_state, ready, State};
  298. %% ErrorResponse
  299. describing({$E, Bin}, State) ->
  300. Reply = {error, decode_error(Bin)},
  301. send(State, $S, []),
  302. {next_state, describing, State#state{reply = Reply}};
  303. %% ReadyForQuery
  304. describing({$Z, <<Status:8>>}, State) ->
  305. #state{reply = Reply, reply_to = Reply_To} = State,
  306. gen_fsm:reply(Reply_To, Reply),
  307. {next_state, ready, State#state{reply = undefined, txstatus = Status}}.
  308. %% DataRow
  309. executing({$D, <<_Count:?int16, Bin/binary>>}, State) ->
  310. #state{statement = #statement{columns = Columns}} = State,
  311. Data = decode_data(Columns, Bin),
  312. notify(State, {data, Data}),
  313. {next_state, executing, State};
  314. %% PortalSuspended
  315. executing({$s, <<>>}, State) ->
  316. notify(State, suspended),
  317. {next_state, ready, State};
  318. %% CommandComplete
  319. executing({$C, Bin}, State) ->
  320. notify(State, {complete, decode_complete(Bin)}),
  321. {next_state, ready, State};
  322. %% EmptyQueryResponse
  323. executing({$I, _Bin}, State) ->
  324. notify(State, {complete, empty}),
  325. {next_state, ready, State};
  326. %% ErrorResponse
  327. executing({$E, Bin}, State) ->
  328. notify(State, {error, decode_error(Bin)}),
  329. {next_state, executing, State}.
  330. %% CloseComplete
  331. closing({$3, <<>>}, State) ->
  332. gen_fsm:reply(State#state.reply_to, ok),
  333. {next_state, ready, State};
  334. %% ErrorResponse
  335. closing({$E, Bin}, State) ->
  336. Error = {error, decode_error(Bin)},
  337. gen_fsm:reply(State#state.reply_to, Error),
  338. {next_state, ready, State}.
  339. %% ErrorResponse
  340. synchronizing({$E, Bin}, State) ->
  341. Reply = {error, decode_error(Bin)},
  342. {next_state, synchronizing, State#state{reply = Reply}};
  343. %% ReadyForQuery
  344. synchronizing({$Z, <<Status:8>>}, State) ->
  345. #state{reply = Reply, reply_to = Reply_To} = State,
  346. gen_fsm:reply(Reply_To, Reply),
  347. {next_state, ready, State#state{reply = undefined, txstatus = Status}}.
  348. %% -- internal functions --
  349. %% decode a single null-terminated string
  350. decode_string(Bin) ->
  351. decode_string(Bin, <<>>).
  352. decode_string(<<0, Rest/binary>>, Str) ->
  353. {Str, Rest};
  354. decode_string(<<C, Rest/binary>>, Str) ->
  355. decode_string(Rest, <<Str/binary, C>>).
  356. %% decode multiple null-terminated string
  357. decode_strings(Bin) ->
  358. decode_strings(Bin, []).
  359. decode_strings(<<>>, Acc) ->
  360. lists:reverse(Acc);
  361. decode_strings(Bin, Acc) ->
  362. {Str, Rest} = decode_string(Bin),
  363. decode_strings(Rest, [Str | Acc]).
  364. %% decode field
  365. decode_fields(Bin) ->
  366. decode_fields(Bin, []).
  367. decode_fields(<<0>>, Acc) ->
  368. Acc;
  369. decode_fields(<<Type:8, Rest/binary>>, Acc) ->
  370. {Str, Rest2} = decode_string(Rest),
  371. decode_fields(Rest2, [{Type, Str} | Acc]).
  372. %% decode data
  373. decode_data(Columns, Bin) ->
  374. decode_data(Columns, Bin, []).
  375. decode_data([], _Bin, Acc) ->
  376. list_to_tuple(lists:reverse(Acc));
  377. decode_data([_C | T], <<-1:?int32, Rest/binary>>, Acc) ->
  378. decode_data(T, Rest, [null | Acc]);
  379. decode_data([C | T], <<Len:?int32, Value:Len/binary, Rest/binary>>, Acc) ->
  380. case C of
  381. #column{type = Type, format = 1} -> Value2 = pgsql_binary:decode(Type, Value);
  382. #column{} -> Value2 = Value
  383. end,
  384. decode_data(T, Rest, [Value2 | Acc]).
  385. %% decode column information
  386. decode_columns(Count, Bin) ->
  387. decode_columns(Count, Bin, []).
  388. decode_columns(0, _Bin, Acc) ->
  389. lists:reverse(Acc);
  390. decode_columns(N, Bin, Acc) ->
  391. {Name, Rest} = decode_string(Bin),
  392. <<_Table_Oid:?int32, _Attrib_Num:?int16, Type_Oid:?int32,
  393. Size:?int16, Modifier:?int32, Format:?int16, Rest2/binary>> = Rest,
  394. Desc = #column{
  395. name = Name,
  396. type = pgsql_types:oid2type(Type_Oid),
  397. size = Size,
  398. modifier = Modifier,
  399. format = Format},
  400. decode_columns(N - 1, Rest2, [Desc | Acc]).
  401. %% decode command complete msg
  402. decode_complete(<<"SELECT", 0>>) -> select;
  403. decode_complete(<<"BEGIN", 0>>) -> 'begin';
  404. decode_complete(<<"ROLLBACK", 0>>) -> rollback;
  405. decode_complete(Bin) ->
  406. {Str, _} = decode_string(Bin),
  407. case string:tokens(binary_to_list(Str), " ") of
  408. ["INSERT", _Oid, Rows] -> {insert, list_to_integer(Rows)};
  409. ["UPDATE", Rows] -> {update, list_to_integer(Rows)};
  410. ["DELETE", Rows] -> {delete, list_to_integer(Rows)};
  411. ["MOVE", Rows] -> {move, list_to_integer(Rows)};
  412. ["FETCH", Rows] -> {fetch, list_to_integer(Rows)};
  413. [Type | _Rest] -> lower_atom(Type)
  414. end.
  415. %% decode ErrorResponse
  416. decode_error(Bin) ->
  417. Fields = decode_fields(Bin),
  418. Error = #error{
  419. severity = lower_atom(proplists:get_value($S, Fields)),
  420. code = proplists:get_value($C, Fields),
  421. message = proplists:get_value($M, Fields),
  422. extra = decode_error_extra(Fields)},
  423. Error.
  424. decode_error_extra(Fields) ->
  425. Types = [{$D, detail}, {$H, hint}, {$P, position}],
  426. decode_error_extra(Types, Fields, []).
  427. decode_error_extra([], _Fields, Extra) ->
  428. Extra;
  429. decode_error_extra([{Type, Name} | T], Fields, Extra) ->
  430. case proplists:get_value(Type, Fields) of
  431. undefined -> decode_error_extra(T, Fields, Extra);
  432. Value -> decode_error_extra(T, Fields, [{Name, Value} | Extra])
  433. end.
  434. %% encode types
  435. encode_types(Types) ->
  436. encode_types(Types, 0, <<>>).
  437. encode_types([], Count, Acc) ->
  438. <<Count:?int16, Acc/binary>>;
  439. encode_types([Type | T], Count, Acc) ->
  440. case Type of
  441. undefined -> Oid = 0;
  442. _Any -> Oid = pgsql_types:type2oid(Type)
  443. end,
  444. encode_types(T, Count + 1, <<Acc/binary, Oid:?int32>>).
  445. %% encode column formats
  446. encode_formats(Columns) ->
  447. encode_formats(Columns, 0, <<>>).
  448. encode_formats([], Count, Acc) ->
  449. <<Count:?int16, Acc/binary>>;
  450. encode_formats([#column{format = Format} | T], Count, Acc) ->
  451. encode_formats(T, Count + 1, <<Acc/binary, Format:?int16>>).
  452. format(Type) ->
  453. case pgsql_binary:supports(Type) of
  454. true -> 1;
  455. false -> 0
  456. end.
  457. %% encode parameters
  458. encode_parameters(Parameters) ->
  459. encode_parameters(Parameters, 0, <<>>, <<>>).
  460. encode_parameters([], Count, Formats, Values) ->
  461. <<Count:?int16, Formats/binary, Count:?int16, Values/binary>>;
  462. encode_parameters([P | T], Count, Formats, Values) ->
  463. {Format, Value} = encode_parameter(P),
  464. Formats2 = <<Formats/binary, Format:?int16>>,
  465. Values2 = <<Values/binary, Value/binary>>,
  466. encode_parameters(T, Count + 1, Formats2, Values2).
  467. %% encode parameter
  468. encode_parameter({Type, Value}) ->
  469. case pgsql_binary:encode(Type, Value) of
  470. Bin when is_binary(Bin) -> {1, Bin};
  471. {error, unsupported} -> {0, Value}
  472. end;
  473. encode_parameter(null) -> {1, pgsql_binary:encode(null, null)};
  474. encode_parameter(A) when is_atom(A) -> {0, encode_list(atom_to_list(A))};
  475. encode_parameter(B) when is_binary(B) -> {0, <<(byte_size(B)):?int32, B/binary>>};
  476. encode_parameter(I) when is_integer(I) -> {0, encode_list(integer_to_list(I))};
  477. encode_parameter(F) when is_float(F) -> {0, encode_list(float_to_list(F))};
  478. encode_parameter(L) when is_list(L) -> {0, encode_list(L)}.
  479. encode_list(L) ->
  480. Bin = list_to_binary(L),
  481. <<(byte_size(Bin)):?int32, Bin/binary>>.
  482. notify(#state{reply_to = {Pid, _Tag}}, Msg) ->
  483. Pid ! {pgsql, self(), Msg}.
  484. lower_atom(Str) when is_binary(Str) ->
  485. lower_atom(binary_to_list(Str));
  486. lower_atom(Str) when is_list(Str) ->
  487. list_to_atom(string:to_lower(Str)).
  488. to_binary(B) when is_binary(B) -> B;
  489. to_binary(L) when is_list(L) -> list_to_binary(L).
  490. hex(Bin) ->
  491. HChar = fun(N) when N < 10 -> $0 + N;
  492. (N) when N < 16 -> $W + N
  493. end,
  494. <<<<(HChar(H)), (HChar(L))>> || <<H:4, L:4>> <= Bin>>.
  495. %% send data to server
  496. send(#state{sock = Sock}, Type, Data) ->
  497. Bin = iolist_to_binary(Data),
  498. gen_tcp:send(Sock, <<Type:8, (byte_size(Bin) + 4):?int32, Bin/binary>>).
  499. send(#state{sock = Sock}, Data) ->
  500. Bin = iolist_to_binary(Data),
  501. gen_tcp:send(Sock, <<(byte_size(Bin) + 4):?int32, Bin/binary>>).
  502. %% -- socket read loop --
  503. read(Fsm, Sock, Tail) ->
  504. case gen_tcp:recv(Sock, 0) of
  505. {ok, Bin} -> decode(Fsm, Sock, <<Tail/binary, Bin/binary>>);
  506. Error -> exit(Error)
  507. end.
  508. decode(Fsm, Sock, <<Type:8, Len:?int32, Rest/binary>> = Bin) ->
  509. Len2 = Len - 4,
  510. case Rest of
  511. <<Data:Len2/binary, Tail/binary>> when Type == $N ->
  512. gen_fsm:send_all_state_event(Fsm, {notice, decode_error(Data)}),
  513. decode(Fsm, Sock, Tail);
  514. <<Data:Len2/binary, Tail/binary>> when Type == $S ->
  515. [Name, Value] = decode_strings(Data),
  516. gen_fsm:send_all_state_event(Fsm, {parameter_status, Name, Value}),
  517. decode(Fsm, Sock, Tail);
  518. <<Data:Len2/binary, Tail/binary>> ->
  519. gen_fsm:send_event(Fsm, {Type, Data}),
  520. decode(Fsm, Sock, Tail);
  521. _Other ->
  522. ?MODULE:read(Fsm, Sock, Bin)
  523. end;
  524. decode(Fsm, Sock, Bin) ->
  525. ?MODULE:read(Fsm, Sock, Bin).