mysql_conn.erl 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. %% MySQL/OTP – MySQL client library for Erlang/OTP
  2. %% Copyright (C) 2014-2018 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 implements parts of the MySQL client/server protocol.
  19. %%
  20. %% The protocol is described in the document "MySQL Internals" which can be
  21. %% found under "MySQL Documentation: Expert Guides" on http://dev.mysql.com/.
  22. %%
  23. %% TCP communication is not handled in this module. Most of the public functions
  24. %% take funs for data communitaction as parameters.
  25. %% @private
  26. -module(mysql_conn).
  27. -behaviour(gen_server).
  28. -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
  29. code_change/3]).
  30. -define(default_host, "localhost").
  31. -define(default_port, 3306).
  32. -define(default_user, <<>>).
  33. -define(default_password, <<>>).
  34. -define(default_query_timeout, infinity).
  35. -define(default_query_cache_time, 60000). %% for query/3.
  36. -define(default_ping_timeout, 60000).
  37. -define(cmd_timeout, 3000). %% Timeout used for various commands to the server
  38. %% Errors that cause "implicit rollback"
  39. -define(ERROR_DEADLOCK, 1213).
  40. %% --- Gen_server callbacks ---
  41. -include("records.hrl").
  42. -include("server_status.hrl").
  43. %% Gen_server state
  44. -record(state, {server_version, connection_id, socket, sockmod, ssl_opts,
  45. host, port, user, password, auth_plugin_data, log_warnings,
  46. ping_timeout,
  47. query_timeout, query_cache_time,
  48. affected_rows = 0, status = 0, warning_count = 0, insert_id = 0,
  49. transaction_levels = [], ping_ref = undefined,
  50. stmts = dict:new(), query_cache = empty, cap_found_rows = false}).
  51. %% @private
  52. init(Opts) ->
  53. %% Connect
  54. Host = proplists:get_value(host, Opts, ?default_host),
  55. DefaultPort = case Host of
  56. {local, _LocalAddr} -> 0;
  57. _NonLocalAddr -> ?default_port
  58. end,
  59. Port = proplists:get_value(port, Opts, DefaultPort),
  60. User = proplists:get_value(user, Opts, ?default_user),
  61. Password = proplists:get_value(password, Opts, ?default_password),
  62. Database = proplists:get_value(database, Opts, undefined),
  63. LogWarn = proplists:get_value(log_warnings, Opts, true),
  64. KeepAlive = proplists:get_value(keep_alive, Opts, false),
  65. Timeout = proplists:get_value(query_timeout, Opts,
  66. ?default_query_timeout),
  67. QueryCacheTime = proplists:get_value(query_cache_time, Opts,
  68. ?default_query_cache_time),
  69. TcpOpts = proplists:get_value(tcp_options, Opts, []),
  70. SetFoundRows = proplists:get_value(found_rows, Opts, false),
  71. SSLOpts = proplists:get_value(ssl, Opts, undefined),
  72. SockMod0 = gen_tcp,
  73. PingTimeout = case KeepAlive of
  74. true -> ?default_ping_timeout;
  75. false -> infinity;
  76. N when N > 0 -> N
  77. end,
  78. %% Connect socket
  79. SockOpts = [binary, {packet, raw}, {active, false} | TcpOpts],
  80. {ok, Socket0} = SockMod0:connect(Host, Port, SockOpts),
  81. %% Exchange handshake communication.
  82. Result = mysql_protocol:handshake(User, Password, Database, SockMod0, SSLOpts,
  83. Socket0, SetFoundRows),
  84. case Result of
  85. {ok, Handshake, SockMod, Socket} ->
  86. setopts(SockMod, Socket, [{active, once}]),
  87. #handshake{server_version = Version, connection_id = ConnId,
  88. status = Status,
  89. auth_plugin_data = AuthPluginData} = Handshake,
  90. State = #state{server_version = Version, connection_id = ConnId,
  91. sockmod = SockMod,
  92. socket = Socket,
  93. ssl_opts = SSLOpts,
  94. host = Host, port = Port,
  95. user = User, password = Password,
  96. auth_plugin_data = AuthPluginData,
  97. status = Status,
  98. log_warnings = LogWarn,
  99. ping_timeout = PingTimeout,
  100. query_timeout = Timeout,
  101. query_cache_time = QueryCacheTime,
  102. cap_found_rows = (SetFoundRows =:= true)},
  103. %% Trap exit so that we can properly disconnect when we die.
  104. process_flag(trap_exit, true),
  105. State1 = schedule_ping(State),
  106. {ok, State1};
  107. #error{} = E ->
  108. {stop, error_to_reason(E)}
  109. end.
  110. %% @private
  111. %% @doc
  112. %%
  113. %% Query and execute calls:
  114. %%
  115. %% <ul>
  116. %% <li>{query, Query, FilterMap, Timeout}</li>
  117. %% <li>{param_query, Query, Params, FilterMap, Timeout}</li>
  118. %% <li>{execute, Stmt, Args, FilterMap, Timeout}</li>
  119. %% </ul>
  120. %%
  121. %% For the calls listed above, we return these values:
  122. %%
  123. %% <dl>
  124. %% <dt>`ok'</dt>
  125. %% <dd>Success without returning any table data (UPDATE, etc.)</dd>
  126. %% <dt>`{ok, ColumnNames, Rows}'</dt>
  127. %% <dd>Queries returning one result set of table data</dd>
  128. %% <dt>`{ok, [{ColumnNames, Rows}, ...]}'</dt>
  129. %% <dd>Queries returning more than one result set of table data</dd>
  130. %% <dt>`{error, ServerReason}'</dt>
  131. %% <dd>MySQL server error</dd>
  132. %% <dt>`{implicit_commit, NestingLevel, Query}'</dt>
  133. %% <dd>A DDL statement (e.g. CREATE TABLE, ALTER TABLE, etc.) results in
  134. %% an implicit commit.
  135. %%
  136. %% If the caller is in a (nested) transaction, it must be aborted. To be
  137. %% able to handle this in the caller's process, we also return the
  138. %% nesting level.</dd>
  139. %% <dt>`{implicit_rollback, NestingLevel, ServerReason}'</dt>
  140. %% <dd>This errors results in an implicit rollback: `{1213, <<"40001">>,
  141. %% <<"Deadlock found when trying to get lock; try restarting "
  142. %% "transaction">>}'.
  143. %%
  144. %% If the caller is in a (nested) transaction, it must be aborted. To be
  145. %% able to handle this in the caller's process, we also return the
  146. %% nesting level.</dd>
  147. %% </dl>
  148. handle_call({query, Query, FilterMap, default_timeout}, From, State) ->
  149. handle_call({query, Query, FilterMap, State#state.query_timeout}, From,
  150. State);
  151. handle_call({query, Query, FilterMap, Timeout}, _From,
  152. #state{sockmod = SockMod, socket = Socket} = State) ->
  153. setopts(SockMod, Socket, [{active, false}]),
  154. Result = mysql_protocol:query(Query, SockMod, Socket, FilterMap, Timeout),
  155. {ok, Recs} = case Result of
  156. {error, timeout} when State#state.server_version >= [5, 0, 0] ->
  157. kill_query(State),
  158. mysql_protocol:fetch_query_response(SockMod, Socket, FilterMap,
  159. ?cmd_timeout);
  160. {error, timeout} ->
  161. %% For MySQL 4.x.x there is no way to recover from timeout except
  162. %% killing the connection itself.
  163. exit(timeout);
  164. QueryResult ->
  165. QueryResult
  166. end,
  167. setopts(SockMod, Socket, [{active, once}]),
  168. State1 = lists:foldl(fun update_state/2, State, Recs),
  169. State1#state.warning_count > 0 andalso State1#state.log_warnings
  170. andalso log_warnings(State1, Query),
  171. handle_query_call_reply(Recs, Query, State1, []);
  172. handle_call({param_query, Query, Params, FilterMap, default_timeout}, From,
  173. State) ->
  174. handle_call({param_query, Query, Params, FilterMap,
  175. State#state.query_timeout}, From, State);
  176. handle_call({param_query, Query, Params, FilterMap, Timeout}, _From,
  177. #state{socket = Socket, sockmod = SockMod} = State) ->
  178. %% Parametrized query: Prepared statement cached with the query as the key
  179. QueryBin = iolist_to_binary(Query),
  180. Cache = State#state.query_cache,
  181. {StmtResult, Cache1} = case mysql_cache:lookup(QueryBin, Cache) of
  182. {found, FoundStmt, NewCache} ->
  183. %% Found
  184. {{ok, FoundStmt}, NewCache};
  185. not_found ->
  186. %% Prepare
  187. setopts(SockMod, Socket, [{active, false}]),
  188. Rec = mysql_protocol:prepare(Query, SockMod, Socket),
  189. setopts(SockMod, Socket, [{active, once}]),
  190. case Rec of
  191. #error{} = E ->
  192. {{error, error_to_reason(E)}, Cache};
  193. #prepared{} = Stmt ->
  194. %% If the first entry in the cache, start the timer.
  195. Cache == empty andalso begin
  196. When = State#state.query_cache_time * 2,
  197. erlang:send_after(When, self(), query_cache)
  198. end,
  199. {{ok, Stmt}, mysql_cache:store(QueryBin, Stmt, Cache)}
  200. end
  201. end,
  202. case StmtResult of
  203. {ok, StmtRec} ->
  204. State1 = State#state{query_cache = Cache1},
  205. execute_stmt(StmtRec, Params, FilterMap, Timeout, State1);
  206. PrepareError ->
  207. {reply, PrepareError, State}
  208. end;
  209. handle_call({execute, Stmt, Args, FilterMap, default_timeout}, From, State) ->
  210. handle_call({execute, Stmt, Args, FilterMap, State#state.query_timeout},
  211. From, State);
  212. handle_call({execute, Stmt, Args, FilterMap, Timeout}, _From, State) ->
  213. case dict:find(Stmt, State#state.stmts) of
  214. {ok, StmtRec} ->
  215. execute_stmt(StmtRec, Args, FilterMap, Timeout, State);
  216. error ->
  217. {reply, {error, not_prepared}, State}
  218. end;
  219. handle_call({prepare, Query}, _From, State) ->
  220. #state{socket = Socket, sockmod = SockMod} = State,
  221. setopts(SockMod, Socket, [{active, false}]),
  222. Rec = mysql_protocol:prepare(Query, SockMod, Socket),
  223. setopts(SockMod, Socket, [{active, once}]),
  224. State1 = update_state(Rec, State),
  225. case Rec of
  226. #error{} = E ->
  227. {reply, {error, error_to_reason(E)}, State1};
  228. #prepared{statement_id = Id} = Stmt ->
  229. Stmts1 = dict:store(Id, Stmt, State1#state.stmts),
  230. State2 = State#state{stmts = Stmts1},
  231. {reply, {ok, Id}, State2}
  232. end;
  233. handle_call({prepare, Name, Query}, _From, State) when is_atom(Name) ->
  234. #state{socket = Socket, sockmod = SockMod} = State,
  235. %% First unprepare if there is an old statement with this name.
  236. setopts(SockMod, Socket, [{active, false}]),
  237. State1 = case dict:find(Name, State#state.stmts) of
  238. {ok, OldStmt} ->
  239. mysql_protocol:unprepare(OldStmt, SockMod, Socket),
  240. State#state{stmts = dict:erase(Name, State#state.stmts)};
  241. error ->
  242. State
  243. end,
  244. Rec = mysql_protocol:prepare(Query, SockMod, Socket),
  245. setopts(SockMod, Socket, [{active, once}]),
  246. State2 = update_state(Rec, State1),
  247. case Rec of
  248. #error{} = E ->
  249. {reply, {error, error_to_reason(E)}, State2};
  250. #prepared{} = Stmt ->
  251. Stmts1 = dict:store(Name, Stmt, State2#state.stmts),
  252. State3 = State2#state{stmts = Stmts1},
  253. {reply, {ok, Name}, State3}
  254. end;
  255. handle_call({unprepare, Stmt}, _From, State) when is_atom(Stmt);
  256. is_integer(Stmt) ->
  257. case dict:find(Stmt, State#state.stmts) of
  258. {ok, StmtRec} ->
  259. #state{socket = Socket, sockmod = SockMod} = State,
  260. setopts(SockMod, Socket, [{active, false}]),
  261. mysql_protocol:unprepare(StmtRec, SockMod, Socket),
  262. setopts(SockMod, Socket, [{active, once}]),
  263. State1 = State#state{stmts = dict:erase(Stmt, State#state.stmts)},
  264. State2 = schedule_ping(State1),
  265. {reply, ok, State2};
  266. error ->
  267. {reply, {error, not_prepared}, State}
  268. end;
  269. handle_call({change_user, Username, Password, Database}, From,
  270. State = #state{transaction_levels = []}) ->
  271. #state{socket = Socket, sockmod = SockMod,
  272. auth_plugin_data = AuthPluginData,
  273. server_version = ServerVersion} = State,
  274. setopts(SockMod, Socket, [{active, false}]),
  275. Result = mysql_protocol:change_user(SockMod, Socket, Username, Password,
  276. AuthPluginData, Database,
  277. ServerVersion),
  278. setopts(SockMod, Socket, [{active, once}]),
  279. State1 = update_state(Result, State),
  280. State1#state.warning_count > 0 andalso State1#state.log_warnings
  281. andalso log_warnings(State1, "CHANGE USER"),
  282. State2 = State1#state{query_cache = empty, stmts = dict:new()},
  283. case Result of
  284. #ok{} ->
  285. {reply, ok, State2#state{user = Username, password = Password}};
  286. #error{} = E ->
  287. gen_server:reply(From, {error, error_to_reason(E)}),
  288. stop_server(change_user_failed, State2)
  289. end;
  290. handle_call(warning_count, _From, State) ->
  291. {reply, State#state.warning_count, State};
  292. handle_call(insert_id, _From, State) ->
  293. {reply, State#state.insert_id, State};
  294. handle_call(affected_rows, _From, State) ->
  295. {reply, State#state.affected_rows, State};
  296. handle_call(autocommit, _From, State) ->
  297. {reply, State#state.status band ?SERVER_STATUS_AUTOCOMMIT /= 0, State};
  298. handle_call(backslash_escapes_enabled, _From, State = #state{status = S}) ->
  299. {reply, S band ?SERVER_STATUS_NO_BACKSLASH_ESCAPES == 0, State};
  300. handle_call(in_transaction, _From, State) ->
  301. {reply, State#state.status band ?SERVER_STATUS_IN_TRANS /= 0, State};
  302. handle_call(start_transaction, {FromPid, _},
  303. State = #state{socket = Socket, sockmod = SockMod,
  304. transaction_levels = L, status = Status})
  305. when Status band ?SERVER_STATUS_IN_TRANS == 0, L == [];
  306. Status band ?SERVER_STATUS_IN_TRANS /= 0, L /= [] ->
  307. MRef = erlang:monitor(process, FromPid),
  308. Query = case L of
  309. [] -> <<"BEGIN">>;
  310. _ -> <<"SAVEPOINT s", (integer_to_binary(length(L)))/binary>>
  311. end,
  312. setopts(SockMod, Socket, [{active, false}]),
  313. {ok, [Res = #ok{}]} = mysql_protocol:query(Query, SockMod, Socket,
  314. ?cmd_timeout),
  315. setopts(SockMod, Socket, [{active, once}]),
  316. State1 = update_state(Res, State),
  317. {reply, ok, State1#state{transaction_levels = [{FromPid, MRef} | L]}};
  318. handle_call(rollback, {FromPid, _},
  319. State = #state{socket = Socket, sockmod = SockMod, status = Status,
  320. transaction_levels = [{FromPid, MRef} | L]})
  321. when Status band ?SERVER_STATUS_IN_TRANS /= 0 ->
  322. erlang:demonitor(MRef),
  323. Query = case L of
  324. [] -> <<"ROLLBACK">>;
  325. _ -> <<"ROLLBACK TO s", (integer_to_binary(length(L)))/binary>>
  326. end,
  327. setopts(SockMod, Socket, [{active, false}]),
  328. {ok, [Res = #ok{}]} = mysql_protocol:query(Query, SockMod, Socket,
  329. ?cmd_timeout),
  330. setopts(SockMod, Socket, [{active, once}]),
  331. State1 = update_state(Res, State),
  332. {reply, ok, State1#state{transaction_levels = L}};
  333. handle_call(commit, {FromPid, _},
  334. State = #state{socket = Socket, sockmod = SockMod, status = Status,
  335. transaction_levels = [{FromPid, MRef} | L]})
  336. when Status band ?SERVER_STATUS_IN_TRANS /= 0 ->
  337. erlang:demonitor(MRef),
  338. Query = case L of
  339. [] -> <<"COMMIT">>;
  340. _ -> <<"RELEASE SAVEPOINT s", (integer_to_binary(length(L)))/binary>>
  341. end,
  342. setopts(SockMod, Socket, [{active, false}]),
  343. {ok, [Res = #ok{}]} = mysql_protocol:query(Query, SockMod, Socket,
  344. ?cmd_timeout),
  345. setopts(SockMod, Socket, [{active, once}]),
  346. State1 = update_state(Res, State),
  347. {reply, ok, State1#state{transaction_levels = L}}.
  348. %% @private
  349. handle_cast(_Msg, State) ->
  350. {noreply, State}.
  351. %% @private
  352. handle_info(query_cache, #state{query_cache = Cache,
  353. query_cache_time = CacheTime} = State) ->
  354. %% Evict expired queries/statements in the cache used by query/3.
  355. {Evicted, Cache1} = mysql_cache:evict_older_than(Cache, CacheTime),
  356. %% Unprepare the evicted statements
  357. #state{socket = Socket, sockmod = SockMod} = State,
  358. setopts(SockMod, Socket, [{active, false}]),
  359. lists:foreach(fun ({_Query, Stmt}) ->
  360. mysql_protocol:unprepare(Stmt, SockMod, Socket)
  361. end,
  362. Evicted),
  363. setopts(SockMod, Socket, [{active, once}]),
  364. %% If nonempty, schedule eviction again.
  365. mysql_cache:size(Cache1) > 0 andalso
  366. erlang:send_after(CacheTime, self(), query_cache),
  367. {noreply, State#state{query_cache = Cache1}};
  368. handle_info({'DOWN', _MRef, _, Pid, _Info}, State) ->
  369. stop_server({application_process_died, Pid}, State);
  370. handle_info(ping, #state{socket = Socket, sockmod = SockMod} = State) ->
  371. setopts(SockMod, Socket, [{active, false}]),
  372. Ok = mysql_protocol:ping(SockMod, Socket),
  373. setopts(SockMod, Socket, [{active, once}]),
  374. {noreply, update_state(Ok, State)};
  375. handle_info({tcp_closed, _Socket}, State) ->
  376. stop_server(tcp_closed, State);
  377. handle_info({tcp_error, _Socket, Reason}, State) ->
  378. stop_server({tcp_error, Reason}, State);
  379. handle_info(_Info, State) ->
  380. {noreply, State}.
  381. %% @private
  382. terminate(Reason, #state{socket = Socket, sockmod = SockMod})
  383. when Reason == normal; Reason == shutdown ->
  384. %% Send the goodbye message for politeness.
  385. setopts(SockMod, Socket, [{active, false}]),
  386. mysql_protocol:quit(SockMod, Socket);
  387. terminate(_Reason, _State) ->
  388. ok.
  389. %% @private
  390. code_change(_OldVsn, State = #state{}, _Extra) ->
  391. {ok, State};
  392. code_change(_OldVsn, _State, _Extra) ->
  393. {error, incompatible_state}.
  394. %% --- Helpers ---
  395. %% @doc Executes a prepared statement and returns {Reply, NextState}.
  396. execute_stmt(Stmt, Args, FilterMap, Timeout,
  397. State = #state{socket = Socket, sockmod = SockMod}) ->
  398. setopts(SockMod, Socket, [{active, false}]),
  399. {ok, Recs} = case mysql_protocol:execute(Stmt, Args, SockMod, Socket,
  400. FilterMap, Timeout) of
  401. {error, timeout} when State#state.server_version >= [5, 0, 0] ->
  402. kill_query(State),
  403. mysql_protocol:fetch_execute_response(SockMod, Socket,
  404. FilterMap, ?cmd_timeout);
  405. {error, timeout} ->
  406. %% For MySQL 4.x.x there is no way to recover from timeout except
  407. %% killing the connection itself.
  408. exit(timeout);
  409. QueryResult ->
  410. QueryResult
  411. end,
  412. setopts(SockMod, Socket, [{active, once}]),
  413. State1 = lists:foldl(fun update_state/2, State, Recs),
  414. State1#state.warning_count > 0 andalso State1#state.log_warnings
  415. andalso log_warnings(State1, Stmt#prepared.orig_query),
  416. handle_query_call_reply(Recs, Stmt#prepared.orig_query, State1, []).
  417. %% @doc Produces a tuple to return as an error reason.
  418. -spec error_to_reason(#error{}) -> mysql:server_reason().
  419. error_to_reason(#error{code = Code, state = State, msg = Msg}) ->
  420. {Code, State, Msg}.
  421. %% @doc Updates a state with information from a response. Also re-schedules
  422. %% ping.
  423. -spec update_state(#ok{} | #eof{} | any(), #state{}) -> #state{}.
  424. update_state(Rec, State) ->
  425. State1 = case Rec of
  426. #ok{status = S, affected_rows = R, insert_id = Id, warning_count = W} ->
  427. State#state{status = S, affected_rows = R, insert_id = Id,
  428. warning_count = W};
  429. #resultset{status = S, warning_count = W} ->
  430. State#state{status = S, warning_count = W};
  431. #prepared{warning_count = W} ->
  432. State#state{warning_count = W};
  433. _Other ->
  434. %% This includes errors.
  435. %% Reset some things. (Note: We don't reset status and insert_id.)
  436. State#state{warning_count = 0, affected_rows = 0}
  437. end,
  438. schedule_ping(State1).
  439. %% @doc Produces a reply for handle_call/3 for queries and prepared statements.
  440. handle_query_call_reply([], _Query, State, ResultSetsAcc) ->
  441. Reply = case ResultSetsAcc of
  442. [] -> ok;
  443. [{ColumnNames, Rows}] -> {ok, ColumnNames, Rows};
  444. [_|_] -> {ok, lists:reverse(ResultSetsAcc)}
  445. end,
  446. {reply, Reply, State};
  447. handle_query_call_reply([Rec|Recs], Query,
  448. #state{transaction_levels = L} = State,
  449. ResultSetsAcc) ->
  450. case Rec of
  451. #ok{status = Status} when Status band ?SERVER_STATUS_IN_TRANS == 0,
  452. L /= [] ->
  453. %% DDL statements (e.g. CREATE TABLE, ALTER TABLE, etc.) result in
  454. %% an implicit commit.
  455. Length = length(L),
  456. Reply = {implicit_commit, Length, Query},
  457. [] = demonitor_processes(L, Length),
  458. {reply, Reply, State#state{transaction_levels = []}};
  459. #ok{} ->
  460. handle_query_call_reply(Recs, Query, State, ResultSetsAcc);
  461. #resultset{cols = ColDefs, rows = Rows} ->
  462. Names = [Def#col.name || Def <- ColDefs],
  463. ResultSetsAcc1 = [{Names, Rows} | ResultSetsAcc],
  464. handle_query_call_reply(Recs, Query, State, ResultSetsAcc1);
  465. #error{code = ?ERROR_DEADLOCK} when L /= [] ->
  466. %% These errors result in an implicit rollback.
  467. Reply = {implicit_rollback, length(L), error_to_reason(Rec)},
  468. %% Everything in the transaction is rolled back, except the BEGIN
  469. %% statement itself. Thus, we are in transaction level 1.
  470. NewMonitors = demonitor_processes(L, length(L) - 1),
  471. {reply, Reply, State#state{transaction_levels = NewMonitors}};
  472. #error{} ->
  473. {reply, {error, error_to_reason(Rec)}, State}
  474. end.
  475. %% @doc Schedules (or re-schedules) ping.
  476. schedule_ping(State = #state{ping_timeout = infinity}) ->
  477. State;
  478. schedule_ping(State = #state{ping_timeout = Timeout, ping_ref = Ref}) ->
  479. is_reference(Ref) andalso erlang:cancel_timer(Ref),
  480. State#state{ping_ref = erlang:send_after(Timeout, self(), ping)}.
  481. %% @doc Fetches and logs warnings. Query is the query that gave the warnings.
  482. log_warnings(#state{socket = Socket, sockmod = SockMod}, Query) ->
  483. setopts(SockMod, Socket, [{active, false}]),
  484. {ok, [#resultset{rows = Rows}]} = mysql_protocol:query(<<"SHOW WARNINGS">>,
  485. SockMod, Socket,
  486. ?cmd_timeout),
  487. setopts(SockMod, Socket, [{active, once}]),
  488. Lines = [[Level, " ", integer_to_binary(Code), ": ", Message, "\n"]
  489. || [Level, Code, Message] <- Rows],
  490. error_logger:warning_msg("~s in ~s~n", [Lines, Query]).
  491. %% @doc Makes a separate connection and execute KILL QUERY. We do this to get
  492. %% our main connection back to normal. KILL QUERY appeared in MySQL 5.0.0.
  493. kill_query(#state{connection_id = ConnId, host = Host, port = Port,
  494. user = User, password = Password, ssl_opts = SSLOpts,
  495. cap_found_rows = SetFoundRows}) ->
  496. %% Connect socket
  497. SockOpts = [{active, false}, binary, {packet, raw}],
  498. {ok, Socket0} = gen_tcp:connect(Host, Port, SockOpts),
  499. %% Exchange handshake communication.
  500. Result = mysql_protocol:handshake(User, Password, undefined, gen_tcp,
  501. SSLOpts, Socket0, SetFoundRows),
  502. case Result of
  503. {ok, #handshake{}, SockMod, Socket} ->
  504. %% Kill and disconnect
  505. IdBin = integer_to_binary(ConnId),
  506. {ok, [#ok{}]} = mysql_protocol:query(<<"KILL QUERY ", IdBin/binary>>,
  507. SockMod, Socket, ?cmd_timeout),
  508. mysql_protocol:quit(SockMod, Socket);
  509. #error{} = E ->
  510. error_logger:error_msg("Failed to connect to kill query: ~p",
  511. [error_to_reason(E)])
  512. end.
  513. stop_server(Reason,
  514. #state{socket = Socket, connection_id = ConnId} = State) ->
  515. error_logger:error_msg("Connection Id ~p closing with reason: ~p~n",
  516. [ConnId, Reason]),
  517. ok = gen_tcp:close(Socket),
  518. {stop, Reason, State#state{socket = undefined, connection_id = undefined}}.
  519. setopts(gen_tcp, Socket, Opts) ->
  520. inet:setopts(Socket, Opts);
  521. setopts(SockMod, Socket, Opts) ->
  522. SockMod:setopts(Socket, Opts).
  523. demonitor_processes(List, 0) ->
  524. List;
  525. demonitor_processes([{_FromPid, MRef}|T], Count) ->
  526. erlang:demonitor(MRef),
  527. demonitor_processes(T, Count - 1).