MySQL client.
Theconnection()
type is a gen_server reference as described in the
documentation for gen_server:call/2,3
, e.g. the pid or the name if the
gen_server is locally registered.
column_names() = [binary()]
connection() = atom() | {Name::atom(), Node::atom()} | {global, GlobalName::term()} | {via, Module::atom(), ViaName::term()} | pid()
query_filtermap_fun() = fun((row()) -> query_filtermap_res()) | fun((column_names(), row()) -> query_filtermap_res())
query_filtermap_res() = boolean() | {true, term()}
query_result() = ok | {ok, column_names(), rows()} | {ok, [{column_names(), rows()}, ...]} | {error, server_reason()}
row() = [term()]
rows() = [row()]
server_reason() = {Code::integer(), SQLState::binary() | undefined, Message::binary()}
affected_rows/1 | Returns the number of inserted, updated and deleted rows of the last executed query or prepared statement. |
autocommit/1 | Returns true if auto-commit is enabled and false otherwise. |
change_user/3 | Equivalent to change_user(Conn, Username, Password, []) . |
change_user/4 | Changes the user of the active connection without closing and and re-opening it. |
encode/2 | Encodes a term as a MySQL literal so that it can be used to inside a query. |
execute/3 | Executes a prepared statement with the default query timeout as given to start_link/1. |
execute/4 | Executes a prepared statement. |
execute/5 | Executes a prepared statement. |
in_transaction/1 | Returns true if the connection is in a transaction and false otherwise. |
insert_id/1 | Returns the last insert-id. |
prepare/2 | Creates a prepared statement from the passed query. |
prepare/3 | Creates a prepared statement from the passed query and associates it with the given name. |
query/2 | |
query/3 | |
query/4 | |
query/5 | Executes a parameterized query with a timeout and applies a filter/map function to the result rows. |
start_link/1 | Starts a connection gen_server process and connects to a database. |
stop/1 | |
stop/2 | Stops a connection process and closes the connection. |
transaction/2 | This function executes the functional object Fun as a transaction. |
transaction/3 | This function executes the functional object Fun as a transaction. |
transaction/4 | This function executes the functional object Fun with arguments Args as a transaction. |
unprepare/2 | Deallocates a prepared statement. |
warning_count/1 | Returns the number of warnings generated by the last query/2 or execute/3 calls. |
affected_rows(Conn::connection()) -> integer()
Returns the number of inserted, updated and deleted rows of the last executed query or prepared statement. If found_rows is set on the connection, for update operation the return value will equal to the number of rows matched by the query.
autocommit(Conn::connection()) -> boolean()
Returns true if auto-commit is enabled and false otherwise.
change_user(Conn, Username, Password) -> Result
Equivalent to change_user(Conn, Username, Password, [])
.
See also: change_user/4.
change_user(Conn, Username, Password, Options) -> Result
Changes the user of the active connection without closing and and re-opening it. The currently active session will be reset (ie, user variables, temporary tables, prepared statements, etc will be lost) independent of whether the operation succeeds or fails.
If change user is called when a transaction is active (ie, neither
committed nor rolled back), calling change_user
will fail with
an error exception and change_user_in_transaction
as the error
message.
If the change user operation fails for other reasons (eg authentication
failure), an error exception occurs, and the connection process
exits with reason change_user_failed
. The connection can not be used
any longer if this happens.
database
, queries
and prepare
options, see start_link/1
.
See also: start_link/1.
encode(Conn::connection(), Term::term()) -> iodata()
Encodes a term as a MySQL literal so that it can be used to inside a query. If backslash escapes are enabled, backslashes and single quotes in strings and binaries are escaped. Otherwise only single quotes are escaped.
Note that the preferred way of sending values is by prepared statements or parametrized queries with placeholders.execute(Conn, StatementRef, Params) -> Result | {error, not_prepared}
Executes a prepared statement with the default query timeout as given to start_link/1.
See also: execute/5, prepare/2, prepare/3, prepare/4.
execute(Conn, StatementRef, Params, Timeout::FilterMap | Timeout) -> Result | {error, not_prepared}
Executes a prepared statement.
See also: execute/5, prepare/2, prepare/3, prepare/4.
execute(Conn, StatementRef, Params, FilterMap, Timeout) -> Result | {error, not_prepared}
Executes a prepared statement.
TheFilterMap
and Timeout
arguments are optional.
FilterMap
argument is the atom no_filtermap_fun
or is
omitted, no row filtering/mapping will be applied and all result rows
will be returned unchanged.Timeout
argument is the atom default_timeout
or is omitted,
the timeout given in start_link/1
is used.query/5
for an explanation of the FilterMap
argument.
See also: prepare/2, prepare/3, prepare/4, query/5.
in_transaction(Conn::connection()) -> boolean()
Returns true if the connection is in a transaction and false otherwise.
This works regardless of whether the transaction has been started using
transaction/2,3 or using a plain mysql:query(Connection, "BEGIN")
.
See also: transaction/2, transaction/4.
insert_id(Conn::connection()) -> integer()
Returns the last insert-id.
prepare(Conn, Query) -> {ok, StatementId} | {error, Reason}
Creates a prepared statement from the passed query.
See also: prepare/3.
prepare(Conn, Name, Query) -> {ok, Name} | {error, Reason}
Creates a prepared statement from the passed query and associates it with the given name.
See also: prepare/2.
query(Conn, Query) -> Result
See also: query/5.
query(Conn, Query, Params::Params | FilterMap | Timeout) -> Result
See also: query/5.
query(Conn, Query, Params, Timeout) -> Result
See also: query/5.
query(Conn, Query, Params, FilterMap, Timeout) -> Result
Executes a parameterized query with a timeout and applies a filter/map function to the result rows.
A prepared statement is created, executed and then cached for a certain time. If the same query is executed again when it is already cached, it does not need to be prepared again.
The minimum time the prepared statement is cached can be specified using the
option {query_cache_time, Milliseconds}
to start_link/1.
Results are returned in the form {ok, ColumnNames, Rows}
if there is one
result set. If there are more than one result sets, they are returned in the
form {ok, [{ColumnNames, Rows}, ...]}
.
For queries that don't return any rows (INSERT, UPDATE, etc.) only the atom
ok
is returned.
Params
, FilterMap
and Timeout
arguments are optional.
Params
argument is the atom no_params
or is omitted, a plain
query will be executed instead of a parameterized one.FilterMap
argument is the atom no_filtermap_fun
or is
omitted, no row filtering/mapping will be applied and all result rows
will be returned unchanged.Timeout
argument is the atom default_timeout
or is omitted,
the timeout given in start_link/1
is used.If the FilterMap
argument is used, it must be a function of arity 1 or 2
that returns either true
, false
, or {true, Value}
.
Each result row is handed to the given function as soon as it is received
from the server, and only when the function has returned, the next row is
fetched. This provides the ability to prevent memory exhaustion; on the
other hand, it can cause the server to time out on sending if your function
is doing something slow (see the MySQL documentation on NET_WRITE_TIMEOUT
).
If the function is of arity 1, only the row is passed to it as the single argument, while if the function is of arity 2, the column names are passed in as the first argument and the row as the second.
The value returned is then used to decide if the row is to be included in
the result(s) returned from the query
call (filtering), or if something
else is to be included in the result instead (mapping). You may also use
this function for side effects, like writing rows to disk or sending them
to another process etc.
Query = "SELECT a, b, c FROM foo", FilterMap = fun %% Include all rows where the first column is < 10. ([A|_]) when A < 10 -> true; %% Exclude all rows where the first column is >= 10 and < 20. ([A|_]) when A < 20 -> false; %% For rows where the first column is >= 20 and < 30, include %% the atom 'foo' in place of the row instead. ([A|_]) when A < 30 -> {true, foo}}; %% For rows where the first row is >= 30 and < 40, send the %% row to a gen_server via call (ie, wait for a response), %% and do not include the row in the result. (R=[A|_]) when A < 40 -> gen_server:call(Pid, R), false; %% For rows where the first column is >= 40 and < 50, send the %% row to a gen_server via cast (ie, do not wait for a reply), %% and include the row in the result, also. (R=[A|_]) when A < 50 -> gen_server:cast(Pid, R), true; %% Exclude all other rows from the result. (_) -> false end, query(Conn, Query, no_params, FilterMap, default_timeout).
start_link(Options) -> {ok, pid()} | ignore | {error, term()}
Starts a connection gen_server process and connects to a database. To
disconnect just do exit(Pid, normal)
.
Options:
{name, ServerName}
{host, Host}
{local, SocketFile}
. Default "localhost"
.{port, Port}
{user, User}
{password, Password}
{database, Database}
USE <database>
.{connect_timeout, Timeout}
{log_warnings, boolean()}
{keep_alive, boolean() | timeout()}
true
,
false
and integer() > 0
for an explicit interval in milliseconds.
The default is false
. For true
a default ping timeout is used.
{prepare, NamedStatements}
{queries, Queries}
{query_timeout, Timeout}
query/3,4
and
execute/4
. The default is infinity
.{found_rows, boolean()}
{query_cache_time, Timeout}
{tcp_options, Options}
gen_tcp:connect/3
. You may want to set
{recbuf, Size}
and {sndbuf, Size}
if you send or receive more than
the default (typically 8K) per query.stop(Conn) -> ok
See also: stop/2.
stop(Conn, Timeout) -> ok
Stops a connection process and closes the connection. The
process calling stop
will be blocked until the connection
process stops or the given timeout expires.
If the connection is not stopped within the given timeout,
an exit exception is raised with reason timeout
.
normal
,
an exit exception is raised with that reason.
transaction(Conn::connection(), Fun::function()) -> {atomic, term()} | {aborted, term()}
This function executes the functional object Fun as a transaction.
See also: transaction/4.
transaction(Conn::connection(), Fun::function(), Retries) -> {atomic, term()} | {aborted, term()}
This function executes the functional object Fun as a transaction.
See also: transaction/4.
transaction(Conn::connection(), Fun::function(), Args::list(), Retries) -> {atomic, term()} | {aborted, term()}
This function executes the functional object Fun with arguments Args as a transaction.
The semantics are as close as possible to mnesia's transactions. Transactions can be nested and are restarted automatically when deadlocks are detected. MySQL's savepoints are used to implement nested transactions.
Fun must be a function and Args must be a list of the same length as the arity of Fun.
If an exception occurs within Fun, the exception is caught and {aborted,
Reason}
is returned. The value of Reason
depends on the class of the
exception.
Note that an error response from a query does not cause a transaction to be
rollbacked. To force a rollback on a MySQL error you can trigger a badmatch
using e.g. ok = mysql:query(Pid, "SELECT some_non_existent_value")
. An
exception to this is the error 1213 "Deadlock", after the specified number
of retries, all failed. In this case, the transaction is aborted and the
error is retured as the reason for the aborted transaction, along with a
stacktrace pointing to where the last deadlock was detected. (In earlier
versions, up to and including 1.3.2, transactions where automatically
restarted also for the error 1205 "Lock wait timeout". This is no longer the
case.)
Some queries such as ALTER TABLE cause an *implicit commit* on the server.
If such a query is executed within a transaction, an error on the form
{implicit_commit, Query}
is raised. This means that the transaction has
been committed prematurely. This also happens if an explicit COMMIT is
executed as a plain query within a managed transaction. (Don't do that!)
Class of exception | Return value |
---|---|
error with reason ErrorReason |
{aborted, {ErrorReason, Stack}} |
exit(Term) | {aborted, Term} |
throw(Term) | {aborted, {throw, Term}} |
unprepare(Conn, StatementRef) -> ok | {error, Reason}
Deallocates a prepared statement.
warning_count(Conn::connection()) -> integer()
Returns the number of warnings generated by the last query/2 or execute/3 calls.
Generated by EDoc