mysql_tests.erl 34 KB

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