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_name() = binary()
connection() = atom() | {Name::atom(), Node::atom()} | {global, GlobalName::term()} | {via, Module::atom(), ViaName::term()} | pid()
option() = {name, ServerName::server_name()} | {host, inet:socket_address() | inet:hostname()} | {port, integer()} | {user, iodata()} | {password, iodata()} | {database, iodata()} | {connect_mode, synchronous | asynchronous | lazy} | {connect_timeout, timeout()} | {allowed_local_paths, [binary()]} | {log_warnings, boolean()} | {log_slow_queries, boolean()} | {keep_alive, boolean() | timeout()} | {prepare, [{StatementName::statement_name(), Statement::query()}]} | {queries, [query()]} | {query_timeout, timeout()} | {found_rows, boolean()} | {query_cache_time, non_neg_integer()} | {tcp_options, [gen_tcp:connect_option()]} | {ssl, term()}
query() = iodata()
query_filtermap_fun() = fun((row()) -> query_filtermap_res()) | fun(([column_name()], row()) -> query_filtermap_res())
query_filtermap_res() = boolean() | {true, term()}
query_param() = term()
query_result() = ok | {ok, [column_name()], [row()]} | {ok, [{[column_name()], [row()]}, ...]} | {error, server_reason()}
row() = [term()]
server_name() = {local, Name::atom()} | {global, GlobalName::term()} | {via, Via::module(), ViaName::term()}
server_reason() = {Code::integer(), SQLState::binary() | undefined, Message::binary()}
statement_id() = integer()
statement_name() = atom()
statement_ref() = statement_id() | statement_name()
transaction_result(Result) = {atomic, Result} | {aborted, Reason::term()}
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 | Executes a plain query. |
query/3 | Executes a query. |
query/4 | Executes a query. |
query/5 | Executes a query. |
reset_connection/1 | |
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, {error, Reason}
will be
returned. Specifically, if the operation itself fails (eg
authentication failure), change_user_failed
will be returned as
the reason, while if the operation itself succeeds but one of
the given initial queries or prepares fails, the reason will
reflect the cause for the failure. In any case, the connection
process will exit with the same reason and cannot be used any longer.
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.
Executes a plain query.
See also: query/5.
query(Conn, Query, Params::Params | FilterMap | Timeout) -> Result
Executes a query.
See also: query/5.
query(Conn, Query, Params, Timeout) -> Result
query(Conn, Query, FilterMap, Timeout) -> Result
query(Conn, Query, Params, FilterMap) -> Result
Executes a query.
See also: query/5.
query(Conn, Query, Params, FilterMap, Timeout) -> Result
Executes a query.
Conn
is identifying a connection process started using
mysql:start_link/1
.
Query
is the query to execute, as a binary or a list.
Params
, FilterMap
and Timeout
are optional.
If Params
(a list) is specified, the query is performed as a prepared
statement. A prepared statement is created, executed and then cached for a
certain time (specified using the option {query_cache_time, Milliseconds}
to start_link/1
). If the same query is executed again during this time,
it does not need to be prepared again. If Params
is omitted, the query
is executed as a plain query. To force a query without parameters to be
executed as a prepared statement, an empty list can be used for Params
.
If FilterMap
(a fun) is specified, the function is applied to each row to
filter or perform other actions on the rows, in a way similar to how
lists:filtermap/2
works, before the result is returned to the caller. See
below for details.
Timeout
specifies the time to wait for a response from the database. If
omitted, the timeout given in start_link/1
is used.
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}, ...]}
. This is typically the case if
multiple queries are specified at the same time, separated by semicolons.
For queries that don't return any rows (INSERT, UPDATE, etc.) only the atom
ok
is returned.
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, FilterMap).
start_link(Options::[option()]) -> {ok, pid()} | ignore | {error, term()}
Starts a connection gen_server process and connects to a database. To
disconnect use mysql:stop/1,2
.
Options:
{name, ServerName}
{host, Host}
{local, SocketFile}
. Default "localhost"
.{port, Port}
{user, User}
{password, Password}
{database, Database}
USE <database>
.{connect_mode, synchronous | asynchronous | lazy}
synchronous
(default)asynchronous
lazy
asynchronous
mode, but an actual connection will be
established and the on-connect prepares and queries executed only
when a connection is needed for the first time, eg. to execute a
query.{connect_timeout, Timeout}
{allowed_local_paths, [binary()]}
LOAD DATA LOCAL INFILE
query. Only absolute paths
without relative components such as ..
and .
are allowed.
The default is an empty list, meaning the client will not send any
local files to the server.{log_warnings, boolean()}
{log_slow_queries, boolean()}
long_query_time
variable.{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.{ssl, Options}
ssl:connect/3
.verify
option, if not given explicitly, defaults to
verify_peer
.server_name_indication
option, if omitted, defaults to the value
of the host
option if it is a hostname string, otherwise no default
value is set.See also: stop/2.
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, TransactionFun) -> TransactionResult
This function executes the functional object Fun as a transaction.
See also: transaction/4.
transaction(Conn, TransactionFun, Retries) -> TransactionResult
This function executes the functional object Fun as a transaction.
See also: transaction/4.
transaction(Conn, TransactionFun, Args, Retries) -> TransactionResult
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