epgsql_SUITE.erl 45 KB

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