mysql_tests.erl 33 KB

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