epgsql_tests.erl 42 KB

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