mysql_tests.erl 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. %% MySQL/OTP – MySQL client library for Erlang/OTP
  2. %% Copyright (C) 2014-2016 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. failing_connect_test() ->
  37. process_flag(trap_exit, true),
  38. ?assertMatch({error, {1045, <<"28000">>, <<"Access denied", _/binary>>}},
  39. mysql:start_link([{user, "dummy"}, {password, "junk"}])),
  40. receive
  41. {'EXIT', _Pid, {1045, <<"28000">>, <<"Access denie", _/binary>>}} -> ok
  42. after 1000 ->
  43. ?assertEqual(ok, no_exit_message)
  44. end,
  45. process_flag(trap_exit, false).
  46. successful_connect_test() ->
  47. %% A connection with a registered name and execute initial queries and
  48. %% create prepared statements.
  49. Options = [{name, {local, tardis}}, {user, ?user}, {password, ?password},
  50. {queries, ["SET @foo = 'bar'", "SELECT 1",
  51. "SELECT 1; SELECT 2"]},
  52. {prepare, [{foo, "SELECT @foo"}]}],
  53. {ok, Pid} = mysql:start_link(Options),
  54. %% Check that queries and prepare has been done.
  55. ?assertEqual({ok, [<<"@foo">>], [[<<"bar">>]]},
  56. mysql:execute(Pid, foo, [])),
  57. %% Test some gen_server callbacks not tested elsewhere
  58. State = get_state(Pid),
  59. ?assertMatch({ok, State}, mysql:code_change("0.1.0", State, [])),
  60. ?assertMatch({error, _}, mysql:code_change("2.0.0", unknown_state, [])),
  61. exit(whereis(tardis), normal).
  62. server_disconnect_test() ->
  63. process_flag(trap_exit, true),
  64. Options = [{user, ?user}, {password, ?password}],
  65. {ok, Pid} = mysql:start_link(Options),
  66. {ok, ok, LoggedErrors} = error_logger_acc:capture(fun () ->
  67. %% Make the server close the connection after 1 second of inactivity.
  68. ok = mysql:query(Pid, <<"SET SESSION wait_timeout = 1">>),
  69. receive
  70. {'EXIT', Pid, tcp_closed} -> ok
  71. after 2000 ->
  72. no_exit_message
  73. end
  74. end),
  75. process_flag(trap_exit, false),
  76. %% Check that we got the expected errors in the error log.
  77. [{error, Msg1}, {error, Msg2}, {error_report, CrashReport}] = LoggedErrors,
  78. %% "Connection Id 24 closing with reason: tcp_closed"
  79. ?assert(lists:prefix("Connection Id", Msg1)),
  80. ExpectedPrefix = io_lib:format("** Generic server ~p terminating", [Pid]),
  81. ?assert(lists:prefix(lists:flatten(ExpectedPrefix), Msg2)),
  82. ?assertMatch({crash_report, _}, CrashReport).
  83. tcp_error_test() ->
  84. process_flag(trap_exit, true),
  85. Options = [{user, ?user}, {password, ?password}],
  86. {ok, Pid} = mysql:start_link(Options),
  87. {ok, ok, LoggedErrors} = error_logger_acc:capture(fun () ->
  88. %% Simulate a tcp error by sending a message. (Is there a better way?)
  89. Pid ! {tcp_error, dummy_socket, tcp_reason},
  90. receive
  91. {'EXIT', Pid, {tcp_error, tcp_reason}} -> ok
  92. after 1000 ->
  93. ?assertEqual(ok, no_exit_message)
  94. end
  95. end),
  96. process_flag(trap_exit, false),
  97. %% Check that we got the expected crash report in the error log.
  98. [{error, Msg1}, {error, Msg2}, {error_report, CrashReport}] = LoggedErrors,
  99. %% "Connection Id 24 closing with reason: tcp_closed"
  100. ?assert(lists:prefix("Connection Id", Msg1)),
  101. ExpectedPrefix = io_lib:format("** Generic server ~p terminating", [Pid]),
  102. ?assert(lists:prefix(lists:flatten(ExpectedPrefix), Msg2)),
  103. ?assertMatch({crash_report, _}, CrashReport).
  104. keep_alive_test() ->
  105. %% Let the connection send a few pings.
  106. process_flag(trap_exit, true),
  107. Options = [{user, ?user}, {password, ?password}, {keep_alive, 20}],
  108. {ok, Pid} = mysql:start_link(Options),
  109. receive after 70 -> ok end,
  110. State = get_state(Pid),
  111. [state, _Version, _ConnectionId, Socket | _] = tuple_to_list(State),
  112. {ok, ExitMessage, LoggedErrors} = error_logger_acc:capture(fun () ->
  113. gen_tcp:close(Socket),
  114. receive
  115. Message -> Message
  116. after 1000 ->
  117. ping_didnt_crash_connection
  118. end
  119. end),
  120. process_flag(trap_exit, false),
  121. %% Check that we got the expected crash report in the error log.
  122. ?assertMatch({'EXIT', Pid, _Reason}, ExitMessage),
  123. [{error, LoggedMsg}, {error_report, LoggedReport}] = LoggedErrors,
  124. ExpectedPrefix = io_lib:format("** Generic server ~p terminating", [Pid]),
  125. ?assert(lists:prefix(lists:flatten(ExpectedPrefix), LoggedMsg)),
  126. ?assertMatch({crash_report, _}, LoggedReport),
  127. exit(Pid, normal).
  128. %% For R16B where sys:get_state/1 is not available.
  129. get_state(Process) ->
  130. {status,_,_,[_,_,_,_,Misc]} = sys:get_status(Process),
  131. hd([State || {data,[{"State", State}]} <- Misc]).
  132. query_test_() ->
  133. {setup,
  134. fun () ->
  135. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  136. {log_warnings, false},
  137. {keep_alive, true}]),
  138. ok = mysql:query(Pid, <<"DROP DATABASE IF EXISTS otptest">>),
  139. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  140. ok = mysql:query(Pid, <<"USE otptest">>),
  141. ok = mysql:query(Pid, <<"SET autocommit = 1">>),
  142. Pid
  143. end,
  144. fun (Pid) ->
  145. ok = mysql:query(Pid, <<"DROP DATABASE otptest">>),
  146. exit(Pid, normal)
  147. end,
  148. fun (Pid) ->
  149. [{"Select db on connect", fun () -> connect_with_db(Pid) end},
  150. {"Autocommit", fun () -> autocommit(Pid) end},
  151. {"Encode", fun () -> encode(Pid) end},
  152. {"Basic queries", fun () -> basic_queries(Pid) end},
  153. {"Multi statements", fun () -> multi_statements(Pid) end},
  154. {"Text protocol", fun () -> text_protocol(Pid) end},
  155. {"Binary protocol", fun () -> binary_protocol(Pid) end},
  156. {"FLOAT rounding", fun () -> float_rounding(Pid) end},
  157. {"DECIMAL", fun () -> decimal(Pid) end},
  158. {"INT", fun () -> int(Pid) end},
  159. {"BIT(N)", fun () -> bit(Pid) end},
  160. {"DATE", fun () -> date(Pid) end},
  161. {"TIME", fun () -> time(Pid) end},
  162. {"DATETIME", fun () -> datetime(Pid) end},
  163. {"Microseconds", fun () -> microseconds(Pid) end}]
  164. end}.
  165. connect_with_db(_Pid) ->
  166. %% Make another connection and set the db in the handshake phase
  167. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  168. {database, "otptest"}]),
  169. ?assertMatch({ok, _, [[<<"otptest">>]]},
  170. mysql:query(Pid, "SELECT DATABASE()")),
  171. exit(Pid, normal).
  172. log_warnings_test() ->
  173. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password}]),
  174. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  175. ok = mysql:query(Pid, <<"USE otptest">>),
  176. %% Capture error log to check that we get a warning logged
  177. ok = mysql:query(Pid, "CREATE TABLE foo (x INT NOT NULL)"),
  178. {ok, insrt} = mysql:prepare(Pid, insrt, "INSERT INTO foo () VALUES ()"),
  179. {ok, ok, LoggedErrors} = error_logger_acc:capture(fun () ->
  180. ok = mysql:query(Pid, "INSERT INTO foo () VALUES ()"),
  181. ok = mysql:query(Pid, "INSeRT INtO foo () VaLUeS ()", []),
  182. ok = mysql:execute(Pid, insrt, [])
  183. end),
  184. [{_, Log1}, {_, Log2}, {_, Log3}] = LoggedErrors,
  185. ?assertEqual("Warning 1364: Field 'x' doesn't have a default value\n"
  186. " in INSERT INTO foo () VALUES ()\n", Log1),
  187. ?assertEqual("Warning 1364: Field 'x' doesn't have a default value\n"
  188. " in INSeRT INtO foo () VaLUeS ()\n", Log2),
  189. ?assertEqual("Warning 1364: Field 'x' doesn't have a default value\n"
  190. " in INSERT INTO foo () VALUES ()\n", Log3),
  191. exit(Pid, normal).
  192. autocommit(Pid) ->
  193. ?assert(mysql:autocommit(Pid)),
  194. ok = mysql:query(Pid, <<"SET autocommit = 0">>),
  195. ?assertNot(mysql:autocommit(Pid)),
  196. ok = mysql:query(Pid, <<"SET autocommit = 1">>),
  197. ?assert(mysql:autocommit(Pid)).
  198. encode(Pid) ->
  199. %% Test with backslash escapes enabled and disabled.
  200. {ok, _, [[OldMode]]} = mysql:query(Pid, "SELECT @@sql_mode"),
  201. ok = mysql:query(Pid, "SET sql_mode = ''"),
  202. ?assertEqual(<<"'foo\\\\bar''baz'">>,
  203. iolist_to_binary(mysql:encode(Pid, "foo\\bar'baz"))),
  204. ok = mysql:query(Pid, "SET sql_mode = 'NO_BACKSLASH_ESCAPES'"),
  205. ?assertEqual(<<"'foo\\bar''baz'">>,
  206. iolist_to_binary(mysql:encode(Pid, "foo\\bar'baz"))),
  207. ok = mysql:query(Pid, "SET sql_mode = ?", [OldMode]).
  208. basic_queries(Pid) ->
  209. %% warning count
  210. ?assertEqual(ok, mysql:query(Pid, <<"DROP TABLE IF EXISTS foo">>)),
  211. ?assertEqual(1, mysql:warning_count(Pid)),
  212. %% SQL parse error
  213. ?assertMatch({error, {1064, <<"42000">>, <<"You have an erro", _/binary>>}},
  214. mysql:query(Pid, <<"FOO">>)),
  215. %% Simple resultset with various types
  216. ?assertEqual({ok, [<<"i">>, <<"s">>], [[42, <<"foo">>]]},
  217. mysql:query(Pid, <<"SELECT 42 AS i, 'foo' AS s;">>)),
  218. ok.
  219. multi_statements(Pid) ->
  220. %% Multiple statements, no result set
  221. ?assertEqual(ok, mysql:query(Pid, "CREATE TABLE foo (bar INT);"
  222. "DROP TABLE foo;")),
  223. %% Multiple statements, one result set
  224. ?assertEqual({ok, [<<"foo">>], [[42]]},
  225. mysql:query(Pid, "CREATE TABLE foo (bar INT);"
  226. "DROP TABLE foo;"
  227. "SELECT 42 AS foo;")),
  228. %% Multiple statements, multiple result sets
  229. ?assertEqual({ok, [{[<<"foo">>], [[42]]}, {[<<"bar">>], [[<<"baz">>]]}]},
  230. mysql:query(Pid, "SELECT 42 AS foo; SELECT 'baz' AS bar;")),
  231. %% Multiple results in a prepared statement.
  232. %% Preparing "SELECT ...; SELECT ...;" gives a syntax error although the
  233. %% docs say it should be possible.
  234. %% Instead, test executing a stored procedure that returns multiple result
  235. %% sets using a prepared statement.
  236. CreateProc = "CREATE PROCEDURE multifoo() BEGIN\n"
  237. " SELECT 42 AS foo;\n"
  238. " SELECT 'baz' AS bar;\n"
  239. "END;\n",
  240. ok = mysql:query(Pid, CreateProc),
  241. ?assertEqual({ok, multifoo},
  242. mysql:prepare(Pid, multifoo, "CALL multifoo();")),
  243. ?assertEqual({ok, [{[<<"foo">>], [[42]]}, {[<<"bar">>], [[<<"baz">>]]}]},
  244. mysql:execute(Pid, multifoo, [])),
  245. ?assertEqual(ok, mysql:unprepare(Pid, multifoo)),
  246. ?assertEqual(ok, mysql:query(Pid, "DROP PROCEDURE multifoo;")),
  247. ok.
  248. text_protocol(Pid) ->
  249. ok = mysql:query(Pid, ?create_table_t),
  250. ok = mysql:query(Pid, <<"INSERT INTO t (bl, f, d, dc, y, ti, ts, da, c)"
  251. " VALUES ('blob', 3.14, 3.14, 3.14, 2014,"
  252. "'00:22:11', '2014-11-03 00:22:24', '2014-11-03',"
  253. " NULL)">>),
  254. ?assertEqual(1, mysql:warning_count(Pid)), %% tx has no default value
  255. ?assertEqual(1, mysql:insert_id(Pid)), %% auto_increment starts from 1
  256. ?assertEqual(1, mysql:affected_rows(Pid)),
  257. %% select
  258. {ok, Columns, Rows} = mysql:query(Pid, <<"SELECT * FROM t">>),
  259. ?assertEqual([<<"id">>, <<"bl">>, <<"tx">>, <<"f">>, <<"d">>, <<"dc">>,
  260. <<"y">>, <<"ti">>, <<"ts">>, <<"da">>, <<"c">>], Columns),
  261. ?assertEqual([[1, <<"blob">>, <<>>, 3.14, 3.14, 3.14,
  262. 2014, {0, {0, 22, 11}},
  263. {{2014, 11, 03}, {00, 22, 24}}, {2014, 11, 03}, null]],
  264. Rows),
  265. ok = mysql:query(Pid, <<"DROP TABLE t">>).
  266. binary_protocol(Pid) ->
  267. ok = mysql:query(Pid, ?create_table_t),
  268. %% The same queries as in the text protocol. Expect the same results.
  269. {ok, Ins} = mysql:prepare(Pid, <<"INSERT INTO t (bl, tx, f, d, dc, y, ti,"
  270. " ts, da, c)"
  271. " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)">>),
  272. %% 16#161 is the codepoint for "s with caron"; <<197, 161>> in UTF-8.
  273. ok = mysql:execute(Pid, Ins, [<<"blob">>, [16#161], 3.14, 3.14, 3.14,
  274. 2014, {0, {0, 22, 11}},
  275. {{2014, 11, 03}, {0, 22, 24}},
  276. {2014, 11, 03}, null]),
  277. {ok, Stmt} = mysql:prepare(Pid, <<"SELECT * FROM t WHERE id=?">>),
  278. {ok, Columns, Rows} = mysql:execute(Pid, Stmt, [1]),
  279. ?assertEqual([<<"id">>, <<"bl">>, <<"tx">>, <<"f">>, <<"d">>, <<"dc">>,
  280. <<"y">>, <<"ti">>,
  281. <<"ts">>, <<"da">>, <<"c">>], Columns),
  282. ?assertEqual([[1, <<"blob">>, <<197, 161>>, 3.14, 3.14, 3.14,
  283. 2014, {0, {0, 22, 11}},
  284. {{2014, 11, 03}, {00, 22, 24}}, {2014, 11, 03}, null]],
  285. Rows),
  286. ok = mysql:query(Pid, <<"DROP TABLE t">>).
  287. float_rounding(Pid) ->
  288. %% This is to make sure we get the same values for 32-bit FLOATs in the text
  289. %% and binary protocols for ordinary queries and prepared statements
  290. %% respectively.
  291. %%
  292. %% MySQL rounds to 6 significant digits when "printing" floats over the
  293. %% text protocol. When we receive a float on the binary protocol, we round
  294. %% it in the same way to match what MySQL does on the text protocol. This
  295. %% way we should to get the same values regardless of which protocol is
  296. %% used.
  297. %% Table for testing floats
  298. ok = mysql:query(Pid, "CREATE TABLE f (f FLOAT)"),
  299. %% Prepared statements
  300. {ok, Insert} = mysql:prepare(Pid, "INSERT INTO f (f) VALUES (?)"),
  301. {ok, Select} = mysql:prepare(Pid, "SELECT f FROM f"),
  302. %% [{Input, Expected}]
  303. TestData = [{1.0, 1.0}, {0.0, 0.0}, {3.14, 3.14}, {0.2, 0.2},
  304. {0.20082111, 0.200821}, {0.000123456789, 0.000123457},
  305. {33.3333333, 33.3333}, {-33.2233443322, -33.2233},
  306. {400.0123, 400.012}, {1000.1234, 1000.12},
  307. {999.00009, 999.0},
  308. {1234.5678, 1234.57}, {68888.8888, 68888.9},
  309. {123456.789, 123457.0}, {7654321.0, 7654320.0},
  310. {80001111.1, 80001100.0}, {987654321.0, 987654000.0},
  311. {-123456789.0, -123457000.0},
  312. {2.12345111e-23, 2.12345e-23}, {-2.12345111e-23, -2.12345e-23},
  313. {2.12345111e23, 2.12345e23}, {-2.12345111e23, -2.12345e23}],
  314. lists:foreach(fun ({Input, Expected}) ->
  315. %% Insert using binary protocol (sending it as a double)
  316. ok = mysql:execute(Pid, Insert, [Input]),
  317. %% Text (plain query)
  318. {ok, _, [[Value]]} = mysql:query(Pid, "SELECT f FROM f"),
  319. ?assertEqual(Expected, Value),
  320. %% Binary (prepared statement)
  321. {ok, _, [[BinValue]]} = mysql:execute(Pid, Select, []),
  322. ?assertEqual(Expected, BinValue),
  323. %% cleanup before the next test
  324. ok = mysql:query(Pid, "DELETE FROM f")
  325. end,
  326. TestData),
  327. ok = mysql:query(Pid, "DROP TABLE f").
  328. decimal(Pid) ->
  329. %% As integer when S == 0
  330. ok = mysql:query(Pid, "CREATE TABLE dec0 (d DECIMAL(50, 0))"),
  331. write_read_text_binary(
  332. Pid, 14159265358979323846264338327950288419716939937510,
  333. <<"14159265358979323846264338327950288419716939937510">>,
  334. <<"dec0">>, <<"d">>
  335. ),
  336. write_read_text_binary(
  337. Pid, -14159265358979323846264338327950288419716939937510,
  338. <<"-14159265358979323846264338327950288419716939937510">>,
  339. <<"dec0">>, <<"d">>
  340. ),
  341. ok = mysql:query(Pid, "DROP TABLE dec0"),
  342. %% As float when P =< 15, S > 0
  343. ok = mysql:query(Pid, "CREATE TABLE dec15 (d DECIMAL(15, 14))"),
  344. write_read_text_binary(Pid, 3.14159265358979, <<"3.14159265358979">>,
  345. <<"dec15">>, <<"d">>),
  346. write_read_text_binary(Pid, -3.14159265358979, <<"-3.14159265358979">>,
  347. <<"dec15">>, <<"d">>),
  348. write_read_text_binary(Pid, 3.0, <<"3">>, <<"dec15">>, <<"d">>),
  349. ok = mysql:query(Pid, "DROP TABLE dec15"),
  350. %% As binary when P >= 16, S > 0
  351. ok = mysql:query(Pid, "CREATE TABLE dec16 (d DECIMAL(16, 15))"),
  352. write_read_text_binary(Pid, <<"3.141592653589793">>,
  353. <<"3.141592653589793">>, <<"dec16">>, <<"d">>),
  354. write_read_text_binary(Pid, <<"-3.141592653589793">>,
  355. <<"-3.141592653589793">>, <<"dec16">>, <<"d">>),
  356. write_read_text_binary(Pid, <<"3.000000000000000">>, <<"3">>,
  357. <<"dec16">>, <<"d">>),
  358. ok = mysql:query(Pid, "DROP TABLE dec16").
  359. int(Pid) ->
  360. ok = mysql:query(Pid, "CREATE TABLE ints (i INT)"),
  361. write_read_text_binary(Pid, 42, <<"42">>, <<"ints">>, <<"i">>),
  362. write_read_text_binary(Pid, -42, <<"-42">>, <<"ints">>, <<"i">>),
  363. write_read_text_binary(Pid, 987654321, <<"987654321">>, <<"ints">>,
  364. <<"i">>),
  365. write_read_text_binary(Pid, -987654321, <<"-987654321">>,
  366. <<"ints">>, <<"i">>),
  367. ok = mysql:query(Pid, "DROP TABLE ints"),
  368. %% Overflow with TINYINT
  369. ok = mysql:query(Pid, "CREATE TABLE tint (i TINYINT)"),
  370. write_read_text_binary(Pid, 127, <<"1000">>, <<"tint">>, <<"i">>),
  371. write_read_text_binary(Pid, -128, <<"-1000">>, <<"tint">>, <<"i">>),
  372. ok = mysql:query(Pid, "DROP TABLE tint"),
  373. %% SMALLINT
  374. ok = mysql:query(Pid, "CREATE TABLE sint (i SMALLINT)"),
  375. write_read_text_binary(Pid, 32000, <<"32000">>, <<"sint">>, <<"i">>),
  376. write_read_text_binary(Pid, -32000, <<"-32000">>, <<"sint">>, <<"i">>),
  377. ok = mysql:query(Pid, "DROP TABLE sint"),
  378. %% BIGINT
  379. ok = mysql:query(Pid, "CREATE TABLE bint (i BIGINT)"),
  380. write_read_text_binary(Pid, 123456789012, <<"123456789012">>,
  381. <<"bint">>, <<"i">>),
  382. write_read_text_binary(Pid, -123456789012, <<"-123456789012">>,
  383. <<"bint">>, <<"i">>),
  384. ok = mysql:query(Pid, "DROP TABLE bint").
  385. %% The BIT(N) datatype in MySQL 5.0.3 and later: the equivallent to bitstring()
  386. bit(Pid) ->
  387. ok = mysql:query(Pid, "CREATE TABLE bits (b BIT(11))"),
  388. write_read_text_binary(Pid, <<16#ff, 0:3>>, <<"b'11111111000'">>,
  389. <<"bits">>, <<"b">>),
  390. write_read_text_binary(Pid, <<16#7f, 6:3>>, <<"b'01111111110'">>,
  391. <<"bits">>, <<"b">>),
  392. ok = mysql:query(Pid, "DROP TABLE bits").
  393. date(Pid) ->
  394. ok = mysql:query(Pid, "CREATE TABLE d (d DATE)"),
  395. lists:foreach(
  396. fun ({Value, SqlLiteral}) ->
  397. write_read_text_binary(Pid, Value, SqlLiteral, <<"d">>, <<"d">>)
  398. end,
  399. [{{2014, 11, 03}, <<"'2014-11-03'">>},
  400. {{0, 0, 0}, <<"'0000-00-00'">>}]
  401. ),
  402. ok = mysql:query(Pid, "DROP TABLE d").
  403. %% Test TIME value representation. There are a few things to check.
  404. time(Pid) ->
  405. ok = mysql:query(Pid, "CREATE TABLE tm (tm TIME)"),
  406. lists:foreach(
  407. fun ({Value, SqlLiteral}) ->
  408. write_read_text_binary(Pid, Value, SqlLiteral, <<"tm">>, <<"tm">>)
  409. end,
  410. [{{0, {10, 11, 12}}, <<"'10:11:12'">>},
  411. {{5, {0, 0, 1}}, <<"'120:00:01'">>},
  412. {{-1, {23, 59, 59}}, <<"'-00:00:01'">>},
  413. {{-1, {23, 59, 0}}, <<"'-00:01:00'">>},
  414. {{-1, {23, 0, 0}}, <<"'-01:00:00'">>},
  415. {{-1, {0, 0, 0}}, <<"'-24:00:00'">>},
  416. {{-5, {10, 0, 0}}, <<"'-110:00:00'">>},
  417. {{0, {0, 0, 0}}, <<"'00:00:00'">>}]
  418. ),
  419. %% Zero seconds as a float.
  420. ok = mysql:query(Pid, "INSERT INTO tm (tm) VALUES (?)",
  421. [{-1, {1, 2, 0.0}}]),
  422. ?assertEqual({ok, [<<"tm">>], [[{-1, {1, 2, 0}}]]},
  423. mysql:query(Pid, "SELECT tm FROM tm")),
  424. ok = mysql:query(Pid, "DROP TABLE tm").
  425. datetime(Pid) ->
  426. ok = mysql:query(Pid, "CREATE TABLE dt (dt DATETIME)"),
  427. lists:foreach(
  428. fun ({Value, SqlLiteral}) ->
  429. write_read_text_binary(Pid, Value, SqlLiteral, <<"dt">>, <<"dt">>)
  430. end,
  431. [{{{2014, 12, 14}, {19, 39, 20}}, <<"'2014-12-14 19:39:20'">>},
  432. {{{2014, 12, 14}, {0, 0, 0}}, <<"'2014-12-14 00:00:00'">>},
  433. {{{0, 0, 0}, {0, 0, 0}}, <<"'0000-00-00 00:00:00'">>}]
  434. ),
  435. ok = mysql:query(Pid, "DROP TABLE dt").
  436. microseconds(Pid) ->
  437. %% Check whether we have the required version for this testcase.
  438. {ok, _, [[Version]]} = mysql:query(Pid, <<"SELECT @@version">>),
  439. try
  440. %% Remove stuff after dash for e.g. "5.5.40-0ubuntu0.12.04.1-log"
  441. [Version1 | _] = binary:split(Version, <<"-">>),
  442. Version2 = lists:map(fun binary_to_integer/1,
  443. binary:split(Version1, <<".">>, [global])),
  444. Version2 >= [5, 6, 4] orelse throw(nope)
  445. of _ ->
  446. test_time_microseconds(Pid),
  447. test_datetime_microseconds(Pid)
  448. catch _:_ ->
  449. error_logger:info_msg("Skipping microseconds test. Current MySQL"
  450. " version is ~s. Required version is >= 5.6.4.~n",
  451. [Version])
  452. end.
  453. test_time_microseconds(Pid) ->
  454. ok = mysql:query(Pid, "CREATE TABLE m (t TIME(6))"),
  455. %% Positive time
  456. write_read_text_binary(Pid, {0, {23, 59, 57.654321}},
  457. <<"'23:59:57.654321'">>, <<"m">>, <<"t">>),
  458. %% Negative time
  459. write_read_text_binary(Pid, {-1, {23, 59, 57.654321}},
  460. <<"'-00:00:02.345679'">>, <<"m">>, <<"t">>),
  461. ok = mysql:query(Pid, "DROP TABLE m").
  462. test_datetime_microseconds(Pid) ->
  463. ok = mysql:query(Pid, "CREATE TABLE dt (dt DATETIME(6))"),
  464. write_read_text_binary(Pid, {{2014, 11, 23}, {23, 59, 57.654321}},
  465. <<"'2014-11-23 23:59:57.654321'">>, <<"dt">>,
  466. <<"dt">>),
  467. ok = mysql:query(Pid, "DROP TABLE dt").
  468. %% @doc Tests write and read in text and the binary protocol, all combinations.
  469. %% This helper function assumes an empty table with a single column.
  470. write_read_text_binary(Conn, Term, SqlLiteral, Table, Column) ->
  471. SelectQuery = <<"SELECT ", Column/binary, " FROM ", Table/binary>>,
  472. {ok, SelectStmt} = mysql:prepare(Conn, SelectQuery),
  473. %% Insert as text, read text and binary, delete
  474. InsertQuery = <<"INSERT INTO ", Table/binary, " (", Column/binary, ")"
  475. " VALUES (", SqlLiteral/binary, ")">>,
  476. ok = mysql:query(Conn, InsertQuery),
  477. ?assertEqual({ok, [Column], [[Term]]}, mysql:query(Conn, SelectQuery)),
  478. ?assertEqual({ok, [Column], [[Term]]}, mysql:execute(Conn, SelectStmt, [])),
  479. mysql:query(Conn, <<"DELETE FROM ", Table/binary>>),
  480. %% Insert as binary, read text and binary, delete
  481. InsertQ = <<"INSERT INTO ", Table/binary, " (", Column/binary, ")",
  482. " VALUES (?)">>,
  483. {ok, InsertStmt} = mysql:prepare(Conn, InsertQ),
  484. ok = mysql:execute(Conn, InsertStmt, [Term]),
  485. ok = mysql:unprepare(Conn, InsertStmt),
  486. ?assertEqual({ok, [Column], [[Term]]}, mysql:query(Conn, SelectQuery)),
  487. ?assertEqual({ok, [Column], [[Term]]}, mysql:execute(Conn, SelectStmt, [])),
  488. mysql:query(Conn, <<"DELETE FROM ", Table/binary>>),
  489. %% Cleanup
  490. ok = mysql:unprepare(Conn, SelectStmt).
  491. %% --------------------------------------------------------------------------
  492. timeout_test_() ->
  493. {setup,
  494. fun () ->
  495. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  496. {log_warnings, false}]),
  497. Pid
  498. end,
  499. fun (Pid) ->
  500. exit(Pid, normal)
  501. end,
  502. {with, [fun (Pid) ->
  503. %% SLEEP was added in MySQL 5.0.12
  504. ?assertEqual({ok, [<<"SLEEP(5)">>], [[1]]},
  505. mysql:query(Pid, <<"SELECT SLEEP(5)">>, 40)),
  506. %% A query after an interrupted query shouldn't get a timeout.
  507. ?assertMatch({ok,[<<"42">>], [[42]]},
  508. mysql:query(Pid, <<"SELECT 42">>)),
  509. %% Parametrized query
  510. ?assertEqual({ok, [<<"SLEEP(?)">>], [[1]]},
  511. mysql:query(Pid, <<"SELECT SLEEP(?)">>, [5], 40)),
  512. %% Prepared statement
  513. {ok, Stmt} = mysql:prepare(Pid, <<"SELECT SLEEP(?)">>),
  514. ?assertEqual({ok, [<<"SLEEP(?)">>], [[1]]},
  515. mysql:execute(Pid, Stmt, [5], 40)),
  516. ok = mysql:unprepare(Pid, Stmt)
  517. end]}}.
  518. %% --------------------------------------------------------------------------
  519. %% Prepared statements
  520. with_table_foo_test_() ->
  521. {setup,
  522. fun () ->
  523. {ok, Pid} = mysql:start_link([{user, ?user}, {password, ?password},
  524. {query_cache_time, 50},
  525. {log_warnings, false}]),
  526. ok = mysql:query(Pid, <<"DROP DATABASE IF EXISTS otptest">>),
  527. ok = mysql:query(Pid, <<"CREATE DATABASE otptest">>),
  528. ok = mysql:query(Pid, <<"USE otptest">>),
  529. ok = mysql:query(Pid, <<"CREATE TABLE foo (bar INT) engine=InnoDB">>),
  530. Pid
  531. end,
  532. fun (Pid) ->
  533. ok = mysql:query(Pid, <<"DROP DATABASE otptest">>),
  534. exit(Pid, normal)
  535. end,
  536. fun (Pid) ->
  537. [{"Prepared statements", fun () -> prepared_statements(Pid) end},
  538. {"Parametrized queries", fun () -> parameterized_query(Pid) end}]
  539. end}.
  540. prepared_statements(Pid) ->
  541. %% Unnamed
  542. ?assertEqual({error,{1146, <<"42S02">>,
  543. <<"Table 'otptest.tab' doesn't exist">>}},
  544. mysql:prepare(Pid, "SELECT * FROM tab WHERE id = ?")),
  545. {ok, StmtId} = mysql:prepare(Pid, "SELECT * FROM foo WHERE bar = ?"),
  546. ?assert(is_integer(StmtId)),
  547. ?assertEqual(ok, mysql:unprepare(Pid, StmtId)),
  548. ?assertEqual({error, not_prepared}, mysql:unprepare(Pid, StmtId)),
  549. %% Named
  550. ?assertEqual({error,{1146, <<"42S02">>,
  551. <<"Table 'otptest.tab' doesn't exist">>}},
  552. mysql:prepare(Pid, tab, "SELECT * FROM tab WHERE id = ?")),
  553. ?assertEqual({ok, foo},
  554. mysql:prepare(Pid, foo, "SELECT * FROM foo WHERE bar = ?")),
  555. %% Prepare again unprepares the old stmt associated with this name.
  556. ?assertEqual({ok, foo},
  557. mysql:prepare(Pid, foo, "SELECT bar FROM foo WHERE bar = ?")),
  558. ?assertEqual(ok, mysql:unprepare(Pid, foo)),
  559. ?assertEqual({error, not_prepared}, mysql:unprepare(Pid, foo)),
  560. %% Execute when not prepared
  561. ?assertEqual({error, not_prepared}, mysql:execute(Pid, not_a_stmt, [])),
  562. ok.
  563. parameterized_query(Conn) ->
  564. %% To see that cache eviction works as expected, look at the code coverage.
  565. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [1]),
  566. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [2]),
  567. receive after 150 -> ok end, %% Now the query cache should emptied
  568. {ok, _, []} = mysql:query(Conn, "SELECT * FROM foo WHERE bar = ?", [3]),
  569. {error, {_, _, _}} = mysql:query(Conn, "Lorem ipsum dolor sit amet", [x]).
  570. %% --- simple gen_server callbacks ---
  571. gen_server_coverage_test() ->
  572. {noreply, state} = mysql:handle_cast(foo, state),
  573. {noreply, state} = mysql:handle_info(foo, state),
  574. ok = mysql:terminate(kill, state).