mysql_tests.erl 36 KB

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