mysql_protocol.erl 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  1. %% MySQL/OTP – MySQL client library for Erlang/OTP
  2. %% Copyright (C) 2014 Viktor Söderqvist
  3. %% 2017 Piotr Nosek, Michal Slaski
  4. %%
  5. %% This file is part of MySQL/OTP.
  6. %%
  7. %% MySQL/OTP is free software: you can redistribute it and/or modify it under
  8. %% the terms of the GNU Lesser General Public License as published by the Free
  9. %% Software Foundation, either version 3 of the License, or (at your option)
  10. %% any later version.
  11. %%
  12. %% This program is distributed in the hope that it will be useful, but WITHOUT
  13. %% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14. %% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  15. %% more details.
  16. %%
  17. %% You should have received a copy of the GNU Lesser General Public License
  18. %% along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. %% @doc This module implements parts of the MySQL client/server protocol.
  20. %%
  21. %% The protocol is described in the document "MySQL Internals" which can be
  22. %% found under "MySQL Documentation: Expert Guides" on http://dev.mysql.com/.
  23. %%
  24. %% TCP communication is not handled in this module. Most of the public functions
  25. %% take funs for data communitaction as parameters.
  26. %% @private
  27. -module(mysql_protocol).
  28. -export([handshake/7, quit/2, ping/2,
  29. query/4, fetch_query_response/3,
  30. prepare/3, unprepare/3, execute/5, fetch_execute_response/3]).
  31. %% How much data do we want per packet?
  32. -define(MAX_BYTES_PER_PACKET, 16#1000000).
  33. -include("records.hrl").
  34. -include("protocol.hrl").
  35. -include("server_status.hrl").
  36. %% Macros for pattern matching on packets.
  37. -define(ok_pattern, <<?OK, _/binary>>).
  38. -define(error_pattern, <<?ERROR, _/binary>>).
  39. -define(eof_pattern, <<?EOF, _:4/binary>>).
  40. %% @doc Performs a handshake using the supplied functions for communication.
  41. %% Returns an ok or an error record. Raises errors when various unimplemented
  42. %% features are requested.
  43. -spec handshake(Username :: iodata(), Password :: iodata(),
  44. Database :: iodata() | undefined,
  45. SockModule :: module(), SSLOpts :: list() | undefined,
  46. Socket :: term(),
  47. SetFoundRows :: boolean()) ->
  48. {ok, #handshake{}, SockModule :: module(), Socket :: term()} |
  49. #error{}.
  50. handshake(Username, Password, Database, SockModule0, SSLOpts, Socket0,
  51. SetFoundRows) ->
  52. SeqNum0 = 0,
  53. {ok, HandshakePacket, SeqNum1} = recv_packet(SockModule0, Socket0, SeqNum0),
  54. case parse_handshake(HandshakePacket) of
  55. #handshake{} = Handshake ->
  56. {ok, SockModule, Socket, SeqNum2} =
  57. maybe_do_ssl_upgrade(SockModule0, Socket0, SeqNum1, Handshake,
  58. SSLOpts, Database, SetFoundRows),
  59. Response = build_handshake_response(Handshake, Username, Password,
  60. Database, SetFoundRows),
  61. {ok, SeqNum3} = send_packet(SockModule, Socket, Response, SeqNum2),
  62. handshake_finish_or_switch_auth(Handshake, Password, SockModule,
  63. Socket, SeqNum3);
  64. #error{} = Error ->
  65. Error
  66. end.
  67. handshake_finish_or_switch_auth(Handshake = #handshake{status = Status}, Password,
  68. SockModule, Socket, SeqNum0) ->
  69. {ok, ConfirmPacket, SeqNum1} = recv_packet(SockModule, Socket, SeqNum0),
  70. case parse_handshake_confirm(ConfirmPacket) of
  71. #ok{status = OkStatus} ->
  72. %% check status, ignoring bit 16#4000, SERVER_SESSION_STATE_CHANGED.
  73. Status = OkStatus band bnot 16#4000,
  74. {ok, Handshake, SockModule, Socket};
  75. #auth_method_switch{auth_plugin_name = AuthPluginName,
  76. auth_plugin_data = AuthPluginData} ->
  77. Hash = case AuthPluginName of
  78. <<>> ->
  79. hash_password(Password, AuthPluginData);
  80. <<"mysql_native_password">> ->
  81. hash_password(Password, AuthPluginData);
  82. UnknownAuthMethod ->
  83. error({auth_method, UnknownAuthMethod})
  84. end,
  85. {ok, SeqNum2} = send_packet(SockModule, Socket, Hash, SeqNum1),
  86. handshake_finish_or_switch_auth(Handshake, Password, SockModule,
  87. Socket, SeqNum2);
  88. Error ->
  89. Error
  90. end.
  91. -spec quit(atom(), term()) -> ok.
  92. quit(SockModule, Socket) ->
  93. {ok, SeqNum1} = send_packet(SockModule, Socket, <<?COM_QUIT>>, 0),
  94. case recv_packet(SockModule, Socket, SeqNum1) of
  95. {error, closed} -> ok; %% MySQL 5.5.40 and more
  96. {ok, ?ok_pattern, _SeqNum2} -> ok %% Some older MySQL versions?
  97. end.
  98. -spec ping(atom(), term()) -> #ok{}.
  99. ping(SockModule, Socket) ->
  100. {ok, SeqNum1} = send_packet(SockModule, Socket, <<?COM_PING>>, 0),
  101. {ok, OkPacket, _SeqNum2} = recv_packet(SockModule, Socket, SeqNum1),
  102. parse_ok_packet(OkPacket).
  103. -spec query(Query :: iodata(), atom(), term(), timeout()) ->
  104. {ok, [#ok{} | #resultset{} | #error{}]} | {error, timeout}.
  105. query(Query, SockModule, Socket, Timeout) ->
  106. Req = <<?COM_QUERY, (iolist_to_binary(Query))/binary>>,
  107. SeqNum0 = 0,
  108. {ok, _SeqNum1} = send_packet(SockModule, Socket, Req, SeqNum0),
  109. fetch_query_response(SockModule, Socket, Timeout).
  110. %% @doc This is used by query/4. If query/4 returns {error, timeout}, this
  111. %% function can be called to retry to fetch the results of the query.
  112. fetch_query_response(SockModule, Socket, Timeout) ->
  113. fetch_response(SockModule, Socket, Timeout, text, []).
  114. %% @doc Prepares a statement.
  115. -spec prepare(iodata(), atom(), term()) -> #error{} | #prepared{}.
  116. prepare(Query, SockModule, Socket) ->
  117. Req = <<?COM_STMT_PREPARE, (iolist_to_binary(Query))/binary>>,
  118. {ok, SeqNum1} = send_packet(SockModule, Socket, Req, 0),
  119. {ok, Resp, SeqNum2} = recv_packet(SockModule, Socket, SeqNum1),
  120. case Resp of
  121. ?error_pattern ->
  122. parse_error_packet(Resp);
  123. <<?OK,
  124. StmtId:32/little,
  125. NumColumns:16/little,
  126. NumParams:16/little,
  127. 0, %% reserved_1 -- [00] filler
  128. WarningCount:16/little>> ->
  129. %% This was the first packet.
  130. %% Now: Parameter Definition Block. The parameter definitions don't
  131. %% contain any useful data at all. They are always TYPE_VAR_STRING
  132. %% with charset 'binary' so we have to select a type ourselves for
  133. %% the parameters we have in execute/4.
  134. {_ParamDefs, SeqNum3} =
  135. fetch_column_definitions_if_any(NumParams, SockModule, Socket,
  136. SeqNum2),
  137. %% Column Definition Block. We get column definitions in execute
  138. %% too, so we don't need them here. We *could* store them to be able
  139. %% to provide the user with some info about a prepared statement.
  140. {_ColDefs, _SeqNum4} =
  141. fetch_column_definitions_if_any(NumColumns, SockModule, Socket,
  142. SeqNum3),
  143. #prepared{statement_id = StmtId,
  144. orig_query = Query,
  145. param_count = NumParams,
  146. warning_count = WarningCount}
  147. end.
  148. %% @doc Deallocates a prepared statement.
  149. -spec unprepare(#prepared{}, atom(), term()) -> ok.
  150. unprepare(#prepared{statement_id = Id}, SockModule, Socket) ->
  151. {ok, _SeqNum} = send_packet(SockModule, Socket,
  152. <<?COM_STMT_CLOSE, Id:32/little>>, 0),
  153. ok.
  154. %% @doc Executes a prepared statement.
  155. -spec execute(#prepared{}, [term()], atom(), term(), timeout()) ->
  156. {ok, [#ok{} | #resultset{} | #error{}]} | {error, timeout}.
  157. execute(#prepared{statement_id = Id, param_count = ParamCount}, ParamValues,
  158. SockModule, Socket, Timeout) when ParamCount == length(ParamValues) ->
  159. %% Flags Constant Name
  160. %% 0x00 CURSOR_TYPE_NO_CURSOR
  161. %% 0x01 CURSOR_TYPE_READ_ONLY
  162. %% 0x02 CURSOR_TYPE_FOR_UPDATE
  163. %% 0x04 CURSOR_TYPE_SCROLLABLE
  164. Flags = 0,
  165. Req0 = <<?COM_STMT_EXECUTE, Id:32/little, Flags, 1:32/little>>,
  166. Req = case ParamCount of
  167. 0 ->
  168. Req0;
  169. _ ->
  170. %% We can't use the parameter types returned by the prepare call.
  171. %% They are all reported as ?TYPE_VAR_STRING with character
  172. %% set 'binary'.
  173. NullBitMap = build_null_bitmap(ParamValues),
  174. %% What does it mean to *not* bind new params? To use the same
  175. %% params as last time? Right now we always bind params each time.
  176. NewParamsBoundFlag = 1,
  177. Req1 = <<Req0/binary, NullBitMap/binary, NewParamsBoundFlag>>,
  178. %% For each value, first append type and signedness (16#80 signed or
  179. %% 00 unsigned) for all values and then the binary encoded values.
  180. EncodedParams = lists:map(fun encode_param/1, ParamValues),
  181. {TypesAndSigns, EncValues} = lists:unzip(EncodedParams),
  182. iolist_to_binary([Req1, TypesAndSigns, EncValues])
  183. end,
  184. {ok, _SeqNum1} = send_packet(SockModule, Socket, Req, 0),
  185. fetch_execute_response(SockModule, Socket, Timeout).
  186. %% @doc This is used by execute/5. If execute/5 returns {error, timeout}, this
  187. %% function can be called to retry to fetch the results of the query.
  188. fetch_execute_response(SockModule, Socket, Timeout) ->
  189. fetch_response(SockModule, Socket, Timeout, binary, []).
  190. %% --- internal ---
  191. %% @doc Parses a handshake. This is the first thing that comes from the server
  192. %% when connecting. If an unsupported version or variant of the protocol is used
  193. %% an error is raised.
  194. -spec parse_handshake(binary()) -> #handshake{} | #error{}.
  195. parse_handshake(<<10, Rest/binary>>) ->
  196. %% Protocol version 10.
  197. {ServerVersion, Rest1} = nulterm_str(Rest),
  198. <<ConnectionId:32/little,
  199. AuthPluginDataPart1:8/binary-unit:8,
  200. 0, %% "filler" -- everything below is optional
  201. CapabilitiesLower:16/little,
  202. CharacterSet:8,
  203. StatusFlags:16/little,
  204. CapabilitiesUpper:16/little,
  205. AuthPluginDataLength:8, %% if cabab & CLIENT_PLUGIN_AUTH, otherwise 0
  206. _Reserved:10/binary-unit:8, %% 10 unused (reserved) bytes
  207. Rest3/binary>> = Rest1,
  208. Capabilities = CapabilitiesLower + 16#10000 * CapabilitiesUpper,
  209. Len = case AuthPluginDataLength of
  210. 0 -> 13; %% Server has not CLIENT_PLUGIN_AUTH
  211. K -> K - 8 %% Part 2 length = Total length minus the 8 bytes in part 1.
  212. end,
  213. <<AuthPluginDataPart2:Len/binary-unit:8, AuthPluginName/binary>> = Rest3,
  214. AuthPluginData = <<AuthPluginDataPart1/binary, AuthPluginDataPart2/binary>>,
  215. %% "Due to Bug#59453 the auth-plugin-name is missing the terminating
  216. %% NUL-char in versions prior to 5.5.10 and 5.6.2."
  217. %% Strip the final NUL byte if any.
  218. %% This may also be <<>> in older versions.
  219. L = byte_size(AuthPluginName) - 1,
  220. AuthPluginName1 = case AuthPluginName of
  221. <<AuthPluginNameTrimmed:L/binary, 0>> -> AuthPluginNameTrimmed;
  222. _ -> AuthPluginName
  223. end,
  224. #handshake{server_version = server_version_to_list(ServerVersion),
  225. connection_id = ConnectionId,
  226. capabilities = Capabilities,
  227. character_set = CharacterSet,
  228. status = StatusFlags,
  229. auth_plugin_data = AuthPluginData,
  230. auth_plugin_name = AuthPluginName1};
  231. parse_handshake(Packet = ?error_pattern) ->
  232. %% 'Too many connections' in MariaDB 10.1.21
  233. parse_error_packet(Packet);
  234. parse_handshake(<<Protocol:8, _/binary>>) when Protocol /= 10 ->
  235. error(unknown_protocol).
  236. %% @doc Converts a version on the form `<<"5.6.21">' to a list `[5, 6, 21]'.
  237. -spec server_version_to_list(binary()) -> [integer()].
  238. server_version_to_list(ServerVersion) ->
  239. %% This must work with e.g. "5.5.40-0ubuntu0.12.04.1-log" and "5.5.33a".
  240. {match, Parts} = re:run(ServerVersion, <<"^(\\d+)\\.(\\d+)\\.(\\d+)">>,
  241. [{capture, all_but_first, binary}]),
  242. lists:map(fun binary_to_integer/1, Parts).
  243. -spec maybe_do_ssl_upgrade(SockModule0 :: module(),
  244. Socket0 :: term(),
  245. SeqNum1 :: non_neg_integer(),
  246. Handshake :: #handshake{},
  247. SSLOpts :: undefined | list(),
  248. Database :: iodata() | undefined,
  249. SetFoundRows :: boolean()) ->
  250. {ok, SockModule :: module(), Socket :: term(),
  251. SeqNum2 :: non_neg_integer()}.
  252. maybe_do_ssl_upgrade(SockModule0, Socket0, SeqNum1, _Handshake, undefined,
  253. _Database, _SetFoundRows) ->
  254. {ok, SockModule0, Socket0, SeqNum1};
  255. maybe_do_ssl_upgrade(SockModule0, Socket0, SeqNum1, Handshake, SSLOpts,
  256. Database, SetFoundRows) ->
  257. Response = build_handshake_response(Handshake, Database, SetFoundRows),
  258. {ok, SeqNum2} = send_packet(SockModule0, Socket0, Response, SeqNum1),
  259. case mysql_sock_ssl:connect(Socket0, SSLOpts, 5000) of
  260. {ok, SSLSocket} ->
  261. {ok, ssl, SSLSocket, SeqNum2};
  262. {error, Reason} ->
  263. exit({failed_to_upgrade_socket, Reason})
  264. end.
  265. %% @doc This function is used when upgrading to encrypted socket. In other,
  266. %% cases, build_handshake_response/5 is used.
  267. -spec build_handshake_response(#handshake{}, iodata() | undefined, boolean()) ->
  268. binary().
  269. build_handshake_response(Handshake, Database, SetFoundRows) ->
  270. CapabilityFlags = basic_capabilities(Database /= undefined, SetFoundRows),
  271. verify_server_capabilities(Handshake, CapabilityFlags),
  272. ClientCapabilities = add_client_capabilities(CapabilityFlags),
  273. ClientSSLCapabilities = ClientCapabilities bor ?CLIENT_SSL,
  274. CharacterSet = ?UTF8,
  275. <<ClientSSLCapabilities:32/little,
  276. ?MAX_BYTES_PER_PACKET:32/little,
  277. CharacterSet:8,
  278. 0:23/unit:8>>.
  279. %% @doc The response sent by the client to the server after receiving the
  280. %% initial handshake from the server
  281. -spec build_handshake_response(#handshake{}, iodata(), iodata(),
  282. iodata() | undefined, boolean()) -> binary().
  283. build_handshake_response(Handshake, Username, Password, Database,
  284. SetFoundRows) ->
  285. CapabilityFlags = basic_capabilities(Database /= undefined, SetFoundRows),
  286. verify_server_capabilities(Handshake, CapabilityFlags),
  287. %% Add some extra capability flags only for signalling to the server what
  288. %% the client wants to do. The server doesn't say it handles them although
  289. %% it does. (http://bugs.mysql.com/bug.php?id=42268)
  290. ClientCapabilityFlags = add_client_capabilities(CapabilityFlags),
  291. Hash = case Handshake#handshake.auth_plugin_name of
  292. <<>> ->
  293. %% Server doesn't know auth plugins
  294. hash_password(Password, Handshake#handshake.auth_plugin_data);
  295. <<"mysql_native_password">> ->
  296. hash_password(Password, Handshake#handshake.auth_plugin_data);
  297. UnknownAuthMethod ->
  298. error({auth_method, UnknownAuthMethod})
  299. end,
  300. HashLength = size(Hash),
  301. CharacterSet = ?UTF8,
  302. UsernameUtf8 = unicode:characters_to_binary(Username),
  303. DbBin = case Database of
  304. undefined -> <<>>;
  305. _ -> <<(iolist_to_binary(Database))/binary, 0>>
  306. end,
  307. <<ClientCapabilityFlags:32/little,
  308. ?MAX_BYTES_PER_PACKET:32/little,
  309. CharacterSet:8,
  310. 0:23/unit:8, %% reserverd
  311. UsernameUtf8/binary,
  312. 0, %% NUL-terminator for the username
  313. HashLength,
  314. Hash/binary,
  315. DbBin/binary>>.
  316. -spec verify_server_capabilities(Handshake :: #handshake{},
  317. CapabilityFlags :: integer()) ->
  318. true | no_return().
  319. verify_server_capabilities(Handshake, CapabilityFlags) ->
  320. %% We require these capabilities. Make sure the server handles them.
  321. Handshake#handshake.capabilities band CapabilityFlags == CapabilityFlags
  322. orelse error(old_server_version).
  323. -spec basic_capabilities(ConnectWithDB :: boolean(),
  324. SetFoundRows :: boolean()) -> integer().
  325. basic_capabilities(ConnectWithDB, SetFoundRows) ->
  326. CapabilityFlags0 = ?CLIENT_PROTOCOL_41 bor
  327. ?CLIENT_TRANSACTIONS bor
  328. ?CLIENT_SECURE_CONNECTION,
  329. CapabilityFlags1 = case ConnectWithDB of
  330. true -> CapabilityFlags0 bor ?CLIENT_CONNECT_WITH_DB;
  331. _ -> CapabilityFlags0
  332. end,
  333. case SetFoundRows of
  334. true -> CapabilityFlags1 bor ?CLIENT_FOUND_ROWS;
  335. _ -> CapabilityFlags1
  336. end.
  337. -spec add_client_capabilities(Caps :: integer()) -> integer().
  338. add_client_capabilities(Caps) ->
  339. Caps bor
  340. ?CLIENT_MULTI_STATEMENTS bor
  341. ?CLIENT_MULTI_RESULTS bor
  342. ?CLIENT_PS_MULTI_RESULTS.
  343. %% @doc Handles the second packet from the server, when we have replied to the
  344. %% initial handshake. Returns an error if the server returns an error. Raises
  345. %% an error if unimplemented features are required.
  346. -spec parse_handshake_confirm(binary()) -> #ok{} | #auth_method_switch{} |
  347. #error{}.
  348. parse_handshake_confirm(Packet) ->
  349. case Packet of
  350. ?ok_pattern ->
  351. %% Connection complete.
  352. parse_ok_packet(Packet);
  353. ?error_pattern ->
  354. %% Access denied, insufficient client capabilities, etc.
  355. parse_error_packet(Packet);
  356. <<?EOF>> ->
  357. %% "Old Authentication Method Switch Request Packet consisting of a
  358. %% single 0xfe byte. It is sent by server to request client to
  359. %% switch to Old Password Authentication if CLIENT_PLUGIN_AUTH
  360. %% capability is not supported (by either the client or the server)"
  361. error(old_auth);
  362. <<?EOF, AuthMethodSwitch/binary>> ->
  363. %% "Authentication Method Switch Request Packet. If both server and
  364. %% client support CLIENT_PLUGIN_AUTH capability, server can send
  365. %% this packet to ask client to use another authentication method."
  366. parse_auth_method_switch(AuthMethodSwitch)
  367. end.
  368. %% -- both text and binary protocol --
  369. %% @doc Fetches one or more results and and parses the result set(s) using
  370. %% either the text format (for plain queries) or the binary format (for
  371. %% prepared statements).
  372. -spec fetch_response(atom(), term(), timeout(), text | binary, list()) ->
  373. {ok, [#ok{} | #resultset{} | #error{}]} | {error, timeout}.
  374. fetch_response(SockModule, Socket, Timeout, Proto, Acc) ->
  375. case recv_packet(SockModule, Socket, Timeout, any) of
  376. {ok, Packet, SeqNum2} ->
  377. Result = case Packet of
  378. ?ok_pattern ->
  379. parse_ok_packet(Packet);
  380. ?error_pattern ->
  381. parse_error_packet(Packet);
  382. ResultPacket ->
  383. %% The first packet in a resultset is only the column count.
  384. {ColCount, <<>>} = lenenc_int(ResultPacket),
  385. R0 = fetch_resultset(SockModule, Socket, ColCount, SeqNum2),
  386. case R0 of
  387. #error{} = E ->
  388. %% TODO: Find a way to get here + testcase
  389. E;
  390. #resultset{} = R ->
  391. parse_resultset(R, ColCount, Proto)
  392. end
  393. end,
  394. Acc1 = [Result | Acc],
  395. case more_results_exists(Result) of
  396. true ->
  397. fetch_response(SockModule, Socket, Timeout, Proto, Acc1);
  398. false ->
  399. {ok, lists:reverse(Acc1)}
  400. end;
  401. {error, timeout} ->
  402. {error, timeout}
  403. end.
  404. %% @doc Fetches packets for a result set. The column definitions are parsed but
  405. %% the rows are unparsed binary packages. This function is used for both the
  406. %% text protocol and the binary protocol. This affects the way the rows need to
  407. %% be parsed.
  408. -spec fetch_resultset(atom(), term(), integer(), integer()) ->
  409. #resultset{} | #error{}.
  410. fetch_resultset(SockModule, Socket, FieldCount, SeqNum) ->
  411. {ok, ColDefs, SeqNum1} = fetch_column_definitions(SockModule, Socket,
  412. SeqNum, FieldCount, []),
  413. {ok, DelimiterPacket, SeqNum2} = recv_packet(SockModule, Socket, SeqNum1),
  414. #eof{status = S, warning_count = W} = parse_eof_packet(DelimiterPacket),
  415. case fetch_resultset_rows(SockModule, Socket, SeqNum2, []) of
  416. {ok, Rows, _SeqNum3} ->
  417. ColDefs1 = lists:map(fun parse_column_definition/1, ColDefs),
  418. #resultset{cols = ColDefs1, rows = Rows,
  419. status = S, warning_count = W};
  420. #error{} = E ->
  421. E
  422. end.
  423. parse_resultset(#resultset{cols = ColDefs, rows = Rows} = R, ColumnCount,
  424. text) ->
  425. %% Parse the rows according to the 'text protocol' representation.
  426. Rows1 = [decode_text_row(ColumnCount, ColDefs, Row) || Row <- Rows],
  427. R#resultset{rows = Rows1};
  428. parse_resultset(#resultset{cols = ColDefs, rows = Rows} = R, ColumnCount,
  429. binary) ->
  430. %% Parse the rows according to the 'binary protocol' representation.
  431. Rows1 = [decode_binary_row(ColumnCount, ColDefs, Row) || Row <- Rows],
  432. R#resultset{rows = Rows1}.
  433. more_results_exists(#ok{status = S}) ->
  434. S band ?SERVER_MORE_RESULTS_EXISTS /= 0;
  435. more_results_exists(#error{}) ->
  436. false; %% No status bits for error
  437. more_results_exists(#resultset{status = S}) ->
  438. S band ?SERVER_MORE_RESULTS_EXISTS /= 0.
  439. %% @doc Receives NumLeft column definition packets. They are not parsed.
  440. %% @see parse_column_definition/1
  441. -spec fetch_column_definitions(atom(), term(), SeqNum :: integer(),
  442. NumLeft :: integer(), Acc :: [binary()]) ->
  443. {ok, ColDefPackets :: [binary()], NextSeqNum :: integer()}.
  444. fetch_column_definitions(SockModule, Socket, SeqNum, NumLeft, Acc)
  445. when NumLeft > 0 ->
  446. {ok, Packet, SeqNum1} = recv_packet(SockModule, Socket, SeqNum),
  447. fetch_column_definitions(SockModule, Socket, SeqNum1, NumLeft - 1,
  448. [Packet | Acc]);
  449. fetch_column_definitions(_SockModule, _Socket, SeqNum, 0, Acc) ->
  450. {ok, lists:reverse(Acc), SeqNum}.
  451. %% @doc Fetches rows in a result set. There is a packet per row. The row packets
  452. %% are not decoded. This function can be used for both the binary and the text
  453. %% protocol result sets.
  454. -spec fetch_resultset_rows(atom(), term(), SeqNum :: integer(), Acc) ->
  455. {ok, Rows, integer()} | #error{}
  456. when Acc :: [binary()],
  457. Rows :: [binary()].
  458. fetch_resultset_rows(SockModule, Socket, SeqNum, Acc) ->
  459. {ok, Packet, SeqNum1} = recv_packet(SockModule, Socket, SeqNum),
  460. case Packet of
  461. ?error_pattern ->
  462. parse_error_packet(Packet);
  463. ?eof_pattern ->
  464. {ok, lists:reverse(Acc), SeqNum1};
  465. Row ->
  466. fetch_resultset_rows(SockModule, Socket, SeqNum1, [Row | Acc])
  467. end.
  468. %% Parses a packet containing a column definition (part of a result set)
  469. parse_column_definition(Data) ->
  470. {<<"def">>, Rest1} = lenenc_str(Data), %% catalog (always "def")
  471. {_Schema, Rest2} = lenenc_str(Rest1), %% schema-name
  472. {_Table, Rest3} = lenenc_str(Rest2), %% virtual table-name
  473. {_OrgTable, Rest4} = lenenc_str(Rest3), %% physical table-name
  474. {Name, Rest5} = lenenc_str(Rest4), %% virtual column name
  475. {_OrgName, Rest6} = lenenc_str(Rest5), %% physical column name
  476. {16#0c, Rest7} = lenenc_int(Rest6), %% length of the following fields
  477. %% (always 0x0c)
  478. <<Charset:16/little, %% column character set
  479. Length:32/little, %% maximum length of the field
  480. Type:8, %% type of the column as defined in Column Type
  481. Flags:16/little, %% flags
  482. Decimals:8, %% max shown decimal digits:
  483. 0, %% "filler" %% - 0x00 for integers and static strings
  484. 0, %% - 0x1f for dynamic strings, double, float
  485. Rest8/binary>> = Rest7, %% - 0x00 to 0x51 for decimals
  486. %% Here, if command was COM_FIELD_LIST {
  487. %% default values: lenenc_str
  488. %% }
  489. <<>> = Rest8,
  490. #col{name = Name, type = Type, charset = Charset, length = Length,
  491. decimals = Decimals, flags = Flags}.
  492. %% -- text protocol --
  493. -spec decode_text_row(NumColumns :: integer(),
  494. ColumnDefinitions :: [#col{}],
  495. Data :: binary()) -> [term()].
  496. decode_text_row(_NumColumns, ColumnDefs, Data) ->
  497. decode_text_row_acc(ColumnDefs, Data, []).
  498. %% parses Data using ColDefs and builds the values Acc.
  499. decode_text_row_acc([ColDef | ColDefs], Data, Acc) ->
  500. case Data of
  501. <<16#fb, Rest/binary>> ->
  502. %% NULL
  503. decode_text_row_acc(ColDefs, Rest, [null | Acc]);
  504. _ ->
  505. %% Every thing except NULL
  506. {Text, Rest} = lenenc_str(Data),
  507. Term = decode_text(ColDef, Text),
  508. decode_text_row_acc(ColDefs, Rest, [Term | Acc])
  509. end;
  510. decode_text_row_acc([], <<>>, Acc) ->
  511. lists:reverse(Acc).
  512. %% @doc When receiving data in the text protocol, we get everything as binaries
  513. %% (except NULL). This function is used to parse these string values.
  514. decode_text(#col{type = T}, Text)
  515. when T == ?TYPE_TINY; T == ?TYPE_SHORT; T == ?TYPE_LONG; T == ?TYPE_LONGLONG;
  516. T == ?TYPE_INT24; T == ?TYPE_YEAR ->
  517. binary_to_integer(Text);
  518. decode_text(#col{type = T}, Text)
  519. when T == ?TYPE_STRING; T == ?TYPE_VARCHAR; T == ?TYPE_VAR_STRING;
  520. T == ?TYPE_ENUM; T == ?TYPE_SET; T == ?TYPE_LONG_BLOB;
  521. T == ?TYPE_MEDIUM_BLOB; T == ?TYPE_BLOB; T == ?TYPE_TINY_BLOB;
  522. T == ?TYPE_GEOMETRY; T == ?TYPE_JSON ->
  523. %% As of MySQL 5.6.21 we receive SET and ENUM values as STRING, i.e. we
  524. %% cannot convert them to atom() or sets:set(), etc.
  525. Text;
  526. decode_text(#col{type = ?TYPE_BIT, length = Length}, Text) ->
  527. %% Convert to <<_:Length/bitstring>>
  528. decode_bitstring(Text, Length);
  529. decode_text(#col{type = T, decimals = S, length = L}, Text)
  530. when T == ?TYPE_DECIMAL; T == ?TYPE_NEWDECIMAL ->
  531. %% Length is the max number of symbols incl. dot and minus sign, e.g. the
  532. %% number of digits plus 2.
  533. decode_decimal(Text, L - 2, S);
  534. decode_text(#col{type = ?TYPE_DATE},
  535. <<Y:4/binary, "-", M:2/binary, "-", D:2/binary>>) ->
  536. {binary_to_integer(Y), binary_to_integer(M), binary_to_integer(D)};
  537. decode_text(#col{type = ?TYPE_TIME}, Text) ->
  538. {match, [Sign, Hbin, Mbin, Sbin, Frac]} =
  539. re:run(Text,
  540. <<"^(-?)(\\d+):(\\d+):(\\d+)(\\.?\\d*)$">>,
  541. [{capture, all_but_first, binary}]),
  542. H = binary_to_integer(Hbin),
  543. M = binary_to_integer(Mbin),
  544. S = binary_to_integer(Sbin),
  545. IsNeg = Sign == <<"-">>,
  546. Fraction = case Frac of
  547. <<>> -> 0;
  548. _ when not IsNeg -> binary_to_float(<<"0", Frac/binary>>);
  549. _ when IsNeg -> 1 - binary_to_float(<<"0", Frac/binary>>)
  550. end,
  551. Sec1 = H * 3600 + M * 60 + S,
  552. Sec2 = if IsNeg -> -Sec1; true -> Sec1 end,
  553. Sec3 = if IsNeg and (Fraction /= 0) -> Sec2 - 1;
  554. true -> Sec2
  555. end,
  556. {Days, {Hours, Minutes, Seconds}} = calendar:seconds_to_daystime(Sec3),
  557. {Days, {Hours, Minutes, Seconds + Fraction}};
  558. decode_text(#col{type = T},
  559. <<Y:4/binary, "-", M:2/binary, "-", D:2/binary, " ",
  560. H:2/binary, ":", Mi:2/binary, ":", S:2/binary>>)
  561. when T == ?TYPE_TIMESTAMP; T == ?TYPE_DATETIME ->
  562. %% Without fractions.
  563. {{binary_to_integer(Y), binary_to_integer(M), binary_to_integer(D)},
  564. {binary_to_integer(H), binary_to_integer(Mi), binary_to_integer(S)}};
  565. decode_text(#col{type = T},
  566. <<Y:4/binary, "-", M:2/binary, "-", D:2/binary, " ",
  567. H:2/binary, ":", Mi:2/binary, ":", FloatS/binary>>)
  568. when T == ?TYPE_TIMESTAMP; T == ?TYPE_DATETIME ->
  569. %% With fractions.
  570. {{binary_to_integer(Y), binary_to_integer(M), binary_to_integer(D)},
  571. {binary_to_integer(H), binary_to_integer(Mi), binary_to_float(FloatS)}};
  572. decode_text(#col{type = T}, Text) when T == ?TYPE_FLOAT;
  573. T == ?TYPE_DOUBLE ->
  574. try binary_to_float(Text)
  575. catch error:badarg ->
  576. try binary_to_integer(Text) of
  577. Int -> float(Int)
  578. catch error:badarg ->
  579. %% It is something like "4e75" that must be turned into "4.0e75"
  580. binary_to_float(binary:replace(Text, <<"e">>, <<".0e">>))
  581. end
  582. end.
  583. %% -- binary protocol --
  584. %% @doc If NumColumns is non-zero, fetches this number of column definitions
  585. %% and an EOF packet. Used by prepare/3.
  586. fetch_column_definitions_if_any(0, _SockModule, _Socket, SeqNum) ->
  587. {[], SeqNum};
  588. fetch_column_definitions_if_any(N, SockModule, Socket, SeqNum) ->
  589. {ok, Defs, SeqNum1} = fetch_column_definitions(SockModule, Socket, SeqNum,
  590. N, []),
  591. {ok, ?eof_pattern, SeqNum2} = recv_packet(SockModule, Socket, SeqNum1),
  592. {Defs, SeqNum2}.
  593. %% @doc Decodes a packet representing a row in a binary result set.
  594. %% It consists of a 0 byte, then a null bitmap, then the values.
  595. %% Returns a list of length NumColumns with terms of appropriate types for each
  596. %% MySQL type in ColumnTypes.
  597. -spec decode_binary_row(NumColumns :: integer(),
  598. ColumnDefs :: [#col{}],
  599. Data :: binary()) -> [term()].
  600. decode_binary_row(NumColumns, ColumnDefs, <<0, Data/binary>>) ->
  601. {NullBitMap, Rest} = null_bitmap_decode(NumColumns, Data, 2),
  602. decode_binary_row_acc(ColumnDefs, NullBitMap, Rest, []).
  603. %% @doc Accumulating helper for decode_binary_row/3.
  604. decode_binary_row_acc([_|ColDefs], <<1:1, NullBitMap/bitstring>>, Data, Acc) ->
  605. %% NULL
  606. decode_binary_row_acc(ColDefs, NullBitMap, Data, [null | Acc]);
  607. decode_binary_row_acc([ColDef | ColDefs], <<0:1, NullBitMap/bitstring>>, Data,
  608. Acc) ->
  609. %% Not NULL
  610. {Term, Rest} = decode_binary(ColDef, Data),
  611. decode_binary_row_acc(ColDefs, NullBitMap, Rest, [Term | Acc]);
  612. decode_binary_row_acc([], _, <<>>, Acc) ->
  613. lists:reverse(Acc).
  614. %% @doc Decodes a null bitmap as stored by MySQL and returns it in a strait
  615. %% bitstring counting bits from left to right in a tuple with remaining data.
  616. %%
  617. %% In the MySQL null bitmap the bits are stored counting bytes from the left and
  618. %% bits within each byte from the right. (Sort of little endian.)
  619. -spec null_bitmap_decode(NumColumns :: integer(), Data :: binary(),
  620. BitOffset :: integer()) ->
  621. {NullBitstring :: bitstring(), Rest :: binary()}.
  622. null_bitmap_decode(NumColumns, Data, BitOffset) ->
  623. %% Binary shift right by 3 is equivallent to integer division by 8.
  624. BitMapLength = (NumColumns + BitOffset + 7) bsr 3,
  625. <<NullBitstring0:BitMapLength/binary, Rest/binary>> = Data,
  626. <<_:BitOffset, NullBitstring:NumColumns/bitstring, _/bitstring>> =
  627. << <<(reverse_byte(B))/binary>> || <<B:1/binary>> <= NullBitstring0 >>,
  628. {NullBitstring, Rest}.
  629. %% @doc The reverse of null_bitmap_decode/3. The number of columns is taken to
  630. %% be the number of bits in NullBitstring. Returns the MySQL null bitmap as a
  631. %% binary (i.e. full bytes). BitOffset is the number of unused bits that should
  632. %% be inserted before the other bits.
  633. -spec null_bitmap_encode(bitstring(), integer()) -> binary().
  634. null_bitmap_encode(NullBitstring, BitOffset) ->
  635. PayloadLength = bit_size(NullBitstring) + BitOffset,
  636. %% Round up to a multiple of 8.
  637. BitMapLength = (PayloadLength + 7) band bnot 7,
  638. PadBitsLength = BitMapLength - PayloadLength,
  639. PaddedBitstring = <<0:BitOffset, NullBitstring/bitstring, 0:PadBitsLength>>,
  640. << <<(reverse_byte(B))/binary>> || <<B:1/binary>> <= PaddedBitstring >>.
  641. %% Reverses the bits in a byte.
  642. reverse_byte(<<A:1, B:1, C:1, D:1, E:1, F:1, G:1, H:1>>) ->
  643. <<H:1, G:1, F:1, E:1, D:1, C:1, B:1, A:1>>.
  644. %% @doc Used for executing prepared statements. The bit offset whould be 0 in
  645. %% this case.
  646. -spec build_null_bitmap([any()]) -> binary().
  647. build_null_bitmap(Values) ->
  648. Bits = << <<(case V of null -> 1; _ -> 0 end):1>> || V <- Values >>,
  649. null_bitmap_encode(Bits, 0).
  650. %% Decodes a value as received in the 'binary protocol' result set.
  651. %%
  652. %% The types are type constants for the binary protocol, such as
  653. %% ProtocolBinary::MYSQL_TYPE_STRING. In the guide "MySQL Internals" these are
  654. %% not listed, but we assume that are the same as for the text protocol.
  655. -spec decode_binary(ColDef :: #col{}, Data :: binary()) ->
  656. {Term :: term(), Rest :: binary()}.
  657. decode_binary(#col{type = T}, Data)
  658. when T == ?TYPE_STRING; T == ?TYPE_VARCHAR; T == ?TYPE_VAR_STRING;
  659. T == ?TYPE_ENUM; T == ?TYPE_SET; T == ?TYPE_LONG_BLOB;
  660. T == ?TYPE_MEDIUM_BLOB; T == ?TYPE_BLOB; T == ?TYPE_TINY_BLOB;
  661. T == ?TYPE_GEOMETRY; T == ?TYPE_JSON ->
  662. %% As of MySQL 5.6.21 we receive SET and ENUM values as STRING, i.e. we
  663. %% cannot convert them to atom() or sets:set(), etc.
  664. lenenc_str(Data);
  665. decode_binary(#col{type = ?TYPE_LONGLONG, flags = F},
  666. <<Value:64/signed-little, Rest/binary>>)
  667. when F band ?UNSIGNED_FLAG == 0 ->
  668. {Value, Rest};
  669. decode_binary(#col{type = ?TYPE_LONGLONG, flags = F},
  670. <<Value:64/unsigned-little, Rest/binary>>)
  671. when F band ?UNSIGNED_FLAG /= 0 ->
  672. {Value, Rest};
  673. decode_binary(#col{type = T, flags = F},
  674. <<Value:32/signed-little, Rest/binary>>)
  675. when (T == ?TYPE_LONG orelse T == ?TYPE_INT24) andalso
  676. F band ?UNSIGNED_FLAG == 0 ->
  677. {Value, Rest};
  678. decode_binary(#col{type = T, flags = F},
  679. <<Value:32/unsigned-little, Rest/binary>>)
  680. when (T == ?TYPE_LONG orelse T == ?TYPE_INT24) andalso
  681. F band ?UNSIGNED_FLAG /= 0 ->
  682. {Value, Rest};
  683. decode_binary(#col{type = ?TYPE_SHORT, flags = F},
  684. <<Value:16/signed-little, Rest/binary>>)
  685. when F band ?UNSIGNED_FLAG == 0 ->
  686. {Value, Rest};
  687. decode_binary(#col{type = T, flags = F},
  688. <<Value:16/unsigned-little, Rest/binary>>)
  689. when (T == ?TYPE_SHORT orelse T == ?TYPE_YEAR) andalso
  690. F band ?UNSIGNED_FLAG /= 0 ->
  691. {Value, Rest};
  692. decode_binary(#col{type = ?TYPE_TINY, flags = F},
  693. <<Value:8/unsigned, Rest/binary>>)
  694. when F band ?UNSIGNED_FLAG /= 0 ->
  695. {Value, Rest};
  696. decode_binary(#col{type = ?TYPE_TINY, flags = F},
  697. <<Value:8/signed, Rest/binary>>)
  698. when F band ?UNSIGNED_FLAG == 0 ->
  699. {Value, Rest};
  700. decode_binary(#col{type = T, decimals = S, length = L}, Data)
  701. when T == ?TYPE_DECIMAL; T == ?TYPE_NEWDECIMAL ->
  702. %% Length is the max number of symbols incl. dot and minus sign, e.g. the
  703. %% number of digits plus 2.
  704. {Binary, Rest} = lenenc_str(Data),
  705. {decode_decimal(Binary, L - 2, S), Rest};
  706. decode_binary(#col{type = ?TYPE_DOUBLE},
  707. <<Value:64/float-little, Rest/binary>>) ->
  708. {Value, Rest};
  709. decode_binary(#col{type = ?TYPE_FLOAT}, <<0.0:32/float-little, Rest/binary>>) ->
  710. %% TYPE_FLOAT conversation fails on math:log10(0.0)
  711. {0.0, Rest};
  712. decode_binary(#col{type = ?TYPE_FLOAT},
  713. <<Value:32/float-little, Rest/binary>>) ->
  714. %% There is a precision loss when storing and fetching a 32-bit float.
  715. %% In the text protocol, it is obviously rounded. Storing 3.14 in a FLOAT
  716. %% column and fetching it using the text protocol, we get "3.14" which we
  717. %% parse to the Erlang double as close as possible to 3.14. Fetching the
  718. %% same value as a binary 32-bit float, we get 3.140000104904175. To achieve
  719. %% the same rounding after receiving it as a 32-bit float, we try to do the
  720. %% same rounding here as MySQL does when sending it over the text protocol.
  721. %%
  722. %% This comment explains the idea:
  723. %%
  724. %% Posted by Geoffrey Downs on March 10 2011 10:26am
  725. %%
  726. %% Following up... I *think* this is correct for the default float
  727. %% columns in mysql:
  728. %%
  729. %% var yourNumber = some floating point value
  730. %% max decimal precision = 10 ^ (-5 + flooring(yourNumber log 10))
  731. %% So:
  732. %% 0 < x < 10 -> max precision is 0.00001
  733. %% 10 <= x < 100 -> max precision is 0.0001
  734. %% 100 <= x < 1000 -> max precision is 0.001
  735. %% etc.
  736. %%
  737. %% (From http://dev.mysql.com/doc/refman/5.7/en/problems-with-float.html
  738. %% fetched 10 Nov 2014)
  739. %%
  740. %% The above is almost correct, except for the example in the interval
  741. %% 0 < x < 1. There are 6 significant digits also for these numbers.
  742. %%
  743. %% Now, instead of P = 0.00001 we want the inverse 100000.0 but if we
  744. %% compute Factor = 1 / P we get a precision loss, so instead we do this:
  745. Factor = math:pow(10, flooring(6 - math:log10(abs(Value)))),
  746. RoundedValue = round(Value * Factor) / Factor,
  747. {RoundedValue, Rest};
  748. decode_binary(#col{type = ?TYPE_BIT, length = Length}, Data) ->
  749. {Binary, Rest} = lenenc_str(Data),
  750. %% Convert to <<_:Length/bitstring>>
  751. {decode_bitstring(Binary, Length), Rest};
  752. decode_binary(#col{type = ?TYPE_DATE}, <<Length, Data/binary>>) ->
  753. %% Coded in the same way as DATETIME and TIMESTAMP below, but returned in
  754. %% a simple triple.
  755. case {Length, Data} of
  756. {0, _} -> {{0, 0, 0}, Data};
  757. {4, <<Y:16/little, M, D, Rest/binary>>} -> {{Y, M, D}, Rest}
  758. end;
  759. decode_binary(#col{type = T}, <<Length, Data/binary>>)
  760. when T == ?TYPE_DATETIME; T == ?TYPE_TIMESTAMP ->
  761. %% length (1) -- number of bytes following (valid values: 0, 4, 7, 11)
  762. case {Length, Data} of
  763. {0, _} ->
  764. {{{0, 0, 0}, {0, 0, 0}}, Data};
  765. {4, <<Y:16/little, M, D, Rest/binary>>} ->
  766. {{{Y, M, D}, {0, 0, 0}}, Rest};
  767. {7, <<Y:16/little, M, D, H, Mi, S, Rest/binary>>} ->
  768. {{{Y, M, D}, {H, Mi, S}}, Rest};
  769. {11, <<Y:16/little, M, D, H, Mi, S, Micro:32/little, Rest/binary>>} ->
  770. {{{Y, M, D}, {H, Mi, S + 0.000001 * Micro}}, Rest}
  771. end;
  772. decode_binary(#col{type = ?TYPE_TIME}, <<Length, Data/binary>>) ->
  773. %% length (1) -- number of bytes following (valid values: 0, 8, 12)
  774. %% is_negative (1) -- (1 if minus, 0 for plus)
  775. %% days (4) -- days
  776. %% hours (1) -- hours
  777. %% minutes (1) -- minutes
  778. %% seconds (1) -- seconds
  779. %% micro_seconds (4) -- micro-seconds
  780. case {Length, Data} of
  781. {0, _} ->
  782. {{0, {0, 0, 0}}, Data};
  783. {8, <<0, D:32/little, H, M, S, Rest/binary>>} ->
  784. {{D, {H, M, S}}, Rest};
  785. {12, <<0, D:32/little, H, M, S, Micro:32/little, Rest/binary>>} ->
  786. {{D, {H, M, S + 0.000001 * Micro}}, Rest};
  787. {8, <<1, D:32/little, H, M, S, Rest/binary>>} ->
  788. %% Negative time. Example: '-00:00:01' --> {-1,{23,59,59}}
  789. Seconds = ((D * 24 + H) * 60 + M) * 60 + S,
  790. %Seconds = D * 86400 + calendar:time_to_seconds({H, M, S}),
  791. {calendar:seconds_to_daystime(-Seconds), Rest};
  792. {12, <<1, D:32/little, H, M, S, Micro:32/little, Rest/binary>>}
  793. when Micro > 0 ->
  794. %% Negate and convert to seconds, excl fractions
  795. Seconds = -(((D * 24 + H) * 60 + M) * 60 + S),
  796. %Seconds = -D * 86400 - calendar:time_to_seconds({H, M, S}),
  797. %% Subtract 1 second for the fractions
  798. {Days, {Hours, Minutes, Sec}} =
  799. calendar:seconds_to_daystime(Seconds - 1),
  800. %% Adding the fractions to Sec again makes it a float
  801. {{Days, {Hours, Minutes, Sec + 1 - 0.000001 * Micro}}, Rest}
  802. end.
  803. %% @doc Like trunc/1 but towards negative infinity instead of towards zero.
  804. flooring(Value) ->
  805. Trunc = trunc(Value),
  806. if
  807. Trunc =< Value -> Trunc;
  808. Trunc > Value -> Trunc - 1 %% for negative values
  809. end.
  810. %% @doc Encodes a term reprenting av value as a binary for use in the binary
  811. %% protocol. As this is used to encode parameters for prepared statements, the
  812. %% encoding is in its required form, namely `<<Type:8, Sign:8, Value/binary>>'.
  813. -spec encode_param(term()) -> {TypeAndSign :: binary(), Data :: binary()}.
  814. encode_param(null) ->
  815. {<<?TYPE_NULL, 0>>, <<>>};
  816. encode_param(Value) when is_binary(Value) ->
  817. EncLength = lenenc_int_encode(byte_size(Value)),
  818. {<<?TYPE_VAR_STRING, 0>>, <<EncLength/binary, Value/binary>>};
  819. encode_param(Value) when is_list(Value) ->
  820. encode_param(unicode:characters_to_binary(Value));
  821. encode_param(Value) when is_integer(Value), Value >= 0 ->
  822. %% We send positive integers with the 'unsigned' flag set.
  823. if
  824. Value =< 16#ff ->
  825. {<<?TYPE_TINY, 16#80>>, <<Value:8>>};
  826. Value =< 16#ffff ->
  827. {<<?TYPE_SHORT, 16#80>>, <<Value:16/little>>};
  828. Value =< 16#ffffffff ->
  829. {<<?TYPE_LONG, 16#80>>, <<Value:32/little>>};
  830. Value =< 16#ffffffffffffffff ->
  831. {<<?TYPE_LONGLONG, 16#80>>, <<Value:64/little>>};
  832. true ->
  833. %% If larger than a 64-bit int we send it as a string. MySQL does
  834. %% silently cast strings in aithmetic expressions. Also, DECIMALs
  835. %% are always sent as strings.
  836. encode_param(integer_to_binary(Value))
  837. end;
  838. encode_param(Value) when is_integer(Value), Value < 0 ->
  839. if
  840. Value >= -16#80 ->
  841. {<<?TYPE_TINY, 0>>, <<Value:8>>};
  842. Value >= -16#8000 ->
  843. {<<?TYPE_SHORT, 0>>, <<Value:16/little>>};
  844. Value >= -16#80000000 ->
  845. {<<?TYPE_LONG, 0>>, <<Value:32/little>>};
  846. Value >= -16#8000000000000000 ->
  847. {<<?TYPE_LONGLONG, 0>>, <<Value:64/little>>};
  848. true ->
  849. encode_param(integer_to_binary(Value))
  850. end;
  851. encode_param(Value) when is_float(Value) ->
  852. {<<?TYPE_DOUBLE, 0>>, <<Value:64/float-little>>};
  853. encode_param(Value) when is_bitstring(Value) ->
  854. Binary = encode_bitstring(Value),
  855. EncLength = lenenc_int_encode(byte_size(Binary)),
  856. {<<?TYPE_VAR_STRING, 0>>, <<EncLength/binary, Binary/binary>>};
  857. encode_param({Y, M, D}) ->
  858. %% calendar:date()
  859. {<<?TYPE_DATE, 0>>, <<4, Y:16/little, M, D>>};
  860. encode_param({{Y, M, D}, {0, 0, 0}}) ->
  861. %% Datetime at midnight
  862. {<<?TYPE_DATETIME, 0>>, <<4, Y:16/little, M, D>>};
  863. encode_param({{Y, M, D}, {H, Mi, S}}) when is_integer(S) ->
  864. %% calendar:datetime()
  865. {<<?TYPE_DATETIME, 0>>, <<7, Y:16/little, M, D, H, Mi, S>>};
  866. encode_param({{Y, M, D}, {H, Mi, S}}) when is_float(S) ->
  867. %% calendar:datetime() with a float for seconds. This way it looks very
  868. %% similar to a datetime. Microseconds in MySQL timestamps are possible but
  869. %% not very common.
  870. Sec = trunc(S),
  871. Micro = round(1000000 * (S - Sec)),
  872. {<<?TYPE_DATETIME, 0>>, <<11, Y:16/little, M, D, H, Mi, Sec,
  873. Micro:32/little>>};
  874. encode_param({D, {H, M, S}}) when is_integer(S), D >= 0 ->
  875. %% calendar:seconds_to_daystime()
  876. {<<?TYPE_TIME, 0>>, <<8, 0, D:32/little, H, M, S>>};
  877. encode_param({D, {H, M, S}}) when is_integer(S), D < 0 ->
  878. %% Convert to seconds, negate and convert back to daystime form.
  879. %% Then set the minus flag.
  880. Seconds = ((D * 24 + H) * 60 + M) * 60 + S,
  881. {D1, {H1, M1, S1}} = calendar:seconds_to_daystime(-Seconds),
  882. {<<?TYPE_TIME, 0>>, <<8, 1, D1:32/little, H1, M1, S1>>};
  883. encode_param({D, {H, M, S}}) when is_float(S), D >= 0 ->
  884. S1 = trunc(S),
  885. Micro = round(1000000 * (S - S1)),
  886. {<<?TYPE_TIME, 0>>, <<12, 0, D:32/little, H, M, S1, Micro:32/little>>};
  887. encode_param({D, {H, M, S}}) when is_float(S), S > 0.0, D < 0 ->
  888. IntS = trunc(S),
  889. Micro = round(1000000 * (1 - S + IntS)),
  890. Seconds = (D * 24 + H) * 3600 + M * 60 + IntS + 1,
  891. {D1, {M1, H1, S1}} = calendar:seconds_to_daystime(-Seconds),
  892. {<<?TYPE_TIME, 0>>, <<12, 1, D1:32/little, H1, M1, S1, Micro:32/little>>};
  893. encode_param({D, {H, M, 0.0}}) ->
  894. encode_param({D, {H, M, 0}}).
  895. %% -- Value representation in both the text and binary protocols --
  896. %% @doc Convert to `<<_:Length/bitstring>>'
  897. decode_bitstring(Binary, Length) ->
  898. PaddingLength = bit_size(Binary) - Length,
  899. <<_:PaddingLength/bitstring, Bitstring:Length/bitstring>> = Binary,
  900. Bitstring.
  901. encode_bitstring(Bitstring) ->
  902. Size = bit_size(Bitstring),
  903. PaddingSize = byte_size(Bitstring) * 8 - Size,
  904. <<0:PaddingSize, Bitstring:Size/bitstring>>.
  905. decode_decimal(Bin, _P, 0) ->
  906. binary_to_integer(Bin);
  907. decode_decimal(Bin, P, S) when P =< 15, S > 0 ->
  908. binary_to_float(Bin);
  909. decode_decimal(Bin, P, S) when P >= 16, S > 0 ->
  910. Bin.
  911. %% -- Protocol basics: packets --
  912. %% @doc Wraps Data in packet headers, sends it by calling SockModule:send/2 with
  913. %% Socket and returns {ok, SeqNum1} where SeqNum1 is the next sequence number.
  914. -spec send_packet(atom(), term(), Data :: binary(), SeqNum :: integer()) ->
  915. {ok, NextSeqNum :: integer()}.
  916. send_packet(SockModule, Socket, Data, SeqNum) ->
  917. {WithHeaders, SeqNum1} = add_packet_headers(Data, SeqNum),
  918. ok = SockModule:send(Socket, WithHeaders),
  919. {ok, SeqNum1}.
  920. %% @see recv_packet/4
  921. recv_packet(SockModule, Socket, SeqNum) ->
  922. recv_packet(SockModule, Socket, infinity, SeqNum).
  923. %% @doc Receives data by calling SockModule:recv/2 and removes the packet
  924. %% headers. Returns the packet contents and the next packet sequence number.
  925. -spec recv_packet(atom(), term(), timeout(), integer() | any) ->
  926. {ok, Data :: binary(), NextSeqNum :: integer()} | {error, term()}.
  927. recv_packet(SockModule, Socket, Timeout, SeqNum) ->
  928. recv_packet(SockModule, Socket, Timeout, SeqNum, <<>>).
  929. %% @doc Accumulating helper for recv_packet/4
  930. -spec recv_packet(atom(), term(), timeout(), integer() | any, binary()) ->
  931. {ok, Data :: binary(), NextSeqNum :: integer()} | {error, term()}.
  932. recv_packet(SockModule, Socket, Timeout, ExpectSeqNum, Acc) ->
  933. case SockModule:recv(Socket, 4, Timeout) of
  934. {ok, Header} ->
  935. {Size, SeqNum, More} = parse_packet_header(Header),
  936. true = SeqNum == ExpectSeqNum orelse ExpectSeqNum == any,
  937. {ok, Body} = SockModule:recv(Socket, Size),
  938. Acc1 = <<Acc/binary, Body/binary>>,
  939. NextSeqNum = (SeqNum + 1) band 16#ff,
  940. case More of
  941. false -> {ok, Acc1, NextSeqNum};
  942. true -> recv_packet(SockModule, Socket, Timeout, NextSeqNum,
  943. Acc1)
  944. end;
  945. {error, Reason} ->
  946. {error, Reason}
  947. end.
  948. %% @doc Parses a packet header (32 bits) and returns a tuple.
  949. %%
  950. %% The client should first read a header and parse it. Then read PacketLength
  951. %% bytes. If there are more packets, read another header and read a new packet
  952. %% length of payload until there are no more packets. The seq num should
  953. %% increment from 0 and may wrap around at 255 back to 0.
  954. %%
  955. %% When all packets are read and the payload of all packets are concatenated, it
  956. %% can be parsed using parse_response/1, etc. depending on what type of response
  957. %% is expected.
  958. -spec parse_packet_header(PackerHeader :: binary()) ->
  959. {PacketLength :: integer(),
  960. SeqNum :: integer(),
  961. MorePacketsExist :: boolean()}.
  962. parse_packet_header(<<PacketLength:24/little-integer, SeqNum:8/integer>>) ->
  963. {PacketLength, SeqNum, PacketLength == 16#ffffff}.
  964. %% @doc Splits a packet body into chunks and wraps them in headers. The
  965. %% resulting list is ready to be sent to the socket. The result is built as a
  966. %% list to avoid copying large binaries.
  967. -spec add_packet_headers(Data :: binary(), SeqNum :: integer()) ->
  968. {PacketsWithHeaders :: iodata(), NextSeqNum :: integer()}.
  969. add_packet_headers(<<Payload:16#ffffff/binary, Rest/binary>>, SeqNum) ->
  970. SeqNum1 = (SeqNum + 1) band 16#ff,
  971. {Packets, NextSeqNum} = add_packet_headers(Rest, SeqNum1),
  972. Header = <<16#ffffff:24/little, SeqNum:8>>,
  973. {[Header, Payload | Packets], NextSeqNum};
  974. add_packet_headers(Bin, SeqNum) when byte_size(Bin) < 16#ffffff ->
  975. NextSeqNum = (SeqNum + 1) band 16#ff,
  976. Header = <<(byte_size(Bin)):24/little, SeqNum:8>>,
  977. {[Header, Bin], NextSeqNum}.
  978. -spec parse_ok_packet(binary()) -> #ok{}.
  979. parse_ok_packet(<<?OK:8, Rest/binary>>) ->
  980. {AffectedRows, Rest1} = lenenc_int(Rest),
  981. {InsertId, Rest2} = lenenc_int(Rest1),
  982. <<StatusFlags:16/little, WarningCount:16/little, Msg/binary>> = Rest2,
  983. %% We have CLIENT_PROTOCOL_41 but not CLIENT_SESSION_TRACK enabled. The
  984. %% protocol is conditional. This is from the protocol documentation:
  985. %%
  986. %% if capabilities & CLIENT_PROTOCOL_41 {
  987. %% int<2> status_flags
  988. %% int<2> warning_count
  989. %% } elseif capabilities & CLIENT_TRANSACTIONS {
  990. %% int<2> status_flags
  991. %% }
  992. %% if capabilities & CLIENT_SESSION_TRACK {
  993. %% string<lenenc> info
  994. %% if status_flags & SERVER_SESSION_STATE_CHANGED {
  995. %% string<lenenc> session_state_changes
  996. %% }
  997. %% } else {
  998. %% string<EOF> info
  999. %% }
  1000. #ok{affected_rows = AffectedRows,
  1001. insert_id = InsertId,
  1002. status = StatusFlags,
  1003. warning_count = WarningCount,
  1004. msg = Msg}.
  1005. -spec parse_error_packet(binary()) -> #error{}.
  1006. parse_error_packet(<<?ERROR:8, ErrNo:16/little, "#", SQLState:5/binary-unit:8,
  1007. Msg/binary>>) ->
  1008. %% Error, 4.1 protocol.
  1009. %% (Older protocol: <<?ERROR:8, ErrNo:16/little, Msg/binary>>)
  1010. #error{code = ErrNo, state = SQLState, msg = Msg}.
  1011. -spec parse_eof_packet(binary()) -> #eof{}.
  1012. parse_eof_packet(<<?EOF:8, NumWarnings:16/little, StatusFlags:16/little>>) ->
  1013. %% EOF packet, 4.1 protocol.
  1014. %% (Older protocol: <<?EOF:8>>)
  1015. #eof{status = StatusFlags, warning_count = NumWarnings}.
  1016. -spec parse_auth_method_switch(binary()) -> #auth_method_switch{}.
  1017. parse_auth_method_switch(AMSData) ->
  1018. {AuthPluginName, AuthPluginData} = get_null_terminated_binary(AMSData),
  1019. #auth_method_switch{
  1020. auth_plugin_name = AuthPluginName,
  1021. auth_plugin_data = AuthPluginData
  1022. }.
  1023. -spec get_null_terminated_binary(binary()) -> {Binary :: binary(),
  1024. Rest :: binary()}.
  1025. get_null_terminated_binary(In) ->
  1026. get_null_terminated_binary(In, <<>>).
  1027. get_null_terminated_binary(<<0, Rest/binary>>, Acc) ->
  1028. {Acc, Rest};
  1029. get_null_terminated_binary(<<Ch, Rest/binary>>, Acc) ->
  1030. get_null_terminated_binary(Rest, <<Acc/binary, Ch>>).
  1031. -spec hash_password(Password :: iodata(), Salt :: binary()) -> Hash :: binary().
  1032. hash_password(Password, Salt) ->
  1033. %% From the "MySQL Internals" manual:
  1034. %% SHA1( password ) XOR SHA1( "20-bytes random data from server" <concat>
  1035. %% SHA1( SHA1( password ) ) )
  1036. %% ----
  1037. %% Make sure the salt is exactly 20 bytes.
  1038. %%
  1039. %% The auth data is obviously nul-terminated. For the "native" auth
  1040. %% method, it should be a 20 byte salt, so let's trim it in this case.
  1041. PasswordBin = case erlang:is_binary(Password) of
  1042. true -> Password;
  1043. false -> erlang:iolist_to_binary(Password)
  1044. end,
  1045. case PasswordBin =:= <<>> of
  1046. true -> <<>>;
  1047. false -> hash_non_empty_password(Password, Salt)
  1048. end.
  1049. -spec hash_non_empty_password(Password :: iodata(), Salt :: binary()) ->
  1050. Hash :: binary().
  1051. hash_non_empty_password(Password, Salt) ->
  1052. Salt1 = case Salt of
  1053. <<SaltNoNul:20/binary-unit:8, 0>> -> SaltNoNul;
  1054. _ when size(Salt) == 20 -> Salt
  1055. end,
  1056. %% Hash as described above.
  1057. <<Hash1Num:160>> = Hash1 = crypto:hash(sha, Password),
  1058. Hash2 = crypto:hash(sha, Hash1),
  1059. <<Hash3Num:160>> = crypto:hash(sha, <<Salt1/binary, Hash2/binary>>),
  1060. <<(Hash1Num bxor Hash3Num):160>>.
  1061. %% --- Lowlevel: variable length integers and strings ---
  1062. %% lenenc_int/1 decodes length-encoded-integer values
  1063. -spec lenenc_int(Input :: binary()) -> {Value :: integer(), Rest :: binary()}.
  1064. lenenc_int(<<Value:8, Rest/bits>>) when Value < 251 -> {Value, Rest};
  1065. lenenc_int(<<16#fc:8, Value:16/little, Rest/binary>>) -> {Value, Rest};
  1066. lenenc_int(<<16#fd:8, Value:24/little, Rest/binary>>) -> {Value, Rest};
  1067. lenenc_int(<<16#fe:8, Value:64/little, Rest/binary>>) -> {Value, Rest}.
  1068. %% Length-encoded-integer encode. Appends the encoded value to Acc.
  1069. %% Values not representable in 64 bits are not accepted.
  1070. -spec lenenc_int_encode(0..16#ffffffffffffffff) -> binary().
  1071. lenenc_int_encode(Value) when Value >= 0 ->
  1072. if Value < 251 -> <<Value>>;
  1073. Value =< 16#ffff -> <<16#fc, Value:16/little>>;
  1074. Value =< 16#ffffff -> <<16#fd, Value:24/little>>;
  1075. Value =< 16#ffffffffffffffff -> <<16#fe, Value:64/little>>
  1076. end.
  1077. %% lenenc_str/1 decodes length-encoded-string values
  1078. -spec lenenc_str(Input :: binary()) -> {String :: binary(), Rest :: binary()}.
  1079. lenenc_str(Bin) ->
  1080. {Length, Rest} = lenenc_int(Bin),
  1081. <<String:Length/binary, Rest1/binary>> = Rest,
  1082. {String, Rest1}.
  1083. %% nts/1 decodes a nul-terminated string
  1084. -spec nulterm_str(Input :: binary()) -> {String :: binary(), Rest :: binary()}.
  1085. nulterm_str(Bin) ->
  1086. [String, Rest] = binary:split(Bin, <<0>>),
  1087. {String, Rest}.
  1088. -ifdef(TEST).
  1089. -include_lib("eunit/include/eunit.hrl").
  1090. %% Testing some of the internal functions, mostly the cases we don't cover in
  1091. %% other tests.
  1092. decode_text_test() ->
  1093. %% Int types
  1094. lists:foreach(fun (T) ->
  1095. ?assertEqual(1, decode_text(#col{type = T}, <<"1">>))
  1096. end,
  1097. [?TYPE_TINY, ?TYPE_SHORT, ?TYPE_LONG, ?TYPE_LONGLONG,
  1098. ?TYPE_INT24, ?TYPE_YEAR]),
  1099. %% BIT
  1100. <<217>> = decode_text(#col{type = ?TYPE_BIT, length = 8}, <<217>>),
  1101. %% Floating point and decimal numbers
  1102. lists:foreach(fun (T) ->
  1103. ?assertEqual(3.0, decode_text(#col{type = T}, <<"3.0">>))
  1104. end,
  1105. [?TYPE_FLOAT, ?TYPE_DOUBLE]),
  1106. %% Decimal types
  1107. lists:foreach(fun (T) ->
  1108. ColDef = #col{type = T, decimals = 1, length = 4},
  1109. ?assertMatch(3.0, decode_text(ColDef, <<"3.0">>))
  1110. end,
  1111. [?TYPE_DECIMAL, ?TYPE_NEWDECIMAL]),
  1112. ?assertEqual(3.0, decode_text(#col{type = ?TYPE_FLOAT}, <<"3">>)),
  1113. ?assertEqual(30.0, decode_text(#col{type = ?TYPE_FLOAT}, <<"3e1">>)),
  1114. ?assertEqual(3, decode_text(#col{type = ?TYPE_LONG}, <<"3">>)),
  1115. %% Date and time
  1116. ?assertEqual({2014, 11, 01},
  1117. decode_text(#col{type = ?TYPE_DATE}, <<"2014-11-01">>)),
  1118. ?assertEqual({0, {23, 59, 01}},
  1119. decode_text(#col{type = ?TYPE_TIME}, <<"23:59:01">>)),
  1120. ?assertEqual({{2014, 11, 01}, {23, 59, 01}},
  1121. decode_text(#col{type = ?TYPE_DATETIME},
  1122. <<"2014-11-01 23:59:01">>)),
  1123. ?assertEqual({{2014, 11, 01}, {23, 59, 01}},
  1124. decode_text(#col{type = ?TYPE_TIMESTAMP},
  1125. <<"2014-11-01 23:59:01">>)),
  1126. %% Strings and blobs
  1127. lists:foreach(fun (T) ->
  1128. ColDef = #col{type = T},
  1129. ?assertEqual(<<"x">>, decode_text(ColDef, <<"x">>))
  1130. end,
  1131. [?TYPE_VARCHAR, ?TYPE_ENUM, ?TYPE_TINY_BLOB,
  1132. ?TYPE_MEDIUM_BLOB, ?TYPE_LONG_BLOB, ?TYPE_BLOB,
  1133. ?TYPE_VAR_STRING, ?TYPE_STRING, ?TYPE_GEOMETRY]),
  1134. ok.
  1135. decode_binary_test() ->
  1136. %% Test the special rounding we apply to (single precision) floats.
  1137. ?assertEqual({1.0, <<>>},
  1138. decode_binary(#col{type = ?TYPE_FLOAT},
  1139. <<1.0:32/float-little>>)),
  1140. ?assertEqual({0.2, <<>>},
  1141. decode_binary(#col{type = ?TYPE_FLOAT},
  1142. <<0.2:32/float-little>>)),
  1143. ?assertEqual({-33.3333, <<>>},
  1144. decode_binary(#col{type = ?TYPE_FLOAT},
  1145. <<-33.333333:32/float-little>>)),
  1146. ?assertEqual({0.000123457, <<>>},
  1147. decode_binary(#col{type = ?TYPE_FLOAT},
  1148. <<0.00012345678:32/float-little>>)),
  1149. ?assertEqual({1234.57, <<>>},
  1150. decode_binary(#col{type = ?TYPE_FLOAT},
  1151. <<1234.56789:32/float-little>>)),
  1152. ok.
  1153. null_bitmap_test() ->
  1154. ?assertEqual({<<0, 1:1>>, <<>>}, null_bitmap_decode(9, <<0, 4>>, 2)),
  1155. ?assertEqual(<<0, 4>>, null_bitmap_encode(<<0, 1:1>>, 2)),
  1156. ok.
  1157. lenenc_int_test() ->
  1158. %% decode
  1159. ?assertEqual({40, <<>>}, lenenc_int(<<40>>)),
  1160. ?assertEqual({16#ff, <<>>}, lenenc_int(<<16#fc, 255, 0>>)),
  1161. ?assertEqual({16#33aaff, <<>>}, lenenc_int(<<16#fd, 16#ff, 16#aa, 16#33>>)),
  1162. ?assertEqual({16#12345678, <<>>}, lenenc_int(<<16#fe, 16#78, 16#56, 16#34,
  1163. 16#12, 0, 0, 0, 0>>)),
  1164. %% encode
  1165. ?assertEqual(<<40>>, lenenc_int_encode(40)),
  1166. ?assertEqual(<<16#fc, 255, 0>>, lenenc_int_encode(255)),
  1167. ?assertEqual(<<16#fd, 16#ff, 16#aa, 16#33>>,
  1168. lenenc_int_encode(16#33aaff)),
  1169. ?assertEqual(<<16#fe, 16#78, 16#56, 16#34, 16#12, 0, 0, 0, 0>>,
  1170. lenenc_int_encode(16#12345678)),
  1171. ok.
  1172. lenenc_str_test() ->
  1173. ?assertEqual({<<"Foo">>, <<"bar">>}, lenenc_str(<<3, "Foobar">>)).
  1174. nulterm_test() ->
  1175. ?assertEqual({<<"Foo">>, <<"bar">>}, nulterm_str(<<"Foo", 0, "bar">>)).
  1176. parse_header_test() ->
  1177. %% Example from "MySQL Internals", revision 307, section 14.1.3.3 EOF_Packet
  1178. Packet = <<16#05, 16#00, 16#00, 16#05, 16#fe, 16#00, 16#00, 16#02, 16#00>>,
  1179. <<Header:4/binary-unit:8, Body/binary>> = Packet,
  1180. %% Check header contents and body length
  1181. ?assertEqual({size(Body), 5, false}, parse_packet_header(Header)),
  1182. ok.
  1183. add_packet_headers_test() ->
  1184. {Data, 43} = add_packet_headers(<<"foo">>, 42),
  1185. ?assertEqual(<<3, 0, 0, 42, "foo">>, list_to_binary(Data)).
  1186. add_packet_headers_equal_to_0xffffff_test() ->
  1187. BigBin = binary:copy(<<1>>, 16#ffffff),
  1188. {Data, 44} = add_packet_headers(BigBin, 42),
  1189. ?assertEqual(<<16#ff, 16#ff, 16#ff, 42, BigBin/binary,
  1190. 0, 0, 0, 43>>,
  1191. list_to_binary(Data)).
  1192. add_packet_headers_greater_than_0xffffff_test() ->
  1193. BigBin = binary:copy(<<1>>, 16#ffffff),
  1194. {Data, 44} = add_packet_headers(<<BigBin/binary, "foo">>, 42),
  1195. ?assertEqual(<<16#ff, 16#ff, 16#ff, 42, BigBin/binary, 3, 0, 0, 43, "foo">>,
  1196. list_to_binary(Data)).
  1197. add_packet_headers_2_times_greater_than_0xffffff_test() ->
  1198. BigBin = binary:copy(<<1>>, 16#ffffff),
  1199. {Data, 45} = add_packet_headers(<<BigBin/binary, BigBin/binary, "foo">>, 42),
  1200. ?assertEqual(<<16#ff, 16#ff, 16#ff, 42, BigBin/binary,
  1201. 16#ff, 16#ff, 16#ff, 43, BigBin/binary,
  1202. 3, 0, 0, 44, "foo">>,
  1203. list_to_binary(Data)).
  1204. parse_ok_test() ->
  1205. Body = <<0, 5, 1, 2, 0, 0, 0, "Foo">>,
  1206. ?assertEqual(#ok{affected_rows = 5,
  1207. insert_id = 1,
  1208. status = ?SERVER_STATUS_AUTOCOMMIT,
  1209. warning_count = 0,
  1210. msg = <<"Foo">>},
  1211. parse_ok_packet(Body)).
  1212. parse_error_test() ->
  1213. %% Protocol 4.1
  1214. Body = <<255, 42, 0, "#", "XYZxx", "Foo">>,
  1215. ?assertEqual(#error{code = 42, state = <<"XYZxx">>, msg = <<"Foo">>},
  1216. parse_error_packet(Body)),
  1217. ok.
  1218. parse_eof_test() ->
  1219. %% Example from "MySQL Internals", revision 307, section 14.1.3.3 EOF_Packet
  1220. Packet = <<16#05, 16#00, 16#00, 16#05, 16#fe, 16#00, 16#00, 16#02, 16#00>>,
  1221. <<_Header:4/binary-unit:8, Body/binary>> = Packet,
  1222. %% Ignore header. Parse body as an eof_packet.
  1223. ?assertEqual(#eof{warning_count = 0,
  1224. status = ?SERVER_STATUS_AUTOCOMMIT},
  1225. parse_eof_packet(Body)),
  1226. ok.
  1227. hash_password_test() ->
  1228. ?assertEqual(<<222,207,222,139,41,181,202,13,191,241,
  1229. 234,234,73,127,244,101,205,3,28,251>>,
  1230. hash_password(<<"foo">>, <<"abcdefghijklmnopqrst">>)),
  1231. ?assertEqual(<<>>, hash_password(<<>>, <<"abcdefghijklmnopqrst">>)).
  1232. -endif.