epgsql_SUITE.erl 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205
  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. end).
  632. uuid_type(Config) ->
  633. check_type(Config, uuid,
  634. io_lib:format("'~s'", [uuid_to_bin_string(?UUID1)]),
  635. uuid_to_bin_string(?UUID1), []).
  636. point_type(Config) ->
  637. check_type(Config, point, "'(23.15, 100)'", {23.15, 100.0}, []).
  638. geometry_type(Config) ->
  639. check_type(Config, geometry, "'COMPOUNDCURVE(CIRCULARSTRING(0 0,1 1,1 0),(1 0,0 1))'",
  640. {compound_curve,'2d', [
  641. {circular_string,'2d', [
  642. {point,'2d',0.0,0.0,undefined,undefined},
  643. {point,'2d',1.0,1.0,undefined,undefined},
  644. {point,'2d',1.0,0.0,undefined,undefined}
  645. ]},
  646. {line_string,'2d', [
  647. {point,'2d',1.0,0.0,undefined,undefined},
  648. {point,'2d',0.0,1.0,undefined,undefined}
  649. ]}
  650. ]}, []).
  651. uuid_select(Config) ->
  652. Module = ?config(module, Config),
  653. epgsql_ct:with_rollback(Config, fun(C) ->
  654. U1 = uuid_to_bin_string(?UUID1),
  655. U2 = uuid_to_bin_string(?UUID2),
  656. U3 = uuid_to_bin_string(?UUID3),
  657. {ok, 1} =
  658. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID1', $1)",
  659. [U1]),
  660. {ok, 1} =
  661. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID2', $1)",
  662. [U2]),
  663. {ok, 1} =
  664. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID3', $1)",
  665. [U3]),
  666. Res = Module:equery(C, "select c_varchar, c_uuid from test_table2 where c_uuid = any($1)",
  667. [[U1, U2]]),
  668. ?assertMatch(
  669. {ok,[#column{name = <<"c_varchar">>, type = varchar},
  670. #column{name = <<"c_uuid">>, type = uuid}],
  671. [{<<"UUID1">>, U1},
  672. {<<"UUID2">>, U2}]}, Res)
  673. end).
  674. date_time_type(Config) ->
  675. Module = ?config(module, Config),
  676. epgsql_ct:with_connection(Config, fun(C) ->
  677. case Module:get_parameter(C, "integer_datetimes") of
  678. {ok, <<"on">>} -> MaxTsDate = 294276;
  679. {ok, <<"off">>} -> MaxTsDate = 5874897
  680. end,
  681. check_type(Config, date, "'2008-01-02'", {2008,1,2}, [{-4712,1,1}, {5874897,1,1}]),
  682. check_type(Config, time, "'00:01:02'", {0,1,2.0}, [{0,0,0.0}, {24,0,0.0}]),
  683. check_type(Config, timetz, "'00:01:02-01'", {{0,1,2.0},1*60*60},
  684. [{{0,0,0.0},0}, {{24,0,0.0},-13*60*60}]),
  685. check_type(Config, timestamp, "'2008-01-02 03:04:05'", {{2008,1,2},{3,4,5.0}},
  686. [{{-4712,1,1},{0,0,0.0}}, {{MaxTsDate,12,31}, {23,59,59.0}}, {1322,334285,440966}]),
  687. check_type(Config, timestamptz, "'2011-01-02 03:04:05+3'", {{2011, 1, 2}, {0, 4, 5.0}}, [{1324,875970,286983}]),
  688. check_type(Config, interval, "'1 hour 2 minutes 3.1 seconds'", {{1,2,3.1},0,0},
  689. [{{0,0,0.0},0,-178000000 * 12}, {{0,0,0.0},0,178000000 * 12}])
  690. end).
  691. json_type(Config) ->
  692. check_type(Config, json, "'{}'", <<"{}">>,
  693. [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>]),
  694. check_type(Config, jsonb, "'{}'", <<"{}">>,
  695. [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>]).
  696. misc_type(Config) ->
  697. check_type(Config, bool, "true", true, [true, false]),
  698. check_type(Config, bytea, "E'\001\002'", <<1,2>>, [<<>>, <<0,128,255>>]).
  699. hstore_type(Config) ->
  700. Values = [
  701. {[]},
  702. {[{null, null}]},
  703. {[{null, undefined}]},
  704. {[{1, null}]},
  705. {[{1.0, null}]},
  706. {[{1, undefined}]},
  707. {[{1.0, undefined}]},
  708. {[{<<"a">>, <<"c">>}, {<<"c">>, <<"d">>}]},
  709. {[{<<"a">>, <<"c">>}, {<<"c">>, null}]},
  710. {[{<<"a">>, <<"c">>}, {<<"c">>, undefined}]}
  711. ],
  712. check_type(Config, hstore, "''", {[]}, []),
  713. check_type(Config, hstore,
  714. "'a => 1, b => 2.0, c => null'",
  715. {[{<<"a">>, <<"1">>}, {<<"b">>, <<"2.0">>}, {<<"c">>, null}]}, Values).
  716. net_type(Config) ->
  717. 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}]),
  718. check_type(Config, inet, "'127.0.0.1'", {127,0,0,1}, [{127,0,0,1}, {0,0,0,0,0,0,0,1}]),
  719. %% macaddr8 available only on PG>=10
  720. check_type(Config, macaddr,
  721. "'FF:FF:FF:FF:FF:FF'", {255, 255, 255, 255, 255, 255},
  722. [{255, 255, 255, 255, 255, 255},
  723. {6, 0, 0, 0, 0, 0}]).
  724. array_type(Config) ->
  725. Module = ?config(module, Config),
  726. epgsql_ct:with_connection(Config, fun(C) ->
  727. {ok, _, [{[1, 2]}]} = Module:equery(C, "select ($1::int[])[1:2]", [[1, 2, 3]]),
  728. {ok, _, [{[{1, <<"one">>}, {2, <<"two">>}]}]} =
  729. Module:equery(C, "select Array(select (id, value) from test_table1)", []),
  730. Select = fun(Type, A) ->
  731. Query = "select $1::" ++ atom_to_list(Type) ++ "[]",
  732. {ok, _Cols, [{A2}]} = Module:equery(C, Query, [A]),
  733. case lists:all(fun({V, V2}) -> compare(Type, V, V2) end, lists:zip(A, A2)) of
  734. true -> ok;
  735. false -> ?assertMatch(A, A2)
  736. end
  737. end,
  738. Select(int2, []),
  739. Select(int2, [1, 2, 3, 4]),
  740. Select(int2, [[1], [2], [3], [4]]),
  741. Select(int2, [[[[[[1, 2]]]]]]),
  742. Select(bool, [true]),
  743. Select(char, [$a, $b, $c]),
  744. Select(int4, [[1, 2]]),
  745. Select(int8, [[[[1, 2]], [[3, 4]]]]),
  746. Select(text, [<<"one">>, <<"two>">>]),
  747. Select(varchar, [<<"one">>, <<"two>">>]),
  748. Select(float4, [0.0, 1.0, 0.123]),
  749. Select(float8, [0.0, 1.0, 0.123]),
  750. Select(date, [{2008,1,2}, {2008,1,3}]),
  751. Select(time, [{0,1,2.0}, {0,1,3.0}]),
  752. Select(timetz, [{{0,1,2.0},1*60*60}, {{0,1,3.0},1*60*60}]),
  753. Select(timestamp, [{{2008,1,2},{3,4,5.0}}, {{2008,1,2},{3,4,6.0}}]),
  754. Select(timestamptz, [{{2008,1,2},{3,4,5.0}}, {{2008,1,2},{3,4,6.0}}]),
  755. Select(interval, [{{1,2,3.1},0,0}, {{1,2,3.2},0,0}]),
  756. Select(hstore, [{[{null, null}, {a, 1}, {1, 2}, {b, undefined}]}]),
  757. Select(hstore, [[{[{null, null}, {a, 1}, {1, 2}, {b, undefined}]}, {[]}], [{[{a, 1}]}, {[{null, 2}]}]]),
  758. Select(cidr, [{{127,0,0,1}, 32}, {{0,0,0,0,0,0,0,1}, 128}]),
  759. Select(inet, [{127,0,0,1}, {0,0,0,0,0,0,0,1}]),
  760. Select(json, [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>]),
  761. Select(jsonb, [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>])
  762. end).
  763. custom_types(Config) ->
  764. Module = ?config(module, Config),
  765. epgsql_ct:with_connection(Config, fun(C) ->
  766. Module:squery(C, "drop table if exists t_foo;"),
  767. Module:squery(C, "drop type if exists my_type;"),
  768. {ok, [], []} = Module:squery(C, "create type my_type as enum('foo', 'bar');"),
  769. {ok, [my_type]} = epgsql:update_type_cache(C, [{epgsql_codec_test_enum, [foo, bar]}]),
  770. {ok, [], []} = Module:squery(C, "create table t_foo (col my_type);"),
  771. {ok, S} = Module:parse(C, "insert_foo", "insert into t_foo values ($1)", [my_type]),
  772. ok = Module:bind(C, S, [bar]),
  773. {ok, 1} = Module:execute(C, S),
  774. ?assertMatch({ok, _, [{bar}]}, Module:equery(C, "SELECT col FROM t_foo"))
  775. end).
  776. text_format(Config) ->
  777. Module = ?config(module, Config),
  778. epgsql_ct:with_connection(Config, fun(C) ->
  779. Select = fun(Type, V) ->
  780. V2 = list_to_binary(V),
  781. Query = "select $1::" ++ Type,
  782. ?assertMatch({ok, _Cols, [{V2}]}, Module:equery(C, Query, [V])),
  783. ?assertMatch({ok, _Cols, [{V2}]}, Module:equery(C, Query, [V2]))
  784. end,
  785. Select("numeric", "123456")
  786. end).
  787. query_timeout(Config) ->
  788. Module = ?config(module, Config),
  789. epgsql_ct:with_connection(Config, fun(C) ->
  790. {ok, _, _} = Module:squery(C, "SET statement_timeout = 500"),
  791. ?assertMatch(?TIMEOUT_ERROR, Module:squery(C, "SELECT pg_sleep(1)")),
  792. ?assertMatch(?TIMEOUT_ERROR, Module:equery(C, "SELECT pg_sleep(2)")),
  793. {ok, _Cols, [{1}]} = Module:equery(C, "SELECT 1")
  794. end, []).
  795. execute_timeout(Config) ->
  796. Module = ?config(module, Config),
  797. epgsql_ct:with_connection(Config, fun(C) ->
  798. {ok, _, _} = Module:squery(C, "SET statement_timeout = 500"),
  799. {ok, S} = Module:parse(C, "select pg_sleep($1)"),
  800. ok = Module:bind(C, S, [2]),
  801. ?assertMatch(?TIMEOUT_ERROR, Module:execute(C, S, 0)),
  802. ok = Module:sync(C),
  803. ok = Module:bind(C, S, [0]),
  804. {ok, [{<<>>}]} = Module:execute(C, S, 0),
  805. ok = Module:close(C, S),
  806. ok = Module:sync(C)
  807. end, []).
  808. connection_closed(Config) ->
  809. {Host, Port} = epgsql_ct:connection_data(Config),
  810. Module = ?config(module, Config),
  811. P = self(),
  812. spawn_link(fun() ->
  813. process_flag(trap_exit, true),
  814. {ok, C} = Module:connect(Host, "epgsql_test",[
  815. {port, Port},
  816. {database, "epgsql_test_db1"}
  817. ]),
  818. P ! {connected, C},
  819. receive
  820. Any -> P ! Any
  821. end
  822. end),
  823. receive
  824. {connected, C} ->
  825. timer:sleep(100),
  826. Module:close(C),
  827. {'EXIT', C, _} = receive R -> R end
  828. end,
  829. epgsql_ct:flush().
  830. connection_closed_by_server(Config) ->
  831. Module = ?config(module, Config),
  832. epgsql_ct:with_connection(Config, fun(C1) ->
  833. P = self(),
  834. spawn_link(fun() ->
  835. process_flag(trap_exit, true),
  836. epgsql_ct:with_connection(Config, fun(C2) ->
  837. {ok, _, [{Pid}]} = Module:equery(C2, "select pg_backend_pid()"),
  838. % emulate of disconnection
  839. {ok, _, [{true}]} = Module:equery(C1,
  840. "select pg_terminate_backend($1)", [Pid]),
  841. receive
  842. {'EXIT', C2, {shutdown, #error{code = <<"57P01">>}}} ->
  843. P ! ok;
  844. Other ->
  845. ?debugFmt("Unexpected msg: ~p~n", [Other]),
  846. P ! error
  847. end
  848. end)
  849. end),
  850. receive ok -> ok end
  851. end).
  852. active_connection_closed(Config) ->
  853. {Host, Port} = epgsql_ct:connection_data(Config),
  854. Module = ?config(module, Config),
  855. P = self(),
  856. F = fun() ->
  857. process_flag(trap_exit, true),
  858. {ok, C} = Module:connect(Host, [
  859. {database, "epgsql_test_db1"},
  860. {port, Port}
  861. ]),
  862. P ! {connected, C},
  863. R = Module:squery(C, "select pg_sleep(10)"),
  864. P ! R
  865. end,
  866. spawn_link(F),
  867. receive
  868. {connected, C} ->
  869. timer:sleep(100),
  870. Module:close(C),
  871. {error, closed} = receive R -> R end
  872. end,
  873. epgsql_ct:flush().
  874. warning_notice(Config) ->
  875. Module = ?config(module, Config),
  876. epgsql_ct:with_connection(Config, fun(C) ->
  877. Q = "create function pg_temp.raise() returns void as $$
  878. begin
  879. raise warning 'oops';
  880. end;
  881. $$ language plpgsql;
  882. select pg_temp.raise()",
  883. [{ok, _, _}, _] = Module:squery(C, Q),
  884. receive
  885. {epgsql, C, {notice, #error{message = <<"oops">>, extra = Extra}}} ->
  886. ?assertMatch([{file, _},{line, _},{routine, _} | _], Extra),
  887. ok
  888. after
  889. 100 -> erlang:error(didnt_receive_notice)
  890. end
  891. end, [{async, self()}]).
  892. listen_notify(Config) ->
  893. Module = ?config(module, Config),
  894. epgsql_ct:with_connection(Config, fun(C) ->
  895. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  896. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  897. {ok, [], []} = Module:squery(C, "notify epgsql_test"),
  898. receive
  899. {epgsql, C, {notification, <<"epgsql_test">>, Pid, <<>>}} -> ok
  900. after
  901. 100 -> erlang:error(didnt_receive_notification)
  902. end
  903. end, [{async, self()}]).
  904. listen_notify_payload(Config) ->
  905. Module = ?config(module, Config),
  906. epgsql_ct:with_min_version(Config, [9, 0], fun(C) ->
  907. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  908. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  909. {ok, [], []} = Module:squery(C, "notify epgsql_test, 'test!'"),
  910. receive
  911. {epgsql, C, {notification, <<"epgsql_test">>, Pid, <<"test!">>}} -> ok
  912. after
  913. 100 -> erlang:error(didnt_receive_notification)
  914. end
  915. end, [{async, self()}]).
  916. set_notice_receiver(Config) ->
  917. Module = ?config(module, Config),
  918. epgsql_ct:with_min_version(Config, [9, 0], fun(C) ->
  919. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  920. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  921. EnsureNoNotification = fun(Payload) ->
  922. {ok, [], []} = Module:squery(C, ["notify epgsql_test, '", Payload, "'"]),
  923. receive
  924. {epgsql, _, _} -> erlang:error(got_unexpected_notification)
  925. after
  926. 10 -> ok
  927. end
  928. end,
  929. EnsureNotification = fun(Payload) ->
  930. {ok, [], []} = Module:squery(C, ["notify epgsql_test, '", Payload, "'"]),
  931. receive
  932. {epgsql, C, {notification, <<"epgsql_test">>, Pid, Payload}} -> ok
  933. after
  934. 100 -> erlang:error(didnt_receive_notification)
  935. end
  936. end,
  937. Self = self(),
  938. EnsureNoNotification(<<"test1">>),
  939. % Set pid()
  940. {ok, undefined} = Module:set_notice_receiver(C, Self),
  941. EnsureNotification(<<"test2">>),
  942. %% test PL/PgSQL NOTICE
  943. {ok, [], []} = Module:squery(C, ["DO $$ BEGIN RAISE WARNING 'test notice'; END $$;"]),
  944. receive
  945. {epgsql, C, {notice, #error{severity = warning,
  946. code = <<"01000">>,
  947. message = <<"test notice">>,
  948. extra = _}}} -> ok
  949. after
  950. 100 -> erlang:error(didnt_receive_notice)
  951. end,
  952. % set registered pid
  953. Receiver = pg_notification_receiver,
  954. register(Receiver, Self),
  955. {ok, Self} = Module:set_notice_receiver(C, Receiver),
  956. EnsureNotification(<<"test3">>),
  957. % make registered name invalid
  958. unregister(Receiver),
  959. EnsureNoNotification(<<"test4">>),
  960. % disable
  961. {ok, Receiver} = Module:set_notice_receiver(C, undefined),
  962. EnsureNoNotification(<<"test5">>)
  963. end, []).
  964. get_cmd_status(Config) ->
  965. Module = ?config(module, Config),
  966. epgsql_ct:with_connection(Config, fun(C) ->
  967. {ok, [], []} = Module:squery(C, "BEGIN"),
  968. ?assertEqual({ok, 'begin'}, Module:get_cmd_status(C)),
  969. {ok, [], []} = epgsql:equery(C, "CREATE TEMPORARY TABLE cmd_status_t(col INTEGER)"),
  970. ?assertEqual({ok, 'create'}, Module:get_cmd_status(C)),
  971. %% Some commands have number of affected rows in status
  972. {ok, N} = Module:squery(C, "INSERT INTO cmd_status_t (col) VALUES (1), (2)"),
  973. ?assertEqual({ok, {'insert', N}}, Module:get_cmd_status(C)),
  974. {ok, 1} = Module:squery(C, "UPDATE cmd_status_t SET col=3 WHERE col=1"),
  975. ?assertEqual({ok, {'update', 1}}, Module:get_cmd_status(C)),
  976. %% Failed queries have no status
  977. {error, _} = Module:squery(C, "DELETE FROM cmd_status_t WHERE not_col=2"),
  978. ?assertEqual({ok, undefined}, Module:get_cmd_status(C)),
  979. %% if COMMIT failed, status will be 'rollback'
  980. {ok, [], []} = Module:squery(C, "COMMIT"),
  981. ?assertEqual({ok, 'rollback'}, Module:get_cmd_status(C)),
  982. %% Only last command's status returned
  983. [_, _, _] = Module:squery(C, "BEGIN; SELECT 1; COMMIT"),
  984. ?assertEqual({ok, 'commit'}, Module:get_cmd_status(C))
  985. end).
  986. range_type(Config) ->
  987. epgsql_ct:with_min_version(Config, [9, 2], fun(_C) ->
  988. check_type(Config, int4range, "int4range(10, 20)", {10, 20}, [
  989. {1, 58}, {-1, 12}, {-985521, 5412687}, {minus_infinity, 0},
  990. {984655, plus_infinity}, {minus_infinity, plus_infinity}
  991. ])
  992. end, []).
  993. range8_type(Config) ->
  994. epgsql_ct:with_min_version(Config, [9, 2], fun(_C) ->
  995. check_type(Config, int8range, "int8range(10, 20)", {10, 20}, [
  996. {1, 58}, {-1, 12}, {-9223372036854775808, 5412687},
  997. {minus_infinity, 9223372036854775807},
  998. {984655, plus_infinity}, {minus_infinity, plus_infinity}
  999. ])
  1000. end, []).
  1001. with_transaction(Config) ->
  1002. Module = ?config(module, Config),
  1003. epgsql_ct:with_connection(
  1004. Config,
  1005. fun(C) ->
  1006. %% Success case
  1007. ?assertEqual(
  1008. success, Module:with_transaction(C, fun(_) -> success end)),
  1009. ?assertEqual(
  1010. success, Module:with_transaction(C, fun(_) -> success end,
  1011. [{ensure_committed, true}])),
  1012. %% begin_opts
  1013. ?assertMatch(
  1014. [{ok, _, [{<<"serializable">>}]},
  1015. {ok, _, [{<<"on">>}]}],
  1016. Module:with_transaction(
  1017. C, fun(C1) ->
  1018. Module:squery(C1, ("SHOW transaction_isolation; "
  1019. "SHOW transaction_read_only"))
  1020. end,
  1021. [{begin_opts, "READ ONLY ISOLATION LEVEL SERIALIZABLE"}])),
  1022. %% ensure_committed failure
  1023. ?assertError(
  1024. {ensure_committed_failed, rollback},
  1025. Module:with_transaction(
  1026. C, fun(C1) ->
  1027. {error, _} = Module:squery(C1, "SELECT col FROM _nowhere_"),
  1028. ok
  1029. end,
  1030. [{ensure_committed, true}])),
  1031. %% reraise
  1032. ?assertEqual(
  1033. {rollback, my_err},
  1034. Module:with_transaction(
  1035. C, fun(_) -> error(my_err) end,
  1036. [{reraise, false}])),
  1037. ?assertError(
  1038. my_err,
  1039. Module:with_transaction(
  1040. C, fun(_) -> error(my_err) end, []))
  1041. end, []).
  1042. %% =============================================================================
  1043. %% Internal functions
  1044. %% ============================================================================
  1045. check_type(Config, Type, In, Out, Values) ->
  1046. Column = "c_" ++ atom_to_list(Type),
  1047. check_type(Config, Type, In, Out, Values, Column).
  1048. check_type(Config, Type, In, Out, Values, Column) ->
  1049. Module = ?config(module, Config),
  1050. epgsql_ct:with_connection(Config, fun(C) ->
  1051. Select = io_lib:format("select ~s::~w", [In, Type]),
  1052. Res = Module:equery(C, Select),
  1053. ?assertMatch({ok, [#column{type = Type}], [{Out}]}, Res),
  1054. Sql = io_lib:format("insert into test_table2 (~s) values ($1) returning ~s", [Column, Column]),
  1055. {ok, #statement{columns = [#column{type = Type}]} = S} = Module:parse(C, Sql),
  1056. Insert = fun(V) ->
  1057. ok = Module:bind(C, S, [V]),
  1058. {ok, 1, [{V2}]} = Module:execute(C, S),
  1059. case compare(Type, V, V2) of
  1060. true -> ok;
  1061. false ->
  1062. error({write_read_compare_failed,
  1063. iolist_to_binary(
  1064. io_lib:format("~p =/= ~p~n", [V, V2]))})
  1065. end,
  1066. ok = Module:sync(C)
  1067. end,
  1068. lists:foreach(Insert, [null, undefined | Values])
  1069. end).
  1070. compare(_Type, null, null) -> true;
  1071. compare(_Type, undefined, null) -> true;
  1072. compare(float4, V1, V2) when is_float(V1) -> abs(V2 - V1) < 0.000001;
  1073. compare(float8, V1, V2) when is_float(V1) -> abs(V2 - V1) < 0.000000000000001;
  1074. compare(hstore, {V1}, V2) -> compare(hstore, V1, V2);
  1075. compare(hstore, V1, {V2}) -> compare(hstore, V1, V2);
  1076. compare(hstore, V1, V2) ->
  1077. orddict:from_list(format_hstore(V1)) =:= orddict:from_list(format_hstore(V2));
  1078. compare(Type, V1 = {_, _, MS}, {D2, {H2, M2, S2}}) when Type == timestamp;
  1079. Type == timestamptz ->
  1080. {D1, {H1, M1, S1}} = calendar:now_to_universal_time(V1),
  1081. ({D1, H1, M1} =:= {D2, H2, M2}) and (abs(S1 + MS/1000000 - S2) < 0.000000000000001);
  1082. compare(_Type, V1, V2) -> V1 =:= V2.
  1083. format_hstore({Hstore}) -> Hstore;
  1084. format_hstore(Hstore) ->
  1085. [{format_hstore_key(Key), format_hstore_value(Value)} || {Key, Value} <- Hstore].
  1086. format_hstore_key(Key) -> format_hstore_string(Key).
  1087. format_hstore_value(null) -> null;
  1088. format_hstore_value(undefined) -> null;
  1089. format_hstore_value(Value) -> format_hstore_string(Value).
  1090. format_hstore_string(Num) when is_number(Num) -> iolist_to_binary(io_lib:format("~w", [Num]));
  1091. format_hstore_string(Str) -> iolist_to_binary(io_lib:format("~s", [Str])).