mysql.erl 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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 API for communicating with MySQL databases.
  19. %%
  20. %% Most of the functions are wrappers for `gen_server' calls. The
  21. %% `connection()' type is the same as returned by `gen_server:start_link/2,3'.
  22. -module(mysql).
  23. -export([start_link/1, query/2, execute/3, prepare/2, warning_count/1,
  24. affected_rows/1, autocommit/1, insert_id/1, in_transaction/1,
  25. transaction/2, transaction/3]).
  26. -export_type([connection/0]).
  27. %% A connection is a ServerRef as in gen_server:call/2,3.
  28. -type connection() :: Name :: atom() |
  29. {Name :: atom(), Node :: atom()} |
  30. {global, GlobalName :: term()} |
  31. {via, Module :: atom(), ViaName :: term()} |
  32. pid().
  33. %% MySQL error with the codes and message returned from the server.
  34. -type reason() :: {Code :: integer(), SQLState :: binary(),
  35. Message :: binary()}.
  36. %% @doc Starts a connection gen_server process and connects to a database. To
  37. %% disconnect just do `exit(Pid, normal)'.
  38. %%
  39. %% This is just a wrapper for `gen_server:start_link(mysql_connection, Options,
  40. %% [])'. If you need to specify gen_server options, use gen_server:start_link/3
  41. %% directly.
  42. -spec start_link(Options) -> {ok, pid()} | ignore | {error, term()}
  43. when Options :: [Option],
  44. Option :: {host, iodata()} | {port, integer()} | {user, iodata()} |
  45. {password, iodata()} | {database, iodata()}.
  46. start_link(Opts) ->
  47. gen_server:start_link(mysql_connection, Opts, []).
  48. %% @doc Executes a query.
  49. -spec query(Conn, Query) -> ok | {ok, ColumnNames, Rows} | {error, Reason}
  50. when Conn :: connection(),
  51. Query :: iodata(),
  52. ColumnNames :: [binary()],
  53. Rows :: [[term()]],
  54. Reason :: reason().
  55. query(Conn, Query) ->
  56. gen_server:call(Conn, {query, Query}).
  57. %% @doc Executes a prepared statement.
  58. %% @see prepare/2
  59. execute(Conn, StatementId, Args) ->
  60. gen_server:call(Conn, {execute, StatementId, Args}).
  61. %% @doc Creates a prepared statement from the passed query.
  62. %% @see execute/3
  63. -spec prepare(Conn :: connection(), Query :: iodata()) ->
  64. {ok, StatementId :: integer()} | {error, Reason :: reason()}.
  65. prepare(Conn, Query) ->
  66. gen_server:call(Conn, {prepare, Query}).
  67. %% @doc Returns the number of warnings generated by the last query/2 or
  68. %% execute/3 calls.
  69. -spec warning_count(connection()) -> integer().
  70. warning_count(Conn) ->
  71. gen_server:call(Conn, warning_count).
  72. %% @doc Returns the number of inserted, updated and deleted rows of the last
  73. %% executed query or prepared statement.
  74. -spec affected_rows(connection()) -> integer().
  75. affected_rows(Conn) ->
  76. gen_server:call(Conn, affected_rows).
  77. %% @doc Returns true if auto-commit is enabled and false otherwise.
  78. -spec autocommit(connection()) -> boolean().
  79. autocommit(Conn) ->
  80. gen_server:call(Conn, autocommit).
  81. %% @doc Returns the last insert-id.
  82. -spec insert_id(connection()) -> integer().
  83. insert_id(Conn) ->
  84. gen_server:call(Conn, insert_id).
  85. %% @doc Returns true if the connection is in a transaction and false otherwise.
  86. %% This works regardless of whether the transaction has been started using
  87. %% transaction/2,3 or using a plain `mysql:query(Connection, "START
  88. %% TRANSACTION")'.
  89. %% @see transaction/2
  90. %% @see transaction/3
  91. -spec in_transaction(connection()) -> boolean().
  92. in_transaction(Conn) ->
  93. gen_server:call(Conn, in_transaction).
  94. %% @doc This function executes the functional object Fun as a transaction.
  95. %% @see transaction/3
  96. %% @see in_transaction/1
  97. -spec transaction(connection(), fun()) -> {atomic, term()} | {aborted, term()}.
  98. transaction(Conn, Fun) ->
  99. transaction(Conn, Fun, []).
  100. %% @doc This function executes the functional object Fun with arguments Args as
  101. %% a transaction.
  102. %%
  103. %% The semantics are the same as for mnesia's transactions.
  104. %%
  105. %% The Fun must be a function and Args must be a list with the same length
  106. %% as the arity of Fun.
  107. %%
  108. %% Current limitations:
  109. %%
  110. %% <ul>
  111. %% <li>Transactions cannot be nested</li>
  112. %% <li>They are not automatically restarted when deadlocks are detected.</li>
  113. %% </ul>
  114. %%
  115. %% If an exception occurs within Fun, the exception is caught and `{aborted,
  116. %% Reason}' is returned. The value of `Reason' depends on the class of the
  117. %% exception.
  118. %%
  119. %% <table>
  120. %% <thead>
  121. %% <tr><th>Class of exception</th><th>Return value</th></tr>
  122. %% </thead>
  123. %% <tbody>
  124. %% <tr>
  125. %% <td>`error' with reason `ErrorReason'</td>
  126. %% <td>`{aborted, {ErrorReason, Stack}}'</td>
  127. %% </tr>
  128. %% <tr><td>`exit(Term)'</td><td>`{aborted, Term}'</td></tr>
  129. %% <tr><td>`throw(Term)'</td><td>`{aborted, {throw, Term}}'</td></tr>
  130. %% </tbody>
  131. %% </table>
  132. %%
  133. %% TODO: Implement nested transactions
  134. %% TODO: Automatic restart on deadlocks
  135. %% @see in_transaction/1
  136. -spec transaction(connection(), fun(), list()) -> {atomic, term()} |
  137. {aborted, term()}.
  138. transaction(Conn, Fun, Args) when is_list(Args),
  139. is_function(Fun, length(Args)) ->
  140. %% The guard makes sure that we can apply Fun to Args. Any error we catch
  141. %% in the try-catch are actual errors that occurred in Fun.
  142. ok = query(Conn, <<"BEGIN">>),
  143. try apply(Fun, Args) of
  144. ResultOfFun ->
  145. %% We must be able to rollback. Otherwise let's go mad.
  146. ok = query(Conn, <<"COMMIT">>),
  147. {atomic, ResultOfFun}
  148. catch
  149. Class:Reason ->
  150. %% We must be able to rollback. Otherwise let's go mad.
  151. ok = query(Conn, <<"ROLLBACK">>),
  152. %% These forms for throw, error and exit mirror Mnesia's behaviour.
  153. Aborted = case Class of
  154. throw -> {throw, Reason};
  155. error -> {Reason, erlang:get_stacktrace()};
  156. exit -> Reason
  157. end,
  158. {aborted, Aborted}
  159. end.