123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977 |
- -module(mysql).
- -export([start_link/1, query/2, query/3, query/4, execute/3, execute/4,
- prepare/2, prepare/3, unprepare/2,
- warning_count/1, affected_rows/1, autocommit/1, insert_id/1,
- encode/2, in_transaction/1,
- transaction/2, transaction/3, transaction/4]).
- -export_type([connection/0, server_reason/0, query_result/0]).
- -behaviour(gen_server).
- -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
- code_change/3]).
- -define(default_host, "localhost").
- -define(default_port, 3306).
- -define(default_user, <<>>).
- -define(default_password, <<>>).
- -define(default_connect_timeout, 5000).
- -define(default_query_timeout, infinity).
- -define(default_query_cache_time, 60000).
- -define(default_ping_timeout, 60000).
- -define(cmd_timeout, 3000).
- -define(ERROR_DEADLOCK, 1213).
- -type connection() :: Name :: atom() |
- {Name :: atom(), Node :: atom()} |
- {global, GlobalName :: term()} |
- {via, Module :: atom(), ViaName :: term()} |
- pid().
- -type server_reason() :: {Code :: integer(), SQLState :: binary(),
- Message :: binary()}.
- -type column_names() :: [binary()].
- -type rows() :: [[term()]].
- -type query_result() :: ok
- | {ok, column_names(), rows()}
- | {ok, [{column_names(), rows()}, ...]}
- | {error, server_reason()}.
- -include("exception.hrl").
- -spec start_link(Options) -> {ok, pid()} | ignore | {error, term()}
- when Options :: [Option],
- Option :: {name, ServerName} |
- {host, inet:socket_address() | inet:hostname()} | {port, integer()} |
- {user, iodata()} | {password, iodata()} |
- {database, iodata()} |
- {connect_timeout, timeout()} |
- {log_warnings, boolean()} |
- {keep_alive, boolean() | timeout()} |
- {prepare, NamedStatements} |
- {queries, [iodata()]} |
- {query_timeout, timeout()} |
- {found_rows, boolean()} |
- {query_cache_time, non_neg_integer()},
- ServerName :: {local, Name :: atom()} |
- {global, GlobalName :: term()} |
- {via, Module :: atom(), ViaName :: term()},
- NamedStatements :: [{StatementName :: atom(), Statement :: iodata()}].
- start_link(Options) ->
- GenSrvOpts = [{timeout, proplists:get_value(connect_timeout, Options,
- ?default_connect_timeout)}],
- Ret = case proplists:get_value(name, Options) of
- undefined ->
- gen_server:start_link(?MODULE, Options, GenSrvOpts);
- ServerName ->
- gen_server:start_link(ServerName, ?MODULE, Options, GenSrvOpts)
- end,
- case Ret of
- {ok, Pid} ->
-
- Queries = proplists:get_value(queries, Options, []),
- lists:foreach(fun (Query) ->
- case mysql:query(Pid, Query) of
- ok -> ok;
- {ok, _, _} -> ok;
- {ok, _} -> ok
- end
- end,
- Queries),
-
- Prepare = proplists:get_value(prepare, Options, []),
- lists:foreach(fun ({Name, Stmt}) ->
- {ok, Name} = mysql:prepare(Pid, Name, Stmt)
- end,
- Prepare);
- _ -> ok
- end,
- Ret.
- -spec query(Conn, Query) -> Result
- when Conn :: connection(),
- Query :: iodata(),
- Result :: query_result().
- query(Conn, Query) ->
- query_call(Conn, {query, Query}).
- -spec query(Conn, Query, Params | Timeout) -> Result
- when Conn :: connection(),
- Query :: iodata(),
- Timeout :: timeout(),
- Params :: [term()],
- Result :: query_result().
- query(Conn, Query, Params) when is_list(Params) ->
- query_call(Conn, {param_query, Query, Params});
- query(Conn, Query, Timeout) when is_integer(Timeout); Timeout == infinity ->
- query_call(Conn, {query, Query, Timeout}).
- -spec query(Conn, Query, Params, Timeout) -> Result
- when Conn :: connection(),
- Query :: iodata(),
- Timeout :: timeout(),
- Params :: [term()],
- Result :: query_result().
- query(Conn, Query, Params, Timeout) ->
- query_call(Conn, {param_query, Query, Params, Timeout}).
- -spec execute(Conn, StatementRef, Params) -> Result | {error, not_prepared}
- when Conn :: connection(),
- StatementRef :: atom() | integer(),
- Params :: [term()],
- Result :: query_result().
- execute(Conn, StatementRef, Params) ->
- query_call(Conn, {execute, StatementRef, Params}).
- -spec execute(Conn, StatementRef, Params, Timeout) ->
- Result | {error, not_prepared}
- when Conn :: connection(),
- StatementRef :: atom() | integer(),
- Params :: [term()],
- Timeout :: timeout(),
- Result :: query_result().
- execute(Conn, StatementRef, Params, Timeout) ->
- query_call(Conn, {execute, StatementRef, Params, Timeout}).
- -spec prepare(Conn, Query) -> {ok, StatementId} | {error, Reason}
- when Conn :: connection(),
- Query :: iodata(),
- StatementId :: integer(),
- Reason :: server_reason().
- prepare(Conn, Query) ->
- gen_server:call(Conn, {prepare, Query}).
- -spec prepare(Conn, Name, Query) -> {ok, Name} | {error, Reason}
- when Conn :: connection(),
- Name :: atom(),
- Query :: iodata(),
- Reason :: server_reason().
- prepare(Conn, Name, Query) ->
- gen_server:call(Conn, {prepare, Name, Query}).
- -spec unprepare(Conn, StatementRef) -> ok | {error, Reason}
- when Conn :: connection(),
- StatementRef :: atom() | integer(),
- Reason :: server_reason() | not_prepared.
- unprepare(Conn, StatementRef) ->
- gen_server:call(Conn, {unprepare, StatementRef}).
- -spec warning_count(connection()) -> integer().
- warning_count(Conn) ->
- gen_server:call(Conn, warning_count).
- -spec affected_rows(connection()) -> integer().
- affected_rows(Conn) ->
- gen_server:call(Conn, affected_rows).
- -spec autocommit(connection()) -> boolean().
- autocommit(Conn) ->
- gen_server:call(Conn, autocommit).
- -spec insert_id(connection()) -> integer().
- insert_id(Conn) ->
- gen_server:call(Conn, insert_id).
- -spec in_transaction(connection()) -> boolean().
- in_transaction(Conn) ->
- gen_server:call(Conn, in_transaction).
- -spec transaction(connection(), fun()) -> {atomic, term()} | {aborted, term()}.
- transaction(Conn, Fun) ->
- transaction(Conn, Fun, [], infinity).
- -spec transaction(connection(), fun(), Retries) -> {atomic, term()} |
- {aborted, term()}
- when Retries :: non_neg_integer() | infinity.
- transaction(Conn, Fun, Retries) ->
- transaction(Conn, Fun, [], Retries).
- -spec transaction(connection(), fun(), list(), Retries) -> {atomic, term()} |
- {aborted, term()}
- when Retries :: non_neg_integer() | infinity.
- transaction(Conn, Fun, Args, Retries) when is_list(Args),
- is_function(Fun, length(Args)) ->
-
-
- ok = gen_server:call(Conn, start_transaction, infinity),
- execute_transaction(Conn, Fun, Args, Retries).
- execute_transaction(Conn, Fun, Args, Retries) ->
- try apply(Fun, Args) of
- ResultOfFun ->
- ok = gen_server:call(Conn, commit, infinity),
- {atomic, ResultOfFun}
- catch
-
-
- ?EXCEPTION(throw, {implicit_rollback, 1, _}, _Stacktrace)
- when Retries == infinity ->
- execute_transaction(Conn, Fun, Args, infinity);
- ?EXCEPTION(throw, {implicit_rollback, 1, _}, _Stacktrace)
- when Retries > 0 ->
- execute_transaction(Conn, Fun, Args, Retries - 1);
- ?EXCEPTION(throw, {implicit_rollback, 1, Reason}, Stacktrace)
- when Retries == 0 ->
-
-
- Trace = ?GET_STACK(Stacktrace),
- ok = gen_server:call(Conn, rollback, infinity),
- {aborted, {Reason, Trace}};
- ?EXCEPTION(throw, {implicit_rollback, N, Reason}, Stacktrace)
- when N > 1 ->
-
- erlang:raise(throw, {implicit_rollback, N - 1, Reason},
- ?GET_STACK(Stacktrace));
- ?EXCEPTION(error, {implicit_commit, _Query} = E, Stacktrace) ->
-
-
-
-
-
-
- erlang:raise(error, E, ?GET_STACK(Stacktrace));
- ?EXCEPTION(Class, Reason, Stacktrace) ->
-
- ok = gen_server:call(Conn, rollback, infinity),
-
- Aborted = case Class of
- throw -> {throw, Reason};
- error -> {Reason, ?GET_STACK(Stacktrace)};
- exit -> Reason
- end,
- {aborted, Aborted}
- end.
- -spec encode(connection(), term()) -> iodata().
- encode(Conn, Term) ->
- Term1 = case (is_list(Term) orelse is_binary(Term)) andalso
- gen_server:call(Conn, backslash_escapes_enabled) of
- true -> mysql_encode:backslash_escape(Term);
- false -> Term
- end,
- mysql_encode:encode(Term1).
- -include("records.hrl").
- -include("server_status.hrl").
- -record(state, {server_version, connection_id, socket, sockmod, ssl_opts,
- host, port, user, password, log_warnings,
- ping_timeout,
- query_timeout, query_cache_time,
- affected_rows = 0, status = 0, warning_count = 0, insert_id = 0,
- transaction_level = 0, ping_ref = undefined,
- monitors = [],
- stmts = dict:new(), query_cache = empty, cap_found_rows = false}).
- init(Opts) ->
-
- Host = proplists:get_value(host, Opts, ?default_host),
- Port = proplists:get_value(port, Opts, ?default_port),
- User = proplists:get_value(user, Opts, ?default_user),
- Password = proplists:get_value(password, Opts, ?default_password),
- Database = proplists:get_value(database, Opts, undefined),
- LogWarn = proplists:get_value(log_warnings, Opts, true),
- KeepAlive = proplists:get_value(keep_alive, Opts, false),
- Timeout = proplists:get_value(query_timeout, Opts,
- ?default_query_timeout),
- QueryCacheTime = proplists:get_value(query_cache_time, Opts,
- ?default_query_cache_time),
- TcpOpts = proplists:get_value(tcp_options, Opts, []),
- SetFoundRows = proplists:get_value(found_rows, Opts, false),
- SSLOpts = proplists:get_value(ssl, Opts, undefined),
- SockMod0 = mysql_sock_tcp,
- PingTimeout = case KeepAlive of
- true -> ?default_ping_timeout;
- false -> infinity;
- N when N > 0 -> N
- end,
-
- SockOpts = [binary, {packet, raw}, {active, false} | TcpOpts],
- {ok, Socket0} = SockMod0:connect(Host, Port, SockOpts),
-
- Result = mysql_protocol:handshake(User, Password, Database, SockMod0, SSLOpts,
- Socket0, SetFoundRows),
- case Result of
- {ok, Handshake, SockMod, Socket} ->
- SockMod:setopts(Socket, [{active, once}]),
- #handshake{server_version = Version, connection_id = ConnId,
- status = Status} = Handshake,
- State = #state{server_version = Version, connection_id = ConnId,
- sockmod = SockMod,
- socket = Socket,
- ssl_opts = SSLOpts,
- host = Host, port = Port, user = User,
- password = Password, status = Status,
- log_warnings = LogWarn,
- ping_timeout = PingTimeout,
- query_timeout = Timeout,
- query_cache_time = QueryCacheTime,
- cap_found_rows = (SetFoundRows =:= true)},
-
- process_flag(trap_exit, true),
- State1 = schedule_ping(State),
- {ok, State1};
- #error{} = E ->
- {stop, error_to_reason(E)}
- end.
- handle_call({query, Query}, From, State) ->
- handle_call({query, Query, State#state.query_timeout}, From, State);
- handle_call({query, Query, Timeout}, _From, State) ->
- SockMod = State#state.sockmod,
- Socket = State#state.socket,
- SockMod:setopts(Socket, [{active, false}]),
- {ok, Recs} = case mysql_protocol:query(Query, SockMod, Socket, Timeout) of
- {error, timeout} when State#state.server_version >= [5, 0, 0] ->
- kill_query(State),
- mysql_protocol:fetch_query_response(SockMod, Socket, ?cmd_timeout);
- {error, timeout} ->
-
-
- exit(timeout);
- QueryResult ->
- QueryResult
- end,
- SockMod:setopts(Socket, [{active, once}]),
- State1 = lists:foldl(fun update_state/2, State, Recs),
- State1#state.warning_count > 0 andalso State1#state.log_warnings
- andalso log_warnings(State1, Query),
- handle_query_call_reply(Recs, Query, State1, []);
- handle_call({param_query, Query, Params}, From, State) ->
- handle_call({param_query, Query, Params, State#state.query_timeout}, From,
- State);
- handle_call({param_query, Query, Params, Timeout}, _From, State) ->
-
- QueryBin = iolist_to_binary(Query),
- #state{socket = Socket, sockmod = SockMod} = State,
- Cache = State#state.query_cache,
- {StmtResult, Cache1} = case mysql_cache:lookup(QueryBin, Cache) of
- {found, FoundStmt, NewCache} ->
-
- {{ok, FoundStmt}, NewCache};
- not_found ->
-
- SockMod:setopts(Socket, [{active, false}]),
- SockMod = State#state.sockmod,
- Rec = mysql_protocol:prepare(Query, SockMod, Socket),
- SockMod:setopts(Socket, [{active, once}]),
- case Rec of
- #error{} = E ->
- {{error, error_to_reason(E)}, Cache};
- #prepared{} = Stmt ->
-
- Cache == empty andalso begin
- When = State#state.query_cache_time * 2,
- erlang:send_after(When, self(), query_cache)
- end,
- {{ok, Stmt}, mysql_cache:store(QueryBin, Stmt, Cache)}
- end
- end,
- case StmtResult of
- {ok, StmtRec} ->
- State1 = State#state{query_cache = Cache1},
- execute_stmt(StmtRec, Params, Timeout, State1);
- PrepareError ->
- {reply, PrepareError, State}
- end;
- handle_call({execute, Stmt, Args}, From, State) ->
- handle_call({execute, Stmt, Args, State#state.query_timeout}, From, State);
- handle_call({execute, Stmt, Args, Timeout}, _From, State) ->
- case dict:find(Stmt, State#state.stmts) of
- {ok, StmtRec} ->
- execute_stmt(StmtRec, Args, Timeout, State);
- error ->
- {reply, {error, not_prepared}, State}
- end;
- handle_call({prepare, Query}, _From, State) ->
- #state{socket = Socket, sockmod = SockMod} = State,
- SockMod:setopts(Socket, [{active, false}]),
- SockMod = State#state.sockmod,
- Rec = mysql_protocol:prepare(Query, SockMod, Socket),
- SockMod:setopts(Socket, [{active, once}]),
- State1 = update_state(Rec, State),
- case Rec of
- #error{} = E ->
- {reply, {error, error_to_reason(E)}, State1};
- #prepared{statement_id = Id} = Stmt ->
- Stmts1 = dict:store(Id, Stmt, State1#state.stmts),
- State2 = State#state{stmts = Stmts1},
- {reply, {ok, Id}, State2}
- end;
- handle_call({prepare, Name, Query}, _From, State) when is_atom(Name) ->
- #state{socket = Socket, sockmod = SockMod} = State,
-
- SockMod:setopts(Socket, [{active, false}]),
- SockMod = State#state.sockmod,
- State1 = case dict:find(Name, State#state.stmts) of
- {ok, OldStmt} ->
- mysql_protocol:unprepare(OldStmt, SockMod, Socket),
- State#state{stmts = dict:erase(Name, State#state.stmts)};
- error ->
- State
- end,
- Rec = mysql_protocol:prepare(Query, SockMod, Socket),
- SockMod:setopts(Socket, [{active, once}]),
- State2 = update_state(Rec, State1),
- case Rec of
- #error{} = E ->
- {reply, {error, error_to_reason(E)}, State2};
- #prepared{} = Stmt ->
- Stmts1 = dict:store(Name, Stmt, State2#state.stmts),
- State3 = State2#state{stmts = Stmts1},
- {reply, {ok, Name}, State3}
- end;
- handle_call({unprepare, Stmt}, _From, State) when is_atom(Stmt);
- is_integer(Stmt) ->
- case dict:find(Stmt, State#state.stmts) of
- {ok, StmtRec} ->
- #state{socket = Socket, sockmod = SockMod} = State,
- SockMod:setopts(Socket, [{active, false}]),
- SockMod = State#state.sockmod,
- mysql_protocol:unprepare(StmtRec, SockMod, Socket),
- SockMod:setopts(Socket, [{active, once}]),
- State1 = State#state{stmts = dict:erase(Stmt, State#state.stmts)},
- State2 = schedule_ping(State1),
- {reply, ok, State2};
- error ->
- {reply, {error, not_prepared}, State}
- end;
- handle_call(warning_count, _From, State) ->
- {reply, State#state.warning_count, State};
- handle_call(insert_id, _From, State) ->
- {reply, State#state.insert_id, State};
- handle_call(affected_rows, _From, State) ->
- {reply, State#state.affected_rows, State};
- handle_call(autocommit, _From, State) ->
- {reply, State#state.status band ?SERVER_STATUS_AUTOCOMMIT /= 0, State};
- handle_call(backslash_escapes_enabled, _From, State = #state{status = S}) ->
- {reply, S band ?SERVER_STATUS_NO_BACKSLASH_ESCAPES == 0, State};
- handle_call(in_transaction, _From, State) ->
- {reply, State#state.status band ?SERVER_STATUS_IN_TRANS /= 0, State};
- handle_call(start_transaction, {FromPid, _},
- State = #state{socket = Socket, sockmod = SockMod,
- transaction_level = L, status = Status, monitors = Monitors})
- when Status band ?SERVER_STATUS_IN_TRANS == 0, L == 0;
- Status band ?SERVER_STATUS_IN_TRANS /= 0, L > 0 ->
- MRef = erlang:monitor(process, FromPid),
- Query = case L of
- 0 -> <<"BEGIN">>;
- _ -> <<"SAVEPOINT s", (integer_to_binary(L))/binary>>
- end,
- SockMod:setopts(Socket, [{active, false}]),
- SockMod = State#state.sockmod,
- {ok, [Res = #ok{}]} = mysql_protocol:query(Query, SockMod, Socket,
- ?cmd_timeout),
- SockMod:setopts(Socket, [{active, once}]),
- State1 = update_state(Res, State),
- {reply, ok, State1#state{transaction_level = L + 1, monitors = [{FromPid, MRef} | Monitors]}};
- handle_call(rollback, {FromPid, _}, State = #state{socket = Socket, sockmod = SockMod,
- status = Status, transaction_level = L,
- monitors = [{FromPid, MRef}|NewMonitors]})
- when Status band ?SERVER_STATUS_IN_TRANS /= 0, L >= 1 ->
- erlang:demonitor(MRef),
- Query = case L of
- 1 -> <<"ROLLBACK">>;
- _ -> <<"ROLLBACK TO s", (integer_to_binary(L - 1))/binary>>
- end,
- SockMod:setopts(Socket, [{active, false}]),
- SockMod = State#state.sockmod,
- {ok, [Res = #ok{}]} = mysql_protocol:query(Query, SockMod, Socket,
- ?cmd_timeout),
- SockMod:setopts(Socket, [{active, once}]),
- State1 = update_state(Res, State),
- {reply, ok, State1#state{transaction_level = L - 1, monitors = NewMonitors}};
- handle_call(commit, {FromPid, _}, State = #state{socket = Socket, sockmod = SockMod,
- status = Status, transaction_level = L,
- monitors = [{FromPid, MRef}|NewMonitors]})
- when Status band ?SERVER_STATUS_IN_TRANS /= 0, L >= 1 ->
- erlang:demonitor(MRef),
- Query = case L of
- 1 -> <<"COMMIT">>;
- _ -> <<"RELEASE SAVEPOINT s", (integer_to_binary(L - 1))/binary>>
- end,
- SockMod:setopts(Socket, [{active, false}]),
- SockMod = State#state.sockmod,
- {ok, [Res = #ok{}]} = mysql_protocol:query(Query, SockMod, Socket,
- ?cmd_timeout),
- SockMod:setopts(Socket, [{active, once}]),
- State1 = update_state(Res, State),
- {reply, ok, State1#state{transaction_level = L - 1, monitors = NewMonitors}}.
- handle_cast(_Msg, State) ->
- {noreply, State}.
- handle_info(query_cache, #state{query_cache = Cache,
- query_cache_time = CacheTime} = State) ->
-
- {Evicted, Cache1} = mysql_cache:evict_older_than(Cache, CacheTime),
-
- #state{socket = Socket, sockmod = SockMod} = State,
- SockMod:setopts(Socket, [{active, false}]),
- SockMod = State#state.sockmod,
- lists:foreach(fun ({_Query, Stmt}) ->
- mysql_protocol:unprepare(Stmt, SockMod, Socket)
- end,
- Evicted),
- SockMod:setopts(Socket, [{active, once}]),
-
- mysql_cache:size(Cache1) > 0 andalso
- erlang:send_after(CacheTime, self(), query_cache),
- {noreply, State#state{query_cache = Cache1}};
- handle_info({'DOWN', _MRef, _, Pid, _Info}, State) ->
- stop_server({application_process_died, Pid}, State);
- handle_info(ping, #state{socket = Socket, sockmod = SockMod} = State) ->
- SockMod:setopts(Socket, [{active, false}]),
- SockMod = State#state.sockmod,
- Ok = mysql_protocol:ping(SockMod, Socket),
- SockMod:setopts(Socket, [{active, once}]),
- {noreply, update_state(Ok, State)};
- handle_info({tcp_closed, _Socket}, State) ->
- stop_server(tcp_closed, State);
- handle_info({tcp_error, _Socket, Reason}, State) ->
- stop_server({tcp_error, Reason}, State);
- handle_info(_Info, State) ->
- {noreply, State}.
- terminate(Reason, #state{socket = Socket, sockmod = SockMod})
- when Reason == normal; Reason == shutdown ->
-
- SockMod:setopts(Socket, [{active, false}]),
- mysql_protocol:quit(SockMod, Socket);
- terminate(_Reason, _State) ->
- ok.
- code_change(_OldVsn, State = #state{}, _Extra) ->
- {ok, State};
- code_change(_OldVsn, _State, _Extra) ->
- {error, incompatible_state}.
- query_call(Conn, CallReq) ->
- case gen_server:call(Conn, CallReq, infinity) of
- {implicit_commit, _NestingLevel, Query} ->
- error({implicit_commit, Query});
- {implicit_rollback, _NestingLevel, _ServerReason} = ImplicitRollback ->
- throw(ImplicitRollback);
- Result ->
- Result
- end.
- execute_stmt(Stmt, Args, Timeout, State = #state{socket = Socket, sockmod = SockMod}) ->
- SockMod:setopts(Socket, [{active, false}]),
- SockMod = State#state.sockmod,
- {ok, Recs} = case mysql_protocol:execute(Stmt, Args, SockMod, Socket,
- Timeout) of
- {error, timeout} when State#state.server_version >= [5, 0, 0] ->
- kill_query(State),
- mysql_protocol:fetch_execute_response(SockMod, Socket,
- ?cmd_timeout);
- {error, timeout} ->
-
-
- exit(timeout);
- QueryResult ->
- QueryResult
- end,
- SockMod:setopts(Socket, [{active, once}]),
- State1 = lists:foldl(fun update_state/2, State, Recs),
- State1#state.warning_count > 0 andalso State1#state.log_warnings
- andalso log_warnings(State1, Stmt#prepared.orig_query),
- handle_query_call_reply(Recs, Stmt#prepared.orig_query, State1, []).
- -spec error_to_reason(#error{}) -> server_reason().
- error_to_reason(#error{code = Code, state = State, msg = Msg}) ->
- {Code, State, Msg}.
- -spec update_state(#ok{} | #eof{} | any(), #state{}) -> #state{}.
- update_state(Rec, State) ->
- State1 = case Rec of
- #ok{status = S, affected_rows = R, insert_id = Id, warning_count = W} ->
- State#state{status = S, affected_rows = R, insert_id = Id,
- warning_count = W};
- #resultset{status = S, warning_count = W} ->
- State#state{status = S, warning_count = W};
- #prepared{warning_count = W} ->
- State#state{warning_count = W};
- _Other ->
-
-
- State#state{warning_count = 0, affected_rows = 0}
- end,
- schedule_ping(State1).
- handle_query_call_reply([], _Query, State, ResultSetsAcc) ->
- Reply = case ResultSetsAcc of
- [] -> ok;
- [{ColumnNames, Rows}] -> {ok, ColumnNames, Rows};
- [_|_] -> {ok, lists:reverse(ResultSetsAcc)}
- end,
- {reply, Reply, State};
- handle_query_call_reply([Rec|Recs], Query, #state{monitors = Monitors} = State, ResultSetsAcc) ->
- case Rec of
- #ok{status = Status} when Status band ?SERVER_STATUS_IN_TRANS == 0,
- State#state.transaction_level > 0 ->
-
-
- Reply = {implicit_commit, State#state.transaction_level, Query},
- NewMonitors = demonitor_processes(Monitors, length(Monitors)),
- {reply, Reply, State#state{transaction_level = 0, monitors = NewMonitors}};
- #ok{} ->
- handle_query_call_reply(Recs, Query, State, ResultSetsAcc);
- #resultset{cols = ColDefs, rows = Rows} ->
- Names = [Def#col.name || Def <- ColDefs],
- ResultSetsAcc1 = [{Names, Rows} | ResultSetsAcc],
- handle_query_call_reply(Recs, Query, State, ResultSetsAcc1);
- #error{code = ?ERROR_DEADLOCK} when State#state.transaction_level > 0 ->
-
- Reply = {implicit_rollback, State#state.transaction_level,
- error_to_reason(Rec)},
-
-
- NewMonitors = demonitor_processes(Monitors, length(Monitors) -1),
- {reply, Reply, State#state{transaction_level = 1, monitors = NewMonitors}};
- #error{} ->
- {reply, {error, error_to_reason(Rec)}, State}
- end.
- schedule_ping(State = #state{ping_timeout = infinity}) ->
- State;
- schedule_ping(State = #state{ping_timeout = Timeout, ping_ref = Ref}) ->
- is_reference(Ref) andalso erlang:cancel_timer(Ref),
- State#state{ping_ref = erlang:send_after(Timeout, self(), ping)}.
- log_warnings(#state{socket = Socket, sockmod = SockMod} = State, Query) ->
- SockMod:setopts(Socket, [{active, false}]),
- SockMod = State#state.sockmod,
- {ok, [#resultset{rows = Rows}]} = mysql_protocol:query(<<"SHOW WARNINGS">>,
- SockMod, Socket,
- ?cmd_timeout),
- SockMod:setopts(Socket, [{active, once}]),
- Lines = [[Level, " ", integer_to_binary(Code), ": ", Message, "\n"]
- || [Level, Code, Message] <- Rows],
- error_logger:warning_msg("~s in ~s~n", [Lines, Query]).
- kill_query(#state{connection_id = ConnId, host = Host, port = Port,
- user = User, password = Password, ssl_opts = SSLOpts,
- cap_found_rows = SetFoundRows}) ->
-
- SockOpts = [{active, false}, binary, {packet, raw}],
- {ok, Socket0} = mysql_sock_tcp:connect(Host, Port, SockOpts),
-
- Result = mysql_protocol:handshake(User, Password, undefined, mysql_sock_tcp,
- SSLOpts, Socket0, SetFoundRows),
- case Result of
- {ok, #handshake{}, SockMod, Socket} ->
-
- IdBin = integer_to_binary(ConnId),
- {ok, [#ok{}]} = mysql_protocol:query(<<"KILL QUERY ", IdBin/binary>>,
- SockMod, Socket, ?cmd_timeout),
- mysql_protocol:quit(SockMod, Socket);
- #error{} = E ->
- error_logger:error_msg("Failed to connect to kill query: ~p",
- [error_to_reason(E)])
- end.
- stop_server(Reason,
- #state{socket = Socket, connection_id = ConnId} = State) ->
- error_logger:error_msg("Connection Id ~p closing with reason: ~p~n",
- [ConnId, Reason]),
- ok = gen_tcp:close(Socket),
- {stop, Reason, State#state{socket = undefined, connection_id = undefined}}.
- demonitor_processes(List, 0) ->
- List;
- demonitor_processes([{_FromPid, MRef}|T], Count) ->
- erlang:demonitor(MRef),
- demonitor_processes(T, Count -1).
|