mysql_tests.erl 17 KB

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