• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

esl / MongooseIM / 16499779126

24 Jul 2025 02:03PM UTC coverage: 85.593% (-0.02%) from 85.614%
16499779126

Pull #4549

github

jacekwegr
Add TODO comments
Pull Request #4549: Support Erlang 28

50 of 68 new or added lines in 5 files covered. (73.53%)

289 existing lines in 7 files now uncovered.

28945 of 33817 relevant lines covered (85.59%)

51736.46 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

70.0
/src/rdbms/mongoose_rdbms.erl
1
%%%----------------------------------------------------------------------
2
%%% File    : mongoose_rdbms.erl
3
%%% Author  : Alexey Shchepin <alexey@process-one.net>
4
%%% Purpose : Serve RDBMS connection
5
%%% Created :  8 Dec 2004 by Alexey Shchepin <alexey@process-one.net>
6
%%%
7
%%%
8
%%% ejabberd, Copyright (C) 2002-2011   ProcessOne
9
%%% Copyright 2016 Erlang Solutions Ltd.
10
%%%
11
%%% This program is free software; you can redistribute it and/or
12
%%% modify it under the terms of the GNU General Public License as
13
%%% published by the Free Software Foundation; either version 2 of the
14
%%% License, or (at your option) any later version.
15
%%%
16
%%% This program is distributed in the hope that it will be useful,
17
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
18
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19
%%% General Public License for more details.
20
%%%
21
%%% You should have received a copy of the GNU General Public License
22
%%% along with this program; if not, write to the Free Software
23
%%% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24
%%%
25
%%%----------------------------------------------------------------------
26

27
-module(mongoose_rdbms).
28
-author('alexey@process-one.net').
29
-author('konrad.zemek@erlang-solutions.com').
30

31
-behaviour(gen_server).
32

33
%% Part of SQL query string, produced by use_escaped/1 function
34
-type sql_query_part() :: iodata().
35
-type sql_query() :: iodata().
36

37
%% Blob data type to be used inside SQL queries
38
-opaque escaped_binary() :: {escaped_binary, sql_query_part()}.
39
%% Unicode string to be used inside SQL queries
40
-opaque escaped_string() :: {escaped_string, sql_query_part()}.
41
%% Unicode string to be used inside LIKE conditions
42
-opaque escaped_like() :: {escaped_like, sql_query_part()}.
43
-opaque escaped_integer() :: {escaped_integer, sql_query_part()}.
44
-opaque escaped_boolean() :: {escaped_boolean, sql_query_part()}.
45
-opaque escaped_null() :: {escaped_null, sql_query_part()}.
46
-opaque escaped_value() :: escaped_string() | escaped_binary() | escaped_integer() |
47
                           escaped_boolean() | escaped_null().
48

49
-export_type([escaped_binary/0,
50
              escaped_string/0,
51
              escaped_like/0,
52
              escaped_integer/0,
53
              escaped_boolean/0,
54
              escaped_null/0,
55
              escaped_value/0,
56
              sql_query/0,
57
              sql_query_part/0]).
58

59
-export([process_options/1]).
60

61
%% External exports
62
-export([prepare/4,
63
         prepared/1,
64
         execute/3, execute/4,
65
         execute_cast/3, execute_cast/4,
66
         execute_request/3, execute_request/4,
67
         execute_wrapped_request/4, execute_wrapped_request/5,
68
         execute_successfully/3, execute_successfully/4,
69
         sql_query/2, sql_query/3,
70
         sql_query_cast/2, sql_query_cast/3,
71
         sql_query_request/2, sql_query_request/3,
72
         sql_transaction/2, sql_transaction/3,
73
         sql_transaction_request/2, sql_transaction_request/3,
74
         sql_dirty/2, sql_dirty/3,
75
         sql_query_t/1,
76
         transaction_with_delayed_retry/3,
77
         to_bool/1,
78
         db_engine/1,
79
         db_type/0,
80
         use_escaped/1]).
81

82
%% Unicode escaping
83
-export([escape_string/1, use_escaped_string/1]).
84

85
%% Integer escaping
86
-export([escape_integer/1, use_escaped_integer/1]).
87

88
%% Boolean escaping
89
-export([escape_boolean/1, use_escaped_boolean/1]).
90

91
%% LIKE escaping
92
-export([escape_like/1, escape_prepared_like/1, escape_like_prefix/1, use_escaped_like/1]).
93

94
%% BLOB escaping
95
-export([escape_binary/2, unescape_binary/2, use_escaped_binary/1]).
96

97
%% Null escaping
98
%% (to keep uniform pattern of passing values)
99
-export([escape_null/0, use_escaped_null/1]).
100

101
%% count / integra types decoding
102
-export([result_to_integer/1, selected_to_integer/1]).
103

104
-export([character_to_integer/1]).
105

106
%% gen_server callbacks
107
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
108

109
%% External exports
110
-ignore_xref([
111
              execute/4, execute_cast/3, execute_cast/4,
112
              execute_request/3, execute_request/4,
113
              execute_wrapped_request/4, execute_wrapped_request/5,
114
              execute_successfully/4,
115
              sql_query/3, sql_query_cast/2, sql_query_cast/3,
116
              sql_query_request/2, sql_query_request/3,
117
              sql_transaction/3, sql_transaction_request/2, sql_transaction_request/3,
118
              sql_dirty/3, sql_query_t/1,
119
              use_escaped/1,
120
              escape_like/1, escape_like_prefix/1, use_escaped_like/1,
121
              escape_binary/2, use_escaped_binary/1,
122
              escape_integer/1, use_escaped_integer/1,
123
              escape_string/1, use_escaped_string/1,
124
              escape_boolean/1, use_escaped_boolean/1,
125
              escape_null/0, use_escaped_null/1
126
             ]).
127

128
%% internal usage
129
-export([get_db_info/1]).
130

131
-include("mongoose.hrl").
132

133
-record(state, {db_ref,
134
                prepared = #{} :: #{binary() => term()},
135
                keepalive_interval :: undefined | pos_integer(),
136
                query_timeout :: pos_integer()
137
               }).
138
-type state() :: #state{}.
139

140
-define(DEFAULT_POOL_TAG, default).
141
-define(STATE_KEY, mongoose_rdbms_state).
142
-define(MAX_TRANSACTION_RESTARTS, 10).
143
-define(TRANSACTION_TIMEOUT, 60000). % milliseconds
144
-define(KEEPALIVE_QUERY, <<"SELECT 1;">>).
145
%% The value is arbitrary; supervisor will restart the connection once
146
%% the retry counter runs out. We just attempt to reduce log pollution.
147
-define(CONNECT_RETRIES, 5).
148

