epgsql_tests.erl 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. -module(epgsql_tests).
  2. -export([run_tests/0]).
  3. -compile([export_all]).
  4. -include_lib("eunit/include/eunit.hrl").
  5. -include_lib("public_key/include/public_key.hrl").
  6. -include("epgsql.hrl").
  7. -define(host, "localhost").
  8. -define(port, 10432).
  9. -define(ssl_apps, [crypto, asn1, public_key, ssl]).
  10. -define(UUID1,
  11. <<163,189,240,40,149,151,17,227,141,6,112,24,139,130,16,73>>).
  12. -define(UUID2,
  13. <<183,55,22,52,149,151,17,227,187,167,112,24,139,130,16,73>>).
  14. -define(UUID3,
  15. <<198,188,155,66,149,151,17,227,138,98,112,24,139,130,16,73>>).
  16. -define(TIMEOUT_ERROR, {error, #error{
  17. severity = error,
  18. code = <<"57014">>,
  19. codename = query_canceled,
  20. message = <<"canceling statement due to statement timeout">>,
  21. extra = []
  22. }}).
  23. %% From uuid.erl in http://gitorious.org/avtobiff/erlang-uuid
  24. uuid_to_string(<<U0:32, U1:16, U2:16, U3:16, U4:48>>) ->
  25. lists:flatten(io_lib:format(
  26. "~8.16.0b-~4.16.0b-~4.16.0b-~4.16.0b-~12.16.0b",
  27. [U0, U1, U2, U3, U4])).
  28. connect_test(Module) ->
  29. connect_only(Module, []).
  30. connect_to_db_test(Module) ->
  31. connect_only(Module, [{database, "epgsql_test_db1"}]).
  32. connect_as_test(Module) ->
  33. connect_only(Module, ["epgsql_test", [{database, "epgsql_test_db1"}]]).
  34. connect_with_cleartext_test(Module) ->
  35. connect_only(Module, ["epgsql_test_cleartext",
  36. "epgsql_test_cleartext",
  37. [{database, "epgsql_test_db1"}]]).
  38. connect_with_md5_test(Module) ->
  39. connect_only(Module, ["epgsql_test_md5",
  40. "epgsql_test_md5",
  41. [{database, "epgsql_test_db1"}]]).
  42. connect_with_invalid_user_test(Module) ->
  43. {error, Why} =
  44. Module:connect(?host,
  45. "epgsql_test_invalid",
  46. "epgsql_test_invalid",
  47. [{port, ?port}, {database, "epgsql_test_db1"}]),
  48. case Why of
  49. invalid_authorization_specification -> ok; % =< 8.4
  50. invalid_password -> ok % >= 9.0
  51. end.
  52. connect_with_invalid_password_test(Module) ->
  53. {error, Why} =
  54. Module:connect(?host,
  55. "epgsql_test_md5",
  56. "epgsql_test_invalid",
  57. [{port, ?port}, {database, "epgsql_test_db1"}]),
  58. case Why of
  59. invalid_authorization_specification -> ok; % =< 8.4
  60. invalid_password -> ok % >= 9.0
  61. end.
  62. connect_with_ssl_test(Module) ->
  63. lists:foreach(fun application:start/1, ?ssl_apps),
  64. with_connection(
  65. Module,
  66. fun(C) ->
  67. {ok, _Cols, [{true}]} = Module:equery(C, "select ssl_is_used()")
  68. end,
  69. "epgsql_test",
  70. [{ssl, true}]).
  71. connect_with_client_cert_test(Module) ->
  72. lists:foreach(fun application:start/1, ?ssl_apps),
  73. Dir = filename:join(filename:dirname(code:which(epgsql_tests)), "../test_data"),
  74. File = fun(Name) -> filename:join(Dir, Name) end,
  75. {ok, Pem} = file:read_file(File("epgsql.crt")),
  76. [{'Certificate', Der, not_encrypted}] = public_key:pem_decode(Pem),
  77. Cert = public_key:pkix_decode_cert(Der, plain),
  78. #'TBSCertificate'{serialNumber = Serial} = Cert#'Certificate'.tbsCertificate,
  79. Serial2 = list_to_binary(integer_to_list(Serial)),
  80. with_connection(
  81. Module,
  82. fun(C) ->
  83. {ok, _, [{true}]} = Module:equery(C, "select ssl_is_used()"),
  84. {ok, _, [{Serial2}]} = Module:equery(C, "select ssl_client_serial()")
  85. end,
  86. "epgsql_test_cert",
  87. [{ssl, true}, {keyfile, File("epgsql.key")}, {certfile, File("epgsql.crt")}]).
  88. select_test(Module) ->
  89. with_connection(
  90. Module,
  91. fun(C) ->
  92. {ok, Cols, Rows} = Module:squery(C, "select * from test_table1"),
  93. [#column{name = <<"id">>, type = int4, size = 4},
  94. #column{name = <<"value">>, type = text, size = -1}] = Cols,
  95. [{<<"1">>, <<"one">>}, {<<"2">>, <<"two">>}] = Rows
  96. end).
  97. insert_test(Module) ->
  98. with_rollback(
  99. Module,
  100. fun(C) ->
  101. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (3, 'three')")
  102. end).
  103. update_test(Module) ->
  104. with_rollback(
  105. Module,
  106. fun(C) ->
  107. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (3, 'three')"),
  108. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (4, 'four')"),
  109. {ok, 2} = Module:squery(C, "update test_table1 set value = 'foo' where id > 2"),
  110. {ok, _, [{<<"2">>}]} = Module:squery(C, "select count(*) from test_table1 where value = 'foo'")
  111. end).
  112. delete_test(Module) ->
  113. with_rollback(
  114. Module,
  115. fun(C) ->
  116. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (3, 'three')"),
  117. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (4, 'four')"),
  118. {ok, 2} = Module:squery(C, "delete from test_table1 where id > 2"),
  119. {ok, _, [{<<"2">>}]} = Module:squery(C, "select count(*) from test_table1")
  120. end).
  121. create_and_drop_table_test(Module) ->
  122. with_rollback(
  123. Module,
  124. fun(C) ->
  125. {ok, [], []} = Module:squery(C, "create table test_table3 (id int4)"),
  126. {ok, [#column{type = int4}], []} = Module:squery(C, "select * from test_table3"),
  127. {ok, [], []} = Module:squery(C, "drop table test_table3")
  128. end).
  129. cursor_test(Module) ->
  130. with_connection(
  131. Module,
  132. fun(C) ->
  133. {ok, [], []} = Module:squery(C, "begin"),
  134. {ok, [], []} = Module:squery(C, "declare c cursor for select id from test_table1"),
  135. {ok, 2} = Module:squery(C, "move forward 2 from c"),
  136. {ok, 1} = Module:squery(C, "move backward 1 from c"),
  137. {ok, 1, _Cols, [{<<"2">>}]} = Module:squery(C, "fetch next from c"),
  138. {ok, [], []} = Module:squery(C, "close c")
  139. end).
  140. multiple_result_test(Module) ->
  141. with_connection(
  142. Module,
  143. fun(C) ->
  144. [{ok, _, [{<<"1">>}]}, {ok, _, [{<<"2">>}]}] = Module:squery(C, "select 1; select 2"),
  145. [{ok, _, [{<<"1">>}]}, {error, #error{}}] = Module:squery(C, "select 1; select foo;")
  146. end).
  147. execute_batch_test(Module) ->
  148. with_connection(
  149. Module,
  150. fun(C) ->
  151. {ok, S1} = Module:parse(C, "one", "select $1", [int4]),
  152. {ok, S2} = Module:parse(C, "two", "select $1 + $2", [int4, int4]),
  153. [{ok, [{1}]}, {ok, [{3}]}] =
  154. Module:execute_batch(C, [{S1, [1]}, {S2, [1, 2]}])
  155. end).
  156. batch_error_test(Module) ->
  157. with_rollback(
  158. Module,
  159. fun(C) ->
  160. {ok, S} = Module:parse(C, "insert into test_table1(id, value) values($1, $2)"),
  161. [{ok, 1}, {error, _}] =
  162. Module:execute_batch(
  163. C,
  164. [{S, [3, "batch_error 3"]},
  165. {S, [2, "batch_error 2"]}, % duplicate key error
  166. {S, [5, "batch_error 5"]} % won't be executed
  167. ])
  168. end).
  169. single_batch_test(Module) ->
  170. with_connection(
  171. Module,
  172. fun(C) ->
  173. {ok, S1} = Module:parse(C, "one", "select $1", [int4]),
  174. [{ok, [{1}]}] = Module:execute_batch(C, [{S1, [1]}])
  175. end).
  176. extended_select_test(Module) ->
  177. with_connection(
  178. Module,
  179. fun(C) ->
  180. {ok, Cols, Rows} = Module:equery(C, "select * from test_table1", []),
  181. [#column{name = <<"id">>, type = int4, size = 4},
  182. #column{name = <<"value">>, type = text, size = -1}] = Cols,
  183. [{1, <<"one">>}, {2, <<"two">>}] = Rows
  184. end).
  185. extended_sync_ok_test(Module) ->
  186. with_connection(
  187. Module,
  188. fun(C) ->
  189. {ok, _Cols, [{<<"one">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [1]),
  190. {ok, _Cols, [{<<"two">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [2])
  191. end).
  192. extended_sync_error_test(Module) ->
  193. with_connection(
  194. Module,
  195. fun(C) ->
  196. {error, #error{}} = Module:equery(C, "select _alue from test_table1 where id = $1", [1]),
  197. {ok, _Cols, [{<<"one">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [1])
  198. end).
  199. returning_from_insert_test(Module) ->
  200. with_rollback(
  201. Module,
  202. fun(C) ->
  203. {ok, 1, _Cols, [{3}]} = Module:equery(C, "insert into test_table1 (id) values (3) returning id")
  204. end).
  205. returning_from_update_test(Module) ->
  206. with_rollback(
  207. Module,
  208. fun(C) ->
  209. {ok, 2, _Cols, [{1}, {2}]} = Module:equery(C, "update test_table1 set value = 'hi' returning id")
  210. end).
  211. returning_from_delete_test(Module) ->
  212. with_rollback(
  213. Module,
  214. fun(C) ->
  215. {ok, 2, _Cols, [{1}, {2}]} = Module:equery(C, "delete from test_table1 returning id")
  216. end).
  217. parse_test(Module) ->
  218. with_connection(
  219. Module,
  220. fun(C) ->
  221. {ok, S} = Module:parse(C, "select * from test_table1"),
  222. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  223. ok = Module:close(C, S),
  224. ok = Module:sync(C)
  225. end).
  226. parse_column_format_test(Module) ->
  227. with_connection(
  228. Module,
  229. fun(C) ->
  230. {ok, S} = Module:parse(C, "select 1::int4, false::bool, 2.0::float4"),
  231. [#column{type = int4},
  232. #column{type = bool},
  233. #column{type = float4}] = S#statement.columns,
  234. ok = Module:bind(C, S, []),
  235. {ok, [{1, false, 2.0}]} = Module:execute(C, S, 0),
  236. ok = Module:close(C, S),
  237. ok = Module:sync(C)
  238. end).
  239. parse_error_test(Module) ->
  240. with_connection(
  241. Module,
  242. fun(C) ->
  243. {error, #error{}} = Module:parse(C, "select _ from test_table1"),
  244. {ok, S} = Module:parse(C, "select * from test_table1"),
  245. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  246. ok = Module:close(C, S),
  247. ok = Module:sync(C)
  248. end).
  249. parse_and_close_test(Module) ->
  250. with_connection(
  251. Module,
  252. fun(C) ->
  253. Parse = fun() -> Module:parse(C, "test", "select * from test_table1", []) end,
  254. {ok, S} = Parse(),
  255. {error, #error{code = <<"42P05">>, codename = duplicate_prepared_statement}} = Parse(),
  256. Module:close(C, S),
  257. {ok, S} = Parse(),
  258. ok = Module:sync(C)
  259. end).
  260. bind_test(Module) ->
  261. with_connection(
  262. Module,
  263. fun(C) ->
  264. {ok, S} = Module:parse(C, "select value from test_table1 where id = $1"),
  265. ok = Module:bind(C, S, [1]),
  266. ok = Module:close(C, S),
  267. ok = Module:sync(C)
  268. end).
  269. bind_parameter_format_test(Module) ->
  270. with_connection(
  271. Module,
  272. fun(C) ->
  273. {ok, S} = Module:parse(C, "select $1, $2, $3", [int2, text, bool]),
  274. [int2, text, bool] = S#statement.types,
  275. ok = Module:bind(C, S, [1, "hi", true]),
  276. {ok, [{1, <<"hi">>, true}]} = Module:execute(C, S, 0),
  277. ok = Module:close(C, S),
  278. ok = Module:sync(C)
  279. end).
  280. bind_error_test(Module) ->
  281. with_connection(
  282. Module,
  283. fun(C) ->
  284. {ok, S} = Module:parse(C, "select $1::char"),
  285. {error, #error{}} = Module:bind(C, S, [0]),
  286. ok = Module:bind(C, S, [$A]),
  287. ok = Module:close(C, S),
  288. ok = Module:sync(C)
  289. end).
  290. bind_and_close_test(Module) ->
  291. with_connection(
  292. Module,
  293. fun(C) ->
  294. {ok, S} = Module:parse(C, "select * from test_table1"),
  295. ok = Module:bind(C, S, "one", []),
  296. {error, #error{code = <<"42P03">>, codename = duplicate_cursor}} = Module:bind(C, S, "one", []),
  297. ok = Module:close(C, portal, "one"),
  298. ok = Module:bind(C, S, "one", []),
  299. ok = Module:sync(C)
  300. end).
  301. execute_error_test(Module) ->
  302. with_connection(
  303. Module,
  304. fun(C) ->
  305. {ok, S} = Module:parse(C, "insert into test_table1 (id, value) values ($1, $2)"),
  306. ok = Module:bind(C, S, [1, <<"foo">>]),
  307. {error, #error{code = <<"23505">>, codename = unique_violation}} = Module:execute(C, S, 0),
  308. {error, sync_required} = Module:bind(C, S, [3, <<"quux">>]),
  309. ok = Module:sync(C),
  310. ok = Module:bind(C, S, [3, <<"quux">>]),
  311. {ok, _} = Module:execute(C, S, 0),
  312. {ok, 1} = Module:squery(C, "delete from test_table1 where id = 3")
  313. end).
  314. describe_test(Module) ->
  315. with_connection(
  316. Module,
  317. fun(C) ->
  318. {ok, S} = Module:parse(C, "select * from test_table1"),
  319. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  320. {ok, S} = Module:describe(C, S),
  321. ok = Module:close(C, S),
  322. ok = Module:sync(C)
  323. end).
  324. describe_with_param_test(Module) ->
  325. with_connection(
  326. Module,
  327. fun(C) ->
  328. {ok, S} = Module:parse(C, "select id from test_table1 where id = $1"),
  329. [int4] = S#statement.types,
  330. [#column{name = <<"id">>}] = S#statement.columns,
  331. {ok, S} = Module:describe(C, S),
  332. ok = Module:close(C, S),
  333. ok = Module:sync(C)
  334. end).
  335. describe_named_test(Module) ->
  336. with_connection(
  337. Module,
  338. fun(C) ->
  339. {ok, S} = Module:parse(C, "name", "select * from test_table1", []),
  340. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  341. {ok, S} = Module:describe(C, S),
  342. ok = Module:close(C, S),
  343. ok = Module:sync(C)
  344. end).
  345. describe_error_test(Module) ->
  346. with_connection(
  347. Module,
  348. fun(C) ->
  349. {error, #error{}} = Module:describe(C, statement, ""),
  350. {ok, S} = Module:parse(C, "select * from test_table1"),
  351. {ok, S} = Module:describe(C, statement, ""),
  352. ok = Module:sync(C)
  353. end).
  354. portal_test(Module) ->
  355. with_connection(
  356. Module,
  357. fun(C) ->
  358. {ok, S} = Module:parse(C, "select value from test_table1"),
  359. ok = Module:bind(C, S, []),
  360. {partial, [{<<"one">>}]} = Module:execute(C, S, 1),
  361. {partial, [{<<"two">>}]} = Module:execute(C, S, 1),
  362. {ok, []} = Module:execute(C, S,1),
  363. ok = Module:close(C, S),
  364. ok = Module:sync(C)
  365. end).
  366. returning_test(Module) ->
  367. with_rollback(
  368. Module,
  369. fun(C) ->
  370. {ok, S} = Module:parse(C, "update test_table1 set value = $1 returning id"),
  371. ok = Module:bind(C, S, ["foo"]),
  372. {ok, 2, [{1}, {2}]} = Module:execute(C, S),
  373. ok = Module:sync(C)
  374. end).
  375. multiple_statement_test(Module) ->
  376. with_connection(
  377. Module,
  378. fun(C) ->
  379. {ok, S1} = Module:parse(C, "one", "select value from test_table1 where id = 1", []),
  380. ok = Module:bind(C, S1, []),
  381. {partial, [{<<"one">>}]} = Module:execute(C, S1, 1),
  382. {ok, S2} = Module:parse(C, "two", "select value from test_table1 where id = 2", []),
  383. ok = Module:bind(C, S2, []),
  384. {partial, [{<<"two">>}]} = Module:execute(C, S2, 1),
  385. {ok, []} = Module:execute(C, S1, 1),
  386. {ok, []} = Module:execute(C, S2, 1),
  387. ok = Module:close(C, S1),
  388. ok = Module:close(C, S2),
  389. ok = Module:sync(C)
  390. end).
  391. multiple_portal_test(Module) ->
  392. with_connection(
  393. Module,
  394. fun(C) ->
  395. {ok, S} = Module:parse(C, "select value from test_table1 where id = $1"),
  396. ok = Module:bind(C, S, "one", [1]),
  397. ok = Module:bind(C, S, "two", [2]),
  398. {ok, [{<<"one">>}]} = Module:execute(C, S, "one", 0),
  399. {ok, [{<<"two">>}]} = Module:execute(C, S, "two", 0),
  400. ok = Module:close(C, S),
  401. ok = Module:sync(C)
  402. end).
  403. execute_function_test(Module) ->
  404. with_rollback(
  405. Module,
  406. fun(C) ->
  407. {ok, _Cols1, [{3}]} = Module:equery(C, "select insert_test1(3, 'three')"),
  408. {ok, _Cols2, [{<<>>}]} = Module:equery(C, "select do_nothing()")
  409. end).
  410. parameter_get_test(Module) ->
  411. with_connection(
  412. Module,
  413. fun(C) ->
  414. {ok, <<"off">>} = Module:get_parameter(C, "is_superuser")
  415. end).
  416. parameter_set_test(Module) ->
  417. with_connection(
  418. Module,
  419. fun(C) ->
  420. {ok, [], []} = Module:squery(C, "set DateStyle = 'ISO, MDY'"),
  421. {ok, <<"ISO, MDY">>} = Module:get_parameter(C, "DateStyle"),
  422. {ok, _Cols, [{<<"2000-01-02">>}]} = Module:squery(C, "select '2000-01-02'::date"),
  423. {ok, [], []} = Module:squery(C, "set DateStyle = 'German'"),
  424. {ok, <<"German, DMY">>} = Module:get_parameter(C, "DateStyle"),
  425. {ok, _Cols, [{<<"02.01.2000">>}]} = Module:squery(C, "select '2000-01-02'::date")
  426. end).
  427. numeric_type_test(Module) ->
  428. check_type(Module, int2, "1", 1, [0, 256, -32768, +32767]),
  429. check_type(Module, int4, "1", 1, [0, 512, -2147483648, +2147483647]),
  430. check_type(Module, int8, "1", 1, [0, 1024, -9223372036854775808, +9223372036854775807]),
  431. check_type(Module, float4, "1.0", 1.0, [0.0, 1.23456, -1.23456]),
  432. check_type(Module, float8, "1.0", 1.0, [0.0, 1.23456789012345, -1.23456789012345]).
  433. character_type_test(Module) ->
  434. Alpha = unicode:characters_to_binary([16#03B1]),
  435. Ka = unicode:characters_to_binary([16#304B]),
  436. One = unicode:characters_to_binary([16#10D360]),
  437. check_type(Module, bpchar, "'A'", $A, [1, $1, 16#7F, Alpha, Ka, One], "c_char"),
  438. check_type(Module, text, "'hi'", <<"hi">>, [<<"">>, <<"hi">>]),
  439. check_type(Module, varchar, "'hi'", <<"hi">>, [<<"">>, <<"hi">>]).
  440. uuid_type_test(Module) ->
  441. check_type(Module, uuid,
  442. io_lib:format("'~s'", [uuid_to_string(?UUID1)]),
  443. list_to_binary(uuid_to_string(?UUID1)), []).
  444. point_type_test(Module) ->
  445. check_type(Module, point, "'(23.15, 100)'", {23.15, 100.0}, []).
  446. geometry_type_test(Module) ->
  447. check_type(Module, geometry, "'COMPOUNDCURVE(CIRCULARSTRING(0 0,1 1,1 0),(1 0,0 1))'",
  448. {compound_curve,'2d',
  449. [{circular_string,'2d',
  450. [{point,'2d',0.0,0.0,undefined,undefined},
  451. {point,'2d',1.0,1.0,undefined,undefined},
  452. {point,'2d',1.0,0.0,undefined,undefined}]},
  453. {line_string,'2d',
  454. [{point,'2d',1.0,0.0,undefined,undefined},
  455. {point,'2d',0.0,1.0,undefined,undefined}]}]},
  456. []).
  457. uuid_select_test(Module) ->
  458. with_rollback(
  459. Module,
  460. fun(C) ->
  461. U1 = uuid_to_string(?UUID1),
  462. U2 = uuid_to_string(?UUID2),
  463. U3 = uuid_to_string(?UUID3),
  464. {ok, 1} =
  465. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID1', $1)",
  466. [U1]),
  467. {ok, 1} =
  468. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID2', $1)",
  469. [U2]),
  470. {ok, 1} =
  471. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID3', $1)",
  472. [U3]),
  473. Res = Module:equery(C, "select c_varchar, c_uuid from test_table2 where c_uuid = any($1)",
  474. [[U1, U2]]),
  475. U1Bin = list_to_binary(U1),
  476. U2Bin = list_to_binary(U2),
  477. {ok,[{column,<<"c_varchar">>,varchar,_,_,_},
  478. {column,<<"c_uuid">>,uuid,_,_,_}],
  479. [{<<"UUID1">>, U1Bin},
  480. {<<"UUID2">>, U2Bin}]} = Res
  481. end).
  482. date_time_type_test(Module) ->
  483. with_connection(
  484. Module,
  485. fun(C) ->
  486. case Module:get_parameter(C, "integer_datetimes") of
  487. {ok, <<"on">>} -> MaxTsDate = 294276;
  488. {ok, <<"off">>} -> MaxTsDate = 5874897
  489. end,
  490. check_type(Module, date, "'2008-01-02'", {2008,1,2}, [{-4712,1,1}, {5874897,1,1}]),
  491. check_type(Module, time, "'00:01:02'", {0,1,2.0}, [{0,0,0.0}, {24,0,0.0}]),
  492. check_type(Module, timetz, "'00:01:02-01'", {{0,1,2.0},1*60*60},
  493. [{{0,0,0.0},0}, {{24,0,0.0},-13*60*60}]),
  494. check_type(Module, timestamp, "'2008-01-02 03:04:05'", {{2008,1,2},{3,4,5.0}},
  495. [{{-4712,1,1},{0,0,0.0}}, {{MaxTsDate,12,31}, {23,59,59.0}}, {1322,334285,440966}]),
  496. check_type(Module, timestamptz, "'2011-01-02 03:04:05+3'", {{2011, 1, 2}, {0, 4, 5.0}}, [{1324,875970,286983}]),
  497. check_type(Module, interval, "'1 hour 2 minutes 3.1 seconds'", {{1,2,3.1},0,0},
  498. [{{0,0,0.0},0,-178000000 * 12}, {{0,0,0.0},0,178000000 * 12}])
  499. end).
  500. misc_type_test(Module) ->
  501. check_type(Module, bool, "true", true, [true, false]),
  502. check_type(Module, bytea, "E'\001\002'", <<1,2>>, [<<>>, <<0,128,255>>]).
  503. hstore_type_test(Module) ->
  504. Values = [
  505. {[]},
  506. {[{null, null}]},
  507. {[{null, undefined}]},
  508. {[{1, null}]},
  509. {[{1.0, null}]},
  510. {[{1, undefined}]},
  511. {[{1.0, undefined}]},
  512. {[{<<"a">>, <<"c">>}, {<<"c">>, <<"d">>}]},
  513. {[{<<"a">>, <<"c">>}, {<<"c">>, null}]},
  514. {[{<<"a">>, <<"c">>}, {<<"c">>, undefined}]}
  515. ],
  516. with_connection(
  517. Module,
  518. fun(_C) ->
  519. check_type(Module, hstore, "''", {[]}, []),
  520. check_type(Module, hstore,
  521. "'a => 1, b => 2.0, c => null'",
  522. {[{<<"c">>, null}, {<<"b">>, <<"2.0">>}, {<<"a">>, <<"1">>}]}, Values)
  523. end).
  524. net_type_test(Module) ->
  525. check_type(Module, cidr, "'127.0.0.1/32'", {{127,0,0,1}, 32}, [{{127,0,0,1}, 32}, {{0,0,0,0,0,0,0,1}, 128}]),
  526. check_type(Module, inet, "'127.0.0.1'", {127,0,0,1}, [{127,0,0,1}, {0,0,0,0,0,0,0,1}]).
  527. array_type_test(Module) ->
  528. with_connection(
  529. Module,
  530. fun(C) ->
  531. {ok, _, [{[1, 2]}]} = Module:equery(C, "select ($1::int[])[1:2]", [[1, 2, 3]]),
  532. {ok, _, [{[{1, <<"one">>}, {2, <<"two">>}]}]} =
  533. Module:equery(C, "select Array(select (id, value) from test_table1)", []),
  534. Select = fun(Type, A) ->
  535. Query = "select $1::" ++ atom_to_list(Type) ++ "[]",
  536. {ok, _Cols, [{A2}]} = Module:equery(C, Query, [A]),
  537. case lists:all(fun({V, V2}) -> compare(Type, V, V2) end, lists:zip(A, A2)) of
  538. true -> ok;
  539. false -> ?assertMatch(A, A2)
  540. end
  541. end,
  542. Select(int2, []),
  543. Select(int2, [1, 2, 3, 4]),
  544. Select(int2, [[1], [2], [3], [4]]),
  545. Select(int2, [[[[[[1, 2]]]]]]),
  546. Select(bool, [true]),
  547. Select(char, [$a, $b, $c]),
  548. Select(int4, [[1, 2]]),
  549. Select(int8, [[[[1, 2]], [[3, 4]]]]),
  550. Select(text, [<<"one">>, <<"two>">>]),
  551. Select(varchar, [<<"one">>, <<"two>">>]),
  552. Select(float4, [0.0, 1.0, 0.123]),
  553. Select(float8, [0.0, 1.0, 0.123]),
  554. Select(date, [{2008,1,2}, {2008,1,3}]),
  555. Select(time, [{0,1,2.0}, {0,1,3.0}]),
  556. Select(timetz, [{{0,1,2.0},1*60*60}, {{0,1,3.0},1*60*60}]),
  557. Select(timestamp, [{{2008,1,2},{3,4,5.0}}, {{2008,1,2},{3,4,6.0}}]),
  558. Select(timestamptz, [{{2008,1,2},{3,4,5.0}}, {{2008,1,2},{3,4,6.0}}]),
  559. Select(interval, [{{1,2,3.1},0,0}, {{1,2,3.2},0,0}]),
  560. Select(hstore, [{[{null, null}, {a, 1}, {1, 2}, {b, undefined}]}]),
  561. Select(hstore, [[{[{null, null}, {a, 1}, {1, 2}, {b, undefined}]}, {[]}], [{[{a, 1}]}, {[{null, 2}]}]]),
  562. Select(cidr, [{{127,0,0,1}, 32}, {{0,0,0,0,0,0,0,1}, 128}]),
  563. Select(inet, [{127,0,0,1}, {0,0,0,0,0,0,0,1}])
  564. end).
  565. custom_types_test(Module) ->
  566. with_connection(
  567. Module,
  568. fun(C) ->
  569. Module:squery(C, "drop table if exists t_foo;"),
  570. Module:squery(C, "drop type foo;"),
  571. {ok, [], []} = Module:squery(C, "create type foo as enum('foo', 'bar');"),
  572. ok = epgsql:update_type_cache(C, [<<"foo">>]),
  573. {ok, [], []} = Module:squery(C, "create table t_foo (col foo);"),
  574. {ok, S} = Module:parse(C, "insert_foo", "insert into t_foo values ($1)", [foo]),
  575. ok = Module:bind(C, S, ["bar"]),
  576. {ok, 1} = Module:execute(C, S)
  577. end).
  578. text_format_test(Module) ->
  579. with_connection(
  580. Module,
  581. fun(C) ->
  582. Select = fun(Type, V) ->
  583. V2 = list_to_binary(V),
  584. Query = "select $1::" ++ Type,
  585. {ok, _Cols, [{V2}]} = Module:equery(C, Query, [V]),
  586. {ok, _Cols, [{V2}]} = Module:equery(C, Query, [V2])
  587. end,
  588. Select("numeric", "123456")
  589. end).
  590. query_timeout_test(Module) ->
  591. with_connection(
  592. Module,
  593. fun(C) ->
  594. {ok, _, _} = Module:squery(C, "SET statement_timeout = 500"),
  595. ?TIMEOUT_ERROR = Module:squery(C, "SELECT pg_sleep(1)"),
  596. ?TIMEOUT_ERROR = Module:equery(C, "SELECT pg_sleep(2)"),
  597. {ok, _Cols, [{1}]} = Module:equery(C, "SELECT 1")
  598. end,
  599. []).
  600. execute_timeout_test(Module) ->
  601. with_connection(
  602. Module,
  603. fun(C) ->
  604. {ok, _, _} = Module:squery(C, "SET statement_timeout = 500"),
  605. {ok, S} = Module:parse(C, "select pg_sleep($1)"),
  606. ok = Module:bind(C, S, [2]),
  607. ?TIMEOUT_ERROR = Module:execute(C, S, 0),
  608. ok = Module:sync(C),
  609. ok = Module:bind(C, S, [0]),
  610. {ok, [{<<>>}]} = Module:execute(C, S, 0),
  611. ok = Module:close(C, S),
  612. ok = Module:sync(C)
  613. end,
  614. []).
  615. connection_closed_test(Module) ->
  616. P = self(),
  617. F = fun() ->
  618. process_flag(trap_exit, true),
  619. {ok, C} = Module:connect(?host, "epgsql_test",
  620. [{port, ?port}, {database, "epgsql_test_db1"}]),
  621. P ! {connected, C},
  622. receive
  623. Any -> P ! Any
  624. end
  625. end,
  626. spawn_link(F),
  627. receive
  628. {connected, C} ->
  629. timer:sleep(100),
  630. Module:close(C),
  631. {'EXIT', C, _} = receive R -> R end
  632. end,
  633. flush().
  634. connection_closed_by_server_test(Module) ->
  635. with_connection(Module,
  636. fun(C1) ->
  637. P = self(),
  638. spawn_link(fun() ->
  639. process_flag(trap_exit, true),
  640. with_connection(Module,
  641. fun(C2) ->
  642. {ok, _, [{Pid}]} = Module:equery(C2, "select pg_backend_pid()"),
  643. % emulate of disconnection
  644. {ok, _, [{true}]} = Module:equery(C1,
  645. "select pg_terminate_backend($1)", [Pid]),
  646. receive
  647. {'EXIT', C2, {shutdown, #error{code = <<"57P01">>}}} ->
  648. P ! ok;
  649. Other ->
  650. ?debugFmt("Unexpected msg: ~p~n", [Other]),
  651. P ! error
  652. end
  653. end)
  654. end),
  655. receive ok -> ok end
  656. end).
  657. active_connection_closed_test(Module) ->
  658. P = self(),
  659. F = fun() ->
  660. process_flag(trap_exit, true),
  661. {ok, C} = Module:connect(?host, [{database,
  662. "epgsql_test_db1"}, {port, ?port}]),
  663. P ! {connected, C},
  664. R = Module:squery(C, "select pg_sleep(10)"),
  665. P ! R
  666. end,
  667. spawn_link(F),
  668. receive
  669. {connected, C} ->
  670. timer:sleep(100),
  671. Module:close(C),
  672. {error, closed} = receive R -> R end
  673. end,
  674. flush().
  675. warning_notice_test(Module) ->
  676. with_connection(
  677. Module,
  678. fun(C) ->
  679. Q = "create function pg_temp.raise() returns void as $$
  680. begin
  681. raise warning 'oops';
  682. end;
  683. $$ language plpgsql;
  684. select pg_temp.raise()",
  685. [{ok, _, _}, _] = Module:squery(C, Q),
  686. receive
  687. {epgsql, C, {notice, #error{message = <<"oops">>}}} -> ok
  688. after
  689. 100 -> erlang:error(didnt_receive_notice)
  690. end
  691. end,
  692. [{async, self()}]).
  693. listen_notify_test(Module) ->
  694. with_connection(
  695. Module,
  696. fun(C) ->
  697. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  698. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  699. {ok, [], []} = Module:squery(C, "notify epgsql_test"),
  700. receive
  701. {epgsql, C, {notification, <<"epgsql_test">>, Pid, <<>>}} -> ok
  702. after
  703. 100 -> erlang:error(didnt_receive_notification)
  704. end
  705. end,
  706. [{async, self()}]).
  707. listen_notify_payload_test(Module) ->
  708. with_min_version(
  709. Module,
  710. 9.0,
  711. fun(C) ->
  712. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  713. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  714. {ok, [], []} = Module:squery(C, "notify epgsql_test, 'test!'"),
  715. receive
  716. {epgsql, C, {notification, <<"epgsql_test">>, Pid, <<"test!">>}} -> ok
  717. after
  718. 100 -> erlang:error(didnt_receive_notification)
  719. end
  720. end,
  721. [{async, self()}]).
  722. application_test(_Module) ->
  723. lists:foreach(fun application:start/1, ?ssl_apps),
  724. ok = application:start(epgsql),
  725. ok = application:stop(epgsql).
  726. range_type_test(Module) ->
  727. with_min_version(
  728. Module,
  729. 9.2,
  730. fun(_C) ->
  731. check_type(Module, int4range, "int4range(10, 20)", <<"[10,20)">>,
  732. [{1, 58}, {-1, 12}, {-985521, 5412687}, {minus_infinity, 0},
  733. {984655, plus_infinity}, {minus_infinity, plus_infinity}])
  734. end,
  735. []).
  736. %% -- run all tests --
  737. run_tests() ->
  738. Files = filelib:wildcard(filename:dirname(code:which(epgsql_tests))
  739. ++ "/*tests.beam"),
  740. Mods = [list_to_atom(filename:basename(F, ".beam")) || F <- Files],
  741. eunit:test(Mods, []).
  742. all_test_() ->
  743. Version =
  744. erlang:list_to_binary(
  745. re:replace(os:cmd("git rev-parse HEAD"), "\\s+", "")),
  746. with_connection(
  747. epgsql,
  748. fun(C) ->
  749. {ok, _Cols, [{DBVersion}]} = epgsql:squery(C, "SELECT version FROM schema_version"),
  750. case DBVersion == Version of
  751. false ->
  752. error_logger:info_msg("Git version of test schema does not match: ~p ~p~nPlease run make create_testdbs to update your test databases", [Version, DBVersion]),
  753. erlang:exit(1);
  754. _ ->
  755. undefined
  756. end
  757. end),
  758. Tests =
  759. lists:map(
  760. fun({Name, _}) ->
  761. {Name, fun(X) -> ?MODULE:Name(X) end}
  762. end,
  763. lists:filter(
  764. fun({Name, Arity}) ->
  765. case {lists:suffix("_test", atom_to_list(Name)), Arity} of
  766. {true, 1} -> true;
  767. _ -> false
  768. end
  769. end,
  770. ?MODULE:module_info(functions))),
  771. WithModule =
  772. fun(Module) ->
  773. lists:map(
  774. fun({Name, Test}) ->
  775. {lists:flatten(
  776. io_lib:format("~s(~s)", [Name, Module])),
  777. fun() -> Test(Module) end}
  778. end,
  779. Tests)
  780. end,
  781. [WithModule(epgsql),
  782. WithModule(epgsql_cast),
  783. WithModule(epgsql_incremental)].
  784. %% -- internal functions --
  785. connect_only(Module, Args) ->
  786. TestOpts = [{port, ?port}],
  787. case Args of
  788. [User, Opts] -> Args2 = [User, TestOpts ++ Opts];
  789. [User, Pass, Opts] -> Args2 = [User, Pass, TestOpts ++ Opts];
  790. Opts -> Args2 = [TestOpts ++ Opts]
  791. end,
  792. {ok, C} = apply(Module, connect, [?host | Args2]),
  793. Module:close(C),
  794. flush().
  795. with_connection(Module, F) ->
  796. with_connection(Module, F, "epgsql_test", []).
  797. with_connection(Module, F, Args) ->
  798. with_connection(Module, F, "epgsql_test", Args).
  799. with_connection(Module, F, Username, Args) ->
  800. Args2 = [{port, ?port}, {database, "epgsql_test_db1"} | Args],
  801. {ok, C} = Module:connect(?host, Username, Args2),
  802. try
  803. F(C)
  804. after
  805. Module:close(C)
  806. end,
  807. flush().
  808. with_rollback(Module, F) ->
  809. with_connection(
  810. Module,
  811. fun(C) ->
  812. try
  813. Module:squery(C, "begin"),
  814. F(C)
  815. after
  816. Module:squery(C, "rollback")
  817. end
  818. end).
  819. with_min_version(Module, Min, F, Args) ->
  820. with_connection(
  821. Module,
  822. fun(C) ->
  823. {ok, Bin} = Module:get_parameter(C, <<"server_version">>),
  824. {ok, [{float, 1, Ver} | _], _} = erl_scan:string(binary_to_list(Bin)),
  825. case Ver >= Min of
  826. true -> F(C);
  827. false -> ?debugFmt("skipping test requiring PostgreSQL >= ~.2f~n", [Min])
  828. end
  829. end,
  830. Args).
  831. check_type(Module, Type, In, Out, Values) ->
  832. Column = "c_" ++ atom_to_list(Type),
  833. check_type(Module, Type, In, Out, Values, Column).
  834. check_type(Module, Type, In, Out, Values, Column) ->
  835. with_connection(
  836. Module,
  837. fun(C) ->
  838. Select = io_lib:format("select ~s::~w", [In, Type]),
  839. Res = Module:equery(C, Select),
  840. {ok, [#column{type = Type}], [{Out}]} = Res,
  841. Sql = io_lib:format("insert into test_table2 (~s) values ($1) returning ~s", [Column, Column]),
  842. {ok, #statement{columns = [#column{type = Type}]} = S} = Module:parse(C, Sql),
  843. Insert = fun(V) ->
  844. ok = Module:bind(C, S, [V]),
  845. {ok, 1, [{V2}]} = Module:execute(C, S),
  846. case compare(Type, V, V2) of
  847. true -> ok;
  848. false -> ?debugFmt("~p =/= ~p~n", [V, V2]), ?assert(false)
  849. end,
  850. ok = Module:sync(C)
  851. end,
  852. lists:foreach(Insert, [null, undefined | Values])
  853. end).
  854. compare(_Type, null, null) -> true;
  855. compare(_Type, undefined, null) -> true;
  856. compare(float4, V1, V2) -> abs(V2 - V1) < 0.000001;
  857. compare(float8, V1, V2) -> abs(V2 - V1) < 0.000000000000001;
  858. compare(hstore, {V1}, V2) -> compare(hstore, V1, V2);
  859. compare(hstore, V1, {V2}) -> compare(hstore, V1, V2);
  860. compare(hstore, V1, V2) ->
  861. orddict:from_list(format_hstore(V1)) =:= orddict:from_list(format_hstore(V2));
  862. compare(Type, V1 = {_, _, MS}, {D2, {H2, M2, S2}}) when Type == timestamp;
  863. Type == timestamptz ->
  864. {D1, {H1, M1, S1}} = calendar:now_to_universal_time(V1),
  865. ({D1, H1, M1} =:= {D2, H2, M2}) and (abs(S1 + MS/1000000 - S2) < 0.000000000000001);
  866. compare(int4range, {Lower, Upper}, Result) ->
  867. translate_infinities(Lower, Upper) =:= Result;
  868. compare(_Type, V1, V2) -> V1 =:= V2.
  869. translate_infinities(Lower, Upper) ->
  870. iolist_to_binary([lower(Lower), [","], upper(Upper)]).
  871. lower(minus_infinity) ->
  872. "(";
  873. lower(Val) ->
  874. io_lib:format("[~p", [Val]).
  875. upper(plus_infinity) ->
  876. ")";
  877. upper(Val) ->
  878. io_lib:format("~p)", [Val]).
  879. format_hstore({Hstore}) -> Hstore;
  880. format_hstore(Hstore) ->
  881. [{format_hstore_key(Key), format_hstore_value(Value)} || {Key, Value} <- Hstore].
  882. format_hstore_key(Key) -> format_hstore_string(Key).
  883. format_hstore_value(null) -> null;
  884. format_hstore_value(undefined) -> null;
  885. format_hstore_value(Value) -> format_hstore_string(Value).
  886. format_hstore_string(Num) when is_number(Num) -> iolist_to_binary(io_lib:format("~w", [Num]));
  887. format_hstore_string(Str) -> iolist_to_binary(io_lib:format("~s", [Str])).
  888. %% flush mailbox
  889. flush() ->
  890. ?assertEqual([], flush([])).
  891. flush(Acc) ->
  892. receive
  893. {'EXIT', _Pid, normal} -> flush(Acc);
  894. M -> flush([M | Acc])
  895. after
  896. 0 -> lists:reverse(Acc)
  897. end.