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, f, d, dc, y, ti,"
  228. " ts, da, c)"
  229. " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)">>),
  230. ok = mysql:execute(Pid, Ins, [<<"blob">>, 3.14, 3.14, 3.14,
  231. 2014, {0, {0, 22, 11}},
  232. {{2014, 11, 03}, {0, 22, 24}},
  233. {2014, 11, 03}, null]),
  234. {ok, Stmt} = mysql:prepare(Pid, <<"SELECT * FROM t WHERE id=?">>),
  235. {ok, Columns, Rows} = mysql:execute(Pid, Stmt, [1]),
  236. ?assertEqual([<<"id">>, <<"bl">>, <<"tx">>, <<"f">>, <<"d">>, <<"dc">>,
  237. <<"y">>, <<"ti">>,
  238. <<"ts">>, <<"da">>, <<"c">>], Columns),
  239. ?assertEqual([[1, <<"blob">>, <<>>, 3.14, 3.14, 3.14,
  240. 2014, {0, {0, 22, 11}},
  241. {{2014, 11, 03}, {00, 22, 24}}, {2014, 11, 03}, null]],
  242. Rows),
  243. ok = mysql:query(Pid, <<"DROP TABLE t">>).
  244. float_rounding(Pid) ->
  245. %% This is to make sure we get the same values for 32-bit FLOATs in the text
  246. %% and binary protocols for ordinary queries and prepared statements
  247. %% respectively.
  248. %%
  249. %% MySQL rounds to 6 significant digits when "printing" floats over the
  250. %% text protocol. When we receive a float on the binary protocol, we round
  251. %% it in the same way to match what MySQL does on the text protocol. This
  252. %% way we should to get the same values regardless of which protocol is
  253. %% used.
  254. %% Table for testing floats
  255. ok = mysql:query(Pid, "CREATE TABLE f (f FLOAT)"),
  256. %% Prepared statements
  257. {ok, Insert} = mysql:prepare(Pid, "INSERT INTO f (f) VALUES (?)"),
  258. {ok, Select} = mysql:prepare(Pid, "SELECT f FROM f"),
  259. %% [{Input, Expected}]
  260. TestData = [{1.0, 1.0}, {3.14, 3.14}, {0.2, 0.2},
  261. {0.20082111, 0.200821}, {0.000123456789, 0.000123457},
  262. {33.3333333, 33.3333}, {-33.2233443322, -33.2233},
  263. {400.0123, 400.012}, {1000.1234, 1000.12},
  264. {999.00009, 999.0},
  265. {1234.5678, 1234.57}, {68888.8888, 68888.9},
  266. {123456.789, 123457.0}, {7654321.0, 7654320.0},
  267. {80001111.1, 80001100.0}, {987654321.0, 987654000.0},
  268. {-123456789.0, -123457000.0},
  269. {2.12345111e-23, 2.12345e-23}, {-2.12345111e-23, -2.12345e-23},
  270. {2.12345111e23, 2.12345e23}, {-2.12345111e23, -2.12345e23}],
  271. lists:foreach(fun ({Input, Expected}) ->
  272. %% Insert using binary protocol (sending it as a double)
  273. ok = mysql:execute(Pid, Insert, [Input]),
  274. %% Text (plain query)
  275. {ok, _, [[Value]]} = mysql:query(Pid, "SELECT f FROM f"),
  276. ?assertEqual(Expected, Value),
  277. %% Binary (prepared statement)
  278. {ok, _, [[BinValue]]} = mysql:execute(Pid, Select, []),
  279. ?assertEqual(Expected, BinValue),
  280. %% cleanup before the next test
  281. ok = mysql:query(Pid, "DELETE FROM f")
  282. end,
  283. TestData),
  284. ok = mysql:query(Pid, "DROP TABLE f").
  285. decimal(Pid) ->
  286. %% As integer when S == 0
  287. ok = mysql:query(Pid, "CREATE TABLE dec0 (d DECIMAL(50, 0))"),
  288. write_read_text_binary(
  289. Pid, 14159265358979323846264338327950288419716939937510,
  290. <<"14159265358979323846264338327950288419716939937510">>,
  291. <<"dec0">>, <<"d">>
  292. ),
  293. write_read_text_binary(
  294. Pid, -14159265358979323846264338327950288419716939937510,
  295. <<"-14159265358979323846264338327950288419716939937510">>,
  296. <<"dec0">>, <<"d">>
  297. ),
  298. ok = mysql:query(Pid, "DROP TABLE dec0"),
  299. %% As float when P =< 15, S > 0
  300. ok = mysql:query(Pid, "CREATE TABLE dec15 (d DECIMAL(15, 14))"),
  301. write_read_text_binary(Pid, 3.14159265358979, <<"3.14159265358979">>,
  302. <<"dec15">>, <<"d">>),
  303. write_read_text_binary(Pid, -3.14159265358979, <<"-3.14159265358979">>,
  304. <<"dec15">>, <<"d">>),
  305. write_read_text_binary(Pid, 3.0, <<"3">>, <<"dec15">>, <<"d">>),
  306. ok = mysql:query(Pid, "DROP TABLE dec15"),
  307. %% As binary when P >= 16, S > 0
  308. ok = mysql:query(Pid, "CREATE TABLE dec16 (d DECIMAL(16, 15))"),
  309. write_read_text_binary(Pid, <<"3.141592653589793">>,
  310. <<"3.141592653589793">>, <<"dec16">>, <<"d">>),
  311. write_read_text_binary(Pid, <<"-3.141592653589793">>,
  312. <<"-3.141592653589793">>, <<"dec16">>, <<"d">>),
  313. write_read_text_binary(Pid, <<"3.000000000000000">>, <<"3">>,
  314. <<"dec16">>, <<"d">>),
  315. ok = mysql:query(Pid, "DROP TABLE dec16").
  316. int(Pid) ->
  317. ok = mysql:query(Pid, "CREATE TABLE ints (i INT)"),
  318. write_read_text_binary(Pid, 42, <<"42">>, <<"ints">>, <<"i">>),
  319. write_read_text_binary(Pid, -42, <<"-42">>, <<"ints">>, <<"i">>),
  320. write_read_text_binary(Pid, 987654321, <<"987654321">>, <<"ints">>,
  321. <<"i">>),
  322. write_read_text_binary(Pid, -987654321, <<"-987654321">>,
  323. <<"ints">>, <<"i">>),
  324. ok = mysql:query(Pid, "DROP TABLE ints"),
  325. %% Overflow with TINYINT
  326. ok = mysql:query(Pid, "CREATE TABLE tint (i TINYINT)"),
  327. write_read_text_binary(Pid, 127, <<"1000">>, <<"tint">>, <<"i">>),
  328. write_read_text_binary(Pid, -128, <<"-1000">>, <<"tint">>, <<"i">>),
  329. ok = mysql:query(Pid, "DROP TABLE tint"),
  330. %% SMALLINT
  331. ok = mysql:query(Pid, "CREATE TABLE sint (i SMALLINT)"),
  332. write_read_text_binary(Pid, 32000, <<"32000">>, <<"sint">>, <<"i">>),
  333. write_read_text_binary(Pid, -32000, <<"-32000">>, <<"sint">>, <<"i">>),
  334. ok = mysql:query(Pid, "DROP TABLE sint"),
  335. %% BIGINT
  336. ok = mysql:query(Pid, "CREATE TABLE bint (i BIGINT)"),
  337. write_read_text_binary(Pid, 123456789012, <<"123456789012">>,
  338. <<"bint">>, <<"i">>),
  339. write_read_text_binary(Pid, -123456789012, <<"-123456789012">>,
  340. <<"bint">>, <<"i">>),
  341. ok = mysql:query(Pid, "DROP TABLE bint").
  342. %% The BIT(N) datatype in MySQL 5.0.3 and later: the equivallent to bitstring()
  343. bit(Pid) ->
  344. ok = mysql:query(Pid, "CREATE TABLE bits (b BIT(11))"),
  345. write_read_text_binary(Pid, <<16#ff, 0:3>>, <<"b'11111111000'">>,
  346. <<"bits">>, <<"b">>),
  347. write_read_text_binary(Pid, <<16#7f, 6:3>>, <<"b'01111111110'">>,
  348. <<"bits">>, <<"b">>),
  349. ok = mysql:query(Pid, "DROP TABLE bits").
  350. date(Pid) ->
  351. ok = mysql:query(Pid, "CREATE TABLE d (d DATE)"),
  352. lists:foreach(
  353. fun ({Value, SqlLiteral}) ->
  354. write_read_text_binary(Pid, Value, SqlLiteral, <<"d">>, <<"d">>)
  355. end,
  356. [{{2014, 11, 03}, <<"'2014-11-03'">>},
  357. {{0, 0, 0}, <<"'0000-00-00'">>}]
  358. ),
  359. ok = mysql:query(Pid, "DROP TABLE d").
  360. %% Test TIME value representation. There are a few things to check.
  361. time(Pid) ->
  362. ok = mysql:query(Pid, "CREATE TABLE tm (tm TIME)"),
  363. lists:foreach(
  364. fun ({Value, SqlLiteral}) ->
  365. write_read_text_binary(Pid, Value, SqlLiteral, <<"tm">>, <<"tm">>)
  366. end,
  367. [{{0, {10, 11, 12}}, <<"'10:11:12'">>},
  368. {{5, {0, 0, 1}}, <<"'120:00:01'">>},
  369. {{-1, {23, 59, 59}}, <<"'-00:00:01'">>},
  370. {{-1, {23, 59, 0}}, <<"'-00:01:00'">>},
  371. {{-1, {23, 0, 0}}, <<"'-01:00:00'">>},
  372. {{-1, {0, 0, 0}}, <<"'-24:00:00'">>},
  373. {{-5, {10, 0, 0}}, <<"'-110:00:00'">>},
  374. {{0, {0, 0, 0}}, <<"'00:00:00'">>}]
  375. ),
  376. %% Zero seconds as a float.
  377. ok = mysql:query(Pid, "INSERT INTO tm (tm) VALUES (?)",
  378. [{-1, {1, 2, 0.0}}]),
  379. ?assertEqual({ok, [<<"tm">>], [[{-1, {1, 2, 0}}]]},
  380. mysql:query(Pid, "SELECT tm FROM tm")),
  381. ok = mysql:query(Pid, "DROP TABLE tm").
  382. datetime(Pid) ->
  383. ok = mysql:query(Pid, "CREATE TABLE dt (dt DATETIME)"),
  384. lists:foreach(
  385. fun ({Value, SqlLiteral}) ->
  386. write_read_text_binary(Pid, Value, SqlLiteral, <<"dt">>, <<"dt">>)
  387. end,
  388. [{{{2014, 12, 14}, {19, 39, 20}}, <<"'2014-12-14 19:39:20'">>},
  389. {{{2014, 12, 14}, {0, 0, 0}}, <<"'2014-12-14 00:00:00'">>},
  390. {{{0, 0, 0}, {0, 0, 0}}, <<"'0000-00-00 00:00:00'">>}]
  391. ),
  392. ok = mysql:query(Pid, "DROP TABLE dt").
  393. microseconds(Pid) ->
  394. %% Check whether we have the required version for this testcase.
  395. {ok, _, [[Version]]} = mysql:query(Pid, <<"SELECT @@version">>),
  396. try
  397. %% Remove stuff after dash for e.g. "5.5.40-0ubuntu0.12.04.1-log"
  398. [Version1 | _] = binary:split(Version, <<"-">>),
  399. Version2 = lists:map(fun binary_to_integer/1,
  400. binary:split(Version1, <<".">>, [global])),
  401. Version2 >= [5, 6, 4] orelse throw(nope)
  402. of _ ->
  403. test_time_microseconds(Pid),
  404. test_datetime_microseconds(Pid)
  405. catch _:_ ->
  406. error_logger:info_msg("Skipping microseconds test. Current MySQL"
  407. " version is ~s. Required version is >= 5.6.4.~n",
  408. [Version])
  409. end.
  410. test_time_microseconds(Pid) ->
  411. ok = mysql:query(Pid, "CREATE TABLE m (t TIME(6))"),
  412. %% Positive time
  413. write_read_text_binary(Pid, {0, {23, 59, 57.654321}},
  414. <<"'23:59:57.654321'">>, <<"m">>, <<"t">>),
  415. %% Negative time
  416. write_read_text_binary(Pid, {-1, {23, 59, 57.654321}},
  417. <<"'-00:00:02.345679'">>, <<"m">>, <<"t">>),
  418. ok = mysql:query(Pid, "DROP TABLE m").
  419. test_datetime_microseconds(Pid) ->
  420. ok = mysql:query(Pid, "CREATE TABLE dt (dt DATETIME(6))"),
  421. write_read_text_binary(Pid, {{2014, 11, 23}, {23, 59, 57.654321}},
  422. <<"'2014-11-23 23:59:57.654321'">>, <<"dt">>,
  423. <<"dt">>),
  424. ok = mysql:query(Pid, "DROP TABLE dt").
  425. %% @doc Tests write and read in text and the binary protocol, all combinations.
  426. %% This helper function assumes an empty table with a single column.
  427. write_read_text_binary(Conn, Term, SqlLiteral, Table, Column) ->
  428. SelectQuery = <<"SELECT ", Column/binary, " FROM ", Table/binary>>,
  429. {ok, SelectStmt} = mysql:prepare(Conn, SelectQuery),
  430. %% Insert as text, read text and binary, delete
  431. InsertQuery = <<"INSERT INTO ", Table/binary, " (", Column/binary, ")"
  432. " VALUES (", SqlLiteral/binary, ")">>,
  433. ok = mysql:query(Conn, InsertQuery),
  434. ?assertEqual({ok, [Column], [[Term]]}, mysql:query(Conn, SelectQuery)),
  435. ?assertEqual({ok, [Column], [[Term]]}, mysql:execute(Conn, SelectStmt, [])),
  436. mysql:query(Conn, <<"DELETE FROM ", Table/binary>>),
  437. %% Insert as binary, read text and binary, delete
  438. InsertQ = <<"INSERT INTO ", Table/binary, " (", Column/binary, ")",
  439. " VALUES (?)">>,
  440. {ok, InsertStmt} = mysql:prepare(Conn, InsertQ),
  441. ok = mysql:execute(Conn, InsertStmt, [Term]),
  442. ok = mysql:unprepare(Conn, InsertStmt),
  443. ?assertEqual({ok, [Column], [[Term]]}, mysql:query(Conn, SelectQuery)),
  444. ?assertEqual({ok, [Column], [[Term]]}, mysql:execute(Conn, SelectStmt, [])),
  445. mysql:query(Conn, <<"DELETE FROM ", Table/binary>>),
  446. %% Cleanup
  447. ok = mysql:unprepare(Conn, SelectStmt).
  448. %% --------------------------------------------------------------------------
  449. timeout_test_() ->
  450. {setup,
  451. fun () ->
  452. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  453. {log_warnings, false}]),
  454. Pid
  455. end,
  456. fun (Pid) ->
  457. exit(Pid, normal)
  458. end,
  459. {with, [fun (Pid) ->
  460. %% SLEEP was added in MySQL 5.0.12
  461. ?assertEqual({ok, [<<"SLEEP(5)">>], [[1]]},
  462. mysql:query(Pid, <<"SELECT SLEEP(5)">>, 40)),
  463. %% A query after an interrupted query shouldn't get a timeout.
  464. ?assertMatch({ok,[<<"42">>], [[42]]},
  465. mysql:query(Pid, <<"SELECT 42">>)),
  466. %% Parametrized query
  467. ?assertEqual({ok, [<<"SLEEP(?)">>], [[1]]},
  468. mysql:query(Pid, <<"SELECT SLEEP(?)">>, [5], 40)),
  469. %% Prepared statement
  470. {ok, Stmt} = mysql:prepare(Pid, <<"SELECT SLEEP(?)">>),
  471. ?assertEqual({ok, [<<"SLEEP(?)">>], [[1]]},
  472. mysql:execute(Pid, Stmt, [5], 40)),
  473. ok = mysql:unprepare(Pid, Stmt)
  474. end]}}.
  475. %% --------------------------------------------------------------------------
  476. %% Prepared statements
  477. with_table_foo_test_() ->
  478. {setup,
  479. fun () ->
  480. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  481. {query_cache_time, 50},
  482. {log_warnings, false}]),
  483. ok = mysql:query(Pid, <<"DROP DATABASE IF EXISTS otptest">>),
  484. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  485. ok = mysql:query(Pid, <<"USE otptest">>),
  486. ok = mysql:query(Pid, <<"CREATE TABLE foo (bar INT) engine=InnoDB">>),
  487. Pid
  488. end,
  489. fun (Pid) ->
  490. ok = mysql:query(Pid, <<"DROP DATABASE otptest">>),
  491. exit(Pid, normal)
  492. end,
  493. fun (Pid) ->
  494. [{"Prepared statements", fun () -> prepared_statements(Pid) end},
  495. {"Parametrized queries", fun () -> parameterized_query(Pid) end}]
  496. end}.
  497. prepared_statements(Pid) ->
  498. %% Unnamed
  499. ?assertEqual({error,{1146, <<"42S02">>,
  500. <<"Table 'otptest.tab' doesn't exist">>}},
  501. mysql:prepare(Pid, "SELECT * FROM tab WHERE id = ?")),
  502. {ok, StmtId} = mysql:prepare(Pid, "SELECT * FROM foo WHERE bar = ?"),
  503. ?assert(is_integer(StmtId)),
  504. ?assertEqual(ok, mysql:unprepare(Pid, StmtId)),
  505. ?assertEqual({error, not_prepared}, mysql:unprepare(Pid, StmtId)),
  506. %% Named
  507. ?assertEqual({error,{1146, <<"42S02">>,
  508. <<"Table 'otptest.tab' doesn't exist">>}},
  509. mysql:prepare(Pid, tab, "SELECT * FROM tab WHERE id = ?")),
  510. ?assertEqual({ok, foo},
  511. mysql:prepare(Pid, foo, "SELECT * FROM foo WHERE bar = ?")),
  512. %% Prepare again unprepares the old stmt associated with this name.
  513. ?assertEqual({ok, foo},
  514. mysql:prepare(Pid, foo, "SELECT bar FROM foo WHERE bar = ?")),
  515. ?assertEqual(ok, mysql:unprepare(Pid, foo)),
  516. ?assertEqual({error, not_prepared}, mysql:unprepare(Pid, foo)),
  517. %% Execute when not prepared
  518. ?assertEqual({error, not_prepared}, mysql:execute(Pid, not_a_stmt, [])),
  519. ok.
  520. parameterized_query(Conn) ->
  521. %% To see that cache eviction works as expected, look at the code coverage.
  522. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [1]),
  523. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [2]),
  524. receive after 150 -> ok end, %% Now the query cache should emptied
  525. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [3]),
  526. {error, {_, _, _}} = mysql:query(Conn, "Lorem ipsum dolor sit amet", [x]).
  527. %% --- simple gen_server callbacks ---
  528. gen_server_coverage_test() ->
  529. {noreply, state} = mysql:handle_cast(foo, state),
  530. {noreply, state} = mysql:handle_info(foo, state),
  531. ok = mysql:terminate(kill, state).