mysql_tests.erl 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. %% MySQL/OTP – MySQL client library for Erlang/OTP
  2. %% Copyright (C) 2014 Viktor Söderqvist
  3. %%
  4. %% This file is part of MySQL/OTP.
  5. %%
  6. %% MySQL/OTP is free software: you can redistribute it and/or modify it under
  7. %% the terms of the GNU Lesser General Public License as published by the Free
  8. %% Software Foundation, either version 3 of the License, or (at your option)
  9. %% any later version.
  10. %%
  11. %% This program is distributed in the hope that it will be useful, but WITHOUT
  12. %% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. %% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  14. %% more details.
  15. %%
  16. %% You should have received a copy of the GNU Lesser General Public License
  17. %% along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. %% @doc This module performs test to an actual database.
  19. -module(mysql_tests).
  20. -include_lib("eunit/include/eunit.hrl").
  21. -define(user, "otptest").
  22. -define(password, "otptest").
  23. -define(create_table_t, <<"CREATE TABLE t ("
  24. " id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,"
  25. " bl BLOB,"
  26. " tx TEXT NOT NULL," %% No default value
  27. " f FLOAT,"
  28. " d DOUBLE,"
  29. " dc DECIMAL(5,3),"
  30. " y YEAR,"
  31. " ti TIME,"
  32. " ts TIMESTAMP,"
  33. " da DATE,"
  34. " c CHAR(2)"
  35. ") ENGINE=InnoDB">>).
  36. connect_test() ->
  37. %% A connection with a registered name
  38. Options = [{name, {local, tardis}}, {user, ?user}, {password, ?password}],
  39. {ok, Pid} = mysql:start_link(Options),
  40. %% Test some gen_server callbacks not tested elsewhere
  41. State = get_state(Pid),
  42. ?assertMatch({ok, State}, mysql:code_change("0.1.0", State, [])),
  43. ?assertMatch({error, _}, mysql:code_change("2.0.0", unknown_state, [])),
  44. exit(whereis(tardis), normal).
  45. %% For R16B where sys:get_state/1 is not available.
  46. get_state(Process) ->
  47. {status,_,_,[_,_,_,_,Misc]} = sys:get_status(Process),
  48. hd([State || {data,[{"State", State}]} <- Misc]).
  49. query_test_() ->
  50. {setup,
  51. fun () ->
  52. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  53. {log_warnings, false}]),
  54. ok = mysql:query(Pid, <<"DROP DATABASE IF EXISTS otptest">>),
  55. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  56. ok = mysql:query(Pid, <<"USE otptest">>),
  57. ok = mysql:query(Pid, <<"SET autocommit = 1">>),
  58. Pid
  59. end,
  60. fun (Pid) ->
  61. ok = mysql:query(Pid, <<"DROP DATABASE otptest">>),
  62. exit(Pid, normal)
  63. end,
  64. fun (Pid) ->
  65. [{"Select db on connect", fun () -> connect_with_db(Pid) end},
  66. {"Autocommit", fun () -> autocommit(Pid) end},
  67. {"Basic queries", fun () -> basic_queries(Pid) end},
  68. {"Text protocol", fun () -> text_protocol(Pid) end},
  69. {"Binary protocol", fun () -> binary_protocol(Pid) end},
  70. {"FLOAT rounding", fun () -> float_rounding(Pid) end},
  71. {"DECIMAL", fun () -> decimal(Pid) end},
  72. {"INT", fun () -> int(Pid) end},
  73. {"BIT(N)", fun () -> bit(Pid) end},
  74. {"DATE", fun () -> date(Pid) end},
  75. {"TIME", fun () -> time(Pid) end},
  76. {"DATETIME", fun () -> datetime(Pid) end},
  77. {"Microseconds", fun () -> microseconds(Pid) end}]
  78. end}.
  79. connect_with_db(_Pid) ->
  80. %% Make another connection and set the db in the handshake phase
  81. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  82. {database, "otptest"}]),
  83. ?assertMatch({ok, _, [[<<"otptest">>]]},
  84. mysql:query(Pid, "SELECT DATABASE()")),
  85. %% Capture error log to check that we get a warning logged
  86. {ok, ok, LoggedErrors} = error_logger_acc:capture(fun () ->
  87. mysql:query(Pid, <<"DROP TABLE IF EXISTS dummy">>)
  88. end),
  89. ?assertMatch([{_, "Note 1051: Unknown table 'dummy'\n"
  90. " in DROP TABLE IF EXISTS dummy\n"}],
  91. LoggedErrors),
  92. exit(Pid, normal).
  93. autocommit(Pid) ->
  94. ?assert(mysql:autocommit(Pid)),
  95. ok = mysql:query(Pid, <<"SET autocommit = 0">>),
  96. ?assertNot(mysql:autocommit(Pid)),
  97. ok = mysql:query(Pid, <<"SET autocommit = 1">>),
  98. ?assert(mysql:autocommit(Pid)).
  99. basic_queries(Pid) ->
  100. %% warning count
  101. ?assertEqual(ok, mysql:query(Pid, <<"DROP TABLE IF EXISTS foo">>)),
  102. ?assertEqual(1, mysql:warning_count(Pid)),
  103. %% SQL parse error
  104. ?assertMatch({error, {1064, <<"42000">>, <<"You have an erro", _/binary>>}},
  105. mysql:query(Pid, <<"FOO">>)),
  106. %% Simple resultset with various types
  107. ?assertEqual({ok, [<<"i">>, <<"s">>], [[42, <<"foo">>]]},
  108. mysql:query(Pid, <<"SELECT 42 AS i, 'foo' AS s;">>)),
  109. ok.
  110. text_protocol(Pid) ->
  111. ok = mysql:query(Pid, ?create_table_t),
  112. ok = mysql:query(Pid, <<"INSERT INTO t (bl, f, d, dc, y, ti, ts, da, c)"
  113. " VALUES ('blob', 3.14, 3.14, 3.14, 2014,"
  114. "'00:22:11', '2014-11-03 00:22:24', '2014-11-03',"
  115. " NULL)">>),
  116. ?assertEqual(1, mysql:warning_count(Pid)), %% tx has no default value
  117. ?assertEqual(1, mysql:insert_id(Pid)), %% auto_increment starts from 1
  118. ?assertEqual(1, mysql:affected_rows(Pid)),
  119. %% select
  120. {ok, Columns, Rows} = mysql:query(Pid, <<"SELECT * FROM t">>),
  121. ?assertEqual([<<"id">>, <<"bl">>, <<"tx">>, <<"f">>, <<"d">>, <<"dc">>,
  122. <<"y">>, <<"ti">>, <<"ts">>, <<"da">>, <<"c">>], Columns),
  123. ?assertEqual([[1, <<"blob">>, <<>>, 3.14, 3.14, 3.14,
  124. 2014, {0, {0, 22, 11}},
  125. {{2014, 11, 03}, {00, 22, 24}}, {2014, 11, 03}, null]],
  126. Rows),
  127. ok = mysql:query(Pid, <<"DROP TABLE t">>).
  128. binary_protocol(Pid) ->
  129. ok = mysql:query(Pid, ?create_table_t),
  130. %% The same queries as in the text protocol. Expect the same results.
  131. {ok, Ins} = mysql:prepare(Pid, <<"INSERT INTO t (bl, f, d, dc, y, ti,"
  132. " ts, da, c)"
  133. " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)">>),
  134. ok = mysql:execute(Pid, Ins, [<<"blob">>, 3.14, 3.14, 3.14,
  135. 2014, {0, {0, 22, 11}},
  136. {{2014, 11, 03}, {0, 22, 24}},
  137. {2014, 11, 03}, null]),
  138. {ok, Stmt} = mysql:prepare(Pid, <<"SELECT * FROM t WHERE id=?">>),
  139. {ok, Columns, Rows} = mysql:execute(Pid, Stmt, [1]),
  140. ?assertEqual([<<"id">>, <<"bl">>, <<"tx">>, <<"f">>, <<"d">>, <<"dc">>,
  141. <<"y">>, <<"ti">>,
  142. <<"ts">>, <<"da">>, <<"c">>], Columns),
  143. ?assertEqual([[1, <<"blob">>, <<>>, 3.14, 3.14, 3.14,
  144. 2014, {0, {0, 22, 11}},
  145. {{2014, 11, 03}, {00, 22, 24}}, {2014, 11, 03}, null]],
  146. Rows),
  147. ok = mysql:query(Pid, <<"DROP TABLE t">>).
  148. float_rounding(Pid) ->
  149. %% This is to make sure we get the same values for 32-bit FLOATs in the text
  150. %% and binary protocols for ordinary queries and prepared statements
  151. %% respectively.
  152. %%
  153. %% MySQL rounds to 6 significant digits when "printing" floats over the
  154. %% text protocol. When we receive a float on the binary protocol, we round
  155. %% it in the same way to match what MySQL does on the text protocol. This
  156. %% way we should to get the same values regardless of which protocol is
  157. %% used.
  158. %% Table for testing floats
  159. ok = mysql:query(Pid, "CREATE TABLE f (f FLOAT)"),
  160. %% Prepared statements
  161. {ok, Insert} = mysql:prepare(Pid, "INSERT INTO f (f) VALUES (?)"),
  162. {ok, Select} = mysql:prepare(Pid, "SELECT f FROM f"),
  163. %% [{Input, Expected}]
  164. TestData = [{1.0, 1.0}, {3.14, 3.14}, {0.2, 0.2},
  165. {0.20082111, 0.200821}, {0.000123456789, 0.000123457},
  166. {33.3333333, 33.3333}, {-33.2233443322, -33.2233},
  167. {400.0123, 400.012}, {1000.1234, 1000.12},
  168. {999.00009, 999.0},
  169. {1234.5678, 1234.57}, {68888.8888, 68888.9},
  170. {123456.789, 123457.0}, {7654321.0, 7654320.0},
  171. {80001111.1, 80001100.0}, {987654321.0, 987654000.0},
  172. {-123456789.0, -123457000.0},
  173. {2.12345111e-23, 2.12345e-23}, {-2.12345111e-23, -2.12345e-23},
  174. {2.12345111e23, 2.12345e23}, {-2.12345111e23, -2.12345e23}],
  175. lists:foreach(fun ({Input, Expected}) ->
  176. %% Insert using binary protocol (sending it as a double)
  177. ok = mysql:execute(Pid, Insert, [Input]),
  178. %% Text (plain query)
  179. {ok, _, [[Value]]} = mysql:query(Pid, "SELECT f FROM f"),
  180. ?assertEqual(Expected, Value),
  181. %% Binary (prepared statement)
  182. {ok, _, [[BinValue]]} = mysql:execute(Pid, Select, []),
  183. ?assertEqual(Expected, BinValue),
  184. %% cleanup before the next test
  185. ok = mysql:query(Pid, "DELETE FROM f")
  186. end,
  187. TestData),
  188. ok = mysql:query(Pid, "DROP TABLE f").
  189. decimal(Pid) ->
  190. %% As integer when S == 0
  191. ok = mysql:query(Pid, "CREATE TABLE dec0 (d DECIMAL(50, 0))"),
  192. write_read_text_binary(
  193. Pid, 14159265358979323846264338327950288419716939937510,
  194. <<"14159265358979323846264338327950288419716939937510">>,
  195. <<"dec0">>, <<"d">>
  196. ),
  197. write_read_text_binary(
  198. Pid, -14159265358979323846264338327950288419716939937510,
  199. <<"-14159265358979323846264338327950288419716939937510">>,
  200. <<"dec0">>, <<"d">>
  201. ),
  202. ok = mysql:query(Pid, "DROP TABLE dec0"),
  203. %% As float when P =< 15, S > 0
  204. ok = mysql:query(Pid, "CREATE TABLE dec15 (d DECIMAL(15, 14))"),
  205. write_read_text_binary(Pid, 3.14159265358979, <<"3.14159265358979">>,
  206. <<"dec15">>, <<"d">>),
  207. write_read_text_binary(Pid, -3.14159265358979, <<"-3.14159265358979">>,
  208. <<"dec15">>, <<"d">>),
  209. write_read_text_binary(Pid, 3.0, <<"3">>, <<"dec15">>, <<"d">>),
  210. ok = mysql:query(Pid, "DROP TABLE dec15"),
  211. %% As binary when P >= 16, S > 0
  212. ok = mysql:query(Pid, "CREATE TABLE dec16 (d DECIMAL(16, 15))"),
  213. write_read_text_binary(Pid, <<"3.141592653589793">>,
  214. <<"3.141592653589793">>, <<"dec16">>, <<"d">>),
  215. write_read_text_binary(Pid, <<"-3.141592653589793">>,
  216. <<"-3.141592653589793">>, <<"dec16">>, <<"d">>),
  217. write_read_text_binary(Pid, <<"3.000000000000000">>, <<"3">>,
  218. <<"dec16">>, <<"d">>),
  219. ok = mysql:query(Pid, "DROP TABLE dec16").
  220. int(Pid) ->
  221. ok = mysql:query(Pid, "CREATE TABLE ints (i INT)"),
  222. write_read_text_binary(Pid, 42, <<"42">>, <<"ints">>, <<"i">>),
  223. write_read_text_binary(Pid, -42, <<"-42">>, <<"ints">>, <<"i">>),
  224. write_read_text_binary(Pid, 987654321, <<"987654321">>, <<"ints">>,
  225. <<"i">>),
  226. write_read_text_binary(Pid, -987654321, <<"-987654321">>,
  227. <<"ints">>, <<"i">>),
  228. ok = mysql:query(Pid, "DROP TABLE ints"),
  229. %% Overflow with TINYINT
  230. ok = mysql:query(Pid, "CREATE TABLE tint (i TINYINT)"),
  231. write_read_text_binary(Pid, 127, <<"1000">>, <<"tint">>, <<"i">>),
  232. write_read_text_binary(Pid, -128, <<"-1000">>, <<"tint">>, <<"i">>),
  233. ok = mysql:query(Pid, "DROP TABLE tint"),
  234. %% SMALLINT
  235. ok = mysql:query(Pid, "CREATE TABLE sint (i SMALLINT)"),
  236. write_read_text_binary(Pid, 32000, <<"32000">>, <<"sint">>, <<"i">>),
  237. write_read_text_binary(Pid, -32000, <<"-32000">>, <<"sint">>, <<"i">>),
  238. ok = mysql:query(Pid, "DROP TABLE sint"),
  239. %% BIGINT
  240. ok = mysql:query(Pid, "CREATE TABLE bint (i BIGINT)"),
  241. write_read_text_binary(Pid, 123456789012, <<"123456789012">>,
  242. <<"bint">>, <<"i">>),
  243. write_read_text_binary(Pid, -123456789012, <<"-123456789012">>,
  244. <<"bint">>, <<"i">>),
  245. ok = mysql:query(Pid, "DROP TABLE bint").
  246. %% The BIT(N) datatype in MySQL 5.0.3 and later: the equivallent to bitstring()
  247. bit(Pid) ->
  248. ok = mysql:query(Pid, "CREATE TABLE bits (b BIT(11))"),
  249. write_read_text_binary(Pid, <<16#ff, 0:3>>, <<"b'11111111000'">>,
  250. <<"bits">>, <<"b">>),
  251. write_read_text_binary(Pid, <<16#7f, 6:3>>, <<"b'01111111110'">>,
  252. <<"bits">>, <<"b">>),
  253. ok = mysql:query(Pid, "DROP TABLE bits").
  254. date(Pid) ->
  255. ok = mysql:query(Pid, "CREATE TABLE d (d DATE)"),
  256. lists:foreach(
  257. fun ({Value, SqlLiteral}) ->
  258. write_read_text_binary(Pid, Value, SqlLiteral, <<"d">>, <<"d">>)
  259. end,
  260. [{{2014, 11, 03}, <<"'2014-11-03'">>},
  261. {{0, 0, 0}, <<"'0000-00-00'">>}]
  262. ),
  263. ok = mysql:query(Pid, "DROP TABLE d").
  264. %% Test TIME value representation. There are a few things to check.
  265. time(Pid) ->
  266. ok = mysql:query(Pid, "CREATE TABLE tm (tm TIME)"),
  267. lists:foreach(
  268. fun ({Value, SqlLiteral}) ->
  269. write_read_text_binary(Pid, Value, SqlLiteral, <<"tm">>, <<"tm">>)
  270. end,
  271. [{{0, {10, 11, 12}}, <<"'10:11:12'">>},
  272. {{5, {0, 0, 1}}, <<"'120:00:01'">>},
  273. {{-1, {23, 59, 59}}, <<"'-00:00:01'">>},
  274. {{-1, {23, 59, 0}}, <<"'-00:01:00'">>},
  275. {{-1, {23, 0, 0}}, <<"'-01:00:00'">>},
  276. {{-1, {0, 0, 0}}, <<"'-24:00:00'">>},
  277. {{-5, {10, 0, 0}}, <<"'-110:00:00'">>},
  278. {{0, {0, 0, 0}}, <<"'00:00:00'">>}]
  279. ),
  280. %% Zero seconds as a float.
  281. ok = mysql:query(Pid, "INSERT INTO tm (tm) VALUES (?)",
  282. [{-1, {1, 2, 0.0}}]),
  283. ?assertEqual({ok, [<<"tm">>], [[{-1, {1, 2, 0}}]]},
  284. mysql:query(Pid, "SELECT tm FROM tm")),
  285. ok = mysql:query(Pid, "DROP TABLE tm").
  286. datetime(Pid) ->
  287. ok = mysql:query(Pid, "CREATE TABLE dt (dt DATETIME)"),
  288. lists:foreach(
  289. fun ({Value, SqlLiteral}) ->
  290. write_read_text_binary(Pid, Value, SqlLiteral, <<"dt">>, <<"dt">>)
  291. end,
  292. [{{{2014, 12, 14}, {19, 39, 20}}, <<"'2014-12-14 19:39:20'">>},
  293. {{{2014, 12, 14}, {0, 0, 0}}, <<"'2014-12-14 00:00:00'">>},
  294. {{{0, 0, 0}, {0, 0, 0}}, <<"'0000-00-00 00:00:00'">>}]
  295. ),
  296. ok = mysql:query(Pid, "DROP TABLE dt").
  297. microseconds(Pid) ->
  298. %% Check whether we have the required version for this testcase.
  299. {ok, _, [[Version]]} = mysql:query(Pid, <<"SELECT @@version">>),
  300. try
  301. %% Remove stuff after dash for e.g. "5.5.40-0ubuntu0.12.04.1-log"
  302. [Version1 | _] = binary:split(Version, <<"-">>),
  303. Version2 = lists:map(fun binary_to_integer/1,
  304. binary:split(Version1, <<".">>, [global])),
  305. Version2 >= [5, 6, 4] orelse throw(nope)
  306. of _ ->
  307. test_time_microseconds(Pid),
  308. test_datetime_microseconds(Pid)
  309. catch _:_ ->
  310. error_logger:info_msg("Skipping microseconds test. Current MySQL"
  311. " version is ~s. Required version is >= 5.6.4.~n",
  312. [Version])
  313. end.
  314. test_time_microseconds(Pid) ->
  315. ok = mysql:query(Pid, "CREATE TABLE m (t TIME(6))"),
  316. %% Positive time
  317. write_read_text_binary(Pid, {0, {23, 59, 57.654321}},
  318. <<"'23:59:57.654321'">>, <<"m">>, <<"t">>),
  319. %% Negative time
  320. write_read_text_binary(Pid, {-1, {23, 59, 57.654321}},
  321. <<"'-00:00:02.345679'">>, <<"m">>, <<"t">>),
  322. ok = mysql:query(Pid, "DROP TABLE m").
  323. test_datetime_microseconds(Pid) ->
  324. ok = mysql:query(Pid, "CREATE TABLE dt (dt DATETIME(6))"),
  325. write_read_text_binary(Pid, {{2014, 11, 23}, {23, 59, 57.654321}},
  326. <<"'2014-11-23 23:59:57.654321'">>, <<"dt">>,
  327. <<"dt">>),
  328. ok = mysql:query(Pid, "DROP TABLE dt").
  329. %% @doc Tests write and read in text and the binary protocol, all combinations.
  330. %% This helper function assumes an empty table with a single column.
  331. write_read_text_binary(Conn, Term, SqlLiteral, Table, Column) ->
  332. SelectQuery = <<"SELECT ", Column/binary, " FROM ", Table/binary>>,
  333. {ok, SelectStmt} = mysql:prepare(Conn, SelectQuery),
  334. %% Insert as text, read text and binary, delete
  335. InsertQuery = <<"INSERT INTO ", Table/binary, " (", Column/binary, ")"
  336. " VALUES (", SqlLiteral/binary, ")">>,
  337. ok = mysql:query(Conn, InsertQuery),
  338. ?assertEqual({ok, [Column], [[Term]]}, mysql:query(Conn, SelectQuery)),
  339. ?assertEqual({ok, [Column], [[Term]]}, mysql:execute(Conn, SelectStmt, [])),
  340. mysql:query(Conn, <<"DELETE FROM ", Table/binary>>),
  341. %% Insert as binary, read text and binary, delete
  342. InsertQ = <<"INSERT INTO ", Table/binary, " (", Column/binary, ")",
  343. " VALUES (?)">>,
  344. {ok, InsertStmt} = mysql:prepare(Conn, InsertQ),
  345. ok = mysql:execute(Conn, InsertStmt, [Term]),
  346. ok = mysql:unprepare(Conn, InsertStmt),
  347. ?assertEqual({ok, [Column], [[Term]]}, mysql:query(Conn, SelectQuery)),
  348. ?assertEqual({ok, [Column], [[Term]]}, mysql:execute(Conn, SelectStmt, [])),
  349. mysql:query(Conn, <<"DELETE FROM ", Table/binary>>),
  350. %% Cleanup
  351. ok = mysql:unprepare(Conn, SelectStmt).
  352. %% --------------------------------------------------------------------------
  353. timeout_test_() ->
  354. {setup,
  355. fun () ->
  356. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  357. {log_warnings, false}]),
  358. Pid
  359. end,
  360. fun (Pid) ->
  361. exit(Pid, normal)
  362. end,
  363. {with, [fun (Pid) ->
  364. %% SLEEP was added in MySQL 5.0.12
  365. ?assertEqual({ok, [<<"SLEEP(5)">>], [[1]]},
  366. mysql:query(Pid, <<"SELECT SLEEP(5)">>, 40)),
  367. %% A query after an interrupted query shouldn't get a timeout.
  368. ?assertMatch({ok,[<<"42">>], [[42]]},
  369. mysql:query(Pid, <<"SELECT 42">>)),
  370. %% Parametrized query
  371. ?assertEqual({ok, [<<"SLEEP(?)">>], [[1]]},
  372. mysql:query(Pid, <<"SELECT SLEEP(?)">>, [5], 40)),
  373. %% Prepared statement
  374. {ok, Stmt} = mysql:prepare(Pid, <<"SELECT SLEEP(?)">>),
  375. ?assertEqual({ok, [<<"SLEEP(?)">>], [[1]]},
  376. mysql:execute(Pid, Stmt, [5], 40)),
  377. ok = mysql:unprepare(Pid, Stmt)
  378. end]}}.
  379. %% --------------------------------------------------------------------------
  380. %% Prepared statements
  381. with_table_foo_test_() ->
  382. {setup,
  383. fun () ->
  384. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  385. {query_cache_time, 50},
  386. {log_warnings, false}]),
  387. ok = mysql:query(Pid, <<"DROP DATABASE IF EXISTS otptest">>),
  388. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  389. ok = mysql:query(Pid, <<"USE otptest">>),
  390. ok = mysql:query(Pid, <<"CREATE TABLE foo (bar INT) engine=InnoDB">>),
  391. Pid
  392. end,
  393. fun (Pid) ->
  394. ok = mysql:query(Pid, <<"DROP DATABASE otptest">>),
  395. exit(Pid, normal)
  396. end,
  397. fun (Pid) ->
  398. [{"Prepared statements", fun () -> prepared_statements(Pid) end},
  399. {"Parametrized queries", fun () -> parameterized_query(Pid) end}]
  400. end}.
  401. prepared_statements(Pid) ->
  402. %% Unnamed
  403. ?assertEqual({error,{1146, <<"42S02">>,
  404. <<"Table 'otptest.tab' doesn't exist">>}},
  405. mysql:prepare(Pid, "SELECT * FROM tab WHERE id = ?")),
  406. {ok, StmtId} = mysql:prepare(Pid, "SELECT * FROM foo WHERE bar = ?"),
  407. ?assert(is_integer(StmtId)),
  408. ?assertEqual(ok, mysql:unprepare(Pid, StmtId)),
  409. ?assertEqual({error, not_prepared}, mysql:unprepare(Pid, StmtId)),
  410. %% Named
  411. ?assertEqual({error,{1146, <<"42S02">>,
  412. <<"Table 'otptest.tab' doesn't exist">>}},
  413. mysql:prepare(Pid, tab, "SELECT * FROM tab WHERE id = ?")),
  414. ?assertEqual({ok, foo},
  415. mysql:prepare(Pid, foo, "SELECT * FROM foo WHERE bar = ?")),
  416. %% Prepare again unprepares the old stmt associated with this name.
  417. ?assertEqual({ok, foo},
  418. mysql:prepare(Pid, foo, "SELECT bar FROM foo WHERE bar = ?")),
  419. ?assertEqual(ok, mysql:unprepare(Pid, foo)),
  420. ?assertEqual({error, not_prepared}, mysql:unprepare(Pid, foo)),
  421. %% Execute when not prepared
  422. ?assertEqual({error, not_prepared}, mysql:execute(Pid, not_a_stmt, [])),
  423. ok.
  424. parameterized_query(Conn) ->
  425. %% To see that cache eviction works as expected, look at the code coverage.
  426. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [1]),
  427. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [2]),
  428. receive after 150 -> ok end, %% Now the query cache should emptied
  429. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [3]).
  430. %% --- simple gen_server callbacks ---
  431. gen_server_coverage_test() ->
  432. {noreply, state} = mysql:handle_cast(foo, state),
  433. {noreply, state} = mysql:handle_info(foo, state),
  434. ok = mysql:terminate(kill, state).