149
-type query_name() :: atom().
150
-type query_params() :: [term()].
151
-type request_wrapper() :: fun((fun(() -> T)) -> T).
152
-type rdbms_msg() :: {sql_query, _}
153
                   | {sql_transaction, fun()}
154
                   | {sql_dirty, fun()}
155
                   | {sql_execute, atom(), [iodata() | boolean() | integer() | null]}
156
                   | {sql_execute_wrapped, atom(), [iodata() | boolean() | integer() | null], request_wrapper()}.
157
-type single_query_result() :: {selected, [tuple()]} |
158
                               {updated, non_neg_integer() | undefined} |
159
                               {updated, non_neg_integer(), [tuple()]} |
160
                               {aborted, Reason :: term()} |
161
                               {error, Reason :: string() | duplicate_key}.
162
-type query_result() :: single_query_result() | [single_query_result()].
163
-type transaction_result() :: {aborted, _} | {atomic, _} | {error, _}.
164
-type dirty_result() :: {ok, any()} | {error, any()}.
165
-export_type([query_name/0, query_result/0, transaction_result/0]).
166

167
-type backend() :: pgsql | mysql | odbc | cockroachdb.
168
-type options() :: #{driver := backend(),
169
                     max_start_interval := pos_integer(),
170
                     query_timeout := pos_integer(),
171
                     atom() => any()}.
172

173
-export_type([options/0, backend/0]).
174

175
%%%----------------------------------------------------------------------
176
%%% API
177
%%%----------------------------------------------------------------------
178

