transaction_tests.erl 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. application_process_kill_test_() ->
  47. {timeout, 30, fun application_process_kill/0}.
  48. application_process_kill() ->
  49. %% This test case simulates a setup where the connection is owned by
  50. %% another process, e.g. a connection pool. An application process (e.g.
  51. %% a cowboy worker) is killed when it using a connection in a transaction.
  52. %% In this case, the connection should not go back in the pool as it would
  53. %% be in a bad state. Therefore, the connection is monitoring the process
  54. %% starting a transaction and kills itself if the caller dies.
  55. {ok, Pid} = mysql:start_link([
  56. {user, ?user},
  57. {password, ?password},
  58. {query_cache_time, 50},
  59. {log_warnings, false}
  60. ]),
  61. unlink(Pid),
  62. Mref = erlang:monitor(process, Pid),
  63. ok = mysql:query(Pid, <<"DROP DATABASE IF EXISTS otptest">>),
  64. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  65. ok = mysql:query(Pid, <<"USE otptest">>),
  66. ok = mysql:query(Pid, <<"CREATE TABLE foo (bar INT) engine=InnoDB">>),
  67. ?assertNot(mysql:in_transaction(Pid)),
  68. ?assert(is_process_alive(Pid)),
  69. Self = self(),
  70. AppPid = spawn(fun() ->
  71. mysql:transaction(Pid, fun () ->
  72. ok = mysql:query(Pid, "INSERT INTO foo (bar) VALUES (42)"),
  73. Self! killme,
  74. receive after 10000 -> throw(too_long) end,
  75. ok
  76. end)
  77. end),
  78. %% Wait for the AppPid to be ready to be killed when in a transaction
  79. receive killme -> ok end,
  80. %% Kill AppPid, the process using the connection, capturing the noise
  81. {ok, ok, LoggedErrors} = error_logger_acc:capture(fun () ->
  82. exit(AppPid, kill),
  83. receive
  84. {'DOWN', Mref, process, Pid, {application_process_died, AppPid}} ->
  85. ok
  86. after 10000 ->
  87. throw(too_long)
  88. end
  89. end),
  90. %% Check that we got the expected error log noise
  91. ?assertMatch([{error, "Connection Id" ++ _}, %% from mysql_conn
  92. {error, "** Generic server" ++ _}, %% from gen_server
  93. {error_report, _}], LoggedErrors),
  94. ?assertNot(is_process_alive(Pid)),
  95. %% Check that the transaction was not commited
  96. {ok, Pid2} = mysql:start_link([
  97. {user, ?user},
  98. {password, ?password},
  99. {query_cache_time, 50},
  100. {log_warnings, false}
  101. ]),
  102. ok = mysql:query(Pid2, <<"USE otptest">>),
  103. ?assertMatch({ok, _, []},
  104. mysql:query(Pid2, <<"SELECT * from foo where bar = 42">>)),
  105. ok = mysql:query(Pid2, <<"DROP DATABASE otptest">>),
  106. exit(Pid2, normal).
  107. simple_atomic(Pid) ->
  108. ?assertNot(mysql:in_transaction(Pid)),
  109. Result = mysql:transaction(Pid, fun () ->
  110. ok = mysql:query(Pid, "INSERT INTO foo (bar) VALUES (42)"),
  111. ?assert(mysql:in_transaction(Pid)),
  112. hello
  113. end),
  114. ?assertEqual({atomic, hello}, Result),
  115. ?assertNot(mysql:in_transaction(Pid)),
  116. ok = mysql:query(Pid, "DELETE FROM foo").
  117. simple_aborted(Pid) ->
  118. ok = mysql:query(Pid, "INSERT INTO foo VALUES (9)"),
  119. ?assertEqual({ok, [<<"bar">>], [[9]]},
  120. mysql:query(Pid, "SELECT bar FROM foo")),
  121. Result = mysql:transaction(Pid, fun () ->
  122. ok = mysql:query(Pid, "INSERT INTO foo VALUES (42)"),
  123. ?assertMatch({ok, _, [[2]]},
  124. mysql:query(Pid, "SELECT COUNT(*) FROM foo")),
  125. error(hello)
  126. end),
  127. ?assertMatch({aborted, {hello, Stacktrace}} when is_list(Stacktrace),
  128. Result),
  129. ?assertEqual({ok, [<<"bar">>], [[9]]},
  130. mysql:query(Pid, "SELECT bar FROM foo")),
  131. ok = mysql:query(Pid, "DELETE FROM foo"),
  132. %% Also check the abort Reason for throw and exit.
  133. ?assertEqual({aborted, {throw, foo}},
  134. mysql:transaction(Pid, fun () -> throw(foo) end)),
  135. ?assertEqual({aborted, foo},
  136. mysql:transaction(Pid, fun () -> exit(foo) end)).
  137. nested_atomic(Pid) ->
  138. OuterResult = mysql:transaction(Pid, fun () ->
  139. ok = mysql:query(Pid, "INSERT INTO foo VALUES (9)"),
  140. InnerResult = mysql:transaction(Pid, fun () ->
  141. ok = mysql:query(Pid, "INSERT INTO foo VALUES (42)"),
  142. inner
  143. end),
  144. ?assertEqual({atomic, inner}, InnerResult),
  145. outer
  146. end),
  147. ?assertMatch({ok, _, [[2]]}, mysql:query(Pid, "SELECT COUNT(*) FROM foo")),
  148. ok = mysql:query(Pid, "DELETE FROM foo"),
  149. ?assertEqual({atomic, outer}, OuterResult).
  150. nested_inner_aborted(Pid) ->
  151. OuterResult = mysql:transaction(Pid, fun () ->
  152. ok = mysql:query(Pid, "INSERT INTO foo VALUES (9)"),
  153. InnerResult = mysql:transaction(Pid, fun () ->
  154. ok = mysql:query(Pid, "INSERT INTO foo VALUES (42)"),
  155. throw(inner)
  156. end),
  157. ?assertEqual({aborted, {throw, inner}}, InnerResult),
  158. outer
  159. end),
  160. ?assertMatch({ok, _, [[9]]}, mysql:query(Pid, "SELECT bar FROM foo")),
  161. ok = mysql:query(Pid, "DELETE FROM foo"),
  162. ?assertEqual({atomic, outer}, OuterResult).
  163. implicit_commit(Conn) ->
  164. %% This causes an implicit commit in a nested transaction.
  165. Query = "ALTER TABLE foo ADD baz INT",
  166. ?assertError({implicit_commit, Query}, mysql:transaction(Conn, fun () ->
  167. mysql:transaction(Conn, fun () ->
  168. mysql:query(Conn, Query)
  169. end)
  170. end)),
  171. ?assertNot(mysql:in_transaction(Conn)).
  172. %% -----------------------------------------------------------------------------
  173. deadlock_test_() ->
  174. {setup,
  175. fun () ->
  176. {ok, Conn1} = mysql:start_link([{user, ?user}, {password, ?password}]),
  177. ok = mysql:query(Conn1, <<"CREATE DATABASE IF NOT EXISTS otptest">>),
  178. ok = mysql:query(Conn1, <<"USE otptest">>),
  179. ok = mysql:query(Conn1, <<"CREATE TABLE foo (k INT PRIMARY KEY, v INT)"
  180. " engine=InnoDB">>),
  181. ok = mysql:query(Conn1, "INSERT INTO foo (k,v) VALUES (1,0), (2,0)"),
  182. {ok, Conn2} = mysql:start_link([{user, ?user}, {password, ?password}]),
  183. ok = mysql:query(Conn2, <<"USE otptest">>),
  184. {Conn1, Conn2}
  185. end,
  186. fun ({Conn1, Conn2}) ->
  187. ok = mysql:query(Conn1, <<"DROP DATABASE otptest">>, 1000),
  188. exit(Conn1, normal),
  189. exit(Conn2, normal)
  190. end,
  191. fun (Conns) ->
  192. [{"Plain queries", fun () -> deadlock_plain_queries(Conns) end},
  193. {"Prep stmts", fun () -> deadlock_prepared_statements(Conns) end},
  194. {"No retry", fun () -> deadlock_no_retry(Conns) end},
  195. {"Lock wait timeout", fun () -> lock_wait_timeout(Conns) end}]
  196. end}.
  197. flush_inbox() ->
  198. receive _ -> flush_inbox() after 0 -> ok end.
  199. deadlock_plain_queries({Conn1, Conn2}) ->
  200. {ok, _, [[2]]} = mysql:query(Conn1, "SELECT COUNT(*) FROM foo"),
  201. MainPid = self(),
  202. %?debugMsg("\nExtra output from the deadlock test:"),
  203. %% Spawn worker 2 to lock rows; first in table foo, then in bar.
  204. Worker2 = spawn_link(fun () ->
  205. {atomic, ok} = mysql:transaction(Conn2, fun () ->
  206. MainPid ! start,
  207. ok = mysql:query(Conn2, "UPDATE foo SET v = 2 WHERE k = 2"),
  208. %% Sync. Send 'go' to worker 1 multiple times in case it restarts.
  209. MainPid ! go, MainPid ! go, MainPid ! go,
  210. receive go -> ok after 10000 -> throw(too_long) end,
  211. {atomic, ok} = mysql:transaction(Conn2, fun () ->
  212. %% Nested transaction, just to make sure we can handle nested.
  213. ok = mysql:query(Conn2, "UPDATE foo SET v = 2 WHERE k = 1")
  214. end),
  215. ok
  216. end),
  217. MainPid ! done
  218. end),
  219. %% Do worker 1's job and lock the rows in the opposite order.
  220. {atomic, ok} = mysql:transaction(Conn1, fun () ->
  221. MainPid ! start,
  222. ok = mysql:query(Conn1, "UPDATE foo SET v = 1 WHERE k = 1"),
  223. %% Sync. Send 'go' to worker 2 multiple times in case it restarts.
  224. Worker2 ! go, Worker2 ! go, Worker2 ! go,
  225. receive go -> ok after 10000 -> throw(too_long) end,
  226. {atomic, ok} = mysql:transaction(Conn1, fun () ->
  227. %% Nested transaction, just to make sure we can handle nested.
  228. ok = mysql:query(Conn1, "UPDATE foo SET v = 1 WHERE k = 2")
  229. end),
  230. ok
  231. end),
  232. %% Wait for a reply from worker 2 to make sure it is done.
  233. receive done -> ok end,
  234. %% None of the connections should be in a transaction at this point
  235. ?assertNot(mysql:in_transaction(Conn1)),
  236. ?assertNot(mysql:in_transaction(Conn2)),
  237. %% Make sure we got at least 3 start messages, i.e. at least 1 restart.
  238. ?assertEqual(ok, receive start -> ok after 0 -> no_worker_ever_started end),
  239. ?assertEqual(ok, receive start -> ok after 0 -> only_one_worker_started end),
  240. ?assertEqual(ok, receive start -> ok after 0 -> there_was_no_deadlock end),
  241. flush_inbox().
  242. %% This case is very similar to the above test. We use prepared statements
  243. %% instead of plain queries. (Some lines of code in the implementation differ.)
  244. deadlock_prepared_statements({Conn1, Conn2}) ->
  245. {ok, _, [[2]]} = mysql:query(Conn1, "SELECT COUNT(*) FROM foo"),
  246. {ok, upd} = mysql:prepare(Conn1, upd, "UPDATE foo SET v = ? WHERE k = ?"),
  247. {ok, upd} = mysql:prepare(Conn2, upd, "UPDATE foo SET v = ? WHERE k = ?"),
  248. MainPid = self(),
  249. %% Spawn worker 2 to lock rows; first in table foo, then in bar.
  250. Worker2 = spawn_link(fun () ->
  251. {atomic, ok} = mysql:transaction(Conn2, fun () ->
  252. MainPid ! start,
  253. ok = mysql:execute(Conn2, upd, [2, 2]),
  254. %% Sync. Send 'go' to worker 1 multiple times in case it restarts.
  255. MainPid ! go, MainPid ! go, MainPid ! go,
  256. receive go -> ok end,
  257. {atomic, ok} = mysql:transaction(Conn2, fun () ->
  258. %% Nested transaction, just to make sure we can handle nested.
  259. ok = mysql:execute(Conn2, upd, [2, 1])
  260. end),
  261. ok
  262. end, 2),
  263. MainPid ! done
  264. end),
  265. %% Do worker 1's job and lock the rows in the opposite order.
  266. {atomic, ok} = mysql:transaction(Conn1, fun () ->
  267. MainPid ! start,
  268. ok = mysql:execute(Conn1, upd, [1, 1]),
  269. %% Sync. Send 'go' to worker 2 multiple times in case it restarts.
  270. Worker2 ! go, Worker2 ! go, Worker2 ! go,
  271. receive go -> ok end,
  272. {atomic, ok} = mysql:transaction(Conn1, fun () ->
  273. %% Nested transaction, just to make sure we can handle nested.
  274. ok = mysql:execute(Conn1, upd, [1, 2])
  275. end),
  276. ok
  277. end, 2),
  278. %% Wait for a reply from worker 2.
  279. receive done -> ok end,
  280. %% None of the connections should be in a transaction at this point
  281. ?assertNot(mysql:in_transaction(Conn1)),
  282. ?assertNot(mysql:in_transaction(Conn2)),
  283. %% Make sure we got at least 3 start messages, i.e. at least 1 restart.
  284. ?assertEqual(ok, receive start -> ok after 0 -> no_worker_ever_started end),
  285. ?assertEqual(ok, receive start -> ok after 0 -> only_one_worker_started end),
  286. ?assertEqual(ok, receive start -> ok after 0 -> there_was_no_deadlock end),
  287. flush_inbox().
  288. deadlock_no_retry({Conn1, Conn2}) ->
  289. {ok, _, [[2]]} = mysql:query(Conn1, "SELECT COUNT(*) FROM foo"),
  290. MainPid = self(),
  291. %?debugMsg("\nExtra output from the deadlock test:"),
  292. %% Spawn worker 2 to lock rows; first in table foo, then in bar.
  293. Worker2 = spawn_link(fun () ->
  294. Result = mysql:transaction(Conn2, fun () ->
  295. MainPid ! start,
  296. ok = mysql:query(Conn2, "UPDATE foo SET v = 2 WHERE k = 2"),
  297. %% Sync. Send 'go' to worker 1 multiple times in case it restarts.
  298. MainPid ! go, MainPid ! go, MainPid ! go,
  299. receive go -> ok after 10000 -> throw(too_long) end,
  300. {atomic, ok} = mysql:transaction(Conn2, fun () ->
  301. %% Nested transaction, just to make sure we can handle nested.
  302. ok = mysql:query(Conn2, "UPDATE foo SET v = 2 WHERE k = 1")
  303. end),
  304. ok
  305. end, 0),
  306. MainPid ! {done, Result}
  307. end),
  308. %% Do worker 1's job and lock the rows in the opposite order.
  309. Result1 = mysql:transaction(Conn1, fun () ->
  310. MainPid ! start,
  311. ok = mysql:query(Conn1, "UPDATE foo SET v = 1 WHERE k = 1"),
  312. %% Sync. Send 'go' to worker 2 multiple times in case it restarts.
  313. Worker2 ! go, Worker2 ! go, Worker2 ! go,
  314. receive go -> ok after 10000 -> throw(too_long) end,
  315. {atomic, ok} = mysql:transaction(Conn1, fun () ->
  316. %% Nested transaction, just to make sure we can handle nested.
  317. ok = mysql:query(Conn1, "UPDATE foo SET v = 1 WHERE k = 2")
  318. end),
  319. ok
  320. end, 0),
  321. %% Wait for a reply from worker 2 to make sure it is done.
  322. Result2 = receive {done, Result} -> Result end,
  323. %% Check that one of them was ok, the other one was aborted.
  324. [ResultAborted, ResultAtomic] = lists:sort([Result1, Result2]),
  325. ?assertEqual({atomic, ok}, ResultAtomic),
  326. ?assertMatch({aborted,
  327. {{1213, <<"40001">>, <<"Deadlock", _/binary>>}, _Trace}},
  328. ResultAborted),
  329. %% None of the connections should be in a transaction at this point
  330. ?assertNot(mysql:in_transaction(Conn1)),
  331. ?assertNot(mysql:in_transaction(Conn2)),
  332. %% Make sure we got exactly 2 start messages, i.e. there was no restart.
  333. ?assertEqual(ok, receive start -> ok after 0 -> no_worker_ever_started end),
  334. ?assertEqual(ok, receive start -> ok after 0 -> only_one_worker_started end),
  335. ?assertEqual(ok, receive start -> there_was_a_restart after 0 -> ok end),
  336. flush_inbox().
  337. lock_wait_timeout({_Conn1, Conn2} = Conns) ->
  338. %% Set the lowest timeout possible to speed up the test.
  339. case mysql:query(Conn2, "SET innodb_lock_wait_timeout = 1") of
  340. ok ->
  341. lock_wait_timeout1(Conns);
  342. {error, {1238, _, <<"Variable 'innodb_lock_wait_timeout' is a read on",
  343. _/binary>>}} ->
  344. error_logger:info_msg("Can't set lock wait timeout in this server"
  345. " version. Skipping the lock wait timeout"
  346. " test.\n")
  347. end.
  348. %% Continuation of lock_wait_timeout/1.
  349. lock_wait_timeout1({Conn1, Conn2}) ->
  350. {ok, _, [[1]]} = mysql:query(Conn2, "SELECT COUNT(*) FROM foo WHERE k = 1"),
  351. MainPid = self(),
  352. %% Create a worker that takes the lock and sleeps on it.
  353. LockingWorker = spawn_link(fun () ->
  354. {atomic, ok} = mysql:transaction(Conn1, fun () ->
  355. ok = mysql:query(Conn1, "UPDATE foo SET v = 0 WHERE k = 1"),
  356. MainPid ! go,
  357. receive release -> ok end
  358. end),
  359. MainPid ! done
  360. end),
  361. %% Wait for the locking worker to take the lock.
  362. receive go -> ok end,
  363. {atomic, ok} = mysql:transaction(Conn2, fun () ->
  364. ?assertMatch({error, {1205, _, <<"Lock wait timeout", _/binary>>}},
  365. mysql:query(Conn2, "UPDATE foo SET v = 42 WHERE k = 1")),
  366. ok
  367. end),
  368. %% Wake the sleeping worker.
  369. LockingWorker ! release,
  370. receive done -> ok end,
  371. flush_inbox().