mysql_tests.erl 24 KB

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