mysql_tests.erl 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. %% MySQL/OTP – MySQL client library for Erlang/OTP
  2. %% Copyright (C) 2014-2016 Viktor Söderqvist
  3. %% 2017 Piotr Nosek
  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 performs test to an actual database.
  20. -module(mysql_tests).
  21. -include_lib("eunit/include/eunit.hrl").
  22. -define(user, "otptest").
  23. -define(password, "otptest").
  24. -define(ssl_user, "otptestssl").
  25. -define(ssl_password, "otptestssl").
  26. %% We need to set a the SQL mode so it is consistent across MySQL versions
  27. %% and distributions.
  28. -define(SQL_MODE, <<"NO_ENGINE_SUBSTITUTION">>).
  29. -define(create_table_t, <<"CREATE TABLE t ("
  30. " id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,"
  31. " bl BLOB,"
  32. " tx TEXT NOT NULL," %% No default value
  33. " f FLOAT,"
  34. " d DOUBLE,"
  35. " dc DECIMAL(5,3),"
  36. " y YEAR,"
  37. " ti TIME,"
  38. " ts TIMESTAMP,"
  39. " da DATE,"
  40. " c CHAR(2)"
  41. ") ENGINE=InnoDB">>).
  42. failing_connect_test() ->
  43. process_flag(trap_exit, true),
  44. {error, Error} = mysql:start_link([{user, "dummy"}, {password, "junk"}]),
  45. case Error of
  46. {1045, <<"28000">>, <<"Access denie", _/binary>>} ->
  47. ok; % MySQL 5.x, etc.
  48. {1251, <<"08004">>, <<"Client does not support authentication "
  49. "protocol requested by server; consider "
  50. "upgrading MariaDB client">>} ->
  51. ok % MariaDB 10.3.13
  52. end,
  53. receive
  54. {'EXIT', _Pid, Error} -> ok
  55. after 1000 ->
  56. error(no_exit_message)
  57. end,
  58. process_flag(trap_exit, false).
  59. successful_connect_test() ->
  60. %% A connection with a registered name and execute initial queries and
  61. %% create prepared statements.
  62. Pid = common_basic_check([{user, ?user}, {password, ?password}]),
  63. %% Test some gen_server callbacks not tested elsewhere
  64. State = get_state(Pid),
  65. ?assertMatch({ok, State}, mysql_conn:code_change("0.1.0", State, [])),
  66. ?assertMatch({error, _}, mysql_conn:code_change("2.0.0", unknown_state, [])),
  67. common_conn_close().
  68. common_basic_check(ExtraOpts) ->
  69. Options = [{name, {local, tardis}},
  70. {queries, ["SET @foo = 'bar'", "SELECT 1",
  71. "SELECT 1; SELECT 2"]},
  72. {prepare, [{foo, "SELECT @foo"}]} | ExtraOpts],
  73. {ok, Pid} = mysql:start_link(Options),
  74. %% Check that queries and prepare has been done.
  75. ?assertEqual({ok, [<<"@foo">>], [[<<"bar">>]]},
  76. mysql:execute(Pid, foo, [])),
  77. Pid.
  78. common_conn_close() ->
  79. Pid = whereis(tardis),
  80. process_flag(trap_exit, true),
  81. mysql:stop(Pid),
  82. receive
  83. {'EXIT', Pid, normal} -> ok
  84. after
  85. 5000 -> error({cant_stop_connection, Pid})
  86. end,
  87. process_flag(trap_exit, false).
  88. exit_normal_test() ->
  89. Options = [{user, ?user}, {password, ?password}],
  90. {ok, Pid} = mysql:start_link(Options),
  91. {ok, ok, LoggedErrors} = error_logger_acc:capture(fun () ->
  92. %% Stop the connection without noise, errors or messages
  93. mysql:stop(Pid),
  94. receive
  95. UnexpectedExitMessage -> UnexpectedExitMessage
  96. after 0 ->
  97. ok
  98. end
  99. end),
  100. %% Check that we got nothing in the error log.
  101. ?assertEqual([], LoggedErrors).
  102. server_disconnect_test() ->
  103. process_flag(trap_exit, true),
  104. Options = [{user, ?user}, {password, ?password}],
  105. {ok, Pid} = mysql:start_link(Options),
  106. {ok, ok, LoggedErrors} = error_logger_acc:capture(fun () ->
  107. %% Make the server close the connection after 1 second of inactivity.
  108. ok = mysql:query(Pid, <<"SET SESSION wait_timeout = 1">>),
  109. receive
  110. {'EXIT', Pid, tcp_closed} -> ok
  111. after 2000 ->
  112. no_exit_message
  113. end
  114. end),
  115. process_flag(trap_exit, false),
  116. %% Check that we got the expected errors in the error log.
  117. [{error, Msg1}, {error, Msg2}, {error_report, CrashReport}] = LoggedErrors,
  118. %% "Connection Id 24 closing with reason: tcp_closed"
  119. ?assert(lists:prefix("Connection Id", Msg1)),
  120. ExpectedPrefix = io_lib:format("** Generic server ~p terminating", [Pid]),
  121. ?assert(lists:prefix(lists:flatten(ExpectedPrefix), Msg2)),
  122. ?assertMatch({crash_report, _}, CrashReport).
  123. tcp_error_test() ->
  124. process_flag(trap_exit, true),
  125. Options = [{user, ?user}, {password, ?password}],
  126. {ok, Pid} = mysql:start_link(Options),
  127. {ok, ok, LoggedErrors} = error_logger_acc:capture(fun () ->
  128. %% Simulate a tcp error by sending a message. (Is there a better way?)
  129. Pid ! {tcp_error, dummy_socket, tcp_reason},
  130. receive
  131. {'EXIT', Pid, {tcp_error, tcp_reason}} -> ok
  132. after 1000 ->
  133. error(no_exit_message)
  134. end
  135. end),
  136. process_flag(trap_exit, false),
  137. %% Check that we got the expected crash report in the error log.
  138. [{error, Msg1}, {error, Msg2}, {error_report, CrashReport}] = LoggedErrors,
  139. %% "Connection Id 24 closing with reason: tcp_closed"
  140. ?assert(lists:prefix("Connection Id", Msg1)),
  141. ExpectedPrefix = io_lib:format("** Generic server ~p terminating", [Pid]),
  142. ?assert(lists:prefix(lists:flatten(ExpectedPrefix), Msg2)),
  143. ?assertMatch({crash_report, _}, CrashReport).
  144. keep_alive_test() ->
  145. %% Let the connection send a few pings.
  146. process_flag(trap_exit, true),
  147. Options = [{user, ?user}, {password, ?password}, {keep_alive, 20}],
  148. {ok, Pid} = mysql:start_link(Options),
  149. receive after 70 -> ok end,
  150. State = get_state(Pid),
  151. [state, _Version, _ConnectionId, Socket | _] = tuple_to_list(State),
  152. {ok, ExitMessage, LoggedErrors} = error_logger_acc:capture(fun () ->
  153. gen_tcp:close(Socket),
  154. receive
  155. Message -> Message
  156. after 1000 ->
  157. ping_didnt_crash_connection
  158. end
  159. end),
  160. process_flag(trap_exit, false),
  161. %% Check that we got the expected crash report in the error log.
  162. ?assertMatch({'EXIT', Pid, _Reason}, ExitMessage),
  163. [{error, LoggedMsg}, {error_report, LoggedReport}] = LoggedErrors,
  164. ExpectedPrefix = io_lib:format("** Generic server ~p terminating", [Pid]),
  165. ?assert(lists:prefix(lists:flatten(ExpectedPrefix), LoggedMsg)),
  166. ?assertMatch({crash_report, _}, LoggedReport),
  167. ?assertExit(noproc, mysql:stop(Pid)).
  168. reset_connection_test() ->
  169. %% Ignored test with MySQL earlier than 5.7
  170. Options = [{user, ?user}, {password, ?password}, {keep_alive, true}],
  171. {ok, Pid} = mysql:start_link(Options),
  172. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  173. ok = mysql:query(Pid, <<"USE otptest">>),
  174. ok = mysql:query(Pid, <<"SET autocommit = 1">>),
  175. ok = mysql:query(Pid, ?create_table_t),
  176. ok = mysql:query(Pid, <<"INSERT INTO t (id, tx) VALUES (1, 'text 1')">>),
  177. ?assertEqual(1, mysql:insert_id(Pid)), %% auto_increment starts from 1
  178. case mysql:reset_connection(Pid) of
  179. ok ->
  180. ?assertEqual(0, mysql:insert_id(Pid)); %% insertid reset to 0;
  181. _Error ->
  182. ?assertEqual(1, mysql:insert_id(Pid)) %% reset failed
  183. end,
  184. mysql:stop(Pid),
  185. ok.
  186. unix_socket_test() ->
  187. try
  188. list_to_integer(erlang:system_info(otp_release))
  189. of
  190. %% Supported in OTP >= 19
  191. OtpRelease when OtpRelease >= 19 ->
  192. %% Get socket file to use
  193. {ok, Pid1} = mysql:start_link([{user, ?user},
  194. {password, ?password}]),
  195. {ok, [<<"@@socket">>], [SockFile]} = mysql:query(Pid1,
  196. "SELECT @@socket"),
  197. mysql:stop(Pid1),
  198. %% Connect through unix socket
  199. case mysql:start_link([{host, {local, SockFile}},
  200. {user, ?user}, {password, ?password}]) of
  201. {ok, Pid2} ->
  202. ?assertEqual({ok, [<<"1">>], [[1]]},
  203. mysql:query(Pid2, <<"SELECT 1">>)),
  204. mysql:stop(Pid2);
  205. {error, eafnosupport} ->
  206. error_logger:info_msg("Skipping unix socket test. "
  207. "Not supported on this OS.~n")
  208. end;
  209. OtpRelease ->
  210. error_logger:info_msg("Skipping unix socket test. Current OTP "
  211. "release is ~B. Required release is >= 19.~n",
  212. [OtpRelease])
  213. catch
  214. error:badarg ->
  215. error_logger:info_msg("Skipping unix socket tests. Current OTP "
  216. "release could not be determined.~n")
  217. end.
  218. connect_queries_failure_test() ->
  219. process_flag(trap_exit, true),
  220. {error, Reason} = mysql:start_link([{user, ?user}, {password, ?password},
  221. {queries, ["foo"]}]),
  222. receive
  223. {'EXIT', _Pid, Reason} -> ok
  224. after 1000 ->
  225. exit(no_exit_message)
  226. end,
  227. process_flag(trap_exit, false).
  228. connect_prepare_failure_test() ->
  229. process_flag(trap_exit, true),
  230. {error, Reason} = mysql:start_link([{user, ?user}, {password, ?password},
  231. {prepare, [{foo, "foo"}]}]),
  232. receive
  233. {'EXIT', _Pid, Reason} -> ok
  234. after 1000 ->
  235. exit(no_exit_message)
  236. end,
  237. process_flag(trap_exit, false).
  238. %% For R16B where sys:get_state/1 is not available.
  239. get_state(Process) ->
  240. {status,_,_,[_,_,_,_,Misc]} = sys:get_status(Process),
  241. hd([State || {data,[{"State", State}]} <- Misc]).
  242. query_test_() ->
  243. {setup,
  244. fun () ->
  245. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  246. {log_warnings, false},
  247. {keep_alive, true}]),
  248. ok = mysql:query(Pid, <<"DROP DATABASE IF EXISTS otptest">>),
  249. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  250. ok = mysql:query(Pid, <<"USE otptest">>),
  251. ok = mysql:query(Pid, <<"SET autocommit = 1">>),
  252. ok = mysql:query(Pid, <<"SET SESSION sql_mode = ?">>, [?SQL_MODE]),
  253. Pid
  254. end,
  255. fun (Pid) ->
  256. ok = mysql:query(Pid, <<"DROP DATABASE otptest">>),
  257. mysql:stop(Pid)
  258. end,
  259. fun (Pid) ->
  260. [{"Select db on connect", fun () -> connect_with_db(Pid) end},
  261. {"Autocommit", fun () -> autocommit(Pid) end},
  262. {"Encode", fun () -> encode(Pid) end},
  263. {"Basic queries", fun () -> basic_queries(Pid) end},
  264. {"Filtermap queries", fun () -> filtermap_queries(Pid) end},
  265. {"FOUND_ROWS option", fun () -> found_rows(Pid) end},
  266. {"Multi statements", fun () -> multi_statements(Pid) end},
  267. {"Text protocol", fun () -> text_protocol(Pid) end},
  268. {"Binary protocol", fun () -> binary_protocol(Pid) end},
  269. {"FLOAT rounding", fun () -> float_rounding(Pid) end},
  270. {"DECIMAL", fun () -> decimal(Pid) end},
  271. {"INT", fun () -> int(Pid) end},
  272. {"BIT(N)", fun () -> bit(Pid) end},
  273. {"DATE", fun () -> date(Pid) end},
  274. {"TIME", fun () -> time(Pid) end},
  275. {"DATETIME", fun () -> datetime(Pid) end},
  276. {"JSON", fun () -> json(Pid) end},
  277. {"Microseconds", fun () -> microseconds(Pid) end},
  278. {"Invalid params", fun () -> invalid_params(Pid) end}]
  279. end}.
  280. connect_with_db(_Pid) ->
  281. %% Make another connection and set the db in the handshake phase
  282. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  283. {database, "otptest"}]),
  284. ?assertMatch({ok, _, [[<<"otptest">>]]},
  285. mysql:query(Pid, "SELECT DATABASE()")),
  286. mysql:stop(Pid).
  287. log_warnings_test() ->
  288. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password}]),
  289. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  290. ok = mysql:query(Pid, <<"USE otptest">>),
  291. ok = mysql:query(Pid, <<"SET SESSION sql_mode = ?">>, [?SQL_MODE]),
  292. %% Capture error log to check that we get a warning logged
  293. ok = mysql:query(Pid, "CREATE TABLE foo (x INT NOT NULL)"),
  294. {ok, insrt} = mysql:prepare(Pid, insrt, "INSERT INTO foo () VALUES ()"),
  295. {ok, ok, LoggedErrors} = error_logger_acc:capture(fun () ->
  296. ok = mysql:query(Pid, "INSERT INTO foo () VALUES ()"),
  297. ok = mysql:query(Pid, "INSeRT INtO foo () VaLUeS ()", []),
  298. ok = mysql:execute(Pid, insrt, [])
  299. end),
  300. [{_, Log1}, {_, Log2}, {_, Log3}] = LoggedErrors,
  301. ?assertEqual("Warning 1364: Field 'x' doesn't have a default value\n"
  302. " in INSERT INTO foo () VALUES ()\n", Log1),
  303. ?assertEqual("Warning 1364: Field 'x' doesn't have a default value\n"
  304. " in INSeRT INtO foo () VaLUeS ()\n", Log2),
  305. ?assertEqual("Warning 1364: Field 'x' doesn't have a default value\n"
  306. " in INSERT INTO foo () VALUES ()\n", Log3),
  307. mysql:stop(Pid).
  308. autocommit(Pid) ->
  309. ?assert(mysql:autocommit(Pid)),
  310. ok = mysql:query(Pid, <<"SET autocommit = 0">>),
  311. ?assertNot(mysql:autocommit(Pid)),
  312. ok = mysql:query(Pid, <<"SET autocommit = 1">>),
  313. ?assert(mysql:autocommit(Pid)).
  314. encode(Pid) ->
  315. %% Test with backslash escapes enabled and disabled.
  316. {ok, _, [[OldMode]]} = mysql:query(Pid, "SELECT @@sql_mode"),
  317. ok = mysql:query(Pid, "SET sql_mode = ''"),
  318. ?assertEqual(<<"'foo\\\\bar''baz'">>,
  319. iolist_to_binary(mysql:encode(Pid, "foo\\bar'baz"))),
  320. ok = mysql:query(Pid, "SET sql_mode = 'NO_BACKSLASH_ESCAPES'"),
  321. ?assertEqual(<<"'foo\\bar''baz'">>,
  322. iolist_to_binary(mysql:encode(Pid, "foo\\bar'baz"))),
  323. ok = mysql:query(Pid, "SET sql_mode = ?", [OldMode]).
  324. basic_queries(Pid) ->
  325. %% warning count
  326. ?assertEqual(ok, mysql:query(Pid, <<"DROP TABLE IF EXISTS foo">>)),
  327. ?assertEqual(1, mysql:warning_count(Pid)),
  328. %% SQL parse error
  329. ?assertMatch({error, {1064, <<"42000">>, <<"You have an erro", _/binary>>}},
  330. mysql:query(Pid, <<"FOO">>)),
  331. %% Simple resultset with various types
  332. ?assertEqual({ok, [<<"i">>, <<"s">>], [[42, <<"foo">>]]},
  333. mysql:query(Pid, <<"SELECT 42 AS i, 'foo' AS s;">>)),
  334. ok.
  335. filtermap_queries(Pid) ->
  336. ok = mysql:query(Pid, ?create_table_t),
  337. ok = mysql:query(Pid, <<"INSERT INTO t (id, tx) VALUES (1, 'text 1')">>),
  338. ok = mysql:query(Pid, <<"INSERT INTO t (id, tx) VALUES (2, 'text 2')">>),
  339. ok = mysql:query(Pid, <<"INSERT INTO t (id, tx) VALUES (3, 'text 3')">>),
  340. Query = <<"SELECT id, tx FROM t ORDER BY id">>,
  341. %% one-ary filtermap fun
  342. FilterMap1 = fun
  343. ([1|_]) ->
  344. true;
  345. ([2|_]) ->
  346. false;
  347. (Row1=[3|_]) ->
  348. {true, list_to_tuple(Row1)}
  349. end,
  350. %% two-ary filtermap fun
  351. FilterMap2 = fun
  352. (_, Row2) ->
  353. FilterMap1(Row2)
  354. end,
  355. Expected = [[1, <<"text 1">>], {3, <<"text 3">>}],
  356. %% test with plain query
  357. {ok, _, Rows1}=mysql:query(Pid, Query, FilterMap1),
  358. ?assertEqual(Expected, Rows1),
  359. {ok, _, Rows2}=mysql:query(Pid, Query, FilterMap2),
  360. ?assertEqual(Expected, Rows2),
  361. %% test with parameterized query
  362. {ok, _, Rows3}=mysql:query(Pid, Query, [], FilterMap1),
  363. ?assertEqual(Expected, Rows3),
  364. {ok, _, Rows4}=mysql:query(Pid, Query, [], FilterMap2),
  365. ?assertEqual(Expected, Rows4),
  366. %% test with prepared statement
  367. {ok, PrepStmt} = mysql:prepare(Pid, Query),
  368. {ok, _, Rows5}=mysql:execute(Pid, PrepStmt, [], FilterMap1),
  369. ?assertEqual(Expected, Rows5),
  370. {ok, _, Rows6}=mysql:execute(Pid, PrepStmt, [], FilterMap2),
  371. ?assertEqual(Expected, Rows6),
  372. ok = mysql:query(Pid, <<"DROP TABLE t">>).
  373. found_rows(Pid) ->
  374. Options = [{user, ?user}, {password, ?password}, {log_warnings, false},
  375. {keep_alive, true}, {found_rows, true}],
  376. {ok, FRPid} = mysql:start_link(Options),
  377. ok = mysql:query(FRPid, <<"USE otptest">>),
  378. ok = mysql:query(Pid, ?create_table_t),
  379. ok = mysql:query(Pid, <<"INSERT INTO t (id, tx) VALUES (1, 'text')">>),
  380. %% With no found_rows option, affected_rows for update returns 0
  381. ok = mysql:query(Pid, <<"UPDATE t SET tx = 'text' WHERE id = 1">>),
  382. ?assertEqual(0, mysql:affected_rows(Pid)),
  383. %% With found_rows, affected_rows returns the number of rows found
  384. ok = mysql:query(FRPid, <<"UPDATE t SET tx = 'text' WHERE id = 1">>),
  385. ?assertEqual(1, mysql:affected_rows(FRPid)),
  386. ok = mysql:query(Pid, <<"DROP TABLE t">>).
  387. multi_statements(Pid) ->
  388. %% Multiple statements, no result set
  389. ?assertEqual(ok, mysql:query(Pid, "CREATE TABLE foo (bar INT);"
  390. "DROP TABLE foo;")),
  391. %% Multiple statements, one result set
  392. ?assertEqual({ok, [<<"foo">>], [[42]]},
  393. mysql:query(Pid, "CREATE TABLE foo (bar INT);"
  394. "DROP TABLE foo;"
  395. "SELECT 42 AS foo;")),
  396. %% Multiple statements, multiple result sets
  397. ?assertEqual({ok, [{[<<"foo">>], [[42]]}, {[<<"bar">>], [[<<"baz">>]]}]},
  398. mysql:query(Pid, "SELECT 42 AS foo; SELECT 'baz' AS bar;")),
  399. %% Multiple results in a prepared statement.
  400. %% Preparing "SELECT ...; SELECT ...;" gives a syntax error although the
  401. %% docs say it should be possible.
  402. %% Instead, test executing a stored procedure that returns multiple result
  403. %% sets using a prepared statement.
  404. CreateProc = "CREATE PROCEDURE multifoo() BEGIN\n"
  405. " SELECT 42 AS foo;\n"
  406. " SELECT 'baz' AS bar;\n"
  407. "END;\n",
  408. ok = mysql:query(Pid, CreateProc),
  409. ?assertEqual({ok, multifoo},
  410. mysql:prepare(Pid, multifoo, "CALL multifoo();")),
  411. ?assertEqual({ok, [{[<<"foo">>], [[42]]}, {[<<"bar">>], [[<<"baz">>]]}]},
  412. mysql:execute(Pid, multifoo, [])),
  413. ?assertEqual(ok, mysql:unprepare(Pid, multifoo)),
  414. ?assertEqual(ok, mysql:query(Pid, "DROP PROCEDURE multifoo;")),
  415. ok.
  416. text_protocol(Pid) ->
  417. ok = mysql:query(Pid, ?create_table_t),
  418. ok = mysql:query(Pid, <<"INSERT INTO t (bl, f, d, dc, y, ti, ts, da, c)"
  419. " VALUES ('blob', 3.14, 3.14, 3.14, 2014,"
  420. "'00:22:11', '2014-11-03 00:22:24', '2014-11-03',"
  421. " NULL)">>),
  422. ?assertEqual(1, mysql:warning_count(Pid)), %% tx has no default value
  423. ?assertEqual(1, mysql:insert_id(Pid)), %% auto_increment starts from 1
  424. ?assertEqual(1, mysql:affected_rows(Pid)),
  425. %% select
  426. {ok, Columns, Rows} = mysql:query(Pid, <<"SELECT * FROM t">>),
  427. ?assertEqual([<<"id">>, <<"bl">>, <<"tx">>, <<"f">>, <<"d">>, <<"dc">>,
  428. <<"y">>, <<"ti">>, <<"ts">>, <<"da">>, <<"c">>], Columns),
  429. ?assertEqual([[1, <<"blob">>, <<>>, 3.14, 3.14, 3.14,
  430. 2014, {0, {0, 22, 11}},
  431. {{2014, 11, 03}, {00, 22, 24}}, {2014, 11, 03}, null]],
  432. Rows),
  433. ok = mysql:query(Pid, <<"DROP TABLE t">>).
  434. binary_protocol(Pid) ->
  435. ok = mysql:query(Pid, ?create_table_t),
  436. %% The same queries as in the text protocol. Expect the same results.
  437. {ok, Ins} = mysql:prepare(Pid, <<"INSERT INTO t (bl, tx, f, d, dc, y, ti,"
  438. " ts, da, c)"
  439. " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)">>),
  440. %% 16#161 is the codepoint for "s with caron"; <<197, 161>> in UTF-8.
  441. ok = mysql:execute(Pid, Ins, [<<"blob">>, [16#161], 3.14, 3.14, 3.14,
  442. 2014, {0, {0, 22, 11}},
  443. {{2014, 11, 03}, {0, 22, 24}},
  444. {2014, 11, 03}, null]),
  445. {ok, Stmt} = mysql:prepare(Pid, <<"SELECT * FROM t WHERE id=?">>),
  446. {ok, Columns, Rows} = mysql:execute(Pid, Stmt, [1]),
  447. ?assertEqual([<<"id">>, <<"bl">>, <<"tx">>, <<"f">>, <<"d">>, <<"dc">>,
  448. <<"y">>, <<"ti">>,
  449. <<"ts">>, <<"da">>, <<"c">>], Columns),
  450. ?assertEqual([[1, <<"blob">>, <<197, 161>>, 3.14, 3.14, 3.14,
  451. 2014, {0, {0, 22, 11}},
  452. {{2014, 11, 03}, {00, 22, 24}}, {2014, 11, 03}, null]],
  453. Rows),
  454. ok = mysql:query(Pid, <<"DROP TABLE t">>).
  455. float_rounding(Pid) ->
  456. %% This is to make sure we get the same values for 32-bit FLOATs in the text
  457. %% and binary protocols for ordinary queries and prepared statements
  458. %% respectively.
  459. %%
  460. %% MySQL rounds to 6 significant digits when "printing" floats over the
  461. %% text protocol. When we receive a float on the binary protocol, we round
  462. %% it in the same way to match what MySQL does on the text protocol. This
  463. %% way we should to get the same values regardless of which protocol is
  464. %% used.
  465. %% Table for testing floats
  466. ok = mysql:query(Pid, "CREATE TABLE f (f FLOAT)"),
  467. %% Prepared statements
  468. {ok, Insert} = mysql:prepare(Pid, "INSERT INTO f (f) VALUES (?)"),
  469. {ok, Select} = mysql:prepare(Pid, "SELECT f FROM f"),
  470. %% [{Input, Expected}]
  471. TestData = [{1.0, 1.0}, {0.0, 0.0}, {3.14, 3.14}, {0.2, 0.2},
  472. {0.20082111, 0.200821}, {0.000123456789, 0.000123457},
  473. {33.3333333, 33.3333}, {-33.2233443322, -33.2233},
  474. {400.0123, 400.012}, {1000.1234, 1000.12},
  475. {999.00009, 999.0},
  476. {1234.5678, 1234.57}, {68888.8888, 68888.9},
  477. {123456.789, 123457.0}, {7654321.0, 7654320.0},
  478. {80001111.1, 80001100.0}, {987654321.0, 987654000.0},
  479. {-123456789.0, -123457000.0},
  480. {2.12345111e-23, 2.12345e-23}, {-2.12345111e-23, -2.12345e-23},
  481. {2.12345111e23, 2.12345e23}, {-2.12345111e23, -2.12345e23}],
  482. lists:foreach(fun ({Input, Expected}) ->
  483. %% Insert using binary protocol (sending it as a double)
  484. ok = mysql:execute(Pid, Insert, [Input]),
  485. %% Text (plain query)
  486. {ok, _, [[Value]]} = mysql:query(Pid, "SELECT f FROM f"),
  487. ?assertEqual(Expected, Value),
  488. %% Binary (prepared statement)
  489. {ok, _, [[BinValue]]} = mysql:execute(Pid, Select, []),
  490. ?assertEqual(Expected, BinValue),
  491. %% cleanup before the next test
  492. ok = mysql:query(Pid, "DELETE FROM f")
  493. end,
  494. TestData),
  495. ok = mysql:query(Pid, "DROP TABLE f").
  496. decimal(Pid) ->
  497. %% As integer when S == 0
  498. ok = mysql:query(Pid, "CREATE TABLE dec0 (d DECIMAL(50, 0))"),
  499. write_read_text_binary(
  500. Pid, 14159265358979323846264338327950288419716939937510,
  501. <<"14159265358979323846264338327950288419716939937510">>,
  502. <<"dec0">>, <<"d">>
  503. ),
  504. write_read_text_binary(
  505. Pid, -14159265358979323846264338327950288419716939937510,
  506. <<"-14159265358979323846264338327950288419716939937510">>,
  507. <<"dec0">>, <<"d">>
  508. ),
  509. ok = mysql:query(Pid, "DROP TABLE dec0"),
  510. %% As float when P =< 15, S > 0
  511. ok = mysql:query(Pid, "CREATE TABLE dec15 (d DECIMAL(15, 14))"),
  512. write_read_text_binary(Pid, 3.14159265358979, <<"3.14159265358979">>,
  513. <<"dec15">>, <<"d">>),
  514. write_read_text_binary(Pid, -3.14159265358979, <<"-3.14159265358979">>,
  515. <<"dec15">>, <<"d">>),
  516. write_read_text_binary(Pid, 3.0, <<"3">>, <<"dec15">>, <<"d">>),
  517. ok = mysql:query(Pid, "DROP TABLE dec15"),
  518. %% As binary when P >= 16, S > 0
  519. ok = mysql:query(Pid, "CREATE TABLE dec16 (d DECIMAL(16, 15))"),
  520. write_read_text_binary(Pid, <<"3.141592653589793">>,
  521. <<"3.141592653589793">>, <<"dec16">>, <<"d">>),
  522. write_read_text_binary(Pid, <<"-3.141592653589793">>,
  523. <<"-3.141592653589793">>, <<"dec16">>, <<"d">>),
  524. write_read_text_binary(Pid, <<"3.000000000000000">>, <<"3">>,
  525. <<"dec16">>, <<"d">>),
  526. ok = mysql:query(Pid, "DROP TABLE dec16").
  527. int(Pid) ->
  528. ok = mysql:query(Pid, "CREATE TABLE ints (i INT)"),
  529. write_read_text_binary(Pid, 42, <<"42">>, <<"ints">>, <<"i">>),
  530. write_read_text_binary(Pid, -42, <<"-42">>, <<"ints">>, <<"i">>),
  531. write_read_text_binary(Pid, 987654321, <<"987654321">>, <<"ints">>,
  532. <<"i">>),
  533. write_read_text_binary(Pid, -987654321, <<"-987654321">>,
  534. <<"ints">>, <<"i">>),
  535. ok = mysql:query(Pid, "DROP TABLE ints"),
  536. %% Overflow with TINYINT
  537. ok = mysql:query(Pid, "CREATE TABLE tint (i TINYINT)"),
  538. write_read_text_binary(Pid, 127, <<"1000">>, <<"tint">>, <<"i">>),
  539. write_read_text_binary(Pid, -128, <<"-1000">>, <<"tint">>, <<"i">>),
  540. ok = mysql:query(Pid, "DROP TABLE tint"),
  541. %% TINYINT UNSIGNED
  542. ok = mysql:query(Pid, "CREATE TABLE tuint (i TINYINT UNSIGNED)"),
  543. write_read_text_binary(Pid, 240, <<"240">>, <<"tuint">>, <<"i">>),
  544. ok = mysql:query(Pid, "DROP TABLE tuint"),
  545. %% SMALLINT
  546. ok = mysql:query(Pid, "CREATE TABLE sint (i SMALLINT)"),
  547. write_read_text_binary(Pid, 32000, <<"32000">>, <<"sint">>, <<"i">>),
  548. write_read_text_binary(Pid, -32000, <<"-32000">>, <<"sint">>, <<"i">>),
  549. ok = mysql:query(Pid, "DROP TABLE sint"),
  550. %% SMALLINT UNSIGNED
  551. ok = mysql:query(Pid, "CREATE TABLE suint (i SMALLINT UNSIGNED)"),
  552. write_read_text_binary(Pid, 64000, <<"64000">>, <<"suint">>, <<"i">>),
  553. ok = mysql:query(Pid, "DROP TABLE suint"),
  554. %% MEDIUMINT
  555. ok = mysql:query(Pid, "CREATE TABLE mint (i MEDIUMINT)"),
  556. write_read_text_binary(Pid, 8388000, <<"8388000">>,
  557. <<"mint">>, <<"i">>),
  558. write_read_text_binary(Pid, -8388000, <<"-8388000">>,
  559. <<"mint">>, <<"i">>),
  560. ok = mysql:query(Pid, "DROP TABLE mint"),
  561. %% MEDIUMINT UNSIGNED
  562. ok = mysql:query(Pid, "CREATE TABLE muint (i MEDIUMINT UNSIGNED)"),
  563. write_read_text_binary(Pid, 16777000, <<"16777000">>,
  564. <<"muint">>, <<"i">>),
  565. ok = mysql:query(Pid, "DROP TABLE muint"),
  566. %% BIGINT
  567. ok = mysql:query(Pid, "CREATE TABLE bint (i BIGINT)"),
  568. write_read_text_binary(Pid, 123456789012, <<"123456789012">>,
  569. <<"bint">>, <<"i">>),
  570. write_read_text_binary(Pid, -123456789012, <<"-123456789012">>,
  571. <<"bint">>, <<"i">>),
  572. ok = mysql:query(Pid, "DROP TABLE bint"),
  573. %% BIGINT UNSIGNED
  574. ok = mysql:query(Pid, "CREATE TABLE buint (i BIGINT UNSIGNED)"),
  575. write_read_text_binary(Pid, 18446744073709551000,
  576. <<"18446744073709551000">>,
  577. <<"buint">>, <<"i">>),
  578. ok = mysql:query(Pid, "DROP TABLE buint").
  579. %% The BIT(N) datatype in MySQL 5.0.3 and later: the equivallent to bitstring()
  580. bit(Pid) ->
  581. ok = mysql:query(Pid, "CREATE TABLE bits (b BIT(11))"),
  582. write_read_text_binary(Pid, <<16#ff, 0:3>>, <<"b'11111111000'">>,
  583. <<"bits">>, <<"b">>),
  584. write_read_text_binary(Pid, <<16#7f, 6:3>>, <<"b'01111111110'">>,
  585. <<"bits">>, <<"b">>),
  586. ok = mysql:query(Pid, "DROP TABLE bits").
  587. date(Pid) ->
  588. ok = mysql:query(Pid, "CREATE TABLE d (d DATE)"),
  589. lists:foreach(
  590. fun ({Value, SqlLiteral}) ->
  591. write_read_text_binary(Pid, Value, SqlLiteral, <<"d">>, <<"d">>)
  592. end,
  593. [{{2014, 11, 03}, <<"'2014-11-03'">>},
  594. {{0, 0, 0}, <<"'0000-00-00'">>}]
  595. ),
  596. ok = mysql:query(Pid, "DROP TABLE d").
  597. %% Test TIME value representation. There are a few things to check.
  598. time(Pid) ->
  599. ok = mysql:query(Pid, "CREATE TABLE tm (tm TIME)"),
  600. lists:foreach(
  601. fun ({Value, SqlLiteral}) ->
  602. write_read_text_binary(Pid, Value, SqlLiteral, <<"tm">>, <<"tm">>)
  603. end,
  604. [{{0, {10, 11, 12}}, <<"'10:11:12'">>},
  605. {{5, {0, 0, 1}}, <<"'120:00:01'">>},
  606. {{-1, {23, 59, 59}}, <<"'-00:00:01'">>},
  607. {{-1, {23, 59, 0}}, <<"'-00:01:00'">>},
  608. {{-1, {23, 0, 0}}, <<"'-01:00:00'">>},
  609. {{-1, {0, 0, 0}}, <<"'-24:00:00'">>},
  610. {{-5, {10, 0, 0}}, <<"'-110:00:00'">>},
  611. {{0, {0, 0, 0}}, <<"'00:00:00'">>}]
  612. ),
  613. %% Zero seconds as a float.
  614. ok = mysql:query(Pid, "INSERT INTO tm (tm) VALUES (?)",
  615. [{-1, {1, 2, 0.0}}]),
  616. ?assertEqual({ok, [<<"tm">>], [[{-1, {1, 2, 0}}]]},
  617. mysql:query(Pid, "SELECT tm FROM tm")),
  618. ok = mysql:query(Pid, "DROP TABLE tm").
  619. datetime(Pid) ->
  620. ok = mysql:query(Pid, "CREATE TABLE dt (dt DATETIME)"),
  621. lists:foreach(
  622. fun ({Value, SqlLiteral}) ->
  623. write_read_text_binary(Pid, Value, SqlLiteral, <<"dt">>, <<"dt">>)
  624. end,
  625. [{{{2014, 12, 14}, {19, 39, 20}}, <<"'2014-12-14 19:39:20'">>},
  626. {{{2014, 12, 14}, {0, 0, 0}}, <<"'2014-12-14 00:00:00'">>},
  627. {{{0, 0, 0}, {0, 0, 0}}, <<"'0000-00-00 00:00:00'">>}]
  628. ),
  629. ok = mysql:query(Pid, "DROP TABLE dt").
  630. json(Pid) ->
  631. Version = db_version_string(Pid),
  632. try
  633. is_mariadb(Version) andalso throw(no_mariadb),
  634. Version1 = parse_db_version(Version),
  635. Version1 >= [5, 7, 8] orelse throw(version_too_small)
  636. of _ ->
  637. test_valid_json(Pid),
  638. test_invalid_json(Pid)
  639. catch
  640. throw:no_mariadb ->
  641. error_logger:info_msg("Skipping JSON test, not supported on"
  642. " MariaDB.~n");
  643. throw:version_too_small ->
  644. error_logger:info_msg("Skipping JSON test. Current MySQL version"
  645. " is ~s. Required version is >= 5.7.8.~n",
  646. [Version])
  647. end.
  648. test_valid_json(Pid) ->
  649. ok = mysql:query(Pid, "CREATE TABLE json_t (json_c JSON)"),
  650. Value = <<"'{\"a\": 1, \"b\": {\"c\": [1, 2, 3, 4]}}'">>,
  651. Expected = <<"{\"a\": 1, \"b\": {\"c\": [1, 2, 3, 4]}}">>,
  652. write_read_text_binary(Pid, Expected, Value,
  653. <<"json_t">>, <<"json_c">>),
  654. ok = mysql:query(Pid, "DROP TABLE json_t").
  655. test_invalid_json(Pid) ->
  656. ok = mysql:query(Pid, "CREATE TABLE json_t (json_c JSON)"),
  657. InvalidJson = <<"'{\"a\": \"c\": 2}'">>,
  658. ?assertMatch({error,{3140, <<"22032">>, _}},
  659. mysql:query(Pid, <<"INSERT INTO json_t (json_c)"
  660. " VALUES (", InvalidJson/binary,
  661. ")">>)),
  662. ok = mysql:query(Pid, "DROP TABLE json_t").
  663. microseconds(Pid) ->
  664. %% Check whether we have the required version for this testcase.
  665. Version = db_version_string(Pid),
  666. try
  667. Version1 = parse_db_version(Version),
  668. Version1 >= [5, 6, 4] orelse throw(nope)
  669. of _ ->
  670. test_time_microseconds(Pid),
  671. test_datetime_microseconds(Pid)
  672. catch _:_ ->
  673. error_logger:info_msg("Skipping microseconds test. Current MySQL"
  674. " version is ~s. Required version is >= 5.6.4.~n",
  675. [Version])
  676. end.
  677. test_time_microseconds(Pid) ->
  678. ok = mysql:query(Pid, "CREATE TABLE m (t TIME(6))"),
  679. %% Positive time
  680. write_read_text_binary(Pid, {0, {23, 59, 57.654321}},
  681. <<"'23:59:57.654321'">>, <<"m">>, <<"t">>),
  682. %% Negative time
  683. write_read_text_binary(Pid, {-1, {23, 59, 57.654321}},
  684. <<"'-00:00:02.345679'">>, <<"m">>, <<"t">>),
  685. ok = mysql:query(Pid, "DROP TABLE m").
  686. test_datetime_microseconds(Pid) ->
  687. ok = mysql:query(Pid, "CREATE TABLE dt (dt DATETIME(6))"),
  688. write_read_text_binary(Pid, {{2014, 11, 23}, {23, 59, 57.654321}},
  689. <<"'2014-11-23 23:59:57.654321'">>, <<"dt">>,
  690. <<"dt">>),
  691. ok = mysql:query(Pid, "DROP TABLE dt").
  692. invalid_params(Pid) ->
  693. {ok, StmtId} = mysql:prepare(Pid, "SELECT ?"),
  694. ?assertError(badarg, mysql:execute(Pid, StmtId, [x])),
  695. ?assertError(badarg, mysql:query(Pid, "SELECT ?", [x])),
  696. ok = mysql:unprepare(Pid, StmtId).
  697. %% @doc Tests write and read in text and the binary protocol, all combinations.
  698. %% This helper function assumes an empty table with a single column.
  699. write_read_text_binary(Conn, Term, SqlLiteral, Table, Column) ->
  700. SelectQuery = <<"SELECT ", Column/binary, " FROM ", Table/binary>>,
  701. {ok, SelectStmt} = mysql:prepare(Conn, SelectQuery),
  702. %% Insert as text, read text and binary, delete
  703. InsertQuery = <<"INSERT INTO ", Table/binary, " (", Column/binary, ")"
  704. " VALUES (", SqlLiteral/binary, ")">>,
  705. ok = mysql:query(Conn, InsertQuery),
  706. R = mysql:query(Conn, SelectQuery),
  707. ?assertEqual({ok, [Column], [[Term]]}, R),
  708. ?assertEqual({ok, [Column], [[Term]]}, mysql:execute(Conn, SelectStmt, [])),
  709. mysql:query(Conn, <<"DELETE FROM ", Table/binary>>),
  710. %% Insert as binary, read text and binary, delete
  711. InsertQ = <<"INSERT INTO ", Table/binary, " (", Column/binary, ")",
  712. " VALUES (?)">>,
  713. {ok, InsertStmt} = mysql:prepare(Conn, InsertQ),
  714. ok = mysql:execute(Conn, InsertStmt, [Term]),
  715. ok = mysql:unprepare(Conn, InsertStmt),
  716. ?assertEqual({ok, [Column], [[Term]]}, mysql:query(Conn, SelectQuery)),
  717. ?assertEqual({ok, [Column], [[Term]]}, mysql:execute(Conn, SelectStmt, [])),
  718. mysql:query(Conn, <<"DELETE FROM ", Table/binary>>),
  719. %% Cleanup
  720. ok = mysql:unprepare(Conn, SelectStmt).
  721. %% --------------------------------------------------------------------------
  722. timeout_test_() ->
  723. {setup,
  724. fun () ->
  725. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  726. {log_warnings, false}]),
  727. Pid
  728. end,
  729. fun (Pid) ->
  730. mysql:stop(Pid)
  731. end,
  732. {with, [fun (Pid) ->
  733. %% SLEEP was added in MySQL 5.0.12
  734. ?assertEqual({ok, [<<"SLEEP(5)">>], [[1]]},
  735. mysql:query(Pid, <<"SELECT SLEEP(5)">>, 40)),
  736. %% A query after an interrupted query shouldn't get a timeout.
  737. ?assertMatch({ok,[<<"42">>], [[42]]},
  738. mysql:query(Pid, <<"SELECT 42">>)),
  739. %% Parametrized query
  740. ?assertEqual({ok, [<<"SLEEP(?)">>], [[1]]},
  741. mysql:query(Pid, <<"SELECT SLEEP(?)">>, [5], 40)),
  742. %% Prepared statement
  743. {ok, Stmt} = mysql:prepare(Pid, <<"SELECT SLEEP(?)">>),
  744. ?assertEqual({ok, [<<"SLEEP(?)">>], [[1]]},
  745. mysql:execute(Pid, Stmt, [5], 40)),
  746. ok = mysql:unprepare(Pid, Stmt)
  747. end]}}.
  748. %% --------------------------------------------------------------------------
  749. %% Prepared statements
  750. with_table_foo_test_() ->
  751. {setup,
  752. fun () ->
  753. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  754. {query_cache_time, 50},
  755. {log_warnings, false}]),
  756. ok = mysql:query(Pid, <<"DROP DATABASE IF EXISTS otptest">>),
  757. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  758. ok = mysql:query(Pid, <<"USE otptest">>),
  759. ok = mysql:query(Pid, <<"CREATE TABLE foo (bar INT) engine=InnoDB">>),
  760. Pid
  761. end,
  762. fun (Pid) ->
  763. ok = mysql:query(Pid, <<"DROP DATABASE otptest">>),
  764. mysql:stop(Pid)
  765. end,
  766. fun (Pid) ->
  767. [{"Prepared statements", fun () -> prepared_statements(Pid) end},
  768. {"Parametrized queries", fun () -> parameterized_query(Pid) end}]
  769. end}.
  770. prepared_statements(Pid) ->
  771. %% Unnamed
  772. ?assertEqual({error,{1146, <<"42S02">>,
  773. <<"Table 'otptest.tab' doesn't exist">>}},
  774. mysql:prepare(Pid, "SELECT * FROM tab WHERE id = ?")),
  775. {ok, StmtId} = mysql:prepare(Pid, "SELECT * FROM foo WHERE bar = ?"),
  776. ?assert(is_integer(StmtId)),
  777. ?assertEqual(ok, mysql:unprepare(Pid, StmtId)),
  778. ?assertEqual({error, not_prepared}, mysql:unprepare(Pid, StmtId)),
  779. %% Named
  780. ?assertEqual({error,{1146, <<"42S02">>,
  781. <<"Table 'otptest.tab' doesn't exist">>}},
  782. mysql:prepare(Pid, tab, "SELECT * FROM tab WHERE id = ?")),
  783. ?assertEqual({ok, foo},
  784. mysql:prepare(Pid, foo, "SELECT * FROM foo WHERE bar = ?")),
  785. %% Prepare again unprepares the old stmt associated with this name.
  786. ?assertEqual({ok, foo},
  787. mysql:prepare(Pid, foo, "SELECT bar FROM foo WHERE bar = ?")),
  788. ?assertEqual(ok, mysql:unprepare(Pid, foo)),
  789. ?assertEqual({error, not_prepared}, mysql:unprepare(Pid, foo)),
  790. %% Execute when not prepared
  791. ?assertEqual({error, not_prepared}, mysql:execute(Pid, not_a_stmt, [])),
  792. ok.
  793. parameterized_query(Conn) ->
  794. %% To see that cache eviction works as expected, look at the code coverage.
  795. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [1]),
  796. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [2]),
  797. receive after 150 -> ok end, %% Now the query cache should emptied
  798. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [3]),
  799. {error, {_, _, _}} = mysql:query(Conn, "Lorem ipsum dolor sit amet", [4]).
  800. %% --- simple gen_server callbacks ---
  801. gen_server_coverage_test() ->
  802. {noreply, state} = mysql_conn:handle_cast(foo, state),
  803. {noreply, state} = mysql_conn:handle_info(foo, state),
  804. ok = mysql_conn:terminate(kill, state).
  805. %% --- Utility functions
  806. db_version_string(Pid) ->
  807. {ok, _, [[Version]]} = mysql:query(Pid, <<"SELECT @@version">>),
  808. Version.
  809. is_mariadb(Version) ->
  810. binary:match(Version, <<"MariaDB">>) =/= nomatch.
  811. parse_db_version(Version) ->
  812. %% Remove stuff after dash for e.g. "5.5.40-0ubuntu0.12.04.1-log"
  813. [Version1 | _] = binary:split(Version, <<"-">>),
  814. lists:map(fun binary_to_integer/1,
  815. binary:split(Version1, <<".">>, [global])).