epgsql_SUITE.erl 44 KB

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