mysql_tests.erl 47 KB

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