mysql_tests.erl 18 KB

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