epgsql_SUITE.erl 45 KB

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