epgsql_SUITE.erl 48 KB

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