mysql_tests.erl 15 KB

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