mysql.erl 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. %% MySQL/OTP – a MySQL driver for Erlang/OTP
  2. %% Copyright (C) 2014 Viktor Söderqvist
  3. %%
  4. %% This program is free software: you can redistribute it and/or modify
  5. %% it under the terms of the GNU General Public License as published by
  6. %% the Free Software Foundation, either version 3 of the License, or
  7. %% (at your option) any later version.
  8. %%
  9. %% This program is distributed in the hope that it will be useful,
  10. %% but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. %% GNU General Public License for more details.
  13. %%
  14. %% You should have received a copy of the GNU General Public License
  15. %% along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. %% @doc MySQL/OTP
  17. -module(mysql).
  18. -export([connect/1, disconnect/1, query/2, query/3, prepare/2, warning_count/1,
  19. affected_rows/1, insert_id/1]).
  20. %% MySQL error with the codes and message returned from the server.
  21. -type reason() :: {Code :: integer(), SQLState :: binary(),
  22. Message :: binary()}.
  23. -spec connect(list()) -> {ok, pid()} | ignore | {error, term()}.
  24. connect(Opts) ->
  25. gen_server:start_link(mysql_connection, Opts, []).
  26. -spec disconnect(pid()) -> ok.
  27. disconnect(Conn) ->
  28. exit(Conn, normal),
  29. ok.
  30. -spec query(Conn, Query) -> ok | {ok, Fields, Rows} | {error, Reason}
  31. when Conn :: pid(),
  32. Query :: iodata(),
  33. Fields :: [binary()],
  34. Rows :: [[term()]],
  35. Reason :: reason().
  36. query(Conn, Query) ->
  37. gen_server:call(Conn, {query, Query}).
  38. %% @doc Executes a prepared statement.
  39. query(Conn, StatementId, Args) ->
  40. gen_server:call(Conn, {query, StatementId, Args}).
  41. -spec prepare(Conn :: pid(), Query :: iodata()) ->
  42. {ok, StatementId :: integer()} | {error, Reason :: reason()}.
  43. prepare(Conn, Query) ->
  44. gen_server:call(Conn, {prepare, Query}).
  45. -spec warning_count(pid()) -> integer().
  46. warning_count(Conn) ->
  47. gen_server:call(Conn, warning_count).
  48. -spec affected_rows(pid()) -> integer().
  49. affected_rows(Conn) ->
  50. gen_server:call(Conn, affected_rows).
  51. -spec insert_id(pid()) -> integer().
  52. insert_id(Conn) ->
  53. gen_server:call(Conn, insert_id).