emqx_bridge_sqlserver_SUITE.erl 23 KB

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