mysql_tests.erl 33 KB

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