mysql.erl 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. %% MySQL/OTP – MySQL client library for Erlang/OTP
  2. %% Copyright (C) 2014-2015, 2018 Viktor Söderqvist,
  3. %% 2016 Johan Lövdahl
  4. %% 2017 Piotr Nosek, Michal Slaski
  5. %%
  6. %% This file is part of MySQL/OTP.
  7. %%
  8. %% MySQL/OTP is free software: you can redistribute it and/or modify it under
  9. %% the terms of the GNU Lesser General Public License as published by the Free
  10. %% Software Foundation, either version 3 of the License, or (at your option)
  11. %% any later version.
  12. %%
  13. %% This program is distributed in the hope that it will be useful, but WITHOUT
  14. %% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  15. %% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  16. %% more details.
  17. %%
  18. %% You should have received a copy of the GNU Lesser General Public License
  19. %% along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. %% @doc MySQL client.
  21. %%
  22. %% The `connection()' type is a gen_server reference as described in the
  23. %% documentation for `gen_server:call/2,3', e.g. the pid or the name if the
  24. %% gen_server is locally registered.
  25. -module(mysql).
  26. -export([start_link/1, stop/1, stop/2,
  27. query/2, query/3, query/4, query/5,
  28. execute/3, execute/4, execute/5,
  29. prepare/2, prepare/3, unprepare/2,
  30. warning_count/1, affected_rows/1, autocommit/1, insert_id/1,
  31. encode/2, in_transaction/1,
  32. transaction/2, transaction/3, transaction/4,
  33. change_user/3, change_user/4]).
  34. -export_type([connection/0, server_reason/0, query_result/0]).
  35. %% A connection is a ServerRef as in gen_server:call/2,3.
  36. -type connection() :: Name :: atom() |
  37. {Name :: atom(), Node :: atom()} |
  38. {global, GlobalName :: term()} |
  39. {via, Module :: atom(), ViaName :: term()} |
  40. pid().
  41. %% MySQL error with the codes and message returned from the server.
  42. -type server_reason() :: {Code :: integer(), SQLState :: binary() | undefined,
  43. Message :: binary()}.
  44. -type column_names() :: [binary()].
  45. -type row() :: [term()].
  46. -type rows() :: [row()].
  47. -type query_filtermap_fun() :: fun((row()) -> query_filtermap_res())
  48. | fun((column_names(), row()) -> query_filtermap_res()).
  49. -type query_filtermap_res() :: boolean()
  50. | {true, term()}.
  51. -type query_result() :: ok
  52. | {ok, column_names(), rows()}
  53. | {ok, [{column_names(), rows()}, ...]}
  54. | {error, server_reason()}.
  55. -define(default_connect_timeout, 5000).
  56. -include("exception.hrl").
  57. %% @doc Starts a connection gen_server process and connects to a database. To
  58. %% disconnect use `mysql:stop/1,2'.
  59. %%
  60. %% Options:
  61. %%
  62. %% <dl>
  63. %% <dt>`{name, ServerName}'</dt>
  64. %% <dd>If a name is provided, the gen_server will be registered with this
  65. %% name. For details see the documentation for the first argument of
  66. %% gen_server:start_link/4.</dd>
  67. %% <dt>`{host, Host}'</dt>
  68. %% <dd>Hostname of the MySQL database. Since OTP version 19, it is also
  69. %% possible to specify a local (Unix) Socket by specifying
  70. %% `{local, SocketFile}'. Default `"localhost"'.</dd>
  71. %% <dt>`{port, Port}'</dt>
  72. %% <dd>Port; default 3306 for non-local or 0 for local (Unix) sockets.</dd>
  73. %% <dt>`{user, User}'</dt>
  74. %% <dd>Username.</dd>
  75. %% <dt>`{password, Password}'</dt>
  76. %% <dd>Password.</dd>
  77. %% <dt>`{database, Database}'</dt>
  78. %% <dd>The name of the database AKA schema to use. This can be changed later
  79. %% using the query `USE <database>'.</dd>
  80. %% <dt>`{connect_timeout, Timeout}'</dt>
  81. %% <dd>The maximum time to spend for start_link/1.</dd>
  82. %% <dt>`{log_warnings, boolean()}'</dt>
  83. %% <dd>Whether to fetch warnings and log them using error_logger; default
  84. %% true.</dd>
  85. %% <dt>`{keep_alive, boolean() | timeout()}'</dt>
  86. %% <dd>Send ping when unused for a certain time. Possible values are `true',
  87. %% `false' and `integer() > 0' for an explicit interval in milliseconds.
  88. %% The default is `false'. For `true' a default ping timeout is used.
  89. %% </dd>
  90. %% <dt>`{prepare, NamedStatements}'</dt>
  91. %% <dd>Named prepared statements to be created as soon as the connection is
  92. %% ready.</dd>
  93. %% <dt>`{queries, Queries}'</dt>
  94. %% <dd>Queries to be executed as soon as the connection is ready. Any results
  95. %% are discarded. Typically, this is used for setting time zone and other
  96. %% session variables.</dd>
  97. %% <dt>`{query_timeout, Timeout}'</dt>
  98. %% <dd>The default time to wait for a response when executing a query or a
  99. %% prepared statement. This can be given per query using `query/3,4' and
  100. %% `execute/4'. The default is `infinity'.</dd>
  101. %% <dt>`{found_rows, boolean()}'</dt>
  102. %% <dd>If set to true, the connection will be established with
  103. %% CLIENT_FOUND_ROWS capability. affected_rows/1 will now return the
  104. %% number of found rows, not the number of rows changed by the
  105. %% query.</dd>
  106. %% <dt>`{query_cache_time, Timeout}'</dt>
  107. %% <dd>The minimum number of milliseconds to cache prepared statements used
  108. %% for parametrized queries with query/3.</dd>
  109. %% <dt>`{tcp_options, Options}'</dt>
  110. %% <dd>Additional options for `gen_tcp:connect/3'. You may want to set
  111. %% `{recbuf, Size}' and `{sndbuf, Size}' if you send or receive more than
  112. %% the default (typically 8K) per query.</dd>
  113. %% <dt>`{ssl, Options}'</dt>
  114. %% <dd>Additional options for `ssl:connect/3'.</dd>
  115. %% </dl>
  116. -spec start_link(Options) -> {ok, pid()} | ignore | {error, term()}
  117. when Options :: [Option],
  118. Option :: {name, ServerName} |
  119. {host, inet:socket_address() | inet:hostname()} | {port, integer()} |
  120. {user, iodata()} | {password, iodata()} |
  121. {database, iodata()} |
  122. {connect_timeout, timeout()} |
  123. {log_warnings, boolean()} |
  124. {keep_alive, boolean() | timeout()} |
  125. {prepare, NamedStatements} |
  126. {queries, [iodata()]} |
  127. {query_timeout, timeout()} |
  128. {found_rows, boolean()} |
  129. {query_cache_time, non_neg_integer()} |
  130. {tcp_options, [gen_tcp:connect_option()]} |
  131. {ssl, term()},
  132. ServerName :: {local, Name :: atom()} |
  133. {global, GlobalName :: term()} |
  134. {via, Module :: atom(), ViaName :: term()},
  135. NamedStatements :: [{StatementName :: atom(), Statement :: iodata()}].
  136. start_link(Options) ->
  137. GenSrvOpts = [{timeout, proplists:get_value(connect_timeout, Options,
  138. ?default_connect_timeout)}],
  139. case proplists:get_value(name, Options) of
  140. undefined ->
  141. gen_server:start_link(mysql_conn, Options, GenSrvOpts);
  142. ServerName ->
  143. gen_server:start_link(ServerName, mysql_conn, Options, GenSrvOpts)
  144. end.
  145. %% @see stop/2.
  146. -spec stop(Conn) -> ok
  147. when Conn :: connection().
  148. stop(Conn) ->
  149. stop(Conn, infinity).
  150. %% @doc Stops a connection process and closes the connection. The
  151. %% process calling `stop' will be blocked until the connection
  152. %% process stops or the given timeout expires.
  153. %%
  154. %% If the connection is not stopped within the given timeout,
  155. %% an exit exception is raised with reason `timeout'.
  156. %%
  157. %% If the connection process exits with any other reason than `normal',
  158. %% an exit exception is raised with that reason.
  159. -spec stop(Conn, Timeout) -> ok
  160. when Conn :: connection(),
  161. Timeout :: timeout().
  162. stop(Conn, Timeout) ->
  163. case erlang:function_exported(gen_server, stop, 3) of
  164. true -> gen_server:stop(Conn, normal, Timeout); %% OTP >= 18
  165. false -> backported_gen_server_stop(Conn, normal, Timeout) %% OTP < 18
  166. end.
  167. -spec backported_gen_server_stop(Conn, Reason, Timeout) -> ok
  168. when Conn :: connection(),
  169. Reason :: term(),
  170. Timeout :: timeout().
  171. backported_gen_server_stop(Conn, Reason, Timeout) ->
  172. Monitor=monitor(process, Conn),
  173. exit(Conn, Reason),
  174. receive
  175. {'DOWN', Monitor, process, Conn, Reason} ->
  176. ok;
  177. {'DOWN', Monitor, process, Conn, UnexpectedReason} ->
  178. exit(UnexpectedReason)
  179. after Timeout ->
  180. exit(Conn, kill),
  181. receive
  182. {'DOWN', Monitor, process, Conn, killed} ->
  183. exit(timeout)
  184. end
  185. end.
  186. %% @see query/5.
  187. -spec query(Conn, Query) -> Result
  188. when Conn :: connection(),
  189. Query :: iodata(),
  190. Result :: query_result().
  191. query(Conn, Query) ->
  192. query(Conn, Query, no_params, no_filtermap_fun, default_timeout).
  193. %% @see query/5.
  194. -spec query(Conn, Query, Params | FilterMap | Timeout) -> Result
  195. when Conn :: connection(),
  196. Query :: iodata(),
  197. Timeout :: default_timeout | timeout(),
  198. Params :: no_params | [term()],
  199. FilterMap :: no_filtermap_fun | query_filtermap_fun(),
  200. Result :: query_result().
  201. query(Conn, Query, Params) when Params == no_params;
  202. is_list(Params) ->
  203. query(Conn, Query, Params, no_filtermap_fun, default_timeout);
  204. query(Conn, Query, FilterMap) when FilterMap == no_filtermap_fun;
  205. is_function(FilterMap, 1);
  206. is_function(FilterMap, 2) ->
  207. query(Conn, Query, no_params, FilterMap, default_timeout);
  208. query(Conn, Query, Timeout) when Timeout == default_timeout;
  209. is_integer(Timeout);
  210. Timeout == infinity ->
  211. query(Conn, Query, no_params, no_filtermap_fun, Timeout).
  212. %% @see query/5.
  213. -spec query(Conn, Query, Params, Timeout) -> Result
  214. when Conn :: connection(),
  215. Query :: iodata(),
  216. Timeout :: default_timeout | timeout(),
  217. Params :: no_params | [term()],
  218. Result :: query_result();
  219. (Conn, Query, FilterMap, Timeout) -> Result
  220. when Conn :: connection(),
  221. Query :: iodata(),
  222. Timeout :: default_timeout | timeout(),
  223. FilterMap :: no_filtermap_fun | query_filtermap_fun(),
  224. Result :: query_result();
  225. (Conn, Query, Params, FilterMap) -> Result
  226. when Conn :: connection(),
  227. Query :: iodata(),
  228. Params :: no_params | [term()],
  229. FilterMap :: no_filtermap_fun | query_filtermap_fun(),
  230. Result :: query_result().
  231. query(Conn, Query, Params, Timeout) when (Params == no_params orelse
  232. is_list(Params)) andalso
  233. (Timeout == default_timeout orelse
  234. is_integer(Timeout) orelse
  235. Timeout == infinity) ->
  236. query(Conn, Query, Params, no_filtermap_fun, Timeout);
  237. query(Conn, Query, FilterMap, Timeout) when (FilterMap == no_filtermap_fun orelse
  238. is_function(FilterMap, 1) orelse
  239. is_function(FilterMap, 2)) andalso
  240. (Timeout == default_timeout orelse
  241. is_integer(Timeout) orelse
  242. Timeout=:=infinity) ->
  243. query(Conn, Query, no_params, FilterMap, Timeout);
  244. query(Conn, Query, Params, FilterMap) when (Params == no_params orelse
  245. is_list(Params)) andalso
  246. (FilterMap == no_filtermap_fun orelse
  247. is_function(FilterMap, 1) orelse
  248. is_function(FilterMap, 2)) ->
  249. query(Conn, Query, Params, FilterMap, default_timeout).
  250. %% @doc Executes a parameterized query with a timeout and applies a filter/map
  251. %% function to the result rows.
  252. %%
  253. %% A prepared statement is created, executed and then cached for a certain
  254. %% time. If the same query is executed again when it is already cached, it does
  255. %% not need to be prepared again.
  256. %%
  257. %% The minimum time the prepared statement is cached can be specified using the
  258. %% option `{query_cache_time, Milliseconds}' to start_link/1.
  259. %%
  260. %% Results are returned in the form `{ok, ColumnNames, Rows}' if there is one
  261. %% result set. If there are more than one result sets, they are returned in the
  262. %% form `{ok, [{ColumnNames, Rows}, ...]}'.
  263. %%
  264. %% For queries that don't return any rows (INSERT, UPDATE, etc.) only the atom
  265. %% `ok' is returned.
  266. %%
  267. %% The `Params', `FilterMap' and `Timeout' arguments are optional.
  268. %% <ul>
  269. %% <li>If the `Params' argument is the atom `no_params' or is omitted, a plain
  270. %% query will be executed instead of a parameterized one.</li>
  271. %% <li>If the `FilterMap' argument is the atom `no_filtermap_fun' or is
  272. %% omitted, no row filtering/mapping will be applied and all result rows
  273. %% will be returned unchanged.</li>
  274. %% <li>If the `Timeout' argument is the atom `default_timeout' or is omitted,
  275. %% the timeout given in `start_link/1' is used.</li>
  276. %% </ul>
  277. %%
  278. %% If the `FilterMap' argument is used, it must be a function of arity 1 or 2
  279. %% that returns either `true', `false', or `{true, Value}'.
  280. %%
  281. %% Each result row is handed to the given function as soon as it is received
  282. %% from the server, and only when the function has returned, the next row is
  283. %% fetched. This provides the ability to prevent memory exhaustion; on the
  284. %% other hand, it can cause the server to time out on sending if your function
  285. %% is doing something slow (see the MySQL documentation on `NET_WRITE_TIMEOUT').
  286. %%
  287. %% If the function is of arity 1, only the row is passed to it as the single
  288. %% argument, while if the function is of arity 2, the column names are passed
  289. %% in as the first argument and the row as the second.
  290. %%
  291. %% The value returned is then used to decide if the row is to be included in
  292. %% the result(s) returned from the `query' call (filtering), or if something
  293. %% else is to be included in the result instead (mapping). You may also use
  294. %% this function for side effects, like writing rows to disk or sending them
  295. %% to another process etc.
  296. %%
  297. %% Here is an example showing some of the things that are possible:
  298. %% ```
  299. %% Query = "SELECT a, b, c FROM foo",
  300. %% FilterMap = fun
  301. %% %% Include all rows where the first column is < 10.
  302. %% ([A|_]) when A < 10 ->
  303. %% true;
  304. %% %% Exclude all rows where the first column is >= 10 and < 20.
  305. %% ([A|_]) when A < 20 ->
  306. %% false;
  307. %% %% For rows where the first column is >= 20 and < 30, include
  308. %% %% the atom 'foo' in place of the row instead.
  309. %% ([A|_]) when A < 30 ->
  310. %% {true, foo}};
  311. %% %% For rows where the first row is >= 30 and < 40, send the
  312. %% %% row to a gen_server via call (ie, wait for a response),
  313. %% %% and do not include the row in the result.
  314. %% (R=[A|_]) when A < 40 ->
  315. %% gen_server:call(Pid, R),
  316. %% false;
  317. %% %% For rows where the first column is >= 40 and < 50, send the
  318. %% %% row to a gen_server via cast (ie, do not wait for a reply),
  319. %% %% and include the row in the result, also.
  320. %% (R=[A|_]) when A < 50 ->
  321. %% gen_server:cast(Pid, R),
  322. %% true;
  323. %% %% Exclude all other rows from the result.
  324. %% (_) ->
  325. %% false
  326. %% end,
  327. %% query(Conn, Query, no_params, FilterMap, default_timeout).
  328. %% '''
  329. -spec query(Conn, Query, Params, FilterMap, Timeout) -> Result
  330. when Conn :: connection(),
  331. Query :: iodata(),
  332. Timeout :: default_timeout | timeout(),
  333. Params :: no_params | [term()],
  334. FilterMap :: no_filtermap_fun | query_filtermap_fun(),
  335. Result :: query_result().
  336. query(Conn, Query, no_params, FilterMap, Timeout) ->
  337. query_call(Conn, {query, Query, FilterMap, Timeout});
  338. query(Conn, Query, Params, FilterMap, Timeout) ->
  339. case mysql_protocol:valid_params(Params) of
  340. true ->
  341. query_call(Conn,
  342. {param_query, Query, Params, FilterMap, Timeout});
  343. false ->
  344. error(badarg)
  345. end.
  346. %% @doc Executes a prepared statement with the default query timeout as given
  347. %% to start_link/1.
  348. %% @see prepare/2
  349. %% @see prepare/3
  350. %% @see prepare/4
  351. %% @see execute/5
  352. -spec execute(Conn, StatementRef, Params) -> Result | {error, not_prepared}
  353. when Conn :: connection(),
  354. StatementRef :: atom() | integer(),
  355. Params :: [term()],
  356. Result :: query_result().
  357. execute(Conn, StatementRef, Params) ->
  358. execute(Conn, StatementRef, Params, no_filtermap_fun, default_timeout).
  359. %% @doc Executes a prepared statement.
  360. %% @see prepare/2
  361. %% @see prepare/3
  362. %% @see prepare/4
  363. %% @see execute/5
  364. -spec execute(Conn, StatementRef, Params, FilterMap | Timeout) ->
  365. Result | {error, not_prepared}
  366. when Conn :: connection(),
  367. StatementRef :: atom() | integer(),
  368. Params :: [term()],
  369. FilterMap :: no_filtermap_fun | query_filtermap_fun(),
  370. Timeout :: default_timeout | timeout(),
  371. Result :: query_result().
  372. execute(Conn, StatementRef, Params, Timeout) when Timeout == default_timeout;
  373. is_integer(Timeout);
  374. Timeout=:=infinity ->
  375. execute(Conn, StatementRef, Params, no_filtermap_fun, Timeout);
  376. execute(Conn, StatementRef, Params, FilterMap) when FilterMap == no_filtermap_fun;
  377. is_function(FilterMap, 1);
  378. is_function(FilterMap, 2) ->
  379. execute(Conn, StatementRef, Params, FilterMap, default_timeout).
  380. %% @doc Executes a prepared statement.
  381. %%
  382. %% The `FilterMap' and `Timeout' arguments are optional.
  383. %% <ul>
  384. %% <li>If the `FilterMap' argument is the atom `no_filtermap_fun' or is
  385. %% omitted, no row filtering/mapping will be applied and all result rows
  386. %% will be returned unchanged.</li>
  387. %% <li>If the `Timeout' argument is the atom `default_timeout' or is omitted,
  388. %% the timeout given in `start_link/1' is used.</li>
  389. %% </ul>
  390. %%
  391. %% See `query/5' for an explanation of the `FilterMap' argument.
  392. %%
  393. %% @see prepare/2
  394. %% @see prepare/3
  395. %% @see prepare/4
  396. %% @see query/5
  397. -spec execute(Conn, StatementRef, Params, FilterMap, Timeout) ->
  398. Result | {error, not_prepared}
  399. when Conn :: connection(),
  400. StatementRef :: atom() | integer(),
  401. Params :: [term()],
  402. FilterMap :: no_filtermap_fun | query_filtermap_fun(),
  403. Timeout :: default_timeout | timeout(),
  404. Result :: query_result().
  405. execute(Conn, StatementRef, Params, FilterMap, Timeout) ->
  406. case mysql_protocol:valid_params(Params) of
  407. true ->
  408. query_call(Conn,
  409. {execute, StatementRef, Params, FilterMap, Timeout});
  410. false ->
  411. error(badarg)
  412. end.
  413. %% @doc Creates a prepared statement from the passed query.
  414. %% @see prepare/3
  415. -spec prepare(Conn, Query) -> {ok, StatementId} | {error, Reason}
  416. when Conn :: connection(),
  417. Query :: iodata(),
  418. StatementId :: integer(),
  419. Reason :: server_reason().
  420. prepare(Conn, Query) ->
  421. gen_server:call(Conn, {prepare, Query}).
  422. %% @doc Creates a prepared statement from the passed query and associates it
  423. %% with the given name.
  424. %% @see prepare/2
  425. -spec prepare(Conn, Name, Query) -> {ok, Name} | {error, Reason}
  426. when Conn :: connection(),
  427. Name :: atom(),
  428. Query :: iodata(),
  429. Reason :: server_reason().
  430. prepare(Conn, Name, Query) ->
  431. gen_server:call(Conn, {prepare, Name, Query}).
  432. %% @doc Deallocates a prepared statement.
  433. -spec unprepare(Conn, StatementRef) -> ok | {error, Reason}
  434. when Conn :: connection(),
  435. StatementRef :: atom() | integer(),
  436. Reason :: server_reason() | not_prepared.
  437. unprepare(Conn, StatementRef) ->
  438. gen_server:call(Conn, {unprepare, StatementRef}).
  439. %% @doc Returns the number of warnings generated by the last query/2 or
  440. %% execute/3 calls.
  441. -spec warning_count(connection()) -> integer().
  442. warning_count(Conn) ->
  443. gen_server:call(Conn, warning_count).
  444. %% @doc Returns the number of inserted, updated and deleted rows of the last
  445. %% executed query or prepared statement. If found_rows is set on the
  446. %% connection, for update operation the return value will equal to the number
  447. %% of rows matched by the query.
  448. -spec affected_rows(connection()) -> integer().
  449. affected_rows(Conn) ->
  450. gen_server:call(Conn, affected_rows).
  451. %% @doc Returns true if auto-commit is enabled and false otherwise.
  452. -spec autocommit(connection()) -> boolean().
  453. autocommit(Conn) ->
  454. gen_server:call(Conn, autocommit).
  455. %% @doc Returns the last insert-id.
  456. -spec insert_id(connection()) -> integer().
  457. insert_id(Conn) ->
  458. gen_server:call(Conn, insert_id).
  459. %% @doc Returns true if the connection is in a transaction and false otherwise.
  460. %% This works regardless of whether the transaction has been started using
  461. %% transaction/2,3 or using a plain `mysql:query(Connection, "BEGIN")'.
  462. %% @see transaction/2
  463. %% @see transaction/4
  464. -spec in_transaction(connection()) -> boolean().
  465. in_transaction(Conn) ->
  466. gen_server:call(Conn, in_transaction).
  467. %% @doc This function executes the functional object Fun as a transaction.
  468. %% @see transaction/4
  469. -spec transaction(connection(), fun()) -> {atomic, term()} | {aborted, term()}.
  470. transaction(Conn, Fun) ->
  471. transaction(Conn, Fun, [], infinity).
  472. %% @doc This function executes the functional object Fun as a transaction.
  473. %% @see transaction/4
  474. -spec transaction(connection(), fun(), Retries) -> {atomic, term()} |
  475. {aborted, term()}
  476. when Retries :: non_neg_integer() | infinity.
  477. transaction(Conn, Fun, Retries) ->
  478. transaction(Conn, Fun, [], Retries).
  479. %% @doc This function executes the functional object Fun with arguments Args as
  480. %% a transaction.
  481. %%
  482. %% The semantics are as close as possible to mnesia's transactions. Transactions
  483. %% can be nested and are restarted automatically when deadlocks are detected.
  484. %% MySQL's savepoints are used to implement nested transactions.
  485. %%
  486. %% Fun must be a function and Args must be a list of the same length as the
  487. %% arity of Fun.
  488. %%
  489. %% If an exception occurs within Fun, the exception is caught and `{aborted,
  490. %% Reason}' is returned. The value of `Reason' depends on the class of the
  491. %% exception.
  492. %%
  493. %% Note that an error response from a query does not cause a transaction to be
  494. %% rollbacked. To force a rollback on a MySQL error you can trigger a `badmatch'
  495. %% using e.g. `ok = mysql:query(Pid, "SELECT some_non_existent_value")'. An
  496. %% exception to this is the error 1213 "Deadlock", after the specified number
  497. %% of retries, all failed. In this case, the transaction is aborted and the
  498. %% error is retured as the reason for the aborted transaction, along with a
  499. %% stacktrace pointing to where the last deadlock was detected. (In earlier
  500. %% versions, up to and including 1.3.2, transactions where automatically
  501. %% restarted also for the error 1205 "Lock wait timeout". This is no longer the
  502. %% case.)
  503. %%
  504. %% Some queries such as ALTER TABLE cause an *implicit commit* on the server.
  505. %% If such a query is executed within a transaction, an error on the form
  506. %% `{implicit_commit, Query}' is raised. This means that the transaction has
  507. %% been committed prematurely. This also happens if an explicit COMMIT is
  508. %% executed as a plain query within a managed transaction. (Don't do that!)
  509. %%
  510. %% <table>
  511. %% <thead>
  512. %% <tr><th>Class of exception</th><th>Return value</th></tr>
  513. %% </thead>
  514. %% <tbody>
  515. %% <tr>
  516. %% <td>`error' with reason `ErrorReason'</td>
  517. %% <td>`{aborted, {ErrorReason, Stack}}'</td>
  518. %% </tr>
  519. %% <tr><td>`exit(Term)'</td><td>`{aborted, Term}'</td></tr>
  520. %% <tr><td>`throw(Term)'</td><td>`{aborted, {throw, Term}}'</td></tr>
  521. %% </tbody>
  522. %% </table>
  523. -spec transaction(connection(), fun(), list(), Retries) -> {atomic, term()} |
  524. {aborted, term()}
  525. when Retries :: non_neg_integer() | infinity.
  526. transaction(Conn, Fun, Args, Retries) when is_list(Args),
  527. is_function(Fun, length(Args)) ->
  528. %% The guard makes sure that we can apply Fun to Args. Any error we catch
  529. %% in the try-catch are actual errors that occurred in Fun.
  530. ok = gen_server:call(Conn, start_transaction, infinity),
  531. execute_transaction(Conn, Fun, Args, Retries).
  532. %% @private
  533. %% @doc This is a helper for transaction/2,3,4. It performs everything except
  534. %% executing the BEGIN statement. It is called recursively when a transaction
  535. %% is retried.
  536. %%
  537. %% "When a transaction rollback occurs due to a deadlock or lock wait timeout,
  538. %% it cancels the effect of the statements within the transaction. But if the
  539. %% start-transaction statement was START TRANSACTION or BEGIN statement,
  540. %% rollback does not cancel that statement."
  541. %% (https://dev.mysql.com/doc/refman/5.6/en/innodb-error-handling.html)
  542. %%
  543. %% Lock Wait Timeout:
  544. %% "InnoDB rolls back only the last statement on a transaction timeout by
  545. %% default. If --innodb_rollback_on_timeout is specified, a transaction timeout
  546. %% causes InnoDB to abort and roll back the entire transaction (the same
  547. %% behavior as in MySQL 4.1)."
  548. %% (https://dev.mysql.com/doc/refman/5.6/en/innodb-parameters.html)
  549. execute_transaction(Conn, Fun, Args, Retries) ->
  550. try apply(Fun, Args) of
  551. ResultOfFun ->
  552. ok = gen_server:call(Conn, commit, infinity),
  553. {atomic, ResultOfFun}
  554. catch
  555. %% We are at the top level, try to restart the transaction if there are
  556. %% retries left
  557. ?EXCEPTION(throw, {implicit_rollback, 1, _}, _Stacktrace)
  558. when Retries == infinity ->
  559. execute_transaction(Conn, Fun, Args, infinity);
  560. ?EXCEPTION(throw, {implicit_rollback, 1, _}, _Stacktrace)
  561. when Retries > 0 ->
  562. execute_transaction(Conn, Fun, Args, Retries - 1);
  563. ?EXCEPTION(throw, {implicit_rollback, 1, Reason}, Stacktrace)
  564. when Retries == 0 ->
  565. %% No more retries. Return 'aborted' along with the deadlock error
  566. %% and a the trace to the line where the deadlock occured.
  567. Trace = ?GET_STACK(Stacktrace),
  568. ok = gen_server:call(Conn, rollback, infinity),
  569. {aborted, {Reason, Trace}};
  570. ?EXCEPTION(throw, {implicit_rollback, N, Reason}, Stacktrace)
  571. when N > 1 ->
  572. %% Nested transaction. Bubble out to the outermost level.
  573. erlang:raise(throw, {implicit_rollback, N - 1, Reason},
  574. ?GET_STACK(Stacktrace));
  575. ?EXCEPTION(error, {implicit_commit, _Query} = E, Stacktrace) ->
  576. %% The called did something like ALTER TABLE which resulted in an
  577. %% implicit commit. The server has already committed. We need to
  578. %% jump out of N levels of transactions.
  579. %%
  580. %% Returning 'atomic' or 'aborted' would both be wrong. Raise an
  581. %% exception is the best we can do.
  582. erlang:raise(error, E, ?GET_STACK(Stacktrace));
  583. ?EXCEPTION(error, change_user_in_transaction = E, Stacktrace) ->
  584. %% The called tried to change user inside the transaction, which
  585. %% is not allowed and a serious mistake. We roll back and raise
  586. %% an error.
  587. ok = gen_server:call(Conn, rollback, infinity),
  588. erlang:raise(error, E, ?GET_STACK(Stacktrace));
  589. ?EXCEPTION(Class, Reason, Stacktrace) ->
  590. %% We must be able to rollback. Otherwise let's crash.
  591. ok = gen_server:call(Conn, rollback, infinity),
  592. %% These forms for throw, error and exit mirror Mnesia's behaviour.
  593. Aborted = case Class of
  594. throw -> {throw, Reason};
  595. error -> {Reason, ?GET_STACK(Stacktrace)};
  596. exit -> Reason
  597. end,
  598. {aborted, Aborted}
  599. end.
  600. %% @doc Equivalent to `change_user(Conn, Username, Password, [])'.
  601. %% @see change_user/4
  602. -spec change_user(Conn, Username, Password) -> Result
  603. when Conn :: connection(),
  604. Username :: iodata(),
  605. Password :: iodata(),
  606. Result :: ok.
  607. change_user(Conn, Username, Password) ->
  608. change_user(Conn, Username, Password, []).
  609. %% @doc Changes the user of the active connection without closing and
  610. %% and re-opening it. The currently active session will be reset (ie,
  611. %% user variables, temporary tables, prepared statements, etc will
  612. %% be lost) independent of whether the operation succeeds or fails.
  613. %%
  614. %% If change user is called when a transaction is active (ie, neither
  615. %% committed nor rolled back), calling `change_user' will fail with
  616. %% an error exception and `change_user_in_transaction' as the error
  617. %% message.
  618. %%
  619. %% If the change user operation fails, `{error, Reason}' will be
  620. %% returned. Specifically, if the operation itself fails (eg
  621. %% authentication failure), `change_user_failed' will be returned as
  622. %% the reason, while if the operation itself succeeds but one of
  623. %% the given initial queries or prepares fails, the reason will
  624. %% reflect the cause for the failure. In any case, the connection
  625. %% process will exit with the same reason and cannot be used any longer.
  626. %%
  627. %% For a description of the `database', `queries' and `prepare'
  628. %% options, see `start_link/1'.
  629. %%
  630. %% @see start_link/1
  631. -spec change_user(Conn, Username, Password, Options) -> Result
  632. when Conn :: connection(),
  633. Username :: iodata(),
  634. Password :: iodata(),
  635. Options :: [Option],
  636. Result :: ok,
  637. Option :: {database, iodata()}
  638. | {queries, [iodata()]}
  639. | {prepare, [NamedStatement]},
  640. NamedStatement :: {StatementName :: atom(), Statement :: iodata()}.
  641. change_user(Conn, Username, Password, Options) ->
  642. case in_transaction(Conn) of
  643. true -> error(change_user_in_transaction);
  644. false -> ok
  645. end,
  646. gen_server:call(Conn, {change_user, Username, Password, Options}).
  647. %% @doc Encodes a term as a MySQL literal so that it can be used to inside a
  648. %% query. If backslash escapes are enabled, backslashes and single quotes in
  649. %% strings and binaries are escaped. Otherwise only single quotes are escaped.
  650. %%
  651. %% Note that the preferred way of sending values is by prepared statements or
  652. %% parametrized queries with placeholders.
  653. %%
  654. %% @see query/3
  655. %% @see execute/3
  656. -spec encode(connection(), term()) -> iodata().
  657. encode(Conn, Term) ->
  658. Term1 = case (is_list(Term) orelse is_binary(Term)) andalso
  659. gen_server:call(Conn, backslash_escapes_enabled) of
  660. true -> mysql_encode:backslash_escape(Term);
  661. false -> Term
  662. end,
  663. mysql_encode:encode(Term1).
  664. %% --- Helpers ---
  665. %% @doc Makes a gen_server call for a query (plain, parametrized or prepared),
  666. %% checks the reply and sometimes throws an exception when we need to jump out
  667. %% of a transaction.
  668. query_call(Conn, CallReq) ->
  669. case gen_server:call(Conn, CallReq, infinity) of
  670. {implicit_commit, _NestingLevel, Query} ->
  671. error({implicit_commit, Query});
  672. {implicit_rollback, _NestingLevel, _ServerReason} = ImplicitRollback ->
  673. throw(ImplicitRollback);
  674. Result ->
  675. Result
  676. end.