179
-spec process_options(map()) -> options().
180
process_options(Opts = #{driver := odbc, settings := _}) ->
181
    Opts;
210✔
182
process_options(Opts = #{host := _Host, database := _DB, username := _User, password := _Pass}) ->
183
    ensure_db_port(process_tls_options(Opts));
624✔
184
process_options(Opts) ->
185
    error(#{what => invalid_rdbms_connection_options, options => Opts}).
28✔
186

187
process_tls_options(Opts = #{driver := mysql, tls := #{required := _}}) ->
188
    error(#{what => invalid_rdbms_tls_options, options => Opts,
2✔
189
            text => <<"The 'required' option is not supported for MySQL">>});
190
process_tls_options(Opts = #{driver := Driver, tls := TLSOpts}) when Driver =:= pgsql;
191
                                                                     Driver =:= cockroachdb ->
192
    Opts#{tls := maps:merge(#{required => false}, TLSOpts)};
458✔
193
process_tls_options(Opts) ->
194
    Opts.
164✔
195

196
ensure_db_port(Opts = #{port := _}) -> Opts;
6✔
197
ensure_db_port(Opts = #{driver := pgsql}) -> Opts#{port => 5432};
456✔
198
ensure_db_port(Opts = #{driver := cockroachdb}) -> Opts#{port => 26257};
32✔
199
ensure_db_port(Opts = #{driver := mysql}) -> Opts#{port => 3306}.
128✔
200

201
-spec prepare(
202
        query_name(), Table :: binary() | atom(), Fields :: [binary() | atom()], Statement :: iodata()) ->
203
    {ok, query_name()} | {error, already_exists}.
204
prepare(Name, Table, Fields, Statement) when is_atom(Table) ->
205
    prepare(Name, atom_to_binary(Table, utf8), Fields, Statement);
188,062✔
206
prepare(Name, Table, [Field | _] = Fields, Statement) when is_atom(Field) ->
207
    prepare(Name, Table, [atom_to_binary(F, utf8) || F <- Fields], Statement);
164,277✔
208
prepare(Name, Table, Fields, Statement) when is_atom(Name), is_binary(Table) ->
209
    true = lists:all(fun is_binary/1, Fields),
188,062✔
210
    Tuple = {Name, Table, Fields, iolist_to_binary(Statement)},
188,062✔
211
    case ets:insert_new(prepared_statements, Tuple) of
188,062✔
212
        true  -> {ok, Name};
41,454✔
213
        false -> {error, already_exists}
146,608✔
214
    end.
215

216
-spec prepared(atom()) -> boolean().
217
prepared(Name) ->
218
    ets:member(prepared_statements, Name).
49,025✔
219

220
-spec execute(mongooseim:host_type_or_global(), query_name(), query_params()) -> query_result().
221
execute(HostType, Name, Parameters) ->
222
    execute(HostType, ?DEFAULT_POOL_TAG, Name, Parameters).
291,502✔
223

224
-spec execute(mongooseim:host_type_or_global(), mongoose_wpool:tag(), query_name(), query_params()) ->
225
    query_result().
226
execute(HostType, PoolTag, Name, Parameters) when is_atom(PoolTag), is_atom(Name), is_list(Parameters) ->
227
    sql_call(HostType, PoolTag, {sql_execute, Name, Parameters}).
1,343,331✔
228

229
-spec execute_cast(mongooseim:host_type_or_global(), query_name(), query_params()) -> query_result().
230
execute_cast(HostType, Name, Parameters) ->
231
    execute_cast(HostType, ?DEFAULT_POOL_TAG, Name, Parameters).
8✔
232

233
-spec execute_cast(mongooseim:host_type_or_global(), mongoose_wpool:tag(), query_name(), query_params()) ->
234
    query_result().
235
execute_cast(HostType, PoolTag, Name, Parameters) when is_atom(PoolTag), is_atom(Name), is_list(Parameters) ->
236
    sql_cast(HostType, PoolTag, {sql_execute, Name, Parameters}).
16✔
237

238
-spec execute_request(mongooseim:host_type_or_global(), query_name(), query_params()) ->
239
    gen_server:request_id().
240
execute_request(HostType, Name, Parameters) when is_atom(Name), is_list(Parameters) ->
241
    execute_request(HostType, ?DEFAULT_POOL_TAG, Name, Parameters).
5,376✔
242

243
-spec execute_request(mongooseim:host_type_or_global(), mongoose_wpool:tag(), query_name(), query_params()) ->
244
    gen_server:request_id().
245
execute_request(HostType, PoolTag, Name, Parameters) when is_atom(PoolTag), is_atom(Name), is_list(Parameters) ->
246
    sql_request(HostType, PoolTag, {sql_execute, Name, Parameters}).
5,384✔
247

248
-spec execute_wrapped_request(mongooseim:host_type_or_global(), query_name(), query_params(), request_wrapper()) ->
249
    gen_server:request_id().
250
execute_wrapped_request(HostType, Name, Parameters, Wrapper) ->
251
    execute_wrapped_request(HostType, ?DEFAULT_POOL_TAG, Name, Parameters, Wrapper).
192✔
252

253
-spec execute_wrapped_request(
254
        mongooseim:host_type_or_global(), mongoose_wpool:tag(), query_name(), query_params(), request_wrapper()) ->
255
    gen_server:request_id().
256
execute_wrapped_request(HostType, PoolTag, Name, Parameters, Wrapper)
257
  when is_atom(PoolTag), is_atom(Name), is_list(Parameters), is_function(Wrapper) ->
258
    sql_request(HostType, PoolTag, {sql_execute_wrapped, Name, Parameters, Wrapper}).
208✔
259

260
%% Same as execute/3, but would fail loudly on any error.
261
-spec execute_successfully(mongooseim:host_type_or_global(), query_name(), query_params()) ->
262
    query_result().
263
execute_successfully(HostType, Name, Parameters) ->
264
    execute_successfully(HostType, ?DEFAULT_POOL_TAG, Name, Parameters).
1,025,991✔
265

266
-spec execute_successfully(mongooseim:host_type_or_global(), mongoose_wpool:tag(), query_name(), query_params()) ->
267
    query_result().
268
execute_successfully(HostType, PoolTag, Name, Parameters) ->
269
    try execute(HostType, PoolTag, Name, Parameters) of
1,026,255✔
270
        {selected, _} = Result ->
271
            Result;
633,119✔
272
        {updated, _} = Result ->
273
            Result;
389,604✔
274
        Other ->
275
            Log = #{what => sql_execute_failed, host => HostType, statement_name => Name,
2,725✔
276
                    statement_query => query_name_to_string(Name),
277
                    statement_params => Parameters, reason => Other},
278
            ?LOG_ERROR(Log),
2,725✔
279
            error(Log)
2,725✔
280
    catch error:Reason:Stacktrace ->
281
            Log = #{what => sql_execute_failed, host => HostType, statement_name => Name,
×
282
                    statement_query => query_name_to_string(Name),
283
                    statement_params => Parameters,
284
                    reason => Reason, stacktrace => Stacktrace},
285
            ?LOG_ERROR(Log),
×
286
            erlang:raise(error, Reason, Stacktrace)
×
287
    end.
288

289
query_name_to_string(Name) ->
290
    case ets:lookup(prepared_statements, Name) of
2,725✔
291
        [] ->
292
            not_found;
×
293
        [{_, _Table, _Fields, Statement}] ->
294
            Statement
2,725✔
295
    end.
296

297
-spec sql_query(mongooseim:host_type_or_global(), Query :: any()) -> query_result().
298
sql_query(HostType, Query) ->
299
    sql_query(HostType, ?DEFAULT_POOL_TAG, Query).
7,858✔
300

301
-spec sql_query(mongooseim:host_type_or_global(), mongoose_wpool:tag(), Query :: any()) ->
302
    query_result().
303
sql_query(HostType, PoolTag, Query) ->
304
    sql_call(HostType, PoolTag, {sql_query, Query}).
15,115✔
305

306
-spec sql_query_request(mongooseim:host_type_or_global(), Query :: any()) ->
307
    gen_server:request_id().
308
sql_query_request(HostType, Query) ->
309
    sql_query_request(HostType, ?DEFAULT_POOL_TAG, Query).
8✔
310

311
-spec sql_query_request(mongooseim:host_type_or_global(), mongoose_wpool:tag(), Query :: any()) ->
312
    gen_server:request_id().
313
sql_query_request(HostType, PoolTag, Query) ->
314
    sql_request(HostType, PoolTag, {sql_query, Query}).
16✔
315

316
-spec sql_query_cast(mongooseim:host_type_or_global(), Query :: any()) -> query_result().
317
sql_query_cast(HostType, Query) ->
318
    sql_query_cast(HostType, ?DEFAULT_POOL_TAG, Query).
8✔
319

320
-spec sql_query_cast(mongooseim:host_type_or_global(), mongoose_wpool:tag(), Query :: any()) ->
321
    query_result().
322
sql_query_cast(HostType, PoolTag, Query) ->
323
    sql_cast(HostType, PoolTag, {sql_query, Query}).
16✔
324

325
%% @doc SQL transaction based on a list of queries
326
-spec sql_transaction(mongooseim:host_type_or_global(), fun() | maybe_improper_list()) ->
327
    transaction_result().
328
sql_transaction(HostType, Msg) ->
329
    sql_transaction(HostType, ?DEFAULT_POOL_TAG, Msg).
160,799✔
330

331
-spec sql_transaction(mongooseim:host_type_or_global(), atom(), fun() | maybe_improper_list()) ->
332
    transaction_result().
333
sql_transaction(HostType, PoolTag, Queries) when is_atom(PoolTag), is_list(Queries) ->
334
    F = fun() -> lists:map(fun sql_query_t/1, Queries) end,
×
335
    sql_transaction(HostType, PoolTag, F);
×
336
%% SQL transaction, based on a erlang anonymous function (F = fun)
337
sql_transaction(HostType, PoolTag, F) when is_atom(PoolTag), is_function(F) ->
338
    sql_call(HostType, PoolTag, {sql_transaction, F}).
160,831✔
339

340
%% @doc SQL transaction based on a list of queries
341
-spec sql_transaction_request(mongooseim:host_type_or_global(), fun() | maybe_improper_list()) ->
342
    gen_server:request_id().
343
sql_transaction_request(HostType, Queries) ->
344
    sql_transaction_request(HostType, ?DEFAULT_POOL_TAG, Queries).
8✔
345

346
-spec sql_transaction_request(mongooseim:host_type_or_global(), atom(), fun() | maybe_improper_list()) ->
347
    gen_server:request_id().
348
sql_transaction_request(HostType, PoolTag, Queries) when is_atom(PoolTag), is_list(Queries) ->
349
    F = fun() -> lists:map(fun sql_query_t/1, Queries) end,
16✔
350
    sql_transaction_request(HostType, PoolTag, F);
16✔
351
%% SQL transaction, based on a erlang anonymous function (F = fun)
352
sql_transaction_request(HostType, PoolTag, F) when is_atom(PoolTag), is_function(F) ->
353
    sql_request(HostType, PoolTag, {sql_transaction, F}).
16✔
354

355
%% This function allows to specify delay between retries.
356
-spec transaction_with_delayed_retry(mongooseim:host_type_or_global(), fun() | maybe_improper_list(), map()) ->
357
    transaction_result().
358
transaction_with_delayed_retry(HostType, F, Info) ->
359
    Retries = maps:get(retries, Info),
3,296✔
360
    Delay = maps:get(delay, Info),
3,296✔
361
    do_transaction_with_delayed_retry(HostType, F, Retries, Delay, Info).
3,296✔
362

363
do_transaction_with_delayed_retry(HostType, F, Retries, Delay, Info) ->
364
    Result = mongoose_rdbms:sql_transaction(HostType, F),
3,296✔
365
    case Result of
3,296✔
366
        {atomic, _} ->
367
            Result;
3,296✔
368
        {aborted, Reason} when Retries > 0 ->
369
            ?LOG_WARNING(Info#{what => rdbms_transaction_aborted,
×
370
                               text => <<"Transaction aborted. Restart">>,
371
                               reason => Reason, retries_left => Retries}),
×
372
            timer:sleep(Delay),
×
373
            do_transaction_with_delayed_retry(HostType, F, Retries - 1, Delay, Info);
×
374
        _ ->
375
            Err = Info#{what => mam_transaction_failed,
×
376
                        text => <<"Transaction failed. Do not restart">>,
377
                        reason => Result},
378
            ?LOG_ERROR(Err),
×
379
            erlang:error(Err)
×
380
    end.
381

382
-spec sql_dirty(mongooseim:host_type_or_global(), fun()) -> any() | no_return().
383
sql_dirty(HostType, F) ->
384
    sql_dirty(HostType, ?DEFAULT_POOL_TAG, F).
6,979✔
385

386
-spec sql_dirty(mongooseim:host_type_or_global(), atom(), fun()) -> any() | no_return().
387
sql_dirty(HostType, PoolTag, F) when is_function(F) ->
388
    case sql_call(HostType, PoolTag, {sql_dirty, F}) of
6,979✔
389
        {ok, Result} -> Result;
6,979✔
390
        {error, Error} -> throw(Error)
×
391
    end.
392

393
%% TODO: Better spec for RPC calls
394
-spec sql_call(mongooseim:host_type_or_global(), mongoose_wpool:tag(), Msg :: rdbms_msg()) -> any().
395
sql_call(HostType, PoolTag, Msg) ->
396
    case get_state() of
1,526,256✔
397
        undefined -> sql_call0(HostType, PoolTag, Msg);
1,131,381✔
398
        State     ->
399
            {Res, NewState} = nested_op(Msg, State),
394,875✔
400
            put_state(NewState),
393,892✔
401
            Res
393,892✔
402
    end.
403

404
-spec sql_call0(mongooseim:host_type_or_global(), mongoose_wpool:tag(), Msg :: rdbms_msg()) -> any().
405
sql_call0(HostType, PoolTag, Msg) ->
406
    Timestamp = erlang:monotonic_time(millisecond),
1,131,381✔
407
    mongoose_wpool:call(rdbms, HostType, PoolTag, {sql_cmd, Msg, Timestamp}).
1,131,381✔
408

409
-spec sql_request(mongooseim:host_type_or_global(), mongoose_wpool:tag(), Msg :: rdbms_msg()) -> any().
410
sql_request(HostType, PoolTag, Msg) ->
411
    case get_state() of
5,624✔
412
        undefined -> sql_request0(HostType, PoolTag, Msg);
5,448✔
413
        State ->
414
            {Res, NewState} = nested_op(Msg, State),
176✔
415
            put_state(NewState),
×
416
            Res
×
417
    end.
418

419
-spec sql_request0(mongooseim:host_type_or_global(), mongoose_wpool:tag(), Msg :: rdbms_msg()) -> any().
420
sql_request0(HostType, PoolTag, Msg) ->
421
    Timestamp = erlang:monotonic_time(millisecond),
5,448✔
422
    mongoose_wpool:send_request(rdbms, HostType, PoolTag, {sql_cmd, Msg, Timestamp}).
5,448✔
423

424
-spec sql_cast(mongooseim:host_type_or_global(), mongoose_wpool:tag(), Msg :: rdbms_msg()) -> any().
425
sql_cast(HostType, PoolTag, Msg) ->
426
    case get_state() of
32✔
427
        undefined -> sql_cast0(HostType, PoolTag, Msg);
32✔
428
        State ->
429
            {Res, NewState} = nested_op(Msg, State),
×
430
            put_state(NewState),
×
431
            Res
×
432
    end.
433

434
-spec sql_cast0(mongooseim:host_type_or_global(), mongoose_wpool:tag(), Msg :: rdbms_msg()) -> any().
435
sql_cast0(HostType, PoolTag, Msg) ->
436
    Timestamp = erlang:monotonic_time(millisecond),
32✔
437
    mongoose_wpool:cast(rdbms, HostType, PoolTag, {sql_cmd, Msg, Timestamp}).
32✔
438

439
-spec get_db_info(Target :: mongooseim:host_type_or_global() | pid()) ->
440
                         {ok, DbType :: atom(), DbRef :: term()} | {error, any()}.
441
get_db_info(Pid) when is_pid(Pid) ->
442
    wpool_process:call(Pid, get_db_info, 5000);
11,770✔
443
get_db_info(HostType) ->
444
    mongoose_wpool:call(rdbms, HostType, get_db_info).
×
445

446
%% This function is intended to be used from inside an sql_transaction:
447
sql_query_t(Query) ->
448
    sql_query_t(Query, get_state()).
32✔
449

450
sql_query_t(Query, State) ->
451
    QRes = sql_query_internal(Query, State),
32✔
452
    case QRes of
32✔
453
        {error, Reason} ->
454
            throw({aborted, #{reason => Reason, sql_query => Query}});
×
455
        _ when is_list(QRes) ->
456
            case lists:keysearch(error, 1, QRes) of
×
457
                {value, {error, Reason}} ->
458
                    throw({aborted, #{reason => Reason, sql_query => Query}});
×
459
                _ ->
460
                    QRes
×
461
            end;
462
        _ ->
463
            QRes
32✔
464
    end.
465

466
%% Only for binaries, escapes only the content, '%' has to be added afterwards
467
%% The escape character is '$' as '\' causes issues in PostgreSQL
468
%% Returned value is NOT safe to use outside of a prepared statement
469
-spec escape_prepared_like(binary()) -> binary().
470
escape_prepared_like(S) ->
471
    << (escape_prepared_like_character(C)) || <<C>> <= S >>.
256✔
472

473
%% @doc Escape character that will confuse an SQL engine
474
%% Percent and underscore only need to be escaped for
475
%% pattern matching like statement
476
%% INFO: Used in mod_vcard_rdbms.
477
%% Searches in the middle of text, non-efficient
478
-spec escape_like(binary() | string()) -> escaped_like().
479
escape_like(S) ->
480
    {escaped_like, [$', $%, escape_like_internal(S), $%, $']}.
112✔
481

482
-spec escape_like_prefix(binary() | string()) -> escaped_like().
483
escape_like_prefix(S) ->
484
    {escaped_like, [$', escape_like_internal(S), $%, $']}.
×
485

486
-spec escape_binary(mongooseim:host_type_or_global(), binary()) -> escaped_binary().
487
escape_binary(_HostType, Bin) when is_binary(Bin) ->
488
    {escaped_binary, mongoose_rdbms_backend:escape_binary(Bin)}.
1,404✔
489

490
%% @doc The same as escape, but returns value including ''
491
-spec escape_string(binary() | string()) -> escaped_string().
492
escape_string(S) ->
493
    {escaped_string, escape_string_internal(S)}.
912✔
494

495
-spec escape_integer(integer()) -> escaped_integer().
496
escape_integer(I) when is_integer(I) ->
497
    {escaped_integer, integer_to_binary(I)}.
×
498

499
%% Be aware, that we can't just use escaped_integer here.
500
%% Because of the error in pgsql:
501
%% column \"match_all\" is of type boolean but expression is of type integer
502
-spec escape_boolean(boolean()) -> escaped_boolean().
503
escape_boolean(true) ->
504
    {escaped_boolean, "'1'"};
16✔
505
escape_boolean(false) ->
506
    {escaped_boolean, "'0'"}.
16✔
507

508
-spec escape_null() -> escaped_null().
509
escape_null() ->
510
    {escaped_null, "null"}.
192✔
511

512

513
%% @doc SQL-injection check.
514
%% Call this function just before using value from escape_string/1 inside a query.
515
-spec use_escaped_string(escaped_string()) -> sql_query_part().
516
use_escaped_string({escaped_string, S}) ->
517
    S;
912✔
518
use_escaped_string(X) ->
519
    %% We need to print an error, because in some places
520
    %% the error can be just ignored, because of too wide catches.
521
    ?LOG_ERROR(#{what => rdbms_use_escaped_failure, value => X,
×
522
        stacktrace => erlang:process_info(self(), current_stacktrace)}),
×
523
    erlang:error({use_escaped_string, X}).
×
524

525
-spec use_escaped_binary(escaped_binary()) -> sql_query_part().
526
use_escaped_binary({escaped_binary, S}) ->
527
    S;
1,404✔
528
use_escaped_binary(X) ->
529
    ?LOG_ERROR(#{what => rdbms_use_escaped_failure, value => X,
×
530
        stacktrace => erlang:process_info(self(), current_stacktrace)}),
×
531
    erlang:error({use_escaped_binary, X}).
×
532

533
-spec use_escaped_like(escaped_like()) -> sql_query_part().
534
use_escaped_like({escaped_like, S}) ->
535
    S;
112✔
536
use_escaped_like(X) ->
537
    ?LOG_ERROR(#{what => rdbms_use_escaped_failure, value => X,
×
538
        stacktrace => erlang:process_info(self(), current_stacktrace)}),
×
539
    erlang:error({use_escaped_like, X}).
×
540

541
-spec use_escaped_integer(escaped_integer()) -> sql_query_part().
542
use_escaped_integer({escaped_integer, S}) ->
543
    S;
×
544
use_escaped_integer(X) ->
545
    ?LOG_ERROR(#{what => rdbms_use_escaped_failure, value => X,
×
546
        stacktrace => erlang:process_info(self(), current_stacktrace)}),
×
547
    erlang:error({use_escaped_integer, X}).
×
548

549
-spec use_escaped_boolean(escaped_boolean()) -> sql_query_part().
550
use_escaped_boolean({escaped_boolean, S}) ->
551
    S;
32✔
552
use_escaped_boolean(X) ->
553
    ?LOG_ERROR(#{what => rdbms_use_escaped_failure, value => X,
×
554
        stacktrace => erlang:process_info(self(), current_stacktrace)}),
×
555
    erlang:error({use_escaped_boolean, X}).
×
556

557
-spec use_escaped_null(escaped_null()) -> sql_query_part().
558
use_escaped_null({escaped_null, S}) ->
559
    S;
192✔
560
use_escaped_null(X) ->
561
    ?LOG_ERROR(#{what => rdbms_use_escaped_failure, value => X,
×
562
        stacktrace => erlang:process_info(self(), current_stacktrace)}),
×
563
    erlang:error({use_escaped_null, X}).
×
564

565
%% Use this function, if type is unknown.
566
%% Be aware, you can't pass escaped_like() there.
567
-spec use_escaped(Value) -> sql_query_part() when
568
      Value :: escaped_value().
569
use_escaped({escaped_string, _}=X) ->
570
    use_escaped_string(X);
912✔
571
use_escaped({escaped_binary, _}=X) ->
572
    use_escaped_binary(X);
1,404✔
573
use_escaped({escaped_integer, _}=X) ->
574
    use_escaped_integer(X);
×
575
use_escaped({escaped_boolean, _}=X) ->
576
    use_escaped_boolean(X);
32✔
577
use_escaped({escaped_null, _}=X) ->
578
    use_escaped_null(X);
192✔
579
use_escaped(X) ->
580
    ?LOG_ERROR(#{what => rdbms_use_escaped_failure, value => X,
×
581
        stacktrace => erlang:process_info(self(), current_stacktrace)}),
×
582
    erlang:error({use_escaped, X}).
×
583

584
-spec escape_prepared_like_character(char()) -> binary().
585
escape_prepared_like_character($%) -> <<"$%">>;
64✔
586
escape_prepared_like_character($_) -> <<"$_">>;
48✔
587
escape_prepared_like_character($$) -> <<"$$">>;
×
588
escape_prepared_like_character(C) -> <<C>>.
952✔
589

590
-spec escape_like_internal(binary() | string()) -> binary() | string().
591
escape_like_internal(S) when is_binary(S) ->
592
    list_to_binary(escape_like_internal(binary_to_list(S)));
112✔
593
escape_like_internal(S) when is_list(S) ->
594
    [escape_like_character(C) || C <- S].
112✔
595

596
escape_string_internal(S) ->
597
    case mongoose_backend:is_exported(global, ?MODULE, escape_string, 1) of
912✔
598
        true ->
599
            mongoose_rdbms_backend:escape_string(S);
228✔
600
        false ->
601
            %% generic escaping
602
            [$', escape_characters(S), $']
684✔
603
    end.
604

605
escape_characters(S) when is_binary(S) ->
606
    list_to_binary(escape_characters(binary_to_list(S)));
684✔
607
escape_characters(S) when is_list(S) ->
608
    [escape_character(C) || C <- S].
684✔
609

610
escape_like_character($%) -> "\\%";
×
611
escape_like_character($_) -> "\\_";
×
612
escape_like_character(C)  -> escape_character(C).
480✔
613

614
%% Characters to escape
615
escape_character($\0) -> "\\0";
×
616
escape_character($\n) -> "\\n";
132,072✔
617
escape_character($\t) -> "\\t";
12,000✔
618
escape_character($\b) -> "\\b";
12,000✔
619
escape_character($\r) -> "\\r";
72✔
620
escape_character($')  -> "''";
216✔
621
escape_character($")  -> "\\\"";
108✔
622
escape_character($\\) -> "\\\\";
108✔
623
escape_character(C)   -> C.
211,368✔
624

625

626
-spec unescape_binary(mongooseim:host_type_or_global(), binary()) -> binary().
627
unescape_binary(_HostType, Bin) when is_binary(Bin) ->
628
    mongoose_rdbms_backend:unescape_binary(Bin).
58,458✔
629

630

631
-spec result_to_integer(binary() | integer()) -> integer().
632
result_to_integer(Int) when is_integer(Int) ->
633
    Int;
328,173✔
634
result_to_integer(Bin) when is_binary(Bin) ->
UNCOV
635
    binary_to_integer(Bin).
×
636

637
selected_to_integer({selected, [{BInt}]}) ->
638
    result_to_integer(BInt).
90,516✔
639

640
%% Converts a value from a CHAR(1) field to integer
641
character_to_integer(<<X>>) -> X;
11,784✔
642
character_to_integer(X) when is_integer(X) -> X.
11,792✔
643

644
%% pgsql returns booleans as "t" or "f"
645
-spec to_bool(binary() | string() | atom() | integer() | any()) -> boolean().
646
to_bool(B) when is_binary(B) ->
647
    to_bool(binary_to_list(B));
32✔
648
to_bool("t") -> true;
16✔
649
to_bool("true") -> true;
×
650
to_bool("1") -> true;
×
651
to_bool(true) -> true;
812✔
652
to_bool(1) -> true;
832✔
653
to_bool(_) -> false.
6,484✔
654

655
%%%----------------------------------------------------------------------
656
%%% Callback functions from gen_server
657
%%%----------------------------------------------------------------------
658
-spec init(options()) -> {ok, state()}.
659
init(Opts = #{query_timeout := QueryTimeout, max_start_interval := MaxStartInterval}) ->
660
    process_flag(trap_exit, true),
3,658✔
661
    KeepaliveInterval = maps:get(keepalive_interval, Opts, undefined),
3,658✔
662
    % retries are delayed exponentially, max_start_interval limits the delay
663
    % e.g. if the limit is 30, the delays are: 2, 4, 8, 16, 30, 30, ...
664
    case connect(Opts, ?CONNECT_RETRIES, 2, MaxStartInterval) of
3,658✔
665
        {ok, DbRef} ->
666
            schedule_keepalive(KeepaliveInterval),
3,652✔
667
            {ok, #state{db_ref = DbRef,
3,652✔
668
                        keepalive_interval = KeepaliveInterval,
669
                        query_timeout = QueryTimeout}};
670
        Error ->
671
            {stop, Error}
6✔
672
    end.
673

674

675
handle_call({sql_cmd, Command, Timestamp}, From, State) ->
676
    {Result, NewState} = run_sql_cmd(Command, From, State, Timestamp),
1,135,579✔
677
    case abort_on_driver_error(Result) of
1,135,579✔
678
        {stop, Reason} -> {stop, Reason, Result, NewState};
×
679
        continue -> {reply, Result, NewState}
1,135,579✔
680
    end;
681
handle_call(get_db_info, _, #state{db_ref = DbRef} = State) ->
682
    {reply, {ok, db_engine(global), DbRef}, State};
11,770✔
683
handle_call(Request, From, State) ->
684
    ?UNEXPECTED_CALL(Request, From),
×
685
    {reply, {error, badarg}, State}.
×
686

687
handle_cast({sql_cmd, Command, Timestamp}, State) ->
688
    {Result, NewState} = run_sql_cmd(Command, undefined, State, Timestamp),
32✔
689
    case abort_on_driver_error(Result) of
32✔
690
        {stop, Reason} -> {stop, Reason, NewState};
×
691
        continue -> {noreply, NewState}
32✔
692
    end;
693
handle_cast(Request, State) ->
694
    ?UNEXPECTED_CAST(Request),
×
695
    {noreply, State}.
×
696

697
code_change(_OldVsn, State, _Extra) ->
698
    {ok, State}.
×
699

700
handle_info(keepalive, #state{keepalive_interval = KeepaliveInterval} = State) ->
701
    case sql_query_internal([?KEEPALIVE_QUERY], State) of
54✔
702
        {selected, _} ->
703
            schedule_keepalive(KeepaliveInterval),
48✔
704
            {noreply, State};
48✔
705
        {error, _} = Error ->
706
            {stop, {keepalive_failed, Error}, State}
6✔
707
    end;
708
handle_info({'EXIT', _Pid, _Reason} = Reason, State) ->
709
    {stop, Reason, State};
×
710
handle_info(Info, State) ->
711
    ?UNEXPECTED_INFO(Info),
×
712
    {noreply, State}.
×
713

714
-spec terminate(Reason :: term(), state()) -> any().
715
terminate(_Reason, #state{db_ref = DbRef}) ->
716
    catch mongoose_rdbms_backend:disconnect(DbRef).
3,526✔
717

718
%%%----------------------------------------------------------------------
719
%%% Internal functions
720
%%%----------------------------------------------------------------------
721

722
-spec run_sql_cmd(Command :: any(), From :: any(), State :: state(), Timestamp :: integer()) ->
723
    {Result :: term(), state()}.
724
run_sql_cmd(Command, _From, State, Timestamp) ->
725
    Now = erlang:monotonic_time(millisecond),
1,135,611✔
726
    case Now - Timestamp of
1,135,611✔
727
        Age when Age  < ?TRANSACTION_TIMEOUT ->
728
            outer_op(Command, State);
1,135,611✔
729
        Age ->
730
            ?LOG_ERROR(#{what => rdbms_db_not_available_or_too_slow,
×
731
                         text => <<"Discarding request">>, age => Age, command => Command}),
×
732
            {reply, {error, timeout}, State}
×
733
    end.
734

735
%% @doc Only called by handle_call, only handles top level operations.
736
-spec outer_op(rdbms_msg(), state()) -> {query_result()
737
                                         | transaction_result()
738
                                         | dirty_result(), state()}.
739
outer_op({sql_query, Query}, State) ->
740
    {sql_query_internal(Query, State), State};
15,099✔
741
outer_op({sql_transaction, F}, State) ->
742
    outer_transaction(F, ?MAX_TRANSACTION_RESTARTS, "", State);
159,575✔
743
outer_op({sql_dirty, F}, State) ->
744
    sql_dirty_internal(F, State);
6,979✔
745
outer_op({sql_execute, Name, Params}, State) ->
746
    sql_execute(outer_op, Name, Params, State);
953,926✔
747
outer_op({sql_execute_wrapped, Name, Params, Wrapper}, State) ->
748
    try
32✔
749
        Wrapper(fun() -> sql_execute(outer_op, Name, Params, State) end)
32✔
750
    catch
751
        _Class:Error ->
752
            ?LOG_ERROR(#{what => sql_execute_wrapped_failed, reason => Error,
16✔
753
                         statement_name => Name, wrapper_fun => Wrapper}),
×
754
            {{error, Error}, State}
16✔
755
    end.
756

757
%% @doc Called via sql_query/transaction/bloc from client code when inside a
758
%% nested operation
759
-spec nested_op(rdbms_msg(), state()) -> any().
760
nested_op({sql_query, Query}, State) ->
761
    %% XXX - use sql_query_t here insted? Most likely would break
762
    %% callers who expect {error, _} tuples (sql_query_t turns
763
    %% these into throws)
764
    {sql_query_internal(Query, State), State};
64✔
765
nested_op({sql_transaction, F}, State) ->
766
    %% Transaction inside a transaction
767
    inner_transaction(F, State);
×
768
nested_op({sql_execute, Name, Params}, State) ->
769
    sql_execute(nested_op, Name, Params, State);
394,811✔
770
nested_op({sql_execute_wrapped, Name, Params, Wrapper}, State) ->
771
    Wrapper(fun() -> sql_execute(nested_op, Name, Params, State) end).
176✔
772

773
%% @doc Never retry nested transactions - only outer transactions
774
-spec inner_transaction(fun(), state()) -> transaction_result() | {'EXIT', any()}.
775
inner_transaction(F, _State) ->
776
    case catch F() of
×
777
        {aborted, Reason} ->
778
            {aborted, Reason};
×
779
        {'EXIT', Reason} ->
780
            {'EXIT', Reason};
×
781
        {atomic, Res} ->
782
            {atomic, Res};
×
783
        Res ->
784
            {atomic, Res}
×
785
    end.
786

787
-spec outer_transaction(F :: fun(),
788
                        NRestarts :: 0..10,
789
                        Reason :: any(), state()) -> {transaction_result(), state()}.
790
outer_transaction(F, NRestarts, _Reason, State) ->
791
    sql_query_internal(rdbms_queries:begin_trans(), State),
160,594✔
792
    put_state(State),
160,594✔
793
    {Result, StackTrace} = apply_transaction_function(F),
160,594✔
794
    NewState = erase_state(),
160,594✔
795
    case Result of
160,594✔
796
        {aborted, Reason} when NRestarts > 0 ->
797
            %% Retry outer transaction upto NRestarts times.
798
            sql_query_internal([<<"rollback;">>], NewState),
1,019✔
799
            outer_transaction(F, NRestarts - 1, Reason, NewState);
1,019✔
800
        {aborted, #{reason := Reason, sql_query := SqlQuery}}
801
            when NRestarts =:= 0 ->
802
            %% Too many retries of outer transaction.
803
            ?LOG_ERROR(#{what => rdbms_sql_transaction_restarts_exceeded,
×
804
                restarts => ?MAX_TRANSACTION_RESTARTS, last_abort_reason => Reason,
805
                last_sql_query => iolist_to_binary(SqlQuery),
806
                stacktrace => StackTrace, state => NewState}),
×
807
            sql_query_internal([<<"rollback;">>], NewState),
×
808
            {{aborted, Reason}, NewState};
×
809
        {aborted, Reason} when NRestarts =:= 0 -> %% old format for abort
810
            %% Too many retries of outer transaction.
811
            ?LOG_ERROR(#{what => rdbms_sql_transaction_restarts_exceeded,
96✔
812
                restarts => ?MAX_TRANSACTION_RESTARTS,
813
                last_abort_reason => Reason, stacktrace => StackTrace,
814
                state => NewState}),
×
815
            sql_query_internal([<<"rollback;">>], NewState),
96✔
816
            {{aborted, Reason}, NewState};
96✔
817
        {'EXIT', Reason} ->
818
            %% Abort sql transaction on EXIT from outer txn only.
819
            sql_query_internal([<<"rollback;">>], NewState),
16✔
820
            {{aborted, Reason}, NewState};
16✔
821
        Res ->
822
            %% Commit successful outer txn
823
            sql_query_internal([<<"commit;">>], NewState),
159,463✔
824
            {{atomic, Res}, NewState}
159,463✔
825
    end.
826

827
-spec apply_transaction_function(F :: fun()) -> {any(), list()}.
828
apply_transaction_function(F) ->
829
    try
160,594✔
830
        {F(), []}
160,594✔
831
    catch
832
        throw:ThrowResult:StackTrace ->
833
            {ThrowResult, StackTrace};
1,115✔
834
        Class:Reason:StackTrace ->
835
            ?LOG_ERROR(#{what => rdbms_outer_transaction_failed, class => Class,
16✔
836
                reason => Reason, stacktrace => StackTrace}),
×
837
            {{'EXIT', Reason}, StackTrace}
16✔
838
    end.
839

840
sql_query_internal(Query, #state{db_ref = DBRef, query_timeout = QueryTimeout}) ->
841
    case mongoose_rdbms_backend:query(DBRef, Query, QueryTimeout) of
336,437✔
842
        {error, "No SQL-driver information available."} ->
843
            {updated, 0}; %% workaround for odbc bug
×
844
        Result ->
845
            Result
336,437✔
846
    end.
847

848
sql_dirty_internal(F, State) ->
849
    put_state(State),
6,979✔
850
    Result =
6,979✔
851
    try F() of
6,979✔
852
        Result0 ->
853
            {ok, Result0}
6,979✔
854
    catch
855
        _C:R ->
856
            {error, R}
×
857
    end,
858
    {Result, erase_state()}.
6,979✔
859

860
-spec sql_execute(Type :: atom(), query_name(), query_params(), state()) ->
861
    {query_result(), state()}.
862
sql_execute(Type, Name, Params, State = #state{db_ref = DBRef, query_timeout = QueryTimeout}) ->
863
    %% Postgres allows to prepare statement only once, so we should take care that NewState is updated
864
    {StatementRef, NewState} = prepare_statement(Name, State),
1,348,929✔
865
    put_state(NewState),
1,348,929✔
866
    Res = try mongoose_rdbms_backend:execute(DBRef, StatementRef, Params, QueryTimeout)
1,348,929✔
867
          catch Class:Reason:StackTrace ->
868
            ?LOG_ERROR(#{what => rdbms_sql_execute_failed, statement_name => Name,
×
869
                class => Class, reason => Reason, params => Params,
870
                stacktrace => StackTrace}),
×
871
            erlang:raise(Class, Reason, StackTrace)
×
872
          end,
873
    check_execute_result(Type, Res, Name, Params),
1,348,929✔
874
    {Res, NewState}.
1,347,770✔
875

876
%% Similar check as in sql_query_t
877
check_execute_result(outer_op, _Res, _Name, _Params) ->
878
    ok;
953,942✔
879
check_execute_result(nested_op, Res, Name, Params) ->
880
    %% Res is not a list (i.e. executes are one query only and one result set only)
881
    case Res of
394,987✔
882
        {error, Reason} ->
883
            throw({aborted, #{reason => Reason, statement_name => Name, params => Params}});
1,159✔
884
        _ when is_tuple(Res) ->
885
            ok
393,828✔
886
    end.
887

888
-spec prepare_statement(query_name(), state()) -> {Ref :: term(), state()}.
889
prepare_statement(Name, State = #state{db_ref = DBRef, prepared = Prepared}) ->
890
    case maps:get(Name, Prepared, undefined) of
1,348,929✔
891
        undefined ->
892
            {_, Table, Fields, Statement} = lookup_statement(Name),
23,110✔
893
            {ok, Ref} = mongoose_rdbms_backend:prepare(DBRef, Name, Table, Fields, Statement),
23,110✔
894
            {Ref, State#state{prepared = maps:put(Name, Ref, Prepared)}};
23,110✔
895

896
        Ref ->
897
            {Ref, State}
1,325,819✔
898
    end.
899

900
lookup_statement(Name) ->
901
    case ets:lookup(prepared_statements, Name) of
23,110✔
902
        [Rec] -> Rec;
23,110✔
903
        [] -> error({lookup_statement_failed, Name})
×
904
    end.
905

906
-spec abort_on_driver_error(_) -> continue | {stop, timeout | closed}.
907
abort_on_driver_error({error, "query timed out"}) -> %% mysql driver error
908
    {stop, timeout};
×
909
abort_on_driver_error({error, "Failed sending data on socket" ++ _}) -> %% mysql driver error
910
    {stop, closed};
×
911
abort_on_driver_error(_) ->
912
    continue.
1,135,611✔
913

914
-spec db_engine(mongooseim:host_type_or_global()) -> backend() | undefined.
915
db_engine(_HostType) ->
916
    try mongoose_backend:get_backend_name(global, ?MODULE)
156,659✔
917
    catch error:badarg -> undefined end.
255✔
918

919
%% @doc Used to optimise queries for different databases.
920
%% @todo Should be refactored to use host types with this module.
921
%% Also, this parameter should not be global, but pool-name parameterized
922
-spec db_type() -> mssql | generic.
923
db_type() ->
924
    case mongoose_config:get_opt(rdbms_server_type) of
240,556✔
925
        mssql -> mssql;
62,301✔
926
        _ -> generic
178,255✔
927
    end.
928

929
-spec connect(options(), Retry :: non_neg_integer(), RetryAfter :: non_neg_integer(),
930
              MaxRetryDelay :: non_neg_integer()) -> {ok, term()} | {error, any()}.
931
connect(#{query_timeout := QueryTimeout} = Options, Retry, RetryAfter, MaxRetryDelay) ->
932
    case mongoose_rdbms_backend:connect(Options, QueryTimeout) of
3,688✔
933
        {ok, _} = Ok ->
934
            Ok;
3,652✔
935
        Error when Retry =:= 0 ->
936
            Error;
6✔
937
        Error ->
938
            SleepFor = rand:uniform(RetryAfter),
30✔
939
            Backend = mongoose_backend:get_backend_name(global, ?MODULE),
30✔
940
            ?LOG_ERROR(#{what => rdbms_connection_attempt_error, backend => Backend,
30✔
941
                error => Error, sleep_for => SleepFor}),
×
942
            timer:sleep(timer:seconds(SleepFor)),
30✔
943
            NextRetryDelay = RetryAfter * RetryAfter,
30✔
944
            connect(Options, Retry - 1, min(MaxRetryDelay, NextRetryDelay), MaxRetryDelay)
30✔
945
    end.
946

947

948
-spec schedule_keepalive(KeepaliveInterval :: undefined | pos_integer()) -> any().
949
schedule_keepalive(KeepaliveInterval) ->
950
    case KeepaliveInterval of
3,700✔
951
        _ when is_integer(KeepaliveInterval) ->
952
            erlang:send_after(timer:seconds(KeepaliveInterval), self(), keepalive);
60✔
953
        undefined ->
954
            ok;
3,640✔
955
        Other ->
956
            ?LOG_ERROR(#{what => rdbms_wrong_keepalive_interval, reason => Other}),
×
957
            ok
×
958
    end.
959

960
%% ----- process state access, for convenient tracing
961

962
put_state(State) ->
963
    put(?STATE_KEY, State).
1,910,394✔
964

965
erase_state() ->
966
    erase(?STATE_KEY).
167,573✔
967

968
get_state() ->
969
    get(?STATE_KEY).
1,531,944✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc