mysql_tests.erl 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  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. socket_backend_test() ->
  244. try
  245. list_to_integer(erlang:system_info(otp_release))
  246. of
  247. %% Supported in OTP >= 23
  248. OtpRelease when OtpRelease >= 23 ->
  249. case mysql:start_link([{user, ?user},
  250. {password, ?password},
  251. {tcp_options, [{inet_backend, socket}]}])
  252. of
  253. {ok, Pid1} ->
  254. {ok, [<<"@@socket">>], [[SockFile]]} =
  255. mysql:query(Pid1, <<"SELECT @@socket">>),
  256. mysql:stop(Pid1),
  257. case mysql:start_link([{host, {local, SockFile}},
  258. {user, ?user}, {password, ?password},
  259. {tcp_options, [{inet_backend, socket}]}]) of
  260. {ok, Pid2} ->
  261. ?assertEqual({ok, [<<"1">>], [[1]]},
  262. mysql:query(Pid2, <<"SELECT 1">>)),
  263. mysql:stop(Pid2);
  264. {error, eafnotsupported} ->
  265. error_logger:info_msg("Skipping socket backend test. "
  266. "Not supported on this OS.~n")
  267. end;
  268. {error, enotsup} ->
  269. error_logger:info_msg("Skipping socket backend test. "
  270. "Not supported on this OS.~n")
  271. end;
  272. OtpRelease ->
  273. error_logger:info_msg("Skipping socket backend test. Current OTP "
  274. "release is ~B. Required release is >= 23.~n",
  275. [OtpRelease])
  276. catch
  277. error:badarg ->
  278. error_logger:info_msg("Skipping socket backend tests. Current OTP "
  279. "release could not be determined.~n")
  280. end.
  281. connect_queries_failure_test() ->
  282. process_flag(trap_exit, true),
  283. {ok, Ret, Logged} = error_logger_acc:capture(
  284. fun () ->
  285. mysql:start_link([{user, ?user}, {password, ?password},
  286. {queries, ["foo"]}])
  287. end),
  288. ?assertMatch([{error_report, {crash_report, _}}], Logged),
  289. {error, Reason} = Ret,
  290. receive
  291. {'EXIT', _Pid, Reason} -> ok
  292. after 1000 ->
  293. exit(no_exit_message)
  294. end,
  295. process_flag(trap_exit, false).
  296. connect_prepare_failure_test() ->
  297. process_flag(trap_exit, true),
  298. {ok, Ret, Logged} = error_logger_acc:capture(
  299. fun () ->
  300. mysql:start_link([{user, ?user}, {password, ?password},
  301. {prepare, [{foo, "foo"}]}])
  302. end),
  303. ?assertMatch([{error_report, {crash_report, _}}], Logged),
  304. {error, Reason} = Ret,
  305. ?assertMatch({1064, <<"42000">>, <<"You have an erro", _/binary>>}, Reason),
  306. receive
  307. {'EXIT', _Pid, Reason} -> ok
  308. after 1000 ->
  309. exit(no_exit_message)
  310. end,
  311. process_flag(trap_exit, false).
  312. %% For R16B where sys:get_state/1 is not available.
  313. get_state(Process) ->
  314. {status,_,_,[_,_,_,_,Misc]} = sys:get_status(Process),
  315. hd([State || {data,[{"State", State}]} <- Misc]).
  316. query_test_() ->
  317. {setup,
  318. fun () ->
  319. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  320. {log_warnings, false},
  321. {keep_alive, true}]),
  322. ok = mysql:query(Pid, <<"DROP DATABASE IF EXISTS otptest">>),
  323. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  324. ok = mysql:query(Pid, <<"USE otptest">>),
  325. ok = mysql:query(Pid, <<"SET autocommit = 1">>),
  326. ok = mysql:query(Pid, <<"SET SESSION sql_mode = ?">>, [?SQL_MODE]),
  327. Pid
  328. end,
  329. fun (Pid) ->
  330. ok = mysql:query(Pid, <<"DROP DATABASE otptest">>),
  331. mysql:stop(Pid)
  332. end,
  333. fun (Pid) ->
  334. [{"Select db on connect", fun () -> connect_with_db(Pid) end},
  335. {"Autocommit", fun () -> autocommit(Pid) end},
  336. {"Encode", fun () -> encode(Pid) end},
  337. {"Basic queries", fun () -> basic_queries(Pid) end},
  338. {"Filtermap queries", fun () -> filtermap_queries(Pid) end},
  339. {"FOUND_ROWS option", fun () -> found_rows(Pid) end},
  340. {"Multi statements", fun () -> multi_statements(Pid) end},
  341. {"Text protocol", fun () -> text_protocol(Pid) end},
  342. {"Binary protocol", fun () -> binary_protocol(Pid) end},
  343. {"FLOAT rounding", fun () -> float_rounding(Pid) end},
  344. {"DECIMAL", fun () -> decimal(Pid) end},
  345. {"DECIMAL truncated", fun () -> decimal_trunc(Pid) end},
  346. {"Float as decimal", fun () -> float_as_decimal(Pid) end},
  347. {"Float as decimal(2)", fun () -> float_as_decimal_2(Pid) end},
  348. {"INT", fun () -> int(Pid) end},
  349. {"BIT(N)", fun () -> bit(Pid) end},
  350. {"DATE", fun () -> date(Pid) end},
  351. {"TIME", fun () -> time(Pid) end},
  352. {"DATETIME", fun () -> datetime(Pid) end},
  353. {"JSON", fun () -> json(Pid) end},
  354. {"Microseconds", fun () -> microseconds(Pid) end},
  355. {"Invalid params", fun () -> invalid_params(Pid) end}]
  356. end}.
  357. local_files_test_() ->
  358. {setup,
  359. fun () ->
  360. {ok, Cwd0} = file:get_cwd(),
  361. Cwd1 = iolist_to_binary(Cwd0),
  362. Cwd2 = case binary:last(Cwd1) of
  363. $/ -> Cwd1;
  364. _ -> <<Cwd1/binary, $/>>
  365. end,
  366. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  367. {log_warnings, false},
  368. {keep_alive, true}, {allowed_local_paths, [Cwd2]}]),
  369. ok = mysql:query(Pid, <<"DROP DATABASE IF EXISTS otptest">>),
  370. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  371. ok = mysql:query(Pid, <<"USE otptest">>),
  372. ok = mysql:query(Pid, <<"SET autocommit = 1">>),
  373. ok = mysql:query(Pid, <<"SET SESSION sql_mode = ?">>, [?SQL_MODE]),
  374. {Pid, Cwd2}
  375. end,
  376. fun ({Pid, _Cwd}) ->
  377. ok = mysql:query(Pid, <<"DROP DATABASE otptest">>),
  378. mysql:stop(Pid)
  379. end,
  380. fun ({Pid, Cwd}) ->
  381. [{"Single statement", fun () -> load_data_local_infile(Pid, Cwd) end},
  382. {"Missing file", fun () -> load_data_local_infile_missing(Pid, Cwd) end},
  383. {"Not allowed", fun () -> load_data_local_infile_not_allowed(Pid, Cwd) end},
  384. {"Multi statements", fun () -> load_data_local_infile_multi(Pid, Cwd) end}]
  385. end}.
  386. connect_with_db(_Pid) ->
  387. %% Make another connection and set the db in the handshake phase
  388. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  389. {database, "otptest"}]),
  390. ?assertMatch({ok, _, [[<<"otptest">>]]},
  391. mysql:query(Pid, "SELECT DATABASE()")),
  392. mysql:stop(Pid).
  393. log_warnings_test() ->
  394. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password}]),
  395. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  396. ok = mysql:query(Pid, <<"USE otptest">>),
  397. ok = mysql:query(Pid, <<"SET SESSION sql_mode = ?">>, [?SQL_MODE]),
  398. %% Capture error log to check that we get a warning logged
  399. ok = mysql:query(Pid, "CREATE TABLE foo (x INT NOT NULL)"),
  400. {ok, insrt} = mysql:prepare(Pid, insrt, "INSERT INTO foo () VALUES ()"),
  401. {ok, ok, LoggedErrors} = error_logger_acc:capture(fun () ->
  402. ok = mysql:query(Pid, "INSERT INTO foo () VALUES ()"),
  403. ok = mysql:query(Pid, "INSeRT INtO foo () VaLUeS ()", []),
  404. ok = mysql:execute(Pid, insrt, [])
  405. end),
  406. [{_, Log1}, {_, Log2}, {_, Log3}] = LoggedErrors,
  407. ?assertEqual("Warning 1364: Field 'x' doesn't have a default value\n"
  408. " in INSERT INTO foo () VALUES ()\n", Log1),
  409. ?assertEqual("Warning 1364: Field 'x' doesn't have a default value\n"
  410. " in INSeRT INtO foo () VaLUeS ()\n", Log2),
  411. ?assertEqual("Warning 1364: Field 'x' doesn't have a default value\n"
  412. " in INSERT INTO foo () VALUES ()\n", Log3),
  413. mysql:stop(Pid).
  414. log_slow_queries_test() ->
  415. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  416. {log_warnings, false}, {log_slow_queries, true}]),
  417. VersionStr = db_version_string(Pid),
  418. try
  419. Version = parse_db_version(VersionStr),
  420. case is_mariadb(VersionStr) of
  421. true when Version < [10, 0, 21] ->
  422. throw({mariadb, version_too_small});
  423. false when Version < [5, 5, 8] ->
  424. throw({mysql, version_too_small});
  425. _ ->
  426. ok
  427. end
  428. of _ ->
  429. ok = mysql:query(Pid, "SET long_query_time = 0.1"),
  430. %% single statement should not include query number
  431. SingleQuery = "SELECT SLEEP(0.2)",
  432. {ok, _, SingleLogged} = error_logger_acc:capture( fun () ->
  433. {ok, _, _} = mysql:query(Pid, SingleQuery)
  434. end),
  435. [{_, SingleLog}] = SingleLogged,
  436. ?assertEqual("MySQL query was slow: " ++ SingleQuery ++ "\n", SingleLog),
  437. %% multi statement should include number of slow query
  438. MultiQuery = "SELECT SLEEP(0.2); " %% #1 -> slow
  439. "SELECT 1; " %% #2 -> not slow
  440. "SET @foo = 1; " %% #3 -> not slow, no result set
  441. "SELECT SLEEP(0.2); " %% #4 -> slow
  442. "SELECT 1", %% #5 -> not slow
  443. {ok, _, MultiLogged} = error_logger_acc:capture(fun () ->
  444. {ok, _} = mysql:query(Pid, MultiQuery)
  445. end),
  446. [{_, MultiLog1}, {_, MultiLog2}] = MultiLogged,
  447. ?assertEqual("MySQL query #1 was slow: " ++ MultiQuery ++ "\n", MultiLog1),
  448. ?assertEqual("MySQL query #4 was slow: " ++ MultiQuery ++ "\n", MultiLog2)
  449. catch
  450. throw:{mysql, version_too_small} ->
  451. error_logger:info_msg("Skipping Log Slow Queries test. Current MySQL version"
  452. " is ~s. Required version is >= 5.5.8.~n",
  453. [VersionStr]);
  454. throw:{mariadb, version_too_small} ->
  455. error_logger:info_msg("Skipping Log Slow Queries test. Current MariaDB version"
  456. " is ~s. Required version is >= 10.0.21.~n",
  457. [VersionStr])
  458. end,
  459. mysql:stop(Pid).
  460. autocommit(Pid) ->
  461. ?assert(mysql:autocommit(Pid)),
  462. ok = mysql:query(Pid, <<"SET autocommit = 0">>),
  463. ?assertNot(mysql:autocommit(Pid)),
  464. ok = mysql:query(Pid, <<"SET autocommit = 1">>),
  465. ?assert(mysql:autocommit(Pid)).
  466. encode(Pid) ->
  467. %% Test with backslash escapes enabled and disabled.
  468. {ok, _, [[OldMode]]} = mysql:query(Pid, "SELECT @@sql_mode"),
  469. ok = mysql:query(Pid, "SET sql_mode = ''"),
  470. ?assertEqual(<<"'foo\\\\bar''baz'">>,
  471. iolist_to_binary(mysql:encode(Pid, "foo\\bar'baz"))),
  472. ok = mysql:query(Pid, "SET sql_mode = 'NO_BACKSLASH_ESCAPES'"),
  473. ?assertEqual(<<"'foo\\bar''baz'">>,
  474. iolist_to_binary(mysql:encode(Pid, "foo\\bar'baz"))),
  475. ok = mysql:query(Pid, "SET sql_mode = ?", [OldMode]).
  476. basic_queries(Pid) ->
  477. %% warning count
  478. ?assertEqual(ok, mysql:query(Pid, <<"DROP TABLE IF EXISTS foo">>)),
  479. ?assertEqual(1, mysql:warning_count(Pid)),
  480. %% SQL parse error
  481. ?assertMatch({error, {1064, <<"42000">>, <<"You have an erro", _/binary>>}},
  482. mysql:query(Pid, <<"FOO">>)),
  483. %% Simple resultset with various types
  484. ?assertEqual({ok, [<<"i">>, <<"s">>], [[42, <<"foo">>]]},
  485. mysql:query(Pid, <<"SELECT 42 AS i, 'foo' AS s;">>)),
  486. ok.
  487. filtermap_queries(Pid) ->
  488. ok = mysql:query(Pid, ?create_table_t),
  489. ok = mysql:query(Pid, <<"INSERT INTO t (id, tx) VALUES (1, 'text 1')">>),
  490. ok = mysql:query(Pid, <<"INSERT INTO t (id, tx) VALUES (2, 'text 2')">>),
  491. ok = mysql:query(Pid, <<"INSERT INTO t (id, tx) VALUES (3, 'text 3')">>),
  492. Query = <<"SELECT id, tx FROM t ORDER BY id">>,
  493. %% one-ary filtermap fun
  494. FilterMap1 = fun
  495. ([1|_]) ->
  496. true;
  497. ([2|_]) ->
  498. false;
  499. (Row1=[3|_]) ->
  500. {true, list_to_tuple(Row1)}
  501. end,
  502. %% two-ary filtermap fun
  503. FilterMap2 = fun
  504. (_, Row2) ->
  505. FilterMap1(Row2)
  506. end,
  507. Expected = [[1, <<"text 1">>], {3, <<"text 3">>}],
  508. %% test with plain query
  509. {ok, _, Rows1}=mysql:query(Pid, Query, FilterMap1),
  510. ?assertEqual(Expected, Rows1),
  511. {ok, _, Rows2}=mysql:query(Pid, Query, FilterMap2),
  512. ?assertEqual(Expected, Rows2),
  513. %% test with parameterized query
  514. {ok, _, Rows3}=mysql:query(Pid, Query, [], FilterMap1),
  515. ?assertEqual(Expected, Rows3),
  516. {ok, _, Rows4}=mysql:query(Pid, Query, [], FilterMap2),
  517. ?assertEqual(Expected, Rows4),
  518. %% test with prepared statement
  519. {ok, PrepStmt} = mysql:prepare(Pid, Query),
  520. {ok, _, Rows5}=mysql:execute(Pid, PrepStmt, [], FilterMap1),
  521. ?assertEqual(Expected, Rows5),
  522. {ok, _, Rows6}=mysql:execute(Pid, PrepStmt, [], FilterMap2),
  523. ?assertEqual(Expected, Rows6),
  524. ok = mysql:query(Pid, <<"DROP TABLE t">>).
  525. found_rows(Pid) ->
  526. Options = [{user, ?user}, {password, ?password}, {log_warnings, false},
  527. {keep_alive, true}, {found_rows, true}],
  528. {ok, FRPid} = mysql:start_link(Options),
  529. ok = mysql:query(FRPid, <<"USE otptest">>),
  530. ok = mysql:query(Pid, ?create_table_t),
  531. ok = mysql:query(Pid, <<"INSERT INTO t (id, tx) VALUES (1, 'text')">>),
  532. %% With no found_rows option, affected_rows for update returns 0
  533. ok = mysql:query(Pid, <<"UPDATE t SET tx = 'text' WHERE id = 1">>),
  534. ?assertEqual(0, mysql:affected_rows(Pid)),
  535. %% With found_rows, affected_rows returns the number of rows found
  536. ok = mysql:query(FRPid, <<"UPDATE t SET tx = 'text' WHERE id = 1">>),
  537. ?assertEqual(1, mysql:affected_rows(FRPid)),
  538. ok = mysql:query(Pid, <<"DROP TABLE t">>).
  539. multi_statements(Pid) ->
  540. %% Multiple statements, no result set
  541. ?assertEqual(ok, mysql:query(Pid, "CREATE TABLE foo (bar INT);"
  542. "DROP TABLE foo;")),
  543. %% Multiple statements, one result set
  544. ?assertEqual({ok, [<<"foo">>], [[42]]},
  545. mysql:query(Pid, "CREATE TABLE foo (bar INT);"
  546. "DROP TABLE foo;"
  547. "SELECT 42 AS foo;")),
  548. %% Multiple statements, multiple result sets
  549. ?assertEqual({ok, [{[<<"foo">>], [[42]]}, {[<<"bar">>], [[<<"baz">>]]}]},
  550. mysql:query(Pid, "SELECT 42 AS foo; SELECT 'baz' AS bar;")),
  551. %% Multiple results in a prepared statement.
  552. %% Preparing "SELECT ...; SELECT ...;" gives a syntax error although the
  553. %% docs say it should be possible.
  554. %% Instead, test executing a stored procedure that returns multiple result
  555. %% sets using a prepared statement.
  556. CreateProc = "CREATE PROCEDURE multifoo() BEGIN\n"
  557. " SELECT 42 AS foo;\n"
  558. " SELECT 'baz' AS bar;\n"
  559. "END;\n",
  560. ok = mysql:query(Pid, CreateProc),
  561. ?assertEqual({ok, multifoo},
  562. mysql:prepare(Pid, multifoo, "CALL multifoo();")),
  563. ?assertEqual({ok, [{[<<"foo">>], [[42]]}, {[<<"bar">>], [[<<"baz">>]]}]},
  564. mysql:execute(Pid, multifoo, [])),
  565. ?assertEqual(ok, mysql:unprepare(Pid, multifoo)),
  566. ?assertEqual(ok, mysql:query(Pid, "DROP PROCEDURE multifoo;")),
  567. ok.
  568. text_protocol(Pid) ->
  569. ok = mysql:query(Pid, ?create_table_t),
  570. ok = mysql:query(Pid, <<"INSERT INTO t (bl, f, d, dc, y, ti, ts, da, c)"
  571. " VALUES ('blob', 3.14, 3.14, 3.14, 2014,"
  572. "'00:22:11', '2014-11-03 00:22:24', '2014-11-03',"
  573. " NULL)">>),
  574. ?assertEqual(1, mysql:warning_count(Pid)), %% tx has no default value
  575. ?assertEqual(1, mysql:insert_id(Pid)), %% auto_increment starts from 1
  576. ?assertEqual(1, mysql:affected_rows(Pid)),
  577. %% select
  578. {ok, Columns, Rows} = mysql:query(Pid, <<"SELECT * FROM t">>),
  579. ?assertEqual([<<"id">>, <<"bl">>, <<"tx">>, <<"f">>, <<"d">>, <<"dc">>,
  580. <<"y">>, <<"ti">>, <<"ts">>, <<"da">>, <<"c">>], Columns),
  581. ?assertEqual([[1, <<"blob">>, <<>>, 3.14, 3.14, 3.14,
  582. 2014, {0, {0, 22, 11}},
  583. {{2014, 11, 03}, {00, 22, 24}}, {2014, 11, 03}, null]],
  584. Rows),
  585. ok = mysql:query(Pid, <<"DROP TABLE t">>).
  586. binary_protocol(Pid) ->
  587. ok = mysql:query(Pid, ?create_table_t),
  588. %% The same queries as in the text protocol. Expect the same results.
  589. {ok, Ins} = mysql:prepare(Pid, <<"INSERT INTO t (bl, tx, f, d, dc, y, ti,"
  590. " ts, da, c)"
  591. " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)">>),
  592. %% 16#161 is the codepoint for "s with caron"; <<197, 161>> in UTF-8.
  593. ok = mysql:execute(Pid, Ins, [<<"blob">>, [16#161], 3.14, 3.14, 3.14,
  594. 2014, {0, {0, 22, 11}},
  595. {{2014, 11, 03}, {0, 22, 24}},
  596. {2014, 11, 03}, null]),
  597. {ok, Stmt} = mysql:prepare(Pid, <<"SELECT * FROM t WHERE id=?">>),
  598. {ok, Columns, Rows} = mysql:execute(Pid, Stmt, [1]),
  599. ?assertEqual([<<"id">>, <<"bl">>, <<"tx">>, <<"f">>, <<"d">>, <<"dc">>,
  600. <<"y">>, <<"ti">>,
  601. <<"ts">>, <<"da">>, <<"c">>], Columns),
  602. ?assertEqual([[1, <<"blob">>, <<197, 161>>, 3.14, 3.14, 3.14,
  603. 2014, {0, {0, 22, 11}},
  604. {{2014, 11, 03}, {00, 22, 24}}, {2014, 11, 03}, null]],
  605. Rows),
  606. ok = mysql:query(Pid, <<"DROP TABLE t">>).
  607. float_rounding(Pid) ->
  608. %% This is to make sure we get the same values for 32-bit FLOATs in the text
  609. %% and binary protocols for ordinary queries and prepared statements
  610. %% respectively.
  611. %%
  612. %% MySQL rounds to 6 significant digits when "printing" floats over the
  613. %% text protocol. When we receive a float on the binary protocol, we round
  614. %% it in the same way to match what MySQL does on the text protocol. This
  615. %% way we should to get the same values regardless of which protocol is
  616. %% used.
  617. %% Table for testing floats
  618. ok = mysql:query(Pid, "CREATE TABLE f (f FLOAT)"),
  619. %% Prepared statements
  620. {ok, Insert} = mysql:prepare(Pid, "INSERT INTO f (f) VALUES (?)"),
  621. {ok, Select} = mysql:prepare(Pid, "SELECT f FROM f"),
  622. %% [{Input, Expected}]
  623. TestData = [{1.0, 1.0}, {0.0, 0.0}, {3.14, 3.14}, {0.2, 0.2},
  624. {0.20082111, 0.200821}, {0.000123456789, 0.000123457},
  625. {33.3333333, 33.3333}, {-33.2233443322, -33.2233},
  626. {400.0123, 400.012}, {1000.1234, 1000.12},
  627. {999.00009, 999.0},
  628. {1234.5678, 1234.57}, {68888.8888, 68888.9},
  629. {123456.789, 123457.0}, {7654321.0, 7654320.0},
  630. {80001111.1, 80001100.0}, {987654321.0, 987654000.0},
  631. {-123456789.0, -123457000.0},
  632. {2.12345111e-23, 2.12345e-23}, {-2.12345111e-23, -2.12345e-23},
  633. {2.12345111e23, 2.12345e23}, {-2.12345111e23, -2.12345e23}],
  634. lists:foreach(fun ({Input, Expected}) ->
  635. %% Insert using binary protocol (sending it as a double)
  636. ok = mysql:execute(Pid, Insert, [Input]),
  637. %% Text (plain query)
  638. {ok, _, [[Value]]} = mysql:query(Pid, "SELECT f FROM f"),
  639. ?assertEqual(Expected, Value),
  640. %% Binary (prepared statement)
  641. {ok, _, [[BinValue]]} = mysql:execute(Pid, Select, []),
  642. ?assertEqual(Expected, BinValue),
  643. %% cleanup before the next test
  644. ok = mysql:query(Pid, "DELETE FROM f")
  645. end,
  646. TestData),
  647. ok = mysql:query(Pid, "DROP TABLE f").
  648. decimal(Pid) ->
  649. %% As integer when S == 0
  650. ok = mysql:query(Pid, "CREATE TABLE dec0 (d DECIMAL(50, 0))"),
  651. write_read_text_binary(
  652. Pid, 14159265358979323846264338327950288419716939937510,
  653. <<"14159265358979323846264338327950288419716939937510">>,
  654. <<"dec0">>, <<"d">>
  655. ),
  656. write_read_text_binary(
  657. Pid, -14159265358979323846264338327950288419716939937510,
  658. <<"-14159265358979323846264338327950288419716939937510">>,
  659. <<"dec0">>, <<"d">>
  660. ),
  661. ok = mysql:query(Pid, "DROP TABLE dec0"),
  662. %% As float when P =< 15, S > 0
  663. ok = mysql:query(Pid, "CREATE TABLE dec15 (d DECIMAL(15, 14))"),
  664. write_read_text_binary(Pid, 3.14159265358979, <<"3.14159265358979">>,
  665. <<"dec15">>, <<"d">>),
  666. write_read_text_binary(Pid, -3.14159265358979, <<"-3.14159265358979">>,
  667. <<"dec15">>, <<"d">>),
  668. write_read_text_binary(Pid, 3.0, <<"3">>, <<"dec15">>, <<"d">>),
  669. ok = mysql:query(Pid, "DROP TABLE dec15"),
  670. %% As binary when P >= 16, S > 0
  671. ok = mysql:query(Pid, "CREATE TABLE dec16 (d DECIMAL(16, 15))"),
  672. write_read_text_binary(Pid, <<"3.141592653589793">>,
  673. <<"3.141592653589793">>, <<"dec16">>, <<"d">>),
  674. write_read_text_binary(Pid, <<"-3.141592653589793">>,
  675. <<"-3.141592653589793">>, <<"dec16">>, <<"d">>),
  676. write_read_text_binary(Pid, <<"3.000000000000000">>, <<"3">>,
  677. <<"dec16">>, <<"d">>),
  678. ok = mysql:query(Pid, "DROP TABLE dec16").
  679. decimal_trunc(_Pid) ->
  680. %% Create another connection with log_warnings enabled.
  681. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  682. {log_warnings, true}]),
  683. ok = mysql:query(Pid, <<"USE otptest">>),
  684. ok = mysql:query(Pid, <<"SET autocommit = 1">>),
  685. ok = mysql:query(Pid, <<"SET SESSION sql_mode = ?">>, [?SQL_MODE]),
  686. ok = mysql:query(Pid, <<"CREATE TABLE `test_decimals` ("
  687. " `id` bigint(20) unsigned NOT NULL,"
  688. " `balance` decimal(13,4) NOT NULL,"
  689. " PRIMARY KEY (`id`)"
  690. ") ENGINE=InnoDB;">>),
  691. ok = mysql:query(Pid, <<"INSERT INTO test_decimals (id, balance)"
  692. " VALUES (1, 5000), (2, 5000), (3, 5000);">>),
  693. {ok, decr} = mysql:prepare(Pid, decr, <<"UPDATE test_decimals"
  694. " SET balance = balance - ?"
  695. " WHERE id = ?">>),
  696. %% Decimal sent as float gives truncation warning.
  697. {ok, ok, [{_, LoggedWarning1}|_]} = error_logger_acc:capture(fun () ->
  698. ok = mysql:execute(Pid, decr, [10.2, 1]),
  699. ok = mysql:execute(Pid, decr, [10.2, 1]),
  700. ok = mysql:execute(Pid, decr, [10.2, 1]),
  701. ok = mysql:execute(Pid, decr, [10.2, 1])
  702. end),
  703. ?assertMatch("Note 1265: Data truncated for column 'balance'" ++ _,
  704. LoggedWarning1),
  705. %% Decimal sent as binary gives truncation warning.
  706. {ok, ok, [{_, LoggedWarning2}|_]} = error_logger_acc:capture(fun () ->
  707. ok = mysql:execute(Pid, decr, [<<"10.2">>, 2]),
  708. ok = mysql:execute(Pid, decr, [<<"10.2">>, 2]),
  709. ok = mysql:execute(Pid, decr, [<<"10.2">>, 2]),
  710. ok = mysql:execute(Pid, decr, [<<"10.2">>, 2])
  711. end),
  712. ?assertMatch("Note 1265: Data truncated for column 'balance'" ++ _,
  713. LoggedWarning2),
  714. %% Decimal sent as DECIMAL => no warning
  715. {ok, ok, []} = error_logger_acc:capture(fun () ->
  716. ok = mysql:execute(Pid, decr, [{decimal, <<"10.2">>}, 3]),
  717. ok = mysql:execute(Pid, decr, [{decimal, "10.2"}, 3]),
  718. ok = mysql:execute(Pid, decr, [{decimal, 10.2}, 3]),
  719. ok = mysql:execute(Pid, decr, [{decimal, 10.2}, 3]),
  720. ok = mysql:execute(Pid, decr, [{decimal, 0}, 3]) % <- integer coverage
  721. end),
  722. ?assertMatch({ok, _, [[1, 4959.2], [2, 4959.2], [3, 4959.2]]},
  723. mysql:query(Pid, <<"SELECT id, balance FROM test_decimals">>)),
  724. ok = mysql:query(Pid, "DROP TABLE test_decimals"),
  725. ok = mysql:stop(Pid).
  726. float_as_decimal(_Pid) ->
  727. %% Create another connection with {float_as_decimal, true}
  728. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  729. {log_warnings, true},
  730. {float_as_decimal, true}]),
  731. ok = mysql:query(Pid, <<"USE otptest">>),
  732. ok = mysql:query(Pid, <<"SET autocommit = 1">>),
  733. ok = mysql:query(Pid, <<"SET SESSION sql_mode = ?">>, [?SQL_MODE]),
  734. ok = mysql:query(Pid, <<"CREATE TABLE float_as_decimal ("
  735. " balance decimal(13,4) NOT NULL"
  736. ") ENGINE=InnoDB;">>),
  737. ok = mysql:query(Pid, <<"INSERT INTO float_as_decimal (balance)"
  738. " VALUES (5000);">>),
  739. {ok, decr} = mysql:prepare(Pid, decr, <<"UPDATE float_as_decimal"
  740. " SET balance = balance - ?">>),
  741. %% Floats sent as decimal => no truncation warning.
  742. {ok, ok, []} = error_logger_acc:capture(fun () ->
  743. ok = mysql:execute(Pid, decr, [10.2]),
  744. ok = mysql:execute(Pid, decr, [10.2]),
  745. ok = mysql:execute(Pid, decr, [10.2]),
  746. ok = mysql:execute(Pid, decr, [10.2])
  747. end),
  748. ok = mysql:query(Pid, "DROP TABLE float_as_decimal;"),
  749. ok = mysql:stop(Pid).
  750. float_as_decimal_2(_Pid) ->
  751. %% Create another connection with {float_as_decimal, 2}.
  752. %% Check that floats are sent as DECIMAL with 2 decimals.
  753. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  754. {log_warnings, true},
  755. {float_as_decimal, 2}]),
  756. ok = mysql:query(Pid, <<"USE otptest">>),
  757. ok = mysql:query(Pid, <<"SET autocommit = 1">>),
  758. ok = mysql:query(Pid, <<"SET SESSION sql_mode = ?">>, [?SQL_MODE]),
  759. ok = mysql:query(Pid, <<"CREATE TABLE dec13_4 (d DECIMAL(13,4))">>),
  760. ok = mysql:query(Pid, <<"INSERT INTO dec13_4 (d) VALUES (?)">>, [3.14159]),
  761. {ok, _, [[Value]]} = mysql:query(Pid, <<"SELECT d FROM dec13_4">>),
  762. ?assertEqual(3.14, Value),
  763. ok = mysql:query(Pid, <<"DROP TABLE dec13_4">>),
  764. ok = mysql:stop(Pid).
  765. int(Pid) ->
  766. ok = mysql:query(Pid, "CREATE TABLE ints (i INT)"),
  767. write_read_text_binary(Pid, 42, <<"42">>, <<"ints">>, <<"i">>),
  768. write_read_text_binary(Pid, -42, <<"-42">>, <<"ints">>, <<"i">>),
  769. write_read_text_binary(Pid, 987654321, <<"987654321">>, <<"ints">>,
  770. <<"i">>),
  771. write_read_text_binary(Pid, -987654321, <<"-987654321">>,
  772. <<"ints">>, <<"i">>),
  773. ok = mysql:query(Pid, "DROP TABLE ints"),
  774. %% Overflow with TINYINT
  775. ok = mysql:query(Pid, "CREATE TABLE tint (i TINYINT)"),
  776. write_read_text_binary(Pid, 127, <<"1000">>, <<"tint">>, <<"i">>),
  777. write_read_text_binary(Pid, -128, <<"-1000">>, <<"tint">>, <<"i">>),
  778. ok = mysql:query(Pid, "DROP TABLE tint"),
  779. %% TINYINT UNSIGNED
  780. ok = mysql:query(Pid, "CREATE TABLE tuint (i TINYINT UNSIGNED)"),
  781. write_read_text_binary(Pid, 240, <<"240">>, <<"tuint">>, <<"i">>),
  782. ok = mysql:query(Pid, "DROP TABLE tuint"),
  783. %% SMALLINT
  784. ok = mysql:query(Pid, "CREATE TABLE sint (i SMALLINT)"),
  785. write_read_text_binary(Pid, 32000, <<"32000">>, <<"sint">>, <<"i">>),
  786. write_read_text_binary(Pid, -32000, <<"-32000">>, <<"sint">>, <<"i">>),
  787. ok = mysql:query(Pid, "DROP TABLE sint"),
  788. %% SMALLINT UNSIGNED
  789. ok = mysql:query(Pid, "CREATE TABLE suint (i SMALLINT UNSIGNED)"),
  790. write_read_text_binary(Pid, 64000, <<"64000">>, <<"suint">>, <<"i">>),
  791. ok = mysql:query(Pid, "DROP TABLE suint"),
  792. %% MEDIUMINT
  793. ok = mysql:query(Pid, "CREATE TABLE mint (i MEDIUMINT)"),
  794. write_read_text_binary(Pid, 8388000, <<"8388000">>,
  795. <<"mint">>, <<"i">>),
  796. write_read_text_binary(Pid, -8388000, <<"-8388000">>,
  797. <<"mint">>, <<"i">>),
  798. ok = mysql:query(Pid, "DROP TABLE mint"),
  799. %% MEDIUMINT UNSIGNED
  800. ok = mysql:query(Pid, "CREATE TABLE muint (i MEDIUMINT UNSIGNED)"),
  801. write_read_text_binary(Pid, 16777000, <<"16777000">>,
  802. <<"muint">>, <<"i">>),
  803. ok = mysql:query(Pid, "DROP TABLE muint"),
  804. %% BIGINT
  805. ok = mysql:query(Pid, "CREATE TABLE bint (i BIGINT)"),
  806. write_read_text_binary(Pid, 123456789012, <<"123456789012">>,
  807. <<"bint">>, <<"i">>),
  808. write_read_text_binary(Pid, -123456789012, <<"-123456789012">>,
  809. <<"bint">>, <<"i">>),
  810. ok = mysql:query(Pid, "DROP TABLE bint"),
  811. %% BIGINT UNSIGNED
  812. ok = mysql:query(Pid, "CREATE TABLE buint (i BIGINT UNSIGNED)"),
  813. write_read_text_binary(Pid, 18446744073709551000,
  814. <<"18446744073709551000">>,
  815. <<"buint">>, <<"i">>),
  816. ok = mysql:query(Pid, "DROP TABLE buint").
  817. %% The BIT(N) datatype in MySQL 5.0.3 and later: the equivallent to bitstring()
  818. bit(Pid) ->
  819. ok = mysql:query(Pid, "CREATE TABLE bits (b BIT(11))"),
  820. write_read_text_binary(Pid, <<16#ff, 0:3>>, <<"b'11111111000'">>,
  821. <<"bits">>, <<"b">>),
  822. write_read_text_binary(Pid, <<16#7f, 6:3>>, <<"b'01111111110'">>,
  823. <<"bits">>, <<"b">>),
  824. ok = mysql:query(Pid, "DROP TABLE bits").
  825. date(Pid) ->
  826. ok = mysql:query(Pid, "CREATE TABLE d (d DATE)"),
  827. lists:foreach(
  828. fun ({Value, SqlLiteral}) ->
  829. write_read_text_binary(Pid, Value, SqlLiteral, <<"d">>, <<"d">>)
  830. end,
  831. [{{2014, 11, 03}, <<"'2014-11-03'">>},
  832. {{0, 0, 0}, <<"'0000-00-00'">>}]
  833. ),
  834. ok = mysql:query(Pid, "DROP TABLE d").
  835. %% Test TIME value representation. There are a few things to check.
  836. time(Pid) ->
  837. ok = mysql:query(Pid, "CREATE TABLE tm (tm TIME)"),
  838. lists:foreach(
  839. fun ({Value, SqlLiteral}) ->
  840. write_read_text_binary(Pid, Value, SqlLiteral, <<"tm">>, <<"tm">>)
  841. end,
  842. [{{0, {10, 11, 12}}, <<"'10:11:12'">>},
  843. {{5, {0, 0, 1}}, <<"'120:00:01'">>},
  844. {{-1, {23, 59, 59}}, <<"'-00:00:01'">>},
  845. {{-1, {23, 59, 0}}, <<"'-00:01:00'">>},
  846. {{-1, {23, 0, 0}}, <<"'-01:00:00'">>},
  847. {{-1, {0, 0, 0}}, <<"'-24:00:00'">>},
  848. {{-5, {10, 0, 0}}, <<"'-110:00:00'">>},
  849. {{0, {0, 0, 0}}, <<"'00:00:00'">>}]
  850. ),
  851. %% Zero seconds as a float.
  852. ok = mysql:query(Pid, "INSERT INTO tm (tm) VALUES (?)",
  853. [{-1, {1, 2, 0.0}}]),
  854. ?assertEqual({ok, [<<"tm">>], [[{-1, {1, 2, 0}}]]},
  855. mysql:query(Pid, "SELECT tm FROM tm")),
  856. ok = mysql:query(Pid, "DROP TABLE tm").
  857. datetime(Pid) ->
  858. ok = mysql:query(Pid, "CREATE TABLE dt (dt DATETIME)"),
  859. lists:foreach(
  860. fun ({Value, SqlLiteral}) ->
  861. write_read_text_binary(Pid, Value, SqlLiteral, <<"dt">>, <<"dt">>)
  862. end,
  863. [{{{2014, 12, 14}, {19, 39, 20}}, <<"'2014-12-14 19:39:20'">>},
  864. {{{2014, 12, 14}, {0, 0, 0}}, <<"'2014-12-14 00:00:00'">>},
  865. {{{0, 0, 0}, {0, 0, 0}}, <<"'0000-00-00 00:00:00'">>}]
  866. ),
  867. ok = mysql:query(Pid, "DROP TABLE dt").
  868. json(Pid) ->
  869. Version = db_version_string(Pid),
  870. try
  871. is_mariadb(Version) andalso throw(no_mariadb),
  872. Version1 = parse_db_version(Version),
  873. Version1 >= [5, 7, 8] orelse throw(version_too_small)
  874. of _ ->
  875. test_valid_json(Pid),
  876. test_invalid_json(Pid)
  877. catch
  878. throw:no_mariadb ->
  879. error_logger:info_msg("Skipping JSON test, not supported on"
  880. " MariaDB.~n");
  881. throw:version_too_small ->
  882. error_logger:info_msg("Skipping JSON test. Current MySQL version"
  883. " is ~s. Required version is >= 5.7.8.~n",
  884. [Version])
  885. end.
  886. test_valid_json(Pid) ->
  887. ok = mysql:query(Pid, "CREATE TABLE json_t (json_c JSON)"),
  888. Value = <<"'{\"a\": 1, \"b\": {\"c\": [1, 2, 3, 4]}}'">>,
  889. Expected = <<"{\"a\": 1, \"b\": {\"c\": [1, 2, 3, 4]}}">>,
  890. write_read_text_binary(Pid, Expected, Value,
  891. <<"json_t">>, <<"json_c">>),
  892. ok = mysql:query(Pid, "DROP TABLE json_t").
  893. test_invalid_json(Pid) ->
  894. ok = mysql:query(Pid, "CREATE TABLE json_t (json_c JSON)"),
  895. InvalidJson = <<"'{\"a\": \"c\": 2}'">>,
  896. ?assertMatch({error,{3140, <<"22032">>, _}},
  897. mysql:query(Pid, <<"INSERT INTO json_t (json_c)"
  898. " VALUES (", InvalidJson/binary,
  899. ")">>)),
  900. ok = mysql:query(Pid, "DROP TABLE json_t").
  901. microseconds(Pid) ->
  902. %% Check whether we have the required version for this testcase.
  903. Version = db_version_string(Pid),
  904. try
  905. Version1 = parse_db_version(Version),
  906. Version1 >= [5, 6, 4] orelse throw(nope)
  907. of _ ->
  908. test_time_microseconds(Pid),
  909. test_datetime_microseconds(Pid)
  910. catch _:_ ->
  911. error_logger:info_msg("Skipping microseconds test. Current MySQL"
  912. " version is ~s. Required version is >= 5.6.4.~n",
  913. [Version])
  914. end.
  915. test_time_microseconds(Pid) ->
  916. ok = mysql:query(Pid, "CREATE TABLE m (t TIME(6))"),
  917. %% Positive time
  918. write_read_text_binary(Pid, {0, {23, 59, 57.654321}},
  919. <<"'23:59:57.654321'">>, <<"m">>, <<"t">>),
  920. %% Negative time
  921. write_read_text_binary(Pid, {-1, {23, 59, 57.654321}},
  922. <<"'-00:00:02.345679'">>, <<"m">>, <<"t">>),
  923. ok = mysql:query(Pid, "DROP TABLE m").
  924. test_datetime_microseconds(Pid) ->
  925. ok = mysql:query(Pid, "CREATE TABLE dt (dt DATETIME(6))"),
  926. write_read_text_binary(Pid, {{2014, 11, 23}, {23, 59, 57.654321}},
  927. <<"'2014-11-23 23:59:57.654321'">>, <<"dt">>,
  928. <<"dt">>),
  929. ok = mysql:query(Pid, "DROP TABLE dt").
  930. invalid_params(Pid) ->
  931. {ok, StmtId} = mysql:prepare(Pid, "SELECT ?"),
  932. ?assertError(badarg, mysql:execute(Pid, StmtId, [x])),
  933. ?assertError(badarg, mysql:query(Pid, "SELECT ?", [x])),
  934. ok = mysql:unprepare(Pid, StmtId).
  935. load_data_local_infile(Pid, Cwd) ->
  936. File = iolist_to_binary(filename:join([Cwd, "load_local_infile_test.csv"])),
  937. ok = file:write_file(File, <<"1;value 1\n2;value 2\n">>),
  938. ok = mysql:query(Pid, <<"CREATE TABLE load_local_test (id int, value blob)">>),
  939. ok = mysql:query(Pid, <<"LOAD DATA LOCAL "
  940. "INFILE '", File/binary, "' "
  941. "INTO TABLE load_local_test "
  942. "FIELDS TERMINATED BY ';' "
  943. "LINES TERMINATED BY '\\n'">>),
  944. ok = file:delete(File),
  945. {ok, Columns, Rows} = mysql:query(Pid,
  946. <<"SELECT * FROM load_local_test ORDER BY id">>),
  947. ?assertEqual([<<"id">>, <<"value">>], Columns),
  948. ?assertEqual([[1, <<"value 1">>], [2, <<"value 2">>]], Rows),
  949. ok = mysql:query(Pid, <<"DROP TABLE load_local_test">>).
  950. load_data_local_infile_missing(Pid, Cwd) ->
  951. File = iolist_to_binary(filename:join([Cwd, "load_local_infile_missing_test.csv"])),
  952. ok = mysql:query(Pid, <<"CREATE TABLE load_local_test (id int, value blob)">>),
  953. Result = mysql:query(Pid, <<"LOAD DATA LOCAL "
  954. "INFILE '", File/binary, "' "
  955. "INTO TABLE load_local_test "
  956. "FIELDS TERMINATED BY ';' "
  957. "LINES TERMINATED BY '\\n'">>),
  958. FilenameSize=byte_size(File),
  959. ?assertMatch({error, {-2, undefined, <<"The server requested a file which could "
  960. "not be opened by the client: ",
  961. File:FilenameSize/binary, _/binary>>}},
  962. Result),
  963. ok = mysql:query(Pid, <<"DROP TABLE load_local_test">>).
  964. load_data_local_infile_not_allowed(Pid, Cwd) ->
  965. File = iolist_to_binary(filename:join([Cwd, "../load_local_infile_not_allowed_test.csv"])),
  966. ok = mysql:query(Pid, <<"CREATE TABLE load_local_test (id int, value blob)">>),
  967. Result = mysql:query(Pid, <<"LOAD DATA LOCAL "
  968. "INFILE '", File/binary, "' "
  969. "INTO TABLE load_local_test "
  970. "FIELDS TERMINATED BY ';' "
  971. "LINES TERMINATED BY '\\n'">>),
  972. ?assertEqual({error, {-1, undefined, <<"The server requested a file not permitted "
  973. "by the client: ", File/binary>>}}, Result),
  974. ok = mysql:query(Pid, <<"DROP TABLE load_local_test">>).
  975. load_data_local_infile_multi(Pid, Cwd) ->
  976. File = iolist_to_binary(filename:join([Cwd, "load_local_infile_test.csv"])),
  977. ok = file:write_file(File, <<"1;value 1\n2;value 2\n">>),
  978. ok = mysql:query(Pid, <<"CREATE TABLE load_local_test (id int, value blob)">>),
  979. {ok, [Res1, Res2]} = mysql:query(Pid, <<"SELECT 'foo'; "
  980. "LOAD DATA LOCAL "
  981. "INFILE '", File/binary, "' "
  982. "INTO TABLE load_local_test "
  983. "FIELDS TERMINATED BY ';' "
  984. "LINES TERMINATED BY '\\n'; "
  985. "SELECT 'bar'">>),
  986. ok = file:delete(File),
  987. ?assertEqual({[<<"foo">>], [[<<"foo">>]]}, Res1),
  988. ?assertEqual({[<<"bar">>], [[<<"bar">>]]}, Res2),
  989. {ok, Columns, Rows} = mysql:query(Pid,
  990. <<"SELECT * FROM load_local_test ORDER BY id">>),
  991. ?assertEqual([<<"id">>, <<"value">>], Columns),
  992. ?assertEqual([[1, <<"value 1">>], [2, <<"value 2">>]], Rows),
  993. ok = mysql:query(Pid, <<"DROP TABLE load_local_test">>).
  994. %% @doc Tests write and read in text and the binary protocol, all combinations.
  995. %% This helper function assumes an empty table with a single column.
  996. write_read_text_binary(Conn, Term, SqlLiteral, Table, Column) ->
  997. SelectQuery = <<"SELECT ", Column/binary, " FROM ", Table/binary>>,
  998. {ok, SelectStmt} = mysql:prepare(Conn, SelectQuery),
  999. %% Insert as text, read text and binary, delete
  1000. InsertQuery = <<"INSERT INTO ", Table/binary, " (", Column/binary, ")"
  1001. " VALUES (", SqlLiteral/binary, ")">>,
  1002. ok = mysql:query(Conn, InsertQuery),
  1003. R = mysql:query(Conn, SelectQuery),
  1004. ?assertEqual({ok, [Column], [[Term]]}, R),
  1005. ?assertEqual({ok, [Column], [[Term]]}, mysql:execute(Conn, SelectStmt, [])),
  1006. mysql:query(Conn, <<"DELETE FROM ", Table/binary>>),
  1007. %% Insert as binary, read text and binary, delete
  1008. InsertQ = <<"INSERT INTO ", Table/binary, " (", Column/binary, ")",
  1009. " VALUES (?)">>,
  1010. {ok, InsertStmt} = mysql:prepare(Conn, InsertQ),
  1011. ok = mysql:execute(Conn, InsertStmt, [Term]),
  1012. ok = mysql:unprepare(Conn, InsertStmt),
  1013. ?assertEqual({ok, [Column], [[Term]]}, mysql:query(Conn, SelectQuery)),
  1014. ?assertEqual({ok, [Column], [[Term]]}, mysql:execute(Conn, SelectStmt, [])),
  1015. mysql:query(Conn, <<"DELETE FROM ", Table/binary>>),
  1016. %% Cleanup
  1017. ok = mysql:unprepare(Conn, SelectStmt).
  1018. %% --------------------------------------------------------------------------
  1019. timeout_test_() ->
  1020. {setup,
  1021. fun () ->
  1022. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  1023. {log_warnings, false}]),
  1024. Pid
  1025. end,
  1026. fun (Pid) ->
  1027. mysql:stop(Pid)
  1028. end,
  1029. {with, [fun (Pid) ->
  1030. %% SLEEP was added in MySQL 5.0.12
  1031. check_sleep_timeout_result(
  1032. mysql:query(Pid, <<"SELECT SLEEP(5)">>, 40)),
  1033. %% A query after an interrupted query shouldn't get a timeout.
  1034. ?assertMatch({ok,[<<"42">>], [[42]]},
  1035. mysql:query(Pid, <<"SELECT 42">>)),
  1036. %% Parametrized query
  1037. check_sleep_timeout_result(
  1038. mysql:query(Pid, <<"SELECT SLEEP(?)">>, [5], 40)),
  1039. %% Prepared statement
  1040. {ok, Stmt} = mysql:prepare(Pid, <<"SELECT SLEEP(?)">>),
  1041. check_sleep_timeout_result(
  1042. mysql:execute(Pid, Stmt, [5], 40)),
  1043. ok = mysql:unprepare(Pid, Stmt)
  1044. end]}}.
  1045. check_sleep_timeout_result({error, {1317, <<"70100">>,
  1046. <<"Query execution was ", _/binary>>}}) ->
  1047. %% MariaDB 10.3 on TravisCI returns this when sleep is interrupted.
  1048. ok;
  1049. check_sleep_timeout_result(Result) ->
  1050. %% Sleep returns 1 when aborted
  1051. ?assertMatch({ok, [<<"SLEEP", _/binary>>], [[1]]}, Result).
  1052. %% --------------------------------------------------------------------------
  1053. %% Prepared statements
  1054. with_table_foo_test_() ->
  1055. {setup,
  1056. fun () ->
  1057. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  1058. {query_cache_time, 50},
  1059. {log_warnings, false}]),
  1060. ok = mysql:query(Pid, <<"DROP DATABASE IF EXISTS otptest">>),
  1061. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  1062. ok = mysql:query(Pid, <<"USE otptest">>),
  1063. ok = mysql:query(Pid, <<"CREATE TABLE foo (bar INT) engine=InnoDB">>),
  1064. Pid
  1065. end,
  1066. fun (Pid) ->
  1067. ok = mysql:query(Pid, <<"DROP DATABASE otptest">>),
  1068. mysql:stop(Pid)
  1069. end,
  1070. fun (Pid) ->
  1071. [{"Prepared statements", fun () -> prepared_statements(Pid) end},
  1072. {"Parametrized queries", fun () -> parameterized_query(Pid) end}]
  1073. end}.
  1074. prepared_statements(Pid) ->
  1075. %% Unnamed
  1076. ?assertEqual({error,{1146, <<"42S02">>,
  1077. <<"Table 'otptest.tab' doesn't exist">>}},
  1078. mysql:prepare(Pid, "SELECT * FROM tab WHERE id = ?")),
  1079. {ok, StmtId} = mysql:prepare(Pid, "SELECT * FROM foo WHERE bar = ?"),
  1080. ?assert(is_integer(StmtId)),
  1081. ?assertEqual(ok, mysql:unprepare(Pid, StmtId)),
  1082. ?assertEqual({error, not_prepared}, mysql:unprepare(Pid, StmtId)),
  1083. %% Named
  1084. ?assertEqual({error,{1146, <<"42S02">>,
  1085. <<"Table 'otptest.tab' doesn't exist">>}},
  1086. mysql:prepare(Pid, tab, "SELECT * FROM tab WHERE id = ?")),
  1087. ?assertEqual({ok, foo},
  1088. mysql:prepare(Pid, foo, "SELECT * FROM foo WHERE bar = ?")),
  1089. %% Prepare again unprepares the old stmt associated with this name.
  1090. ?assertEqual({ok, foo},
  1091. mysql:prepare(Pid, foo, "SELECT bar FROM foo WHERE bar = ?")),
  1092. ?assertEqual(ok, mysql:unprepare(Pid, foo)),
  1093. ?assertEqual({error, not_prepared}, mysql:unprepare(Pid, foo)),
  1094. %% Execute when not prepared
  1095. ?assertEqual({error, not_prepared}, mysql:execute(Pid, not_a_stmt, [])),
  1096. ok.
  1097. parameterized_query(Conn) ->
  1098. %% To see that cache eviction works as expected, look at the code coverage.
  1099. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [1]),
  1100. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [2]),
  1101. receive after 150 -> ok end, %% Now the query cache should emptied
  1102. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [3]),
  1103. {error, {_, _, _}} = mysql:query(Conn, "Lorem ipsum dolor sit amet", [4]).
  1104. %% --- simple gen_server callbacks ---
  1105. gen_server_coverage_test() ->
  1106. {noreply, state} = mysql_conn:handle_cast(foo, state),
  1107. {noreply, state} = mysql_conn:handle_info(foo, state),
  1108. ok = mysql_conn:terminate(kill, state).
  1109. %% --- Utility functions
  1110. db_version_string(Pid) ->
  1111. {ok, _, [[Version]]} = mysql:query(Pid, <<"SELECT @@version">>),
  1112. Version.
  1113. is_mariadb(Version) ->
  1114. binary:match(Version, <<"MariaDB">>) =/= nomatch.
  1115. parse_db_version(Version) ->
  1116. %% Remove stuff after dash for e.g. "5.5.40-0ubuntu0.12.04.1-log"
  1117. [Version1 | _] = binary:split(Version, <<"-">>),
  1118. lists:map(fun binary_to_integer/1,
  1119. binary:split(Version1, <<".">>, [global])).
  1120. is_access_denied({1045, <<"28000">>, <<"Access denie", _/binary>>}) ->
  1121. true; % MySQL 5.x, etc.
  1122. is_access_denied({1698, <<"28000">>, <<"Access denie", _/binary>>}) ->
  1123. true; % MariaDB 10.3.15
  1124. is_access_denied({1251, <<"08004">>, <<"Client does not support authentication "
  1125. "protocol requested", _/binary>>}) ->
  1126. true; % This has been observed with MariaDB 10.3.13
  1127. is_access_denied(_) ->
  1128. false.