mysql_tests.erl 54 KB

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