mysql_tests.erl 54 KB

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