transaction_tests.erl 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. {"Lock wait timeout", fun () -> lock_wait_timeout(Conns) end}]
  134. end}.
  135. flush_inbox() ->
  136. receive _ -> flush_inbox() after 0 -> ok end.
  137. deadlock_plain_queries({Conn1, Conn2}) ->
  138. {ok, _, [[2]]} = mysql:query(Conn1, "SELECT COUNT(*) FROM foo"),
  139. MainPid = self(),
  140. %?debugMsg("\nExtra output from the deadlock test:"),
  141. %% Spawn worker 2 to lock rows; first in table foo, then in bar.
  142. Worker2 = spawn_link(fun () ->
  143. {atomic, ok} = mysql:transaction(Conn2, fun () ->
  144. MainPid ! start,
  145. %?debugMsg("Worker 2: Starting. First get a lock on row 2."),
  146. ok = mysql:query(Conn2, "UPDATE foo SET v = 2 WHERE k = 2"),
  147. %?debugMsg("Worker 2: Got lock on foo. Now wait for signal from 1."),
  148. %% Sync. Send 'go' to worker 1 multiple times in case it restarts.
  149. MainPid ! go, MainPid ! go, MainPid ! go,
  150. receive go -> ok after 10000 -> throw(too_long) end,
  151. %?debugMsg("Worker 2: Got signal from 1. Now get a lock on row 1."),
  152. {atomic, ok} = mysql:transaction(Conn2, fun () ->
  153. %% Nested transaction, just to make sure we can handle nested.
  154. ok = mysql:query(Conn2, "UPDATE foo SET v = 2 WHERE k = 1")
  155. end),
  156. %?debugMsg("Worker 2: Got both locks and is done."),
  157. ok
  158. end),
  159. MainPid ! done
  160. end),
  161. %% Do worker 1's job and lock the rows in the opposite order.
  162. {atomic, ok} = mysql:transaction(Conn1, fun () ->
  163. MainPid ! start,
  164. %?debugMsg("Worker 1: Starting. First get a lock on row 1."),
  165. ok = mysql:query(Conn1, "UPDATE foo SET v = 1 WHERE k = 1"),
  166. %?debugMsg("Worker 1: Got lock on bar. Now wait for signal from 2."),
  167. %% Sync. Send 'go' to worker 2 multiple times in case it restarts.
  168. Worker2 ! go, Worker2 ! go, Worker2 ! go,
  169. receive go -> ok after 10000 -> throw(too_long) end,
  170. %?debugMsg("Worker 1: Got signal from 2. Now get lock on row 2."),
  171. {atomic, ok} = mysql:transaction(Conn1, fun () ->
  172. %% Nested transaction, just to make sure we can handle nested.
  173. ok = mysql:query(Conn1, "UPDATE foo SET v = 1 WHERE k = 2")
  174. end),
  175. %?debugMsg("Worker 1: Got both locks and is done."),
  176. ok
  177. end),
  178. %% Wait for a reply from worker 2 to make sure it is done.
  179. receive done -> ok end,
  180. %% None of the connections should be in a transaction at this point
  181. ?assertNot(mysql:in_transaction(Conn1)),
  182. ?assertNot(mysql:in_transaction(Conn2)),
  183. %% Make sure we got at least 3 start messages, i.e. at least 1 restart.
  184. ?assertEqual(ok, receive start -> ok after 0 -> no_worker_ever_started end),
  185. ?assertEqual(ok, receive start -> ok after 0 -> only_one_worker_started end),
  186. ?assertEqual(ok, receive start -> ok after 0 -> there_was_no_deadlock end),
  187. flush_inbox().
  188. %% This case is very similar to the above test. We use prepared statements
  189. %% instead of plain queries. (Some lines of code in the implementation differ.)
  190. deadlock_prepared_statements({Conn1, Conn2}) ->
  191. {ok, _, [[2]]} = mysql:query(Conn1, "SELECT COUNT(*) FROM foo"),
  192. {ok, upd} = mysql:prepare(Conn1, upd, "UPDATE foo SET v = ? WHERE k = ?"),
  193. {ok, upd} = mysql:prepare(Conn2, upd, "UPDATE foo SET v = ? WHERE k = ?"),
  194. MainPid = self(),
  195. %% Spawn worker 2 to lock rows; first in table foo, then in bar.
  196. Worker2 = spawn_link(fun () ->
  197. {atomic, ok} = mysql:transaction(Conn2, fun () ->
  198. MainPid ! start,
  199. ok = mysql:execute(Conn2, upd, [2, 2]),
  200. %% Sync. Send 'go' to worker 1 multiple times in case it restarts.
  201. MainPid ! go, MainPid ! go, MainPid ! go,
  202. receive go -> ok end,
  203. {atomic, ok} = mysql:transaction(Conn2, fun () ->
  204. %% Nested transaction, just to make sure we can handle nested.
  205. ok = mysql:execute(Conn2, upd, [2, 1])
  206. end),
  207. ok
  208. end, 2),
  209. MainPid ! done
  210. end),
  211. %% Do worker 1's job and lock the rows in the opposite order.
  212. {atomic, ok} = mysql:transaction(Conn1, fun () ->
  213. MainPid ! start,
  214. ok = mysql:execute(Conn1, upd, [1, 1]),
  215. %% Sync. Send 'go' to worker 2 multiple times in case it restarts.
  216. Worker2 ! go, Worker2 ! go, Worker2 ! go,
  217. receive go -> ok end,
  218. {atomic, ok} = mysql:transaction(Conn1, fun () ->
  219. %% Nested transaction, just to make sure we can handle nested.
  220. ok = mysql:execute(Conn1, upd, [1, 2])
  221. end),
  222. ok
  223. end, 2),
  224. %% Wait for a reply from worker 2.
  225. receive done -> ok end,
  226. %% None of the connections should be in a transaction at this point
  227. ?assertNot(mysql:in_transaction(Conn1)),
  228. ?assertNot(mysql:in_transaction(Conn2)),
  229. %% Make sure we got at least 3 start messages, i.e. at least 1 restart.
  230. ?assertEqual(ok, receive start -> ok after 0 -> no_worker_ever_started end),
  231. ?assertEqual(ok, receive start -> ok after 0 -> only_one_worker_started end),
  232. ?assertEqual(ok, receive start -> ok after 0 -> there_was_no_deadlock end),
  233. flush_inbox().
  234. lock_wait_timeout({_Conn1, Conn2} = Conns) ->
  235. %% Set the lowest timeout possible to speed up the test.
  236. case mysql:query(Conn2, "SET innodb_lock_wait_timeout = 1") of
  237. ok ->
  238. lock_wait_timeout1(Conns);
  239. {error, {1238, _, <<"Variable 'innodb_lock_wait_timeout' is a read on",
  240. _/binary>>}} ->
  241. error_logger:info_msg("Can't set lock wait timeout in this server"
  242. " version. Skipping the lock wait timeout"
  243. " test.\n")
  244. end.
  245. %% Continuation of lock_wait_timeout/1.
  246. lock_wait_timeout1({Conn1, Conn2}) ->
  247. {ok, _, [[1]]} = mysql:query(Conn2, "SELECT COUNT(*) FROM foo WHERE k = 1"),
  248. MainPid = self(),
  249. %% Create a worker that takes the lock and sleeps on it.
  250. LockingWorker = spawn_link(fun () ->
  251. {atomic, ok} = mysql:transaction(Conn1, fun () ->
  252. ok = mysql:query(Conn1, "UPDATE foo SET v = 0 WHERE k = 1"),
  253. MainPid ! go,
  254. receive release -> ok end
  255. end),
  256. MainPid ! done
  257. end),
  258. %% Wait for the locking worker to take the lock.
  259. receive go -> ok end,
  260. {aborted, Reason} = mysql:transaction(Conn2, fun () ->
  261. ok = mysql:query(Conn2, "UPDATE foo SET v = 42 WHERE k = 1")
  262. end),
  263. ?assertMatch({{1205, _, <<"Lock wait timeout", _/binary>>}, _Trace},
  264. Reason),
  265. %% Wake the sleeping worker.
  266. LockingWorker ! release,
  267. receive done -> ok end,
  268. flush_inbox().