mysql_tests.erl 31 KB

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