mysql_tests.erl 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. " dc DECIMAL(5,3),"
  29. " ti TIME,"
  30. " ts TIMESTAMP,"
  31. " da DATE,"
  32. " c CHAR(2)"
  33. ") ENGINE=InnoDB">>).
  34. connect_test() ->
  35. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password}]),
  36. exit(Pid, normal).
  37. query_test_() ->
  38. {setup,
  39. fun () ->
  40. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password}]),
  41. ok = mysql:query(Pid, <<"DROP DATABASE IF EXISTS otptest">>),
  42. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  43. ok = mysql:query(Pid, <<"USE otptest">>),
  44. ok = mysql:query(Pid, <<"SET autocommit = 1">>),
  45. Pid
  46. end,
  47. fun (Pid) ->
  48. ok = mysql:query(Pid, <<"DROP DATABASE otptest">>),
  49. exit(Pid, normal)
  50. end,
  51. {with, [fun autocommit/1,
  52. fun basic_queries/1,
  53. fun text_protocol/1,
  54. fun binary_protocol/1,
  55. fun float_rounding/1,
  56. fun time/1,
  57. fun microseconds/1]}}.
  58. autocommit(Pid) ->
  59. ?assert(mysql:autocommit(Pid)),
  60. ok = mysql:query(Pid, <<"SET autocommit = 0">>),
  61. ?assertNot(mysql:autocommit(Pid)),
  62. ok = mysql:query(Pid, <<"SET autocommit = 1">>),
  63. ?assert(mysql:autocommit(Pid)).
  64. basic_queries(Pid) ->
  65. %% warning count
  66. ?assertEqual(ok, mysql:query(Pid, <<"DROP TABLE IF EXISTS foo">>)),
  67. ?assertEqual(1, mysql:warning_count(Pid)),
  68. %% SQL parse error
  69. ?assertMatch({error, {1064, <<"42000">>, <<"You have an erro", _/binary>>}},
  70. mysql:query(Pid, <<"FOO">>)),
  71. %% Simple resultset with various types
  72. ?assertEqual({ok, [<<"i">>, <<"s">>], [[42, <<"foo">>]]},
  73. mysql:query(Pid, <<"SELECT 42 AS i, 'foo' AS s;">>)),
  74. ok.
  75. text_protocol(Pid) ->
  76. ok = mysql:query(Pid, ?create_table_t),
  77. ok = mysql:query(Pid, <<"INSERT INTO t (bl, f, dc, ti, ts, da, c)"
  78. " VALUES ('blob', 3.14, 3.14, '00:22:11',"
  79. " '2014-11-03 00:22:24', '2014-11-03',"
  80. " NULL)">>),
  81. ?assertEqual(1, mysql:warning_count(Pid)), %% tx has no default value
  82. ?assertEqual(1, mysql:insert_id(Pid)), %% auto_increment starts from 1
  83. ?assertEqual(1, mysql:affected_rows(Pid)),
  84. %% select
  85. {ok, Columns, Rows} = mysql:query(Pid, <<"SELECT * FROM t">>),
  86. ?assertEqual([<<"id">>, <<"bl">>, <<"tx">>, <<"f">>, <<"dc">>, <<"ti">>,
  87. <<"ts">>, <<"da">>, <<"c">>], Columns),
  88. ?assertEqual([[1, <<"blob">>, <<>>, 3.14, <<"3.140">>, {0, {0, 22, 11}},
  89. {{2014, 11, 03}, {00, 22, 24}}, {2014, 11, 03}, null]],
  90. Rows),
  91. %% TODO:
  92. %% * More types: BIT, SET, ENUM, GEOMETRY
  93. %% * TIME with negative hours
  94. %% * TIME with more than 2 digits in hour.
  95. %% * TIME with microseconds
  96. %% * Negative TIME
  97. ok = mysql:query(Pid, <<"DROP TABLE t">>).
  98. binary_protocol(Pid) ->
  99. ok = mysql:query(Pid, ?create_table_t),
  100. %% The same queries as in the text protocol. Expect the same results.
  101. {ok, Ins} = mysql:prepare(Pid, <<"INSERT INTO t (bl, f, dc, ti, ts, da, c)"
  102. " VALUES (?, ?, ?, ?, ?, ?, ?)">>),
  103. ok = mysql:execute(Pid, Ins, [<<"blob">>, 3.14, <<"3.14">>,
  104. {0, {0, 22, 11}},
  105. {{2014, 11, 03}, {0, 22, 24}},
  106. {2014, 11, 03}, null]),
  107. %% TODO: Put the expected result in a macro to make sure they are identical
  108. %% for the text and the binary protocol tests.
  109. {ok, Stmt} = mysql:prepare(Pid, <<"SELECT * FROM t WHERE id=?">>),
  110. {ok, Columns, Rows} = mysql:execute(Pid, Stmt, [1]),
  111. ?assertEqual([<<"id">>, <<"bl">>, <<"tx">>, <<"f">>, <<"dc">>, <<"ti">>,
  112. <<"ts">>, <<"da">>, <<"c">>], Columns),
  113. ?assertEqual([[1, <<"blob">>, <<>>, 3.14, <<"3.140">>,
  114. {0, {0, 22, 11}},
  115. {{2014, 11, 03}, {00, 22, 24}}, {2014, 11, 03}, null]],
  116. Rows),
  117. %% TODO: Both send and receive the following values:
  118. %% * Values for all types
  119. %% * Negative numbers for all integer types
  120. %% * Integer overflow
  121. %% * TIME with more than 2 digits in hour.
  122. %% * TIME with microseconds
  123. %% * Negative TIME
  124. ok = mysql:query(Pid, <<"DROP TABLE t">>).
  125. float_rounding(Pid) ->
  126. %% This is to make sure we get the same values for 32-bit FLOATs in the text
  127. %% and binary protocols for ordinary queries and prepared statements
  128. %% respectively.
  129. %%
  130. %% MySQL rounds to 6 significant digits when "printing" floats over the
  131. %% text protocol. When we receive a float on the binary protocol, we round
  132. %% it in the same way to match what MySQL does on the text protocol. This
  133. %% way we should to get the same values regardless of which protocol is
  134. %% used.
  135. %% Table for testing floats
  136. ok = mysql:query(Pid, "CREATE TABLE f (f FLOAT)"),
  137. %% Prepared statements
  138. {ok, Insert} = mysql:prepare(Pid, "INSERT INTO f (f) VALUES (?)"),
  139. {ok, Select} = mysql:prepare(Pid, "SELECT f FROM f"),
  140. %% [{Input, Expected}]
  141. TestData = [{1.0, 1.0}, {3.14, 3.14}, {0.2, 0.2},
  142. {0.20082111, 0.200821}, {0.000123456789, 0.000123457},
  143. {33.3333333, 33.3333}, {-33.2233443322, -33.2233},
  144. {400.0123, 400.012}, {1000.1234, 1000.12},
  145. {999.00009, 999.0},
  146. {1234.5678, 1234.57}, {68888.8888, 68888.9},
  147. {123456.789, 123457.0}, {7654321.0, 7654320.0},
  148. {80001111.1, 80001100.0}, {987654321.0, 987654000.0},
  149. {-123456789.0, -123457000.0},
  150. {2.12345111e-23, 2.12345e-23}, {-2.12345111e-23, -2.12345e-23},
  151. {2.12345111e23, 2.12345e23}, {-2.12345111e23, -2.12345e23}],
  152. lists:foreach(fun ({Input, Expected}) ->
  153. %% Insert using binary protocol (sending it as a double)
  154. ok = mysql:execute(Pid, Insert, [Input]),
  155. %% Text (plain query)
  156. {ok, _, [[Value]]} = mysql:query(Pid, "SELECT f FROM f"),
  157. ?assertEqual(Expected, Value),
  158. %% Binary (prepared statement)
  159. {ok, _, [[BinValue]]} = mysql:execute(Pid, Select, []),
  160. ?assertEqual(Expected, BinValue),
  161. %% cleanup before the next test
  162. ok = mysql:query(Pid, "DELETE FROM f")
  163. end,
  164. TestData),
  165. ok = mysql:query(Pid, "DROP TABLE f").
  166. %% Test TIME value representation. There are a few things to check.
  167. time(Pid) ->
  168. ok = mysql:query(Pid, "CREATE TABLE tm (tm TIME)"),
  169. {ok, Insert} = mysql:prepare(Pid, "INSERT INTO tm VALUES (?)"),
  170. {ok, Select} = mysql:prepare(Pid, "SELECT tm FROM tm"),
  171. lists:foreach(
  172. fun ({Value, Text}) ->
  173. %% --- Insert using text query ---
  174. ok = mysql:query(Pid, ["INSERT INTO tm VALUES ('", Text, "')"]),
  175. %% Select using prepared statement
  176. ?assertEqual({ok, [<<"tm">>], [[Value]]},
  177. mysql:execute(Pid, Select, [])),
  178. %% Select using plain query
  179. ?assertEqual({ok, [<<"tm">>], [[Value]]},
  180. mysql:query(Pid, "SELECT tm FROM tm")),
  181. %% Empty table
  182. ok = mysql:query(Pid, "DELETE FROM tm"),
  183. %% --- Insert using prepared statement ---
  184. ok = mysql:execute(Pid, Insert, [Value]),
  185. %% Select using prepared statement
  186. ?assertEqual({ok, [<<"tm">>], [[Value]]},
  187. mysql:execute(Pid, Select, [])),
  188. %% Select using plain query
  189. ?assertEqual({ok, [<<"tm">>], [[Value]]},
  190. mysql:query(Pid, "SELECT tm FROM tm")),
  191. %% Empty table
  192. ok = mysql:query(Pid, "DELETE FROM tm"),
  193. ok
  194. end,
  195. [{{0, {10, 11, 12}}, "10:11:12"},
  196. {{5, {0, 0, 1}}, "120:00:01"},
  197. {{-1, {23, 59, 59}}, "-00:00:01"},
  198. {{-1, {23, 59, 0}}, "-00:01:00"},
  199. {{-1, {23, 0, 0}}, "-01:00:00"},
  200. {{-1, {0, 0, 0}}, "-24:00:00"},
  201. {{-5, {10, 0, 0}}, "-110:00:00"}]
  202. ),
  203. ok = mysql:query(Pid, "DROP TABLE tm").
  204. microseconds(Pid) ->
  205. %% Check whether we have the required version for this testcase.
  206. {ok, _, [[Version]]} = mysql:query(Pid, <<"SELECT @@version">>),
  207. try
  208. %% Remove stuff after dash for e.g. "5.5.40-0ubuntu0.12.04.1-log"
  209. [Version1 | _] = binary:split(Version, <<"-">>),
  210. Version2 = lists:map(fun binary_to_integer/1,
  211. binary:split(Version1, <<".">>, [global])),
  212. Version2 >= [5, 6, 4] orelse throw(nope)
  213. of _ ->
  214. run_test_microseconds(Pid)
  215. catch _:_ ->
  216. error_logger:info_msg("Skipping microseconds test. Current MySQL"
  217. " version is ~s. Required version is >= 5.6.4.~n",
  218. [Version])
  219. end.
  220. run_test_microseconds(Pid) ->
  221. ok = mysql:query(Pid, "CREATE TABLE m (t TIME(6))"),
  222. SelectTime = "SELECT t FROM m",
  223. {ok, SelectStmt} = mysql:prepare(Pid, SelectTime),
  224. {ok, InsertStmt} = mysql:prepare(Pid, "INSERT INTO m VALUES (?)"),
  225. %% Positive time, insert using plain query
  226. E1 = {0, {23, 59, 57.654321}},
  227. ok = mysql:query(Pid, <<"INSERT INTO m VALUES ('23:59:57.654321')">>),
  228. ?assertEqual({ok, [<<"t">>], [[E1]]}, mysql:query(Pid, SelectTime)),
  229. ?assertEqual({ok, [<<"t">>], [[E1]]}, mysql:execute(Pid, SelectStmt, [])),
  230. ok = mysql:query(Pid, "DELETE FROM m"),
  231. %% The same, but insert using prepared stmt
  232. ok = mysql:execute(Pid, InsertStmt, [E1]),
  233. ?assertEqual({ok, [<<"t">>], [[E1]]}, mysql:query(Pid, SelectTime)),
  234. ?assertEqual({ok, [<<"t">>], [[E1]]}, mysql:execute(Pid, SelectStmt, [])),
  235. ok = mysql:query(Pid, "DELETE FROM m"),
  236. %% Negative time
  237. E2 = {-1, {23, 59, 57.654321}},
  238. ok = mysql:query(Pid, <<"INSERT INTO m VALUES ('-00:00:02.345679')">>),
  239. ?assertEqual({ok, [<<"t">>], [[E2]]}, mysql:query(Pid, SelectTime)),
  240. ?assertEqual({ok, [<<"t">>], [[E2]]}, mysql:execute(Pid, SelectStmt, [])),
  241. ok = mysql:query(Pid, "DELETE FROM m"),
  242. %% The same, but insert using prepared stmt
  243. ok = mysql:execute(Pid, InsertStmt, [E2]),
  244. ?assertEqual({ok, [<<"t">>], [[E2]]}, mysql:query(Pid, SelectTime)),
  245. ?assertEqual({ok, [<<"t">>], [[E2]]}, mysql:execute(Pid, SelectStmt, [])),
  246. ok = mysql:query(Pid, "DROP TABLE m"),
  247. %% Datetime
  248. Q3 = <<"SELECT TIMESTAMP '2014-11-23 23:59:57.654321' AS t">>,
  249. E3 = [[{{2014, 11, 23}, {23, 59, 57.654321}}]],
  250. ?assertEqual({ok, [<<"t">>], E3}, mysql:query(Pid, Q3)),
  251. {ok, S3} = mysql:prepare(Pid, Q3),
  252. ?assertEqual({ok, [<<"t">>], E3}, mysql:execute(Pid, S3, [])),
  253. ok.
  254. %% --------------------------------------------------------------------------
  255. %% Prepared statements and transactions
  256. with_table_foo_test_() ->
  257. {setup,
  258. fun () ->
  259. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password}]),
  260. ok = mysql:query(Pid, <<"DROP DATABASE IF EXISTS otptest">>),
  261. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  262. ok = mysql:query(Pid, <<"USE otptest">>),
  263. ok = mysql:query(Pid, <<"CREATE TABLE foo (bar INT) engine=InnoDB">>),
  264. Pid
  265. end,
  266. fun (Pid) ->
  267. ok = mysql:query(Pid, <<"DROP DATABASE otptest">>),
  268. exit(Pid, normal)
  269. end,
  270. {with, [fun prepared_statements/1,
  271. fun transaction_simple_success/1,
  272. fun transaction_simple_aborted/1]}}.
  273. prepared_statements(Pid) ->
  274. %% Unnamed
  275. ?assertEqual({error,{1146, <<"42S02">>,
  276. <<"Table 'otptest.tab' doesn't exist">>}},
  277. mysql:prepare(Pid, "SELECT * FROM tab WHERE id = ?")),
  278. {ok, StmtId} = mysql:prepare(Pid, "SELECT * FROM foo WHERE bar = ?"),
  279. ?assert(is_integer(StmtId)),
  280. ?assertEqual(ok, mysql:unprepare(Pid, StmtId)),
  281. ?assertEqual({error, not_prepared}, mysql:unprepare(Pid, StmtId)),
  282. %% Named
  283. ?assertEqual({error,{1146, <<"42S02">>,
  284. <<"Table 'otptest.tab' doesn't exist">>}},
  285. mysql:prepare(Pid, tab, "SELECT * FROM tab WHERE id = ?")),
  286. ?assertEqual({ok, foo},
  287. mysql:prepare(Pid, foo, "SELECT * FROM foo WHERE bar = ?")),
  288. %% Prepare again unprepares the old stmt associated with this name.
  289. ?assertEqual({ok, foo},
  290. mysql:prepare(Pid, foo, "SELECT bar FROM foo WHERE bar = ?")),
  291. ?assertEqual(ok, mysql:unprepare(Pid, foo)),
  292. ?assertEqual({error, not_prepared}, mysql:unprepare(Pid, foo)),
  293. %% Execute when not prepared
  294. ?assertEqual({error, not_prepared}, mysql:execute(Pid, not_a_stmt, [])),
  295. ok.
  296. transaction_simple_success(Pid) ->
  297. ?assertNot(mysql:in_transaction(Pid)),
  298. Result = mysql:transaction(Pid, fun () ->
  299. ok = mysql:query(Pid, "INSERT INTO foo VALUES (42)"),
  300. ?assert(mysql:in_transaction(Pid)),
  301. hello
  302. end),
  303. ?assertEqual({atomic, hello}, Result),
  304. ?assertNot(mysql:in_transaction(Pid)),
  305. ok = mysql:query(Pid, "DELETE FROM foo").
  306. transaction_simple_aborted(Pid) ->
  307. ok = mysql:query(Pid, "INSERT INTO foo VALUES (9)"),
  308. ?assertEqual({ok, [<<"bar">>], [[9]]},
  309. mysql:query(Pid, "SELECT bar FROM foo")),
  310. Result = mysql:transaction(Pid, fun () ->
  311. ok = mysql:query(Pid, "INSERT INTO foo VALUES (42)"),
  312. ?assertMatch({ok, _, [[2]]},
  313. mysql:query(Pid, "SELECT COUNT(*) FROM foo")),
  314. error(hello)
  315. end),
  316. ?assertMatch({aborted, {hello, Stacktrace}} when is_list(Stacktrace),
  317. Result),
  318. ?assertEqual({ok, [<<"bar">>], [[9]]},
  319. mysql:query(Pid, "SELECT bar FROM foo")),
  320. ok = mysql:query(Pid, "DELETE FROM foo"),
  321. %% Also check the abort Reason for throw and exit.
  322. ?assertEqual({aborted, {throw, foo}},
  323. mysql:transaction(Pid, fun () -> throw(foo) end)),
  324. ?assertEqual({aborted, foo},
  325. mysql:transaction(Pid, fun () -> exit(foo) end)).