mysql_tests.erl 39 KB

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