mysql_tests.erl 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. %% MySQL/OTP – MySQL client library for Erlang/OTP
  2. %% Copyright (C) 2014 Viktor Söderqvist
  3. %%
  4. %% This file is part of MySQL/OTP.
  5. %%
  6. %% MySQL/OTP is free software: you can redistribute it and/or modify it under
  7. %% the terms of the GNU Lesser General Public License as published by the Free
  8. %% Software Foundation, either version 3 of the License, or (at your option)
  9. %% any later version.
  10. %%
  11. %% This program is distributed in the hope that it will be useful, but WITHOUT
  12. %% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. %% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  14. %% more details.
  15. %%
  16. %% You should have received a copy of the GNU Lesser General Public License
  17. %% along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. %% @doc This module performs test to an actual database.
  19. -module(mysql_tests).
  20. -include_lib("eunit/include/eunit.hrl").
  21. -define(user, "otptest").
  22. -define(password, "otptest").
  23. -define(create_table_t, <<"CREATE TABLE t ("
  24. " id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,"
  25. " bl BLOB,"
  26. " tx TEXT NOT NULL," %% No default value
  27. " f FLOAT,"
  28. " d DOUBLE,"
  29. " dc DECIMAL(5,3),"
  30. " y YEAR,"
  31. " ti TIME,"
  32. " ts TIMESTAMP,"
  33. " da DATE,"
  34. " c CHAR(2)"
  35. ") ENGINE=InnoDB">>).
  36. failing_connect_test() ->
  37. process_flag(trap_exit, true),
  38. ?assertMatch({error, {1045, <<"28000">>, <<"Access denied", _/binary>>}},
  39. mysql:start_link([{user, "dummy"}, {password, "junk"}])),
  40. receive
  41. {'EXIT', _Pid, {1045, <<"28000">>, <<"Access denie", _/binary>>}} -> ok
  42. after 1000 ->
  43. ?assertEqual(ok, no_exit_message)
  44. end,
  45. process_flag(trap_exit, false).
  46. successful_connect_test() ->
  47. %% A connection with a registered name and execute initial queries and
  48. %% create prepared statements.
  49. Options = [{name, {local, tardis}}, {user, ?user}, {password, ?password},
  50. {queries, ["SET @foo = 'bar'", "SELECT 1",
  51. "SELECT 1; SELECT 2"]},
  52. {prepare, [{foo, "SELECT @foo"}]}],
  53. {ok, Pid} = mysql:start_link(Options),
  54. %% Check that queries and prepare has been done.
  55. ?assertEqual({ok, [<<"@foo">>], [[<<"bar">>]]},
  56. mysql:execute(Pid, foo, [])),
  57. %% Test some gen_server callbacks not tested elsewhere
  58. State = get_state(Pid),
  59. ?assertMatch({ok, State}, mysql:code_change("0.1.0", State, [])),
  60. ?assertMatch({error, _}, mysql:code_change("2.0.0", unknown_state, [])),
  61. exit(whereis(tardis), normal).
  62. keep_alive_test() ->
  63. %% Let the connection send a few pings.
  64. process_flag(trap_exit, true),
  65. Options = [{user, ?user}, {password, ?password}, {keep_alive, 20}],
  66. {ok, Pid} = mysql:start_link(Options),
  67. receive after 70 -> ok end,
  68. State = get_state(Pid),
  69. [state, _Version, _ConnectionId, Socket | _] = tuple_to_list(State),
  70. {ok, ExitMessage, LoggedErrors} = error_logger_acc:capture(fun () ->
  71. gen_tcp:close(Socket),
  72. receive
  73. Message -> Message
  74. after 1000 ->
  75. ping_didnt_crash_connection
  76. end
  77. end),
  78. process_flag(trap_exit, false),
  79. %% Check that we got the expected crash report in the error log.
  80. ?assertMatch({'EXIT', Pid, _Reason}, ExitMessage),
  81. [{error, LoggedMsg}, {error_report, LoggedReport}] = LoggedErrors,
  82. ExpectedPrefix = io_lib:format("** Generic server ~p terminating", [Pid]),
  83. ?assert(lists:prefix(lists:flatten(ExpectedPrefix), LoggedMsg)),
  84. ?assertMatch({crash_report, _}, LoggedReport),
  85. exit(Pid, normal).
  86. %% For R16B where sys:get_state/1 is not available.
  87. get_state(Process) ->
  88. {status,_,_,[_,_,_,_,Misc]} = sys:get_status(Process),
  89. hd([State || {data,[{"State", State}]} <- Misc]).
  90. query_test_() ->
  91. {setup,
  92. fun () ->
  93. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  94. {log_warnings, false},
  95. {keep_alive, true}]),
  96. ok = mysql:query(Pid, <<"DROP DATABASE IF EXISTS otptest">>),
  97. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  98. ok = mysql:query(Pid, <<"USE otptest">>),
  99. ok = mysql:query(Pid, <<"SET autocommit = 1">>),
  100. Pid
  101. end,
  102. fun (Pid) ->
  103. ok = mysql:query(Pid, <<"DROP DATABASE otptest">>),
  104. exit(Pid, normal)
  105. end,
  106. fun (Pid) ->
  107. [{"Select db on connect", fun () -> connect_with_db(Pid) end},
  108. {"Autocommit", fun () -> autocommit(Pid) end},
  109. {"Encode", fun () -> encode(Pid) end},
  110. {"Basic queries", fun () -> basic_queries(Pid) end},
  111. {"Multi statements", fun () -> multi_statements(Pid) end},
  112. {"Text protocol", fun () -> text_protocol(Pid) end},
  113. {"Binary protocol", fun () -> binary_protocol(Pid) end},
  114. {"FLOAT rounding", fun () -> float_rounding(Pid) end},
  115. {"DECIMAL", fun () -> decimal(Pid) end},
  116. {"INT", fun () -> int(Pid) end},
  117. {"BIT(N)", fun () -> bit(Pid) end},
  118. {"DATE", fun () -> date(Pid) end},
  119. {"TIME", fun () -> time(Pid) end},
  120. {"DATETIME", fun () -> datetime(Pid) end},
  121. {"Microseconds", fun () -> microseconds(Pid) end}]
  122. end}.
  123. connect_with_db(_Pid) ->
  124. %% Make another connection and set the db in the handshake phase
  125. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  126. {database, "otptest"}]),
  127. ?assertMatch({ok, _, [[<<"otptest">>]]},
  128. mysql:query(Pid, "SELECT DATABASE()")),
  129. exit(Pid, normal).
  130. log_warnings_test() ->
  131. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password}]),
  132. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  133. ok = mysql:query(Pid, <<"USE otptest">>),
  134. %% Capture error log to check that we get a warning logged
  135. ok = mysql:query(Pid, "CREATE TABLE foo (x INT NOT NULL)"),
  136. {ok, insrt} = mysql:prepare(Pid, insrt, "INSERT INTO foo () VALUES ()"),
  137. {ok, ok, LoggedErrors} = error_logger_acc:capture(fun () ->
  138. ok = mysql:query(Pid, "INSERT INTO foo () VALUES ()"),
  139. ok = mysql:query(Pid, "INSeRT INtO foo () VaLUeS ()", []),
  140. ok = mysql:execute(Pid, insrt, [])
  141. end),
  142. [{_, Log1}, {_, Log2}, {_, Log3}] = LoggedErrors,
  143. ?assertEqual("Warning 1364: Field 'x' doesn't have a default value\n"
  144. " in INSERT INTO foo () VALUES ()\n", Log1),
  145. ?assertEqual("Warning 1364: Field 'x' doesn't have a default value\n"
  146. " in INSeRT INtO foo () VaLUeS ()\n", Log2),
  147. ?assertEqual("Warning 1364: Field 'x' doesn't have a default value\n"
  148. " in INSERT INTO foo () VALUES ()\n", Log3),
  149. exit(Pid, normal).
  150. autocommit(Pid) ->
  151. ?assert(mysql:autocommit(Pid)),
  152. ok = mysql:query(Pid, <<"SET autocommit = 0">>),
  153. ?assertNot(mysql:autocommit(Pid)),
  154. ok = mysql:query(Pid, <<"SET autocommit = 1">>),
  155. ?assert(mysql:autocommit(Pid)).
  156. encode(Pid) ->
  157. %% Test with backslash escapes enabled and disabled.
  158. {ok, _, [[OldMode]]} = mysql:query(Pid, "SELECT @@sql_mode"),
  159. ok = mysql:query(Pid, "SET sql_mode = ''"),
  160. ?assertEqual(<<"'foo\\\\bar''baz'">>,
  161. iolist_to_binary(mysql:encode(Pid, "foo\\bar'baz"))),
  162. ok = mysql:query(Pid, "SET sql_mode = 'NO_BACKSLASH_ESCAPES'"),
  163. ?assertEqual(<<"'foo\\bar''baz'">>,
  164. iolist_to_binary(mysql:encode(Pid, "foo\\bar'baz"))),
  165. ok = mysql:query(Pid, "SET sql_mode = ?", [OldMode]).
  166. basic_queries(Pid) ->
  167. %% warning count
  168. ?assertEqual(ok, mysql:query(Pid, <<"DROP TABLE IF EXISTS foo">>)),
  169. ?assertEqual(1, mysql:warning_count(Pid)),
  170. %% SQL parse error
  171. ?assertMatch({error, {1064, <<"42000">>, <<"You have an erro", _/binary>>}},
  172. mysql:query(Pid, <<"FOO">>)),
  173. %% Simple resultset with various types
  174. ?assertEqual({ok, [<<"i">>, <<"s">>], [[42, <<"foo">>]]},
  175. mysql:query(Pid, <<"SELECT 42 AS i, 'foo' AS s;">>)),
  176. ok.
  177. multi_statements(Pid) ->
  178. %% Multiple statements, no result set
  179. ?assertEqual(ok, mysql:query(Pid, "CREATE TABLE foo (bar INT);"
  180. "DROP TABLE foo;")),
  181. %% Multiple statements, one result set
  182. ?assertEqual({ok, [<<"foo">>], [[42]]},
  183. mysql:query(Pid, "CREATE TABLE foo (bar INT);"
  184. "DROP TABLE foo;"
  185. "SELECT 42 AS foo;")),
  186. %% Multiple statements, multiple result sets
  187. ?assertEqual({ok, [{[<<"foo">>], [[42]]}, {[<<"bar">>], [[<<"baz">>]]}]},
  188. mysql:query(Pid, "SELECT 42 AS foo; SELECT 'baz' AS bar;")),
  189. %% Multiple results in a prepared statement.
  190. %% Preparing "SELECT ...; SELECT ...;" gives a syntax error although the
  191. %% docs say it should be possible.
  192. %% Instead, test executing a stored procedure that returns multiple result
  193. %% sets using a prepared statement.
  194. CreateProc = "CREATE PROCEDURE multifoo() BEGIN\n"
  195. " SELECT 42 AS foo;\n"
  196. " SELECT 'baz' AS bar;\n"
  197. "END;\n",
  198. ok = mysql:query(Pid, CreateProc),
  199. ?assertEqual({ok, multifoo},
  200. mysql:prepare(Pid, multifoo, "CALL multifoo();")),
  201. ?assertEqual({ok, [{[<<"foo">>], [[42]]}, {[<<"bar">>], [[<<"baz">>]]}]},
  202. mysql:execute(Pid, multifoo, [])),
  203. ?assertEqual(ok, mysql:unprepare(Pid, multifoo)),
  204. ?assertEqual(ok, mysql:query(Pid, "DROP PROCEDURE multifoo;")),
  205. ok.
  206. text_protocol(Pid) ->
  207. ok = mysql:query(Pid, ?create_table_t),
  208. ok = mysql:query(Pid, <<"INSERT INTO t (bl, f, d, dc, y, ti, ts, da, c)"
  209. " VALUES ('blob', 3.14, 3.14, 3.14, 2014,"
  210. "'00:22:11', '2014-11-03 00:22:24', '2014-11-03',"
  211. " NULL)">>),
  212. ?assertEqual(1, mysql:warning_count(Pid)), %% tx has no default value
  213. ?assertEqual(1, mysql:insert_id(Pid)), %% auto_increment starts from 1
  214. ?assertEqual(1, mysql:affected_rows(Pid)),
  215. %% select
  216. {ok, Columns, Rows} = mysql:query(Pid, <<"SELECT * FROM t">>),
  217. ?assertEqual([<<"id">>, <<"bl">>, <<"tx">>, <<"f">>, <<"d">>, <<"dc">>,
  218. <<"y">>, <<"ti">>, <<"ts">>, <<"da">>, <<"c">>], Columns),
  219. ?assertEqual([[1, <<"blob">>, <<>>, 3.14, 3.14, 3.14,
  220. 2014, {0, {0, 22, 11}},
  221. {{2014, 11, 03}, {00, 22, 24}}, {2014, 11, 03}, null]],
  222. Rows),
  223. ok = mysql:query(Pid, <<"DROP TABLE t">>).
  224. binary_protocol(Pid) ->
  225. ok = mysql:query(Pid, ?create_table_t),
  226. %% The same queries as in the text protocol. Expect the same results.
  227. {ok, Ins} = mysql:prepare(Pid, <<"INSERT INTO t (bl, tx, f, d, dc, y, ti,"
  228. " ts, da, c)"
  229. " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)">>),
  230. %% 16#161 is the codepoint for "s with caron"; <<197, 161>> in UTF-8.
  231. ok = mysql:execute(Pid, Ins, [<<"blob">>, [16#161], 3.14, 3.14, 3.14,
  232. 2014, {0, {0, 22, 11}},
  233. {{2014, 11, 03}, {0, 22, 24}},
  234. {2014, 11, 03}, null]),
  235. {ok, Stmt} = mysql:prepare(Pid, <<"SELECT * FROM t WHERE id=?">>),
  236. {ok, Columns, Rows} = mysql:execute(Pid, Stmt, [1]),
  237. ?assertEqual([<<"id">>, <<"bl">>, <<"tx">>, <<"f">>, <<"d">>, <<"dc">>,
  238. <<"y">>, <<"ti">>,
  239. <<"ts">>, <<"da">>, <<"c">>], Columns),
  240. ?assertEqual([[1, <<"blob">>, <<197, 161>>, 3.14, 3.14, 3.14,
  241. 2014, {0, {0, 22, 11}},
  242. {{2014, 11, 03}, {00, 22, 24}}, {2014, 11, 03}, null]],
  243. Rows),
  244. ok = mysql:query(Pid, <<"DROP TABLE t">>).
  245. float_rounding(Pid) ->
  246. %% This is to make sure we get the same values for 32-bit FLOATs in the text
  247. %% and binary protocols for ordinary queries and prepared statements
  248. %% respectively.
  249. %%
  250. %% MySQL rounds to 6 significant digits when "printing" floats over the
  251. %% text protocol. When we receive a float on the binary protocol, we round
  252. %% it in the same way to match what MySQL does on the text protocol. This
  253. %% way we should to get the same values regardless of which protocol is
  254. %% used.
  255. %% Table for testing floats
  256. ok = mysql:query(Pid, "CREATE TABLE f (f FLOAT)"),
  257. %% Prepared statements
  258. {ok, Insert} = mysql:prepare(Pid, "INSERT INTO f (f) VALUES (?)"),
  259. {ok, Select} = mysql:prepare(Pid, "SELECT f FROM f"),
  260. %% [{Input, Expected}]
  261. TestData = [{1.0, 1.0}, {0.0, 0.0}, {3.14, 3.14}, {0.2, 0.2},
  262. {0.20082111, 0.200821}, {0.000123456789, 0.000123457},
  263. {33.3333333, 33.3333}, {-33.2233443322, -33.2233},
  264. {400.0123, 400.012}, {1000.1234, 1000.12},
  265. {999.00009, 999.0},
  266. {1234.5678, 1234.57}, {68888.8888, 68888.9},
  267. {123456.789, 123457.0}, {7654321.0, 7654320.0},
  268. {80001111.1, 80001100.0}, {987654321.0, 987654000.0},
  269. {-123456789.0, -123457000.0},
  270. {2.12345111e-23, 2.12345e-23}, {-2.12345111e-23, -2.12345e-23},
  271. {2.12345111e23, 2.12345e23}, {-2.12345111e23, -2.12345e23}],
  272. lists:foreach(fun ({Input, Expected}) ->
  273. %% Insert using binary protocol (sending it as a double)
  274. ok = mysql:execute(Pid, Insert, [Input]),
  275. %% Text (plain query)
  276. {ok, _, [[Value]]} = mysql:query(Pid, "SELECT f FROM f"),
  277. ?assertEqual(Expected, Value),
  278. %% Binary (prepared statement)
  279. {ok, _, [[BinValue]]} = mysql:execute(Pid, Select, []),
  280. ?assertEqual(Expected, BinValue),
  281. %% cleanup before the next test
  282. ok = mysql:query(Pid, "DELETE FROM f")
  283. end,
  284. TestData),
  285. ok = mysql:query(Pid, "DROP TABLE f").
  286. decimal(Pid) ->
  287. %% As integer when S == 0
  288. ok = mysql:query(Pid, "CREATE TABLE dec0 (d DECIMAL(50, 0))"),
  289. write_read_text_binary(
  290. Pid, 14159265358979323846264338327950288419716939937510,
  291. <<"14159265358979323846264338327950288419716939937510">>,
  292. <<"dec0">>, <<"d">>
  293. ),
  294. write_read_text_binary(
  295. Pid, -14159265358979323846264338327950288419716939937510,
  296. <<"-14159265358979323846264338327950288419716939937510">>,
  297. <<"dec0">>, <<"d">>
  298. ),
  299. ok = mysql:query(Pid, "DROP TABLE dec0"),
  300. %% As float when P =< 15, S > 0
  301. ok = mysql:query(Pid, "CREATE TABLE dec15 (d DECIMAL(15, 14))"),
  302. write_read_text_binary(Pid, 3.14159265358979, <<"3.14159265358979">>,
  303. <<"dec15">>, <<"d">>),
  304. write_read_text_binary(Pid, -3.14159265358979, <<"-3.14159265358979">>,
  305. <<"dec15">>, <<"d">>),
  306. write_read_text_binary(Pid, 3.0, <<"3">>, <<"dec15">>, <<"d">>),
  307. ok = mysql:query(Pid, "DROP TABLE dec15"),
  308. %% As binary when P >= 16, S > 0
  309. ok = mysql:query(Pid, "CREATE TABLE dec16 (d DECIMAL(16, 15))"),
  310. write_read_text_binary(Pid, <<"3.141592653589793">>,
  311. <<"3.141592653589793">>, <<"dec16">>, <<"d">>),
  312. write_read_text_binary(Pid, <<"-3.141592653589793">>,
  313. <<"-3.141592653589793">>, <<"dec16">>, <<"d">>),
  314. write_read_text_binary(Pid, <<"3.000000000000000">>, <<"3">>,
  315. <<"dec16">>, <<"d">>),
  316. ok = mysql:query(Pid, "DROP TABLE dec16").
  317. int(Pid) ->
  318. ok = mysql:query(Pid, "CREATE TABLE ints (i INT)"),
  319. write_read_text_binary(Pid, 42, <<"42">>, <<"ints">>, <<"i">>),
  320. write_read_text_binary(Pid, -42, <<"-42">>, <<"ints">>, <<"i">>),
  321. write_read_text_binary(Pid, 987654321, <<"987654321">>, <<"ints">>,
  322. <<"i">>),
  323. write_read_text_binary(Pid, -987654321, <<"-987654321">>,
  324. <<"ints">>, <<"i">>),
  325. ok = mysql:query(Pid, "DROP TABLE ints"),
  326. %% Overflow with TINYINT
  327. ok = mysql:query(Pid, "CREATE TABLE tint (i TINYINT)"),
  328. write_read_text_binary(Pid, 127, <<"1000">>, <<"tint">>, <<"i">>),
  329. write_read_text_binary(Pid, -128, <<"-1000">>, <<"tint">>, <<"i">>),
  330. ok = mysql:query(Pid, "DROP TABLE tint"),
  331. %% SMALLINT
  332. ok = mysql:query(Pid, "CREATE TABLE sint (i SMALLINT)"),
  333. write_read_text_binary(Pid, 32000, <<"32000">>, <<"sint">>, <<"i">>),
  334. write_read_text_binary(Pid, -32000, <<"-32000">>, <<"sint">>, <<"i">>),
  335. ok = mysql:query(Pid, "DROP TABLE sint"),
  336. %% BIGINT
  337. ok = mysql:query(Pid, "CREATE TABLE bint (i BIGINT)"),
  338. write_read_text_binary(Pid, 123456789012, <<"123456789012">>,
  339. <<"bint">>, <<"i">>),
  340. write_read_text_binary(Pid, -123456789012, <<"-123456789012">>,
  341. <<"bint">>, <<"i">>),
  342. ok = mysql:query(Pid, "DROP TABLE bint").
  343. %% The BIT(N) datatype in MySQL 5.0.3 and later: the equivallent to bitstring()
  344. bit(Pid) ->
  345. ok = mysql:query(Pid, "CREATE TABLE bits (b BIT(11))"),
  346. write_read_text_binary(Pid, <<16#ff, 0:3>>, <<"b'11111111000'">>,
  347. <<"bits">>, <<"b">>),
  348. write_read_text_binary(Pid, <<16#7f, 6:3>>, <<"b'01111111110'">>,
  349. <<"bits">>, <<"b">>),
  350. ok = mysql:query(Pid, "DROP TABLE bits").
  351. date(Pid) ->
  352. ok = mysql:query(Pid, "CREATE TABLE d (d DATE)"),
  353. lists:foreach(
  354. fun ({Value, SqlLiteral}) ->
  355. write_read_text_binary(Pid, Value, SqlLiteral, <<"d">>, <<"d">>)
  356. end,
  357. [{{2014, 11, 03}, <<"'2014-11-03'">>},
  358. {{0, 0, 0}, <<"'0000-00-00'">>}]
  359. ),
  360. ok = mysql:query(Pid, "DROP TABLE d").
  361. %% Test TIME value representation. There are a few things to check.
  362. time(Pid) ->
  363. ok = mysql:query(Pid, "CREATE TABLE tm (tm TIME)"),
  364. lists:foreach(
  365. fun ({Value, SqlLiteral}) ->
  366. write_read_text_binary(Pid, Value, SqlLiteral, <<"tm">>, <<"tm">>)
  367. end,
  368. [{{0, {10, 11, 12}}, <<"'10:11:12'">>},
  369. {{5, {0, 0, 1}}, <<"'120:00:01'">>},
  370. {{-1, {23, 59, 59}}, <<"'-00:00:01'">>},
  371. {{-1, {23, 59, 0}}, <<"'-00:01:00'">>},
  372. {{-1, {23, 0, 0}}, <<"'-01:00:00'">>},
  373. {{-1, {0, 0, 0}}, <<"'-24:00:00'">>},
  374. {{-5, {10, 0, 0}}, <<"'-110:00:00'">>},
  375. {{0, {0, 0, 0}}, <<"'00:00:00'">>}]
  376. ),
  377. %% Zero seconds as a float.
  378. ok = mysql:query(Pid, "INSERT INTO tm (tm) VALUES (?)",
  379. [{-1, {1, 2, 0.0}}]),
  380. ?assertEqual({ok, [<<"tm">>], [[{-1, {1, 2, 0}}]]},
  381. mysql:query(Pid, "SELECT tm FROM tm")),
  382. ok = mysql:query(Pid, "DROP TABLE tm").
  383. datetime(Pid) ->
  384. ok = mysql:query(Pid, "CREATE TABLE dt (dt DATETIME)"),
  385. lists:foreach(
  386. fun ({Value, SqlLiteral}) ->
  387. write_read_text_binary(Pid, Value, SqlLiteral, <<"dt">>, <<"dt">>)
  388. end,
  389. [{{{2014, 12, 14}, {19, 39, 20}}, <<"'2014-12-14 19:39:20'">>},
  390. {{{2014, 12, 14}, {0, 0, 0}}, <<"'2014-12-14 00:00:00'">>},
  391. {{{0, 0, 0}, {0, 0, 0}}, <<"'0000-00-00 00:00:00'">>}]
  392. ),
  393. ok = mysql:query(Pid, "DROP TABLE dt").
  394. microseconds(Pid) ->
  395. %% Check whether we have the required version for this testcase.
  396. {ok, _, [[Version]]} = mysql:query(Pid, <<"SELECT @@version">>),
  397. try
  398. %% Remove stuff after dash for e.g. "5.5.40-0ubuntu0.12.04.1-log"
  399. [Version1 | _] = binary:split(Version, <<"-">>),
  400. Version2 = lists:map(fun binary_to_integer/1,
  401. binary:split(Version1, <<".">>, [global])),
  402. Version2 >= [5, 6, 4] orelse throw(nope)
  403. of _ ->
  404. test_time_microseconds(Pid),
  405. test_datetime_microseconds(Pid)
  406. catch _:_ ->
  407. error_logger:info_msg("Skipping microseconds test. Current MySQL"
  408. " version is ~s. Required version is >= 5.6.4.~n",
  409. [Version])
  410. end.
  411. test_time_microseconds(Pid) ->
  412. ok = mysql:query(Pid, "CREATE TABLE m (t TIME(6))"),
  413. %% Positive time
  414. write_read_text_binary(Pid, {0, {23, 59, 57.654321}},
  415. <<"'23:59:57.654321'">>, <<"m">>, <<"t">>),
  416. %% Negative time
  417. write_read_text_binary(Pid, {-1, {23, 59, 57.654321}},
  418. <<"'-00:00:02.345679'">>, <<"m">>, <<"t">>),
  419. ok = mysql:query(Pid, "DROP TABLE m").
  420. test_datetime_microseconds(Pid) ->
  421. ok = mysql:query(Pid, "CREATE TABLE dt (dt DATETIME(6))"),
  422. write_read_text_binary(Pid, {{2014, 11, 23}, {23, 59, 57.654321}},
  423. <<"'2014-11-23 23:59:57.654321'">>, <<"dt">>,
  424. <<"dt">>),
  425. ok = mysql:query(Pid, "DROP TABLE dt").
  426. %% @doc Tests write and read in text and the binary protocol, all combinations.
  427. %% This helper function assumes an empty table with a single column.
  428. write_read_text_binary(Conn, Term, SqlLiteral, Table, Column) ->
  429. SelectQuery = <<"SELECT ", Column/binary, " FROM ", Table/binary>>,
  430. {ok, SelectStmt} = mysql:prepare(Conn, SelectQuery),
  431. %% Insert as text, read text and binary, delete
  432. InsertQuery = <<"INSERT INTO ", Table/binary, " (", Column/binary, ")"
  433. " VALUES (", SqlLiteral/binary, ")">>,
  434. ok = mysql:query(Conn, InsertQuery),
  435. ?assertEqual({ok, [Column], [[Term]]}, mysql:query(Conn, SelectQuery)),
  436. ?assertEqual({ok, [Column], [[Term]]}, mysql:execute(Conn, SelectStmt, [])),
  437. mysql:query(Conn, <<"DELETE FROM ", Table/binary>>),
  438. %% Insert as binary, read text and binary, delete
  439. InsertQ = <<"INSERT INTO ", Table/binary, " (", Column/binary, ")",
  440. " VALUES (?)">>,
  441. {ok, InsertStmt} = mysql:prepare(Conn, InsertQ),
  442. ok = mysql:execute(Conn, InsertStmt, [Term]),
  443. ok = mysql:unprepare(Conn, InsertStmt),
  444. ?assertEqual({ok, [Column], [[Term]]}, mysql:query(Conn, SelectQuery)),
  445. ?assertEqual({ok, [Column], [[Term]]}, mysql:execute(Conn, SelectStmt, [])),
  446. mysql:query(Conn, <<"DELETE FROM ", Table/binary>>),
  447. %% Cleanup
  448. ok = mysql:unprepare(Conn, SelectStmt).
  449. %% --------------------------------------------------------------------------
  450. timeout_test_() ->
  451. {setup,
  452. fun () ->
  453. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  454. {log_warnings, false}]),
  455. Pid
  456. end,
  457. fun (Pid) ->
  458. exit(Pid, normal)
  459. end,
  460. {with, [fun (Pid) ->
  461. %% SLEEP was added in MySQL 5.0.12
  462. ?assertEqual({ok, [<<"SLEEP(5)">>], [[1]]},
  463. mysql:query(Pid, <<"SELECT SLEEP(5)">>, 40)),
  464. %% A query after an interrupted query shouldn't get a timeout.
  465. ?assertMatch({ok,[<<"42">>], [[42]]},
  466. mysql:query(Pid, <<"SELECT 42">>)),
  467. %% Parametrized query
  468. ?assertEqual({ok, [<<"SLEEP(?)">>], [[1]]},
  469. mysql:query(Pid, <<"SELECT SLEEP(?)">>, [5], 40)),
  470. %% Prepared statement
  471. {ok, Stmt} = mysql:prepare(Pid, <<"SELECT SLEEP(?)">>),
  472. ?assertEqual({ok, [<<"SLEEP(?)">>], [[1]]},
  473. mysql:execute(Pid, Stmt, [5], 40)),
  474. ok = mysql:unprepare(Pid, Stmt)
  475. end]}}.
  476. %% --------------------------------------------------------------------------
  477. %% Prepared statements
  478. with_table_foo_test_() ->
  479. {setup,
  480. fun () ->
  481. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  482. {query_cache_time, 50},
  483. {log_warnings, false}]),
  484. ok = mysql:query(Pid, <<"DROP DATABASE IF EXISTS otptest">>),
  485. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  486. ok = mysql:query(Pid, <<"USE otptest">>),
  487. ok = mysql:query(Pid, <<"CREATE TABLE foo (bar INT) engine=InnoDB">>),
  488. Pid
  489. end,
  490. fun (Pid) ->
  491. ok = mysql:query(Pid, <<"DROP DATABASE otptest">>),
  492. exit(Pid, normal)
  493. end,
  494. fun (Pid) ->
  495. [{"Prepared statements", fun () -> prepared_statements(Pid) end},
  496. {"Parametrized queries", fun () -> parameterized_query(Pid) end}]
  497. end}.
  498. prepared_statements(Pid) ->
  499. %% Unnamed
  500. ?assertEqual({error,{1146, <<"42S02">>,
  501. <<"Table 'otptest.tab' doesn't exist">>}},
  502. mysql:prepare(Pid, "SELECT * FROM tab WHERE id = ?")),
  503. {ok, StmtId} = mysql:prepare(Pid, "SELECT * FROM foo WHERE bar = ?"),
  504. ?assert(is_integer(StmtId)),
  505. ?assertEqual(ok, mysql:unprepare(Pid, StmtId)),
  506. ?assertEqual({error, not_prepared}, mysql:unprepare(Pid, StmtId)),
  507. %% Named
  508. ?assertEqual({error,{1146, <<"42S02">>,
  509. <<"Table 'otptest.tab' doesn't exist">>}},
  510. mysql:prepare(Pid, tab, "SELECT * FROM tab WHERE id = ?")),
  511. ?assertEqual({ok, foo},
  512. mysql:prepare(Pid, foo, "SELECT * FROM foo WHERE bar = ?")),
  513. %% Prepare again unprepares the old stmt associated with this name.
  514. ?assertEqual({ok, foo},
  515. mysql:prepare(Pid, foo, "SELECT bar FROM foo WHERE bar = ?")),
  516. ?assertEqual(ok, mysql:unprepare(Pid, foo)),
  517. ?assertEqual({error, not_prepared}, mysql:unprepare(Pid, foo)),
  518. %% Execute when not prepared
  519. ?assertEqual({error, not_prepared}, mysql:execute(Pid, not_a_stmt, [])),
  520. ok.
  521. parameterized_query(Conn) ->
  522. %% To see that cache eviction works as expected, look at the code coverage.
  523. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [1]),
  524. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [2]),
  525. receive after 150 -> ok end, %% Now the query cache should emptied
  526. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [3]),
  527. {error, {_, _, _}} = mysql:query(Conn, "Lorem ipsum dolor sit amet", [x]).
  528. %% --- simple gen_server callbacks ---
  529. gen_server_coverage_test() ->
  530. {noreply, state} = mysql:handle_cast(foo, state),
  531. {noreply, state} = mysql:handle_info(foo, state),
  532. ok = mysql:terminate(kill, state).