transaction_tests.erl 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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(transaction_tests).
  20. -include_lib("eunit/include/eunit.hrl").
  21. -define(user, "otptest").
  22. -define(password, "otptest").
  23. single_connection_test_() ->
  24. {setup,
  25. fun () ->
  26. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  27. {query_cache_time, 50},
  28. {log_warnings, false}]),
  29. ok = mysql:query(Pid, <<"DROP DATABASE IF EXISTS otptest">>),
  30. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  31. ok = mysql:query(Pid, <<"USE otptest">>),
  32. ok = mysql:query(Pid, <<"CREATE TABLE foo (bar INT) engine=InnoDB">>),
  33. Pid
  34. end,
  35. fun (Pid) ->
  36. ok = mysql:query(Pid, <<"DROP DATABASE otptest">>),
  37. exit(Pid, normal)
  38. end,
  39. fun (Pid) ->
  40. [{"Simple atomic", fun () -> simple_atomic(Pid) end},
  41. {"Simple aborted", fun () -> simple_aborted(Pid) end},
  42. {"Nested atomic", fun () -> nested_atomic(Pid) end},
  43. {"Nested inner aborted", fun () -> nested_inner_aborted(Pid) end},
  44. {"Implicit commit", fun () -> implicit_commit(Pid) end}]
  45. end}.
  46. simple_atomic(Pid) ->
  47. ?assertNot(mysql:in_transaction(Pid)),
  48. Result = mysql:transaction(Pid, fun () ->
  49. ok = mysql:query(Pid, "INSERT INTO foo (bar) VALUES (42)"),
  50. ?assert(mysql:in_transaction(Pid)),
  51. hello
  52. end),
  53. ?assertEqual({atomic, hello}, Result),
  54. ?assertNot(mysql:in_transaction(Pid)),
  55. ok = mysql:query(Pid, "DELETE FROM foo").
  56. simple_aborted(Pid) ->
  57. ok = mysql:query(Pid, "INSERT INTO foo VALUES (9)"),
  58. ?assertEqual({ok, [<<"bar">>], [[9]]},
  59. mysql:query(Pid, "SELECT bar FROM foo")),
  60. Result = mysql:transaction(Pid, fun () ->
  61. ok = mysql:query(Pid, "INSERT INTO foo VALUES (42)"),
  62. ?assertMatch({ok, _, [[2]]},
  63. mysql:query(Pid, "SELECT COUNT(*) FROM foo")),
  64. error(hello)
  65. end),
  66. ?assertMatch({aborted, {hello, Stacktrace}} when is_list(Stacktrace),
  67. Result),
  68. ?assertEqual({ok, [<<"bar">>], [[9]]},
  69. mysql:query(Pid, "SELECT bar FROM foo")),
  70. ok = mysql:query(Pid, "DELETE FROM foo"),
  71. %% Also check the abort Reason for throw and exit.
  72. ?assertEqual({aborted, {throw, foo}},
  73. mysql:transaction(Pid, fun () -> throw(foo) end)),
  74. ?assertEqual({aborted, foo},
  75. mysql:transaction(Pid, fun () -> exit(foo) end)).
  76. nested_atomic(Pid) ->
  77. OuterResult = mysql:transaction(Pid, fun () ->
  78. ok = mysql:query(Pid, "INSERT INTO foo VALUES (9)"),
  79. InnerResult = mysql:transaction(Pid, fun () ->
  80. ok = mysql:query(Pid, "INSERT INTO foo VALUES (42)"),
  81. inner
  82. end),
  83. ?assertEqual({atomic, inner}, InnerResult),
  84. outer
  85. end),
  86. ?assertMatch({ok, _, [[2]]}, mysql:query(Pid, "SELECT COUNT(*) FROM foo")),
  87. ok = mysql:query(Pid, "DELETE FROM foo"),
  88. ?assertEqual({atomic, outer}, OuterResult).
  89. nested_inner_aborted(Pid) ->
  90. OuterResult = mysql:transaction(Pid, fun () ->
  91. ok = mysql:query(Pid, "INSERT INTO foo VALUES (9)"),
  92. InnerResult = mysql:transaction(Pid, fun () ->
  93. ok = mysql:query(Pid, "INSERT INTO foo VALUES (42)"),
  94. throw(inner)
  95. end),
  96. ?assertEqual({aborted, {throw, inner}}, InnerResult),
  97. outer
  98. end),
  99. ?assertMatch({ok, _, [[9]]}, mysql:query(Pid, "SELECT bar FROM foo")),
  100. ok = mysql:query(Pid, "DELETE FROM foo"),
  101. ?assertEqual({atomic, outer}, OuterResult).
  102. implicit_commit(Conn) ->
  103. %% This causes an implicit commit in a nested transaction.
  104. Query = "ALTER TABLE foo ADD baz INT",
  105. ?assertError({implicit_commit, Query}, mysql:transaction(Conn, fun () ->
  106. mysql:transaction(Conn, fun () ->
  107. mysql:query(Conn, Query)
  108. end)
  109. end)),
  110. ?assertNot(mysql:in_transaction(Conn)).
  111. %% -----------------------------------------------------------------------------
  112. deadlock_test_() ->
  113. {setup,
  114. fun () ->
  115. {ok, Conn1} = mysql:start_link([{user, ?user}, {password, ?password}]),
  116. ok = mysql:query(Conn1, <<"CREATE DATABASE IF NOT EXISTS otptest">>),
  117. ok = mysql:query(Conn1, <<"USE otptest">>),
  118. ok = mysql:query(Conn1, <<"CREATE TABLE foo (k INT PRIMARY KEY, v INT)"
  119. " engine=InnoDB">>),
  120. ok = mysql:query(Conn1, "INSERT INTO foo (k,v) VALUES (1,0), (2,0)"),
  121. {ok, Conn2} = mysql:start_link([{user, ?user}, {password, ?password}]),
  122. ok = mysql:query(Conn2, <<"USE otptest">>),
  123. {Conn1, Conn2}
  124. end,
  125. fun ({Conn1, Conn2}) ->
  126. ok = mysql:query(Conn1, <<"DROP DATABASE otptest">>, 1000),
  127. exit(Conn1, normal),
  128. exit(Conn2, normal)
  129. end,
  130. fun (Conns) ->
  131. [{"Plain queries", fun () -> deadlock_plain_queries(Conns) end},
  132. {"Prep stmts", fun () -> deadlock_prepared_statements(Conns) end},
  133. {"No retry", fun () -> deadlock_no_retry(Conns) end},
  134. {"Lock wait timeout", fun () -> lock_wait_timeout(Conns) end}]
  135. end}.
  136. flush_inbox() ->
  137. receive _ -> flush_inbox() after 0 -> ok end.
  138. deadlock_plain_queries({Conn1, Conn2}) ->
  139. {ok, _, [[2]]} = mysql:query(Conn1, "SELECT COUNT(*) FROM foo"),
  140. MainPid = self(),
  141. %?debugMsg("\nExtra output from the deadlock test:"),
  142. %% Spawn worker 2 to lock rows; first in table foo, then in bar.
  143. Worker2 = spawn_link(fun () ->
  144. {atomic, ok} = mysql:transaction(Conn2, fun () ->
  145. MainPid ! start,
  146. ok = mysql:query(Conn2, "UPDATE foo SET v = 2 WHERE k = 2"),
  147. %% Sync. Send 'go' to worker 1 multiple times in case it restarts.
  148. MainPid ! go, MainPid ! go, MainPid ! go,
  149. receive go -> ok after 10000 -> throw(too_long) end,
  150. {atomic, ok} = mysql:transaction(Conn2, fun () ->
  151. %% Nested transaction, just to make sure we can handle nested.
  152. ok = mysql:query(Conn2, "UPDATE foo SET v = 2 WHERE k = 1")
  153. end),
  154. ok
  155. end),
  156. MainPid ! done
  157. end),
  158. %% Do worker 1's job and lock the rows in the opposite order.
  159. {atomic, ok} = mysql:transaction(Conn1, fun () ->
  160. MainPid ! start,
  161. ok = mysql:query(Conn1, "UPDATE foo SET v = 1 WHERE k = 1"),
  162. %% Sync. Send 'go' to worker 2 multiple times in case it restarts.
  163. Worker2 ! go, Worker2 ! go, Worker2 ! go,
  164. receive go -> ok after 10000 -> throw(too_long) end,
  165. {atomic, ok} = mysql:transaction(Conn1, fun () ->
  166. %% Nested transaction, just to make sure we can handle nested.
  167. ok = mysql:query(Conn1, "UPDATE foo SET v = 1 WHERE k = 2")
  168. end),
  169. ok
  170. end),
  171. %% Wait for a reply from worker 2 to make sure it is done.
  172. receive done -> ok end,
  173. %% None of the connections should be in a transaction at this point
  174. ?assertNot(mysql:in_transaction(Conn1)),
  175. ?assertNot(mysql:in_transaction(Conn2)),
  176. %% Make sure we got at least 3 start messages, i.e. at least 1 restart.
  177. ?assertEqual(ok, receive start -> ok after 0 -> no_worker_ever_started end),
  178. ?assertEqual(ok, receive start -> ok after 0 -> only_one_worker_started end),
  179. ?assertEqual(ok, receive start -> ok after 0 -> there_was_no_deadlock end),
  180. flush_inbox().
  181. %% This case is very similar to the above test. We use prepared statements
  182. %% instead of plain queries. (Some lines of code in the implementation differ.)
  183. deadlock_prepared_statements({Conn1, Conn2}) ->
  184. {ok, _, [[2]]} = mysql:query(Conn1, "SELECT COUNT(*) FROM foo"),
  185. {ok, upd} = mysql:prepare(Conn1, upd, "UPDATE foo SET v = ? WHERE k = ?"),
  186. {ok, upd} = mysql:prepare(Conn2, upd, "UPDATE foo SET v = ? WHERE k = ?"),
  187. MainPid = self(),
  188. %% Spawn worker 2 to lock rows; first in table foo, then in bar.
  189. Worker2 = spawn_link(fun () ->
  190. {atomic, ok} = mysql:transaction(Conn2, fun () ->
  191. MainPid ! start,
  192. ok = mysql:execute(Conn2, upd, [2, 2]),
  193. %% Sync. Send 'go' to worker 1 multiple times in case it restarts.
  194. MainPid ! go, MainPid ! go, MainPid ! go,
  195. receive go -> ok end,
  196. {atomic, ok} = mysql:transaction(Conn2, fun () ->
  197. %% Nested transaction, just to make sure we can handle nested.
  198. ok = mysql:execute(Conn2, upd, [2, 1])
  199. end),
  200. ok
  201. end, 2),
  202. MainPid ! done
  203. end),
  204. %% Do worker 1's job and lock the rows in the opposite order.
  205. {atomic, ok} = mysql:transaction(Conn1, fun () ->
  206. MainPid ! start,
  207. ok = mysql:execute(Conn1, upd, [1, 1]),
  208. %% Sync. Send 'go' to worker 2 multiple times in case it restarts.
  209. Worker2 ! go, Worker2 ! go, Worker2 ! go,
  210. receive go -> ok end,
  211. {atomic, ok} = mysql:transaction(Conn1, fun () ->
  212. %% Nested transaction, just to make sure we can handle nested.
  213. ok = mysql:execute(Conn1, upd, [1, 2])
  214. end),
  215. ok
  216. end, 2),
  217. %% Wait for a reply from worker 2.
  218. receive done -> ok end,
  219. %% None of the connections should be in a transaction at this point
  220. ?assertNot(mysql:in_transaction(Conn1)),
  221. ?assertNot(mysql:in_transaction(Conn2)),
  222. %% Make sure we got at least 3 start messages, i.e. at least 1 restart.
  223. ?assertEqual(ok, receive start -> ok after 0 -> no_worker_ever_started end),
  224. ?assertEqual(ok, receive start -> ok after 0 -> only_one_worker_started end),
  225. ?assertEqual(ok, receive start -> ok after 0 -> there_was_no_deadlock end),
  226. flush_inbox().
  227. deadlock_no_retry({Conn1, Conn2}) ->
  228. {ok, _, [[2]]} = mysql:query(Conn1, "SELECT COUNT(*) FROM foo"),
  229. MainPid = self(),
  230. %?debugMsg("\nExtra output from the deadlock test:"),
  231. %% Spawn worker 2 to lock rows; first in table foo, then in bar.
  232. Worker2 = spawn_link(fun () ->
  233. Result = mysql:transaction(Conn2, fun () ->
  234. MainPid ! start,
  235. ok = mysql:query(Conn2, "UPDATE foo SET v = 2 WHERE k = 2"),
  236. %% Sync. Send 'go' to worker 1 multiple times in case it restarts.
  237. MainPid ! go, MainPid ! go, MainPid ! go,
  238. receive go -> ok after 10000 -> throw(too_long) end,
  239. {atomic, ok} = mysql:transaction(Conn2, fun () ->
  240. %% Nested transaction, just to make sure we can handle nested.
  241. ok = mysql:query(Conn2, "UPDATE foo SET v = 2 WHERE k = 1")
  242. end),
  243. ok
  244. end, 0),
  245. MainPid ! {done, Result}
  246. end),
  247. %% Do worker 1's job and lock the rows in the opposite order.
  248. Result1 = mysql:transaction(Conn1, fun () ->
  249. MainPid ! start,
  250. ok = mysql:query(Conn1, "UPDATE foo SET v = 1 WHERE k = 1"),
  251. %% Sync. Send 'go' to worker 2 multiple times in case it restarts.
  252. Worker2 ! go, Worker2 ! go, Worker2 ! go,
  253. receive go -> ok after 10000 -> throw(too_long) end,
  254. {atomic, ok} = mysql:transaction(Conn1, fun () ->
  255. %% Nested transaction, just to make sure we can handle nested.
  256. ok = mysql:query(Conn1, "UPDATE foo SET v = 1 WHERE k = 2")
  257. end),
  258. ok
  259. end, 0),
  260. %% Wait for a reply from worker 2 to make sure it is done.
  261. Result2 = receive {done, Result} -> Result end,
  262. %% Check that one of them was ok, the other one was aborted.
  263. [ResultAborted, ResultAtomic] = lists:sort([Result1, Result2]),
  264. ?assertEqual({atomic, ok}, ResultAtomic),
  265. ?assertMatch({aborted,
  266. {{1213, <<"40001">>, <<"Deadlock", _/binary>>}, _Trace}},
  267. ResultAborted),
  268. %% None of the connections should be in a transaction at this point
  269. ?assertNot(mysql:in_transaction(Conn1)),
  270. ?assertNot(mysql:in_transaction(Conn2)),
  271. %% Make sure we got exactly 2 start messages, i.e. there was no restart.
  272. ?assertEqual(ok, receive start -> ok after 0 -> no_worker_ever_started end),
  273. ?assertEqual(ok, receive start -> ok after 0 -> only_one_worker_started end),
  274. ?assertEqual(ok, receive start -> there_was_a_restart after 0 -> ok end),
  275. flush_inbox().
  276. lock_wait_timeout({_Conn1, Conn2} = Conns) ->
  277. %% Set the lowest timeout possible to speed up the test.
  278. case mysql:query(Conn2, "SET innodb_lock_wait_timeout = 1") of
  279. ok ->
  280. lock_wait_timeout1(Conns);
  281. {error, {1238, _, <<"Variable 'innodb_lock_wait_timeout' is a read on",
  282. _/binary>>}} ->
  283. error_logger:info_msg("Can't set lock wait timeout in this server"
  284. " version. Skipping the lock wait timeout"
  285. " test.\n")
  286. end.
  287. %% Continuation of lock_wait_timeout/1.
  288. lock_wait_timeout1({Conn1, Conn2}) ->
  289. {ok, _, [[1]]} = mysql:query(Conn2, "SELECT COUNT(*) FROM foo WHERE k = 1"),
  290. MainPid = self(),
  291. %% Create a worker that takes the lock and sleeps on it.
  292. LockingWorker = spawn_link(fun () ->
  293. {atomic, ok} = mysql:transaction(Conn1, fun () ->
  294. ok = mysql:query(Conn1, "UPDATE foo SET v = 0 WHERE k = 1"),
  295. MainPid ! go,
  296. receive release -> ok end
  297. end),
  298. MainPid ! done
  299. end),
  300. %% Wait for the locking worker to take the lock.
  301. receive go -> ok end,
  302. {atomic, ok} = mysql:transaction(Conn2, fun () ->
  303. ?assertMatch({error, {1205, _, <<"Lock wait timeout", _/binary>>}},
  304. mysql:query(Conn2, "UPDATE foo SET v = 42 WHERE k = 1")),
  305. ok
  306. end),
  307. %% Wake the sleeping worker.
  308. LockingWorker ! release,
  309. receive done -> ok end,
  310. flush_inbox().