mysql_tests.erl 42 KB

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