mysql_tests.erl 52 KB

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