epgsql_tests.erl 37 KB

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