emqx_ee_bridge_sqlserver_SUITE.erl 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. %%--------------------------------------------------------------------
  2. % Copyright (c) 2022-2023 EMQ Technologies Co., Ltd. All Rights Reserved.
  3. %%--------------------------------------------------------------------
  4. -module(emqx_ee_bridge_sqlserver_SUITE).
  5. -compile(nowarn_export_all).
  6. -compile(export_all).
  7. -include_lib("eunit/include/eunit.hrl").
  8. -include_lib("common_test/include/ct.hrl").
  9. -include_lib("snabbkaffe/include/snabbkaffe.hrl").
  10. % SQL definitions
  11. -define(SQL_BRIDGE,
  12. "insert into t_mqtt_msg(msgid, topic, qos, payload) values ( ${id}, ${topic}, ${qos}, ${payload})"
  13. ).
  14. -define(SQL_SERVER_DRIVER, "ms-sql").
  15. -define(SQL_CREATE_DATABASE_IF_NOT_EXISTS,
  16. " IF NOT EXISTS(SELECT name FROM sys.databases WHERE name = 'mqtt')"
  17. " BEGIN"
  18. " CREATE DATABASE mqtt;"
  19. " END"
  20. ).
  21. -define(SQL_CREATE_TABLE_IN_DB_MQTT,
  22. " CREATE TABLE mqtt.dbo.t_mqtt_msg"
  23. " (id int PRIMARY KEY IDENTITY(1000000001,1) NOT NULL,"
  24. " msgid VARCHAR(64) NULL,"
  25. " topic VARCHAR(100) NULL,"
  26. " qos tinyint NOT NULL DEFAULT 0,"
  27. %% use VARCHAR to use utf8 encoding
  28. %% for default, sqlserver use utf16 encoding NVARCHAR()
  29. " payload VARCHAR(100) NULL,"
  30. " arrived DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)"
  31. ).
  32. -define(SQL_DROP_DB_MQTT, "DROP DATABASE mqtt").
  33. -define(SQL_DROP_TABLE, "DROP TABLE mqtt.dbo.t_mqtt_msg").
  34. -define(SQL_DELETE, "DELETE from mqtt.dbo.t_mqtt_msg").
  35. -define(SQL_SELECT, "SELECT payload FROM mqtt.dbo.t_mqtt_msg").
  36. -define(SQL_SELECT_COUNT, "SELECT COUNT(*) FROM mqtt.dbo.t_mqtt_msg").
  37. % DB defaults
  38. -define(SQL_SERVER_DATABASE, "mqtt").
  39. -define(SQL_SERVER_USERNAME, "sa").
  40. -define(SQL_SERVER_PASSWORD, "mqtt_public1").
  41. -define(BATCH_SIZE, 10).
  42. -define(REQUEST_TIMEOUT_MS, 500).
  43. -define(WORKER_POOL_SIZE, 4).
  44. -define(WITH_CON(Process),
  45. Con = connect_direct_sqlserver(Config),
  46. Process,
  47. ok = disconnect(Con)
  48. ).
  49. %% How to run it locally (all commands are run in $PROJ_ROOT dir):
  50. %% A: run ct on host
  51. %% 1. Start all deps services
  52. %% sudo docker compose -f .ci/docker-compose-file/docker-compose.yaml \
  53. %% -f .ci/docker-compose-file/docker-compose-sqlserver.yaml \
  54. %% -f .ci/docker-compose-file/docker-compose-toxiproxy.yaml \
  55. %% up --build
  56. %%
  57. %% 2. Run use cases with special environment variables
  58. %% 11433 is toxiproxy exported port.
  59. %% Local:
  60. %% ```
  61. %% SQLSERVER_HOST=toxiproxy SQLSERVER_PORT=11433 \
  62. %% PROXY_HOST=toxiproxy PROXY_PORT=1433 \
  63. %% ./rebar3 as test ct -c -v --readable true --name ct@127.0.0.1 --suite lib-ee/emqx_ee_bridge/test/emqx_ee_bridge_sqlserver_SUITE.erl
  64. %% ```
  65. %%
  66. %% B: run ct in docker container
  67. %% run script:
  68. %% ./scripts/ct/run.sh --ci --app lib-ee/emqx_ee_bridge/ \
  69. %% -- --name 'test@127.0.0.1' -c -v --readable true --suite lib-ee/emqx_ee_bridge/test/emqx_ee_bridge_sqlserver_SUITE.erl
  70. %%------------------------------------------------------------------------------
  71. %% CT boilerplate
  72. %%------------------------------------------------------------------------------
  73. all() ->
  74. [
  75. {group, async},
  76. {group, sync}
  77. ].
  78. groups() ->
  79. TCs = emqx_common_test_helpers:all(?MODULE),
  80. NonBatchCases = [t_write_timeout],
  81. BatchingGroups = [{group, with_batch}, {group, without_batch}],
  82. [
  83. {async, BatchingGroups},
  84. {sync, BatchingGroups},
  85. {with_batch, TCs -- NonBatchCases},
  86. {without_batch, TCs}
  87. ].
  88. init_per_group(async, Config) ->
  89. [{query_mode, async} | Config];
  90. init_per_group(sync, Config) ->
  91. [{query_mode, sync} | Config];
  92. init_per_group(with_batch, Config0) ->
  93. Config = [{enable_batch, true} | Config0],
  94. common_init(Config);
  95. init_per_group(without_batch, Config0) ->
  96. Config = [{enable_batch, false} | Config0],
  97. common_init(Config);
  98. init_per_group(_Group, Config) ->
  99. Config.
  100. end_per_group(Group, Config) when Group =:= with_batch; Group =:= without_batch ->
  101. connect_and_drop_table(Config),
  102. connect_and_drop_db(Config),
  103. ProxyHost = ?config(proxy_host, Config),
  104. ProxyPort = ?config(proxy_port, Config),
  105. emqx_common_test_helpers:reset_proxy(ProxyHost, ProxyPort),
  106. ok;
  107. end_per_group(_Group, _Config) ->
  108. ok.
  109. init_per_suite(Config) ->
  110. Config.
  111. end_per_suite(_Config) ->
  112. emqx_mgmt_api_test_util:end_suite(),
  113. ok = emqx_common_test_helpers:stop_apps([emqx_bridge, emqx_conf]),
  114. ok.
  115. init_per_testcase(_Testcase, Config) ->
  116. %% drop database and table
  117. %% connect_and_clear_table(Config),
  118. %% create a new one
  119. %% TODO: create a new database for each test case
  120. delete_bridge(Config),
  121. snabbkaffe:start_trace(),
  122. Config.
  123. end_per_testcase(_Testcase, Config) ->
  124. ProxyHost = ?config(proxy_host, Config),
  125. ProxyPort = ?config(proxy_port, Config),
  126. emqx_common_test_helpers:reset_proxy(ProxyHost, ProxyPort),
  127. connect_and_clear_table(Config),
  128. ok = snabbkaffe:stop(),
  129. delete_bridge(Config),
  130. ok.
  131. %%------------------------------------------------------------------------------
  132. %% Testcases
  133. %%------------------------------------------------------------------------------
  134. t_setup_via_config_and_publish(Config) ->
  135. ?assertMatch(
  136. {ok, _},
  137. create_bridge(Config)
  138. ),
  139. Val = str(erlang:unique_integer()),
  140. SentData = sent_data(Val),
  141. ?check_trace(
  142. begin
  143. ?wait_async_action(
  144. ?assertEqual(ok, send_message(Config, SentData)),
  145. #{?snk_kind := sqlserver_connector_query_return},
  146. 10_000
  147. ),
  148. ?assertMatch(
  149. [{Val}],
  150. connect_and_get_payload(Config)
  151. ),
  152. ok
  153. end,
  154. fun(Trace0) ->
  155. Trace = ?of_kind(sqlserver_connector_query_return, Trace0),
  156. ?assertMatch([#{result := ok}], Trace),
  157. ok
  158. end
  159. ),
  160. ok.
  161. t_setup_via_http_api_and_publish(Config) ->
  162. BridgeType = ?config(sqlserver_bridge_type, Config),
  163. Name = ?config(sqlserver_name, Config),
  164. SQLServerConfig0 = ?config(sqlserver_config, Config),
  165. SQLServerConfig = SQLServerConfig0#{
  166. <<"name">> => Name,
  167. <<"type">> => BridgeType
  168. },
  169. ?assertMatch(
  170. {ok, _},
  171. create_bridge_http(SQLServerConfig)
  172. ),
  173. Val = str(erlang:unique_integer()),
  174. SentData = sent_data(Val),
  175. ?check_trace(
  176. begin
  177. ?wait_async_action(
  178. ?assertEqual(ok, send_message(Config, SentData)),
  179. #{?snk_kind := sqlserver_connector_query_return},
  180. 10_000
  181. ),
  182. ?assertMatch(
  183. [{Val}],
  184. connect_and_get_payload(Config)
  185. ),
  186. ok
  187. end,
  188. fun(Trace0) ->
  189. Trace = ?of_kind(sqlserver_connector_query_return, Trace0),
  190. ?assertMatch([#{result := ok}], Trace),
  191. ok
  192. end
  193. ),
  194. ok.
  195. t_get_status(Config) ->
  196. ?assertMatch(
  197. {ok, _},
  198. create_bridge(Config)
  199. ),
  200. ProxyPort = ?config(proxy_port, Config),
  201. ProxyHost = ?config(proxy_host, Config),
  202. ProxyName = ?config(proxy_name, Config),
  203. health_check_resource_ok(Config),
  204. emqx_common_test_helpers:with_failure(down, ProxyName, ProxyHost, ProxyPort, fun() ->
  205. health_check_resource_down(Config)
  206. end),
  207. ok.
  208. t_create_disconnected(Config) ->
  209. ProxyPort = ?config(proxy_port, Config),
  210. ProxyHost = ?config(proxy_host, Config),
  211. ProxyName = ?config(proxy_name, Config),
  212. emqx_common_test_helpers:with_failure(down, ProxyName, ProxyHost, ProxyPort, fun() ->
  213. ?assertMatch({ok, _}, create_bridge(Config)),
  214. health_check_resource_down(Config)
  215. end),
  216. health_check_resource_ok(Config),
  217. ok.
  218. t_create_with_invalid_password(Config) ->
  219. BridgeType = ?config(sqlserver_bridge_type, Config),
  220. Name = ?config(sqlserver_name, Config),
  221. SQLServerConfig0 = ?config(sqlserver_config, Config),
  222. SQLServerConfig = SQLServerConfig0#{
  223. <<"name">> => Name,
  224. <<"type">> => BridgeType,
  225. <<"password">> => <<"wrong_password">>
  226. },
  227. ?check_trace(
  228. begin
  229. ?assertMatch(
  230. {ok, _},
  231. create_bridge_http(SQLServerConfig)
  232. )
  233. end,
  234. fun(Trace) ->
  235. ?assertMatch(
  236. [#{error := {start_pool_failed, _, _}}],
  237. ?of_kind(sqlserver_connector_start_failed, Trace)
  238. ),
  239. ok
  240. end
  241. ),
  242. ok.
  243. t_write_failure(Config) ->
  244. ProxyName = ?config(proxy_name, Config),
  245. ProxyPort = ?config(proxy_port, Config),
  246. ProxyHost = ?config(proxy_host, Config),
  247. QueryMode = ?config(query_mode, Config),
  248. Val = str(erlang:unique_integer()),
  249. SentData = sent_data(Val),
  250. {{ok, _}, {ok, _}} =
  251. ?wait_async_action(
  252. create_bridge(Config),
  253. #{?snk_kind := resource_connected_enter},
  254. 20_000
  255. ),
  256. emqx_common_test_helpers:with_failure(down, ProxyName, ProxyHost, ProxyPort, fun() ->
  257. case QueryMode of
  258. sync ->
  259. ?assertMatch(
  260. {error, {resource_error, #{reason := timeout}}},
  261. send_message(Config, SentData)
  262. );
  263. async ->
  264. ?assertMatch(
  265. ok, send_message(Config, SentData)
  266. )
  267. end
  268. end),
  269. ok.
  270. t_write_timeout(_Config) ->
  271. %% msodbc driver handled all connection exceptions
  272. %% the case is same as t_write_failure/1
  273. ok.
  274. t_simple_query(Config) ->
  275. BatchSize = batch_size(Config),
  276. ?assertMatch(
  277. {ok, _},
  278. create_bridge(Config)
  279. ),
  280. {Requests, Vals} = gen_batch_req(BatchSize),
  281. ?check_trace(
  282. begin
  283. ?wait_async_action(
  284. begin
  285. [?assertEqual(ok, query_resource(Config, Request)) || Request <- Requests]
  286. end,
  287. #{?snk_kind := sqlserver_connector_query_return},
  288. 10_000
  289. ),
  290. %% just assert the data count is correct
  291. ?assertMatch(
  292. BatchSize,
  293. connect_and_get_count(Config)
  294. ),
  295. %% assert the data order is correct
  296. ?assertMatch(
  297. Vals,
  298. connect_and_get_payload(Config)
  299. )
  300. end,
  301. fun(Trace0) ->
  302. Trace = ?of_kind(sqlserver_connector_query_return, Trace0),
  303. case BatchSize of
  304. 1 ->
  305. ?assertMatch([#{result := ok}], Trace);
  306. _ ->
  307. [?assertMatch(#{result := ok}, Trace1) || Trace1 <- Trace]
  308. end,
  309. ok
  310. end
  311. ),
  312. ok.
  313. -define(MISSING_TINYINT_ERROR,
  314. "[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]"
  315. "Conversion failed when converting the varchar value 'undefined' to data type tinyint. SQLSTATE IS: 22018"
  316. ).
  317. t_missing_data(Config) ->
  318. QueryMode = ?config(query_mode, Config),
  319. ?assertMatch(
  320. {ok, _},
  321. create_bridge(Config)
  322. ),
  323. Result = send_message(Config, #{}),
  324. case QueryMode of
  325. sync ->
  326. ?assertMatch(
  327. {error, {unrecoverable_error, {invalid_request, ?MISSING_TINYINT_ERROR}}},
  328. Result
  329. );
  330. async ->
  331. ?assertMatch(
  332. ok, send_message(Config, #{})
  333. )
  334. end,
  335. ok.
  336. t_bad_parameter(Config) ->
  337. QueryMode = ?config(query_mode, Config),
  338. ?assertMatch(
  339. {ok, _},
  340. create_bridge(Config)
  341. ),
  342. Result = send_message(Config, #{}),
  343. case QueryMode of
  344. sync ->
  345. ?assertMatch(
  346. {error, {unrecoverable_error, {invalid_request, ?MISSING_TINYINT_ERROR}}},
  347. Result
  348. );
  349. async ->
  350. ?assertMatch(
  351. ok, send_message(Config, #{})
  352. )
  353. end,
  354. ok.
  355. %%------------------------------------------------------------------------------
  356. %% Helper fns
  357. %%------------------------------------------------------------------------------
  358. common_init(ConfigT) ->
  359. Host = os:getenv("SQLSERVER_HOST", "toxiproxy"),
  360. Port = list_to_integer(os:getenv("SQLSERVER_PORT", "1433")),
  361. Config0 = [
  362. {sqlserver_host, Host},
  363. {sqlserver_port, Port},
  364. %% see also for `proxy_name` : $PROJ_ROOT/.ci/docker-compose-file/toxiproxy.json
  365. {proxy_name, "sqlserver"},
  366. {batch_size, batch_size(ConfigT)}
  367. | ConfigT
  368. ],
  369. BridgeType = proplists:get_value(bridge_type, Config0, <<"sqlserver">>),
  370. case emqx_common_test_helpers:is_tcp_server_available(Host, Port) of
  371. true ->
  372. % Setup toxiproxy
  373. ProxyHost = os:getenv("PROXY_HOST", "toxiproxy"),
  374. ProxyPort = list_to_integer(os:getenv("PROXY_PORT", "8474")),
  375. emqx_common_test_helpers:reset_proxy(ProxyHost, ProxyPort),
  376. % Ensure EE bridge module is loaded
  377. _ = application:load(emqx_ee_bridge),
  378. _ = emqx_ee_bridge:module_info(),
  379. ok = emqx_common_test_helpers:start_apps([emqx_conf, emqx_bridge]),
  380. emqx_mgmt_api_test_util:init_suite(),
  381. % Connect to sqlserver directly
  382. % drop old db and table, and then create new ones
  383. connect_and_create_db_and_table(Config0),
  384. {Name, SQLServerConf} = sqlserver_config(BridgeType, Config0),
  385. Config =
  386. [
  387. {sqlserver_config, SQLServerConf},
  388. {sqlserver_bridge_type, BridgeType},
  389. {sqlserver_name, Name},
  390. {proxy_host, ProxyHost},
  391. {proxy_port, ProxyPort}
  392. | Config0
  393. ],
  394. Config;
  395. false ->
  396. case os:getenv("IS_CI") of
  397. "yes" ->
  398. throw(no_sqlserver);
  399. _ ->
  400. {skip, no_sqlserver}
  401. end
  402. end.
  403. sqlserver_config(BridgeType, Config) ->
  404. Port = integer_to_list(?config(sqlserver_port, Config)),
  405. Server = ?config(sqlserver_host, Config) ++ ":" ++ Port,
  406. Name = atom_to_binary(?MODULE),
  407. BatchSize = batch_size(Config),
  408. QueryMode = ?config(query_mode, Config),
  409. ConfigString =
  410. io_lib:format(
  411. "bridges.~s.~s {\n"
  412. " enable = true\n"
  413. " server = ~p\n"
  414. " database = ~p\n"
  415. " username = ~p\n"
  416. " password = ~p\n"
  417. " sql = ~p\n"
  418. " driver = ~p\n"
  419. " resource_opts = {\n"
  420. " request_timeout = 500ms\n"
  421. " batch_size = ~b\n"
  422. " query_mode = ~s\n"
  423. " worker_pool_size = ~b\n"
  424. " }\n"
  425. "}",
  426. [
  427. BridgeType,
  428. Name,
  429. Server,
  430. ?SQL_SERVER_DATABASE,
  431. ?SQL_SERVER_USERNAME,
  432. ?SQL_SERVER_PASSWORD,
  433. ?SQL_BRIDGE,
  434. ?SQL_SERVER_DRIVER,
  435. BatchSize,
  436. QueryMode,
  437. ?WORKER_POOL_SIZE
  438. ]
  439. ),
  440. {Name, parse_and_check(ConfigString, BridgeType, Name)}.
  441. parse_and_check(ConfigString, BridgeType, Name) ->
  442. {ok, RawConf} = hocon:binary(ConfigString, #{format => map}),
  443. hocon_tconf:check_plain(emqx_bridge_schema, RawConf, #{required => false, atom_key => false}),
  444. #{<<"bridges">> := #{BridgeType := #{Name := Config}}} = RawConf,
  445. Config.
  446. create_bridge(Config) ->
  447. create_bridge(Config, _Overrides = #{}).
  448. create_bridge(Config, Overrides) ->
  449. BridgeType = ?config(sqlserver_bridge_type, Config),
  450. Name = ?config(sqlserver_name, Config),
  451. SSConfig0 = ?config(sqlserver_config, Config),
  452. SSConfig = emqx_utils_maps:deep_merge(SSConfig0, Overrides),
  453. emqx_bridge:create(BridgeType, Name, SSConfig).
  454. delete_bridge(Config) ->
  455. BridgeType = ?config(sqlserver_bridge_type, Config),
  456. Name = ?config(sqlserver_name, Config),
  457. emqx_bridge:remove(BridgeType, Name).
  458. create_bridge_http(Params) ->
  459. Path = emqx_mgmt_api_test_util:api_path(["bridges"]),
  460. AuthHeader = emqx_mgmt_api_test_util:auth_header_(),
  461. case emqx_mgmt_api_test_util:request_api(post, Path, "", AuthHeader, Params) of
  462. {ok, Res} -> {ok, emqx_utils_json:decode(Res, [return_maps])};
  463. Error -> Error
  464. end.
  465. send_message(Config, Payload) ->
  466. Name = ?config(sqlserver_name, Config),
  467. BridgeType = ?config(sqlserver_bridge_type, Config),
  468. BridgeID = emqx_bridge_resource:bridge_id(BridgeType, Name),
  469. emqx_bridge:send_message(BridgeID, Payload).
  470. query_resource(Config, Request) ->
  471. Name = ?config(sqlserver_name, Config),
  472. BridgeType = ?config(sqlserver_bridge_type, Config),
  473. ResourceID = emqx_bridge_resource:resource_id(BridgeType, Name),
  474. emqx_resource:query(ResourceID, Request, #{timeout => 1_000}).
  475. query_resource_async(Config, Request) ->
  476. Name = ?config(sqlserver_name, Config),
  477. BridgeType = ?config(sqlserver_bridge_type, Config),
  478. Ref = alias([reply]),
  479. AsyncReplyFun = fun(Result) -> Ref ! {result, Ref, Result} end,
  480. ResourceID = emqx_bridge_resource:resource_id(BridgeType, Name),
  481. Return = emqx_resource:query(ResourceID, Request, #{
  482. timeout => 500, async_reply_fun => {AsyncReplyFun, []}
  483. }),
  484. {Return, Ref}.
  485. resource_id(Config) ->
  486. Name = ?config(sqlserver_name, Config),
  487. BridgeType = ?config(sqlserver_bridge_type, Config),
  488. _ResourceID = emqx_bridge_resource:resource_id(BridgeType, Name).
  489. health_check_resource_ok(Config) ->
  490. ?assertEqual({ok, connected}, emqx_resource_manager:health_check(resource_id(Config))).
  491. health_check_resource_down(Config) ->
  492. case emqx_resource_manager:health_check(resource_id(Config)) of
  493. {ok, Status} when Status =:= disconnected orelse Status =:= connecting ->
  494. ok;
  495. {error, timeout} ->
  496. ok;
  497. Other ->
  498. ?assert(
  499. false, lists:flatten(io_lib:format("invalid health check result:~p~n", [Other]))
  500. )
  501. end.
  502. receive_result(Ref, Timeout) ->
  503. receive
  504. {result, Ref, Result} ->
  505. {ok, Result};
  506. {Ref, Result} ->
  507. {ok, Result}
  508. after Timeout ->
  509. timeout
  510. end.
  511. connect_direct_sqlserver(Config) ->
  512. Opts = [
  513. {host, ?config(sqlserver_host, Config)},
  514. {port, ?config(sqlserver_port, Config)},
  515. {username, ?SQL_SERVER_USERNAME},
  516. {password, ?SQL_SERVER_PASSWORD},
  517. {driver, ?SQL_SERVER_DRIVER},
  518. {pool_size, 8}
  519. ],
  520. {ok, Con} = connect(Opts),
  521. Con.
  522. connect(Options) ->
  523. ConnectStr = lists:concat(conn_str(Options, [])),
  524. Opts = proplists:get_value(options, Options, []),
  525. odbc:connect(ConnectStr, Opts).
  526. disconnect(Ref) ->
  527. odbc:disconnect(Ref).
  528. % These funs connect and then stop the sqlserver connection
  529. connect_and_create_db_and_table(Config) ->
  530. ?WITH_CON(begin
  531. {updated, undefined} = directly_query(Con, ?SQL_CREATE_DATABASE_IF_NOT_EXISTS),
  532. {updated, undefined} = directly_query(Con, ?SQL_CREATE_TABLE_IN_DB_MQTT)
  533. end).
  534. connect_and_drop_db(Config) ->
  535. ?WITH_CON({updated, undefined} = directly_query(Con, ?SQL_DROP_DB_MQTT)).
  536. connect_and_drop_table(Config) ->
  537. ?WITH_CON({updated, undefined} = directly_query(Con, ?SQL_DROP_TABLE)).
  538. connect_and_clear_table(Config) ->
  539. ?WITH_CON({updated, _} = directly_query(Con, ?SQL_DELETE)).
  540. connect_and_get_payload(Config) ->
  541. ?WITH_CON(
  542. {selected, ["payload"], Rows} = directly_query(Con, ?SQL_SELECT)
  543. ),
  544. Rows.
  545. connect_and_get_count(Config) ->
  546. ?WITH_CON(
  547. {selected, [[]], [{Count}]} = directly_query(Con, ?SQL_SELECT_COUNT)
  548. ),
  549. Count.
  550. directly_query(Con, Query) ->
  551. directly_query(Con, Query, ?REQUEST_TIMEOUT_MS).
  552. directly_query(Con, Query, Timeout) ->
  553. odbc:sql_query(Con, Query, Timeout).
  554. %%--------------------------------------------------------------------
  555. %% help functions
  556. %%--------------------------------------------------------------------
  557. batch_size(Config) ->
  558. case ?config(enable_batch, Config) of
  559. true -> ?BATCH_SIZE;
  560. false -> 1
  561. end.
  562. conn_str([], Acc) ->
  563. %% TODO: for msodbc 18+, we need to add "Encrypt=YES;TrustServerCertificate=YES"
  564. %% but havn't tested now
  565. %% we should use this for msodbcsql 18+
  566. %% lists:join(";", ["Encrypt=YES", "TrustServerCertificate=YES" | Acc]);
  567. lists:join(";", Acc);
  568. conn_str([{driver, Driver} | Opts], Acc) ->
  569. conn_str(Opts, ["Driver=" ++ str(Driver) | Acc]);
  570. conn_str([{host, Host} | Opts], Acc) ->
  571. Port = proplists:get_value(port, Opts, "1433"),
  572. NOpts = proplists:delete(port, Opts),
  573. conn_str(NOpts, ["Server=" ++ str(Host) ++ "," ++ str(Port) | Acc]);
  574. conn_str([{port, Port} | Opts], Acc) ->
  575. Host = proplists:get_value(host, Opts, "localhost"),
  576. NOpts = proplists:delete(host, Opts),
  577. conn_str(NOpts, ["Server=" ++ str(Host) ++ "," ++ str(Port) | Acc]);
  578. conn_str([{database, Database} | Opts], Acc) ->
  579. conn_str(Opts, ["Database=" ++ str(Database) | Acc]);
  580. conn_str([{username, Username} | Opts], Acc) ->
  581. conn_str(Opts, ["UID=" ++ str(Username) | Acc]);
  582. conn_str([{password, Password} | Opts], Acc) ->
  583. conn_str(Opts, ["PWD=" ++ str(Password) | Acc]);
  584. conn_str([{_, _} | Opts], Acc) ->
  585. conn_str(Opts, Acc).
  586. sent_data(Payload) ->
  587. #{
  588. payload => to_bin(Payload),
  589. id => <<"0005F8F84FFFAFB9F44200000D810002">>,
  590. topic => <<"test/topic">>,
  591. qos => 0
  592. }.
  593. gen_batch_req(Count) when
  594. is_integer(Count) andalso Count > 0
  595. ->
  596. Vals = [{str(erlang:unique_integer())} || _Seq <- lists:seq(1, Count)],
  597. Requests = [{send_message, sent_data(Payload)} || {Payload} <- Vals],
  598. {Requests, Vals};
  599. gen_batch_req(Count) ->
  600. ct:pal("Gen batch requests failed with unexpected Count: ~p", [Count]).
  601. str(List) when is_list(List) ->
  602. unicode:characters_to_list(List, utf8);
  603. str(Bin) when is_binary(Bin) ->
  604. unicode:characters_to_list(Bin, utf8);
  605. str(Num) when is_number(Num) ->
  606. number_to_list(Num).
  607. number_to_list(Int) when is_integer(Int) ->
  608. integer_to_list(Int);
  609. number_to_list(Float) when is_float(Float) ->
  610. float_to_list(Float, [{decimals, 10}, compact]).
  611. to_bin(List) when is_list(List) ->
  612. unicode:characters_to_binary(List, utf8);
  613. to_bin(Bin) when is_binary(Bin) ->
  614. Bin.