mysql_tests.erl 38 KB

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