epgsql_SUITE.erl 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  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_with_ssl,
  38. connect_with_client_cert,
  39. connect_to_closed_port,
  40. connect_map
  41. ]},
  42. {types, [parallel], [
  43. numeric_type,
  44. character_type,
  45. uuid_type,
  46. point_type,
  47. geometry_type,
  48. uuid_select,
  49. date_time_type,
  50. json_type,
  51. misc_type,
  52. hstore_type,
  53. net_type,
  54. array_type,
  55. range_type,
  56. range8_type,
  57. custom_types
  58. ]},
  59. {generic, [parallel], [
  60. with_transaction
  61. ]}
  62. ],
  63. Tests = [
  64. {group, connect},
  65. {group, types},
  66. prepared_query,
  67. select,
  68. insert,
  69. update,
  70. delete,
  71. create_and_drop_table,
  72. cursor,
  73. multiple_result,
  74. execute_batch,
  75. batch_error,
  76. single_batch,
  77. extended_select,
  78. extended_sync_ok,
  79. extended_sync_error,
  80. returning_from_insert,
  81. returning_from_update,
  82. returning_from_delete,
  83. parse,
  84. parse_column_format,
  85. parse_error,
  86. parse_and_close,
  87. bind,
  88. bind_parameter_format,
  89. bind_error,
  90. bind_and_close,
  91. execute_error,
  92. describe,
  93. describe_with_param,
  94. describe_named,
  95. describe_error,
  96. portal,
  97. returning,
  98. multiple_statement,
  99. multiple_portal,
  100. execute_function,
  101. parameter_get,
  102. parameter_set,
  103. text_format,
  104. query_timeout,
  105. execute_timeout,
  106. connection_closed,
  107. connection_closed_by_server,
  108. active_connection_closed,
  109. warning_notice,
  110. listen_notify,
  111. listen_notify_payload,
  112. set_notice_receiver,
  113. get_cmd_status
  114. ],
  115. Groups ++ [case Module of
  116. epgsql ->
  117. {Module, [], [{group, generic} | Tests]};
  118. _ ->
  119. {Module, [], Tests}
  120. end || Module <- modules()].
  121. end_per_suite(_Config) ->
  122. ok.
  123. init_per_group(GroupName, Config) ->
  124. case lists:member(GroupName, modules()) of
  125. true -> [{module, GroupName}|Config];
  126. false -> Config
  127. end.
  128. end_per_group(_GroupName, _Config) ->
  129. ok.
  130. -define(UUID1,
  131. <<163,189,240,40,149,151,17,227,141,6,112,24,139,130,16,73>>).
  132. -define(UUID2,
  133. <<183,55,22,52,149,151,17,227,187,167,112,24,139,130,16,73>>).
  134. -define(UUID3,
  135. <<198,188,155,66,149,151,17,227,138,98,112,24,139,130,16,73>>).
  136. -define(TIMEOUT_ERROR, {error, #error{
  137. severity = error,
  138. code = <<"57014">>,
  139. codename = query_canceled,
  140. message = <<"canceling statement due to statement timeout">>,
  141. extra = [{file, <<"postgres.c">>},
  142. {line, _},
  143. {routine, _} | _]
  144. }}).
  145. %% From uuid.erl in http://gitorious.org/avtobiff/erlang-uuid
  146. uuid_to_bin_string(<<U0:32, U1:16, U2:16, U3:16, U4:48>>) ->
  147. iolist_to_binary(io_lib:format(
  148. "~8.16.0b-~4.16.0b-~4.16.0b-~4.16.0b-~12.16.0b",
  149. [U0, U1, U2, U3, U4])).
  150. connect(Config) ->
  151. epgsql_ct:connect_only(Config, []).
  152. connect_to_db(Connect) ->
  153. epgsql_ct:connect_only(Connect, [{database, "epgsql_test_db1"}]).
  154. connect_as(Config) ->
  155. epgsql_ct:connect_only(Config, ["epgsql_test", [{database, "epgsql_test_db1"}]]).
  156. connect_with_cleartext(Config) ->
  157. epgsql_ct:connect_only(Config, [
  158. "epgsql_test_cleartext",
  159. "epgsql_test_cleartext",
  160. [{database, "epgsql_test_db1"}]
  161. ]).
  162. connect_with_md5(Config) ->
  163. epgsql_ct:connect_only(Config, [
  164. "epgsql_test_md5",
  165. "epgsql_test_md5",
  166. [{database, "epgsql_test_db1"}]
  167. ]).
  168. connect_with_scram(Config) ->
  169. PgConf = ?config(pg_config, Config),
  170. Ver = ?config(version, PgConf),
  171. (Ver >= [10, 0])
  172. andalso
  173. epgsql_ct:connect_only(
  174. Config,
  175. [
  176. "epgsql_test_scram",
  177. "epgsql_test_scram",
  178. [{database, "epgsql_test_db1"}]
  179. ]).
  180. connect_with_invalid_user(Config) ->
  181. {Host, Port} = epgsql_ct:connection_data(Config),
  182. Module = ?config(module, Config),
  183. {error, Why} = Module:connect(
  184. Host,
  185. "epgsql_test_invalid",
  186. "epgsql_test_invalid",
  187. [{port, Port}, {database, "epgsql_test_db1"}]),
  188. case Why of
  189. invalid_authorization_specification -> ok; % =< 8.4
  190. invalid_password -> ok % >= 9.0
  191. end.
  192. connect_with_invalid_password(Config) ->
  193. {Host, Port} = epgsql_ct:connection_data(Config),
  194. Module = ?config(module, Config),
  195. {error, Why} = Module:connect(
  196. Host,
  197. "epgsql_test_md5",
  198. "epgsql_test_invalid",
  199. [{port, Port}, {database, "epgsql_test_db1"}]),
  200. case Why of
  201. invalid_authorization_specification -> ok; % =< 8.4
  202. invalid_password -> ok % >= 9.0
  203. end.
  204. connect_with_ssl(Config) ->
  205. Module = ?config(module, Config),
  206. epgsql_ct:with_connection(Config,
  207. fun(C) ->
  208. {ok, _Cols, [{true}]} = Module:equery(C, "select ssl_is_used()")
  209. end,
  210. "epgsql_test",
  211. [{ssl, true}]).
  212. connect_with_client_cert(Config) ->
  213. Module = ?config(module, Config),
  214. Dir = filename:join(code:lib_dir(epgsql), ?TEST_DATA_DIR),
  215. File = fun(Name) -> filename:join(Dir, Name) end,
  216. {ok, Pem} = file:read_file(File("epgsql.crt")),
  217. [{'Certificate', Der, not_encrypted}] = public_key:pem_decode(Pem),
  218. Cert = public_key:pkix_decode_cert(Der, plain),
  219. #'TBSCertificate'{serialNumber = Serial} = Cert#'Certificate'.tbsCertificate,
  220. Serial2 = list_to_binary(integer_to_list(Serial)),
  221. epgsql_ct:with_connection(Config,
  222. fun(C) ->
  223. {ok, _, [{true}]} = Module:equery(C, "select ssl_is_used()"),
  224. {ok, _, [{Serial2}]} = Module:equery(C, "select ssl_client_serial()")
  225. end,
  226. "epgsql_test_cert",
  227. [{ssl, true}, {ssl_opts, [{keyfile, File("epgsql.key")},
  228. {certfile, File("epgsql.crt")}]}]).
  229. connect_map(Config) ->
  230. {Host, Port} = epgsql_ct:connection_data(Config),
  231. Module = ?config(module, Config),
  232. Opts = #{
  233. host => Host,
  234. port => Port,
  235. database => "epgsql_test_db1",
  236. username => "epgsql_test_md5",
  237. password => "epgsql_test_md5"
  238. },
  239. {ok, C} = Module:connect(Opts),
  240. Module:close(C),
  241. epgsql_ct:flush(),
  242. ok.
  243. connect_to_closed_port(Config) ->
  244. {Host, Port} = epgsql_ct:connection_data(Config),
  245. Module = ?config(module, Config),
  246. Trap = process_flag(trap_exit, true),
  247. ?assertEqual({error, econnrefused},
  248. Module:connect(
  249. Host,
  250. "epgsql_test",
  251. "epgsql_test",
  252. [{port, Port + 1}, {database, "epgsql_test_db1"}])),
  253. ?assertMatch({'EXIT', _, econnrefused}, receive Stop -> Stop end),
  254. process_flag(trap_exit, Trap).
  255. prepared_query(Config) ->
  256. Module = ?config(module, Config),
  257. epgsql_ct:with_connection(Config, fun(C) ->
  258. {ok, _} = Module:parse(C, "inc", "select $1+1", []),
  259. {ok, Cols, [{5}]} = Module:prepared_query(C, "inc", [4]),
  260. {ok, Cols, [{2}]} = Module:prepared_query(C, "inc", [1]),
  261. {ok, Cols, [{23}]} = Module:prepared_query(C, "inc", [22]),
  262. {error, _} = Module:prepared_query(C, "non_existent_query", [4])
  263. end).
  264. select(Config) ->
  265. Module = ?config(module, Config),
  266. epgsql_ct:with_connection(Config, fun(C) ->
  267. {ok, Cols, Rows} = Module:squery(C, "select * from test_table1"),
  268. [
  269. #column{name = <<"id">>, type = int4, size = 4},
  270. #column{name = <<"value">>, type = text, size = -1}
  271. ] = Cols,
  272. [{<<"1">>, <<"one">>}, {<<"2">>, <<"two">>}] = Rows
  273. end).
  274. insert(Config) ->
  275. Module = ?config(module, Config),
  276. epgsql_ct:with_rollback(Config, fun(C) ->
  277. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (3, 'three')")
  278. end).
  279. update(Config) ->
  280. Module = ?config(module, Config),
  281. epgsql_ct:with_rollback(Config, fun(C) ->
  282. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (3, 'three')"),
  283. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (4, 'four')"),
  284. {ok, 2} = Module:squery(C, "update test_table1 set value = 'foo' where id > 2"),
  285. {ok, _, [{<<"2">>}]} = Module:squery(C, "select count(*) from test_table1 where value = 'foo'")
  286. end).
  287. delete(Config) ->
  288. Module = ?config(module, Config),
  289. epgsql_ct:with_rollback(Config, fun(C) ->
  290. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (3, 'three')"),
  291. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (4, 'four')"),
  292. {ok, 2} = Module:squery(C, "delete from test_table1 where id > 2"),
  293. {ok, _, [{<<"2">>}]} = Module:squery(C, "select count(*) from test_table1")
  294. end).
  295. create_and_drop_table(Config) ->
  296. Module = ?config(module, Config),
  297. epgsql_ct:with_rollback(Config, fun(C) ->
  298. {ok, [], []} = Module:squery(C, "create table test_table3 (id int4)"),
  299. {ok, [#column{type = int4}], []} = Module:squery(C, "select * from test_table3"),
  300. {ok, [], []} = Module:squery(C, "drop table test_table3")
  301. end).
  302. cursor(Config) ->
  303. Module = ?config(module, Config),
  304. epgsql_ct:with_connection(Config, fun(C) ->
  305. {ok, [], []} = Module:squery(C, "begin"),
  306. {ok, [], []} = Module:squery(C, "declare c cursor for select id from test_table1"),
  307. {ok, 2} = Module:squery(C, "move forward 2 from c"),
  308. {ok, 1} = Module:squery(C, "move backward 1 from c"),
  309. {ok, 1, _Cols, [{<<"2">>}]} = Module:squery(C, "fetch next from c"),
  310. {ok, [], []} = Module:squery(C, "close c")
  311. end).
  312. multiple_result(Config) ->
  313. Module = ?config(module, Config),
  314. epgsql_ct:with_connection(Config, fun(C) ->
  315. [{ok, _, [{<<"1">>}]}, {ok, _, [{<<"2">>}]}] = Module:squery(C, "select 1; select 2"),
  316. [{ok, _, [{<<"1">>}]}, {error, #error{}}] = Module:squery(C, "select 1; select foo;")
  317. end).
  318. execute_batch(Config) ->
  319. Module = ?config(module, Config),
  320. epgsql_ct:with_connection(Config, fun(C) ->
  321. {ok, S1} = Module:parse(C, "one", "select $1", [int4]),
  322. {ok, S2} = Module:parse(C, "two", "select $1 + $2", [int4, int4]),
  323. [{ok, [{1}]}, {ok, [{3}]}] =
  324. Module:execute_batch(C, [{S1, [1]}, {S2, [1, 2]}])
  325. end).
  326. batch_error(Config) ->
  327. Module = ?config(module, Config),
  328. epgsql_ct:with_rollback(Config, fun(C) ->
  329. {ok, S} = Module:parse(C, "insert into test_table1(id, value) values($1, $2)"),
  330. [{ok, 1}, {error, _}] =
  331. Module:execute_batch(
  332. C,
  333. [{S, [3, "batch_error 3"]},
  334. {S, [2, "batch_error 2"]}, % duplicate key error
  335. {S, [5, "batch_error 5"]} % won't be executed
  336. ])
  337. end).
  338. single_batch(Config) ->
  339. Module = ?config(module, Config),
  340. epgsql_ct:with_connection(Config, fun(C) ->
  341. {ok, S1} = Module:parse(C, "one", "select $1", [int4]),
  342. [{ok, [{1}]}] = Module:execute_batch(C, [{S1, [1]}])
  343. end).
  344. extended_select(Config) ->
  345. Module = ?config(module, Config),
  346. epgsql_ct:with_connection(Config, fun(C) ->
  347. {ok, Cols, Rows} = Module:equery(C, "select * from test_table1", []),
  348. [#column{name = <<"id">>, type = int4, size = 4},
  349. #column{name = <<"value">>, type = text, size = -1}] = Cols,
  350. [{1, <<"one">>}, {2, <<"two">>}] = Rows
  351. end).
  352. extended_sync_ok(Config) ->
  353. Module = ?config(module, Config),
  354. epgsql_ct:with_connection(Config, fun(C) ->
  355. {ok, _Cols, [{<<"one">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [1]),
  356. {ok, _Cols, [{<<"two">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [2])
  357. end).
  358. extended_sync_error(Config) ->
  359. Module = ?config(module, Config),
  360. epgsql_ct:with_connection(Config, fun(C) ->
  361. {error, #error{}} = Module:equery(C, "select _alue from test_table1 where id = $1", [1]),
  362. {ok, _Cols, [{<<"one">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [1])
  363. end).
  364. returning_from_insert(Config) ->
  365. Module = ?config(module, Config),
  366. epgsql_ct:with_rollback(Config, fun(C) ->
  367. {ok, 1, _Cols, [{3}]} = Module:equery(C, "insert into test_table1 (id) values (3) returning id")
  368. end).
  369. returning_from_update(Config) ->
  370. Module = ?config(module, Config),
  371. epgsql_ct:with_rollback(Config, fun(C) ->
  372. {ok, 2, _Cols, [{1}, {2}]} = Module:equery(C, "update test_table1 set value = 'hi' returning id"),
  373. ?assertMatch({ok, 0, [#column{}], []},
  374. Module:equery(C, "update test_table1 set value = 'hi' where false returning id")),
  375. ?assertMatch([{ok, 2, [#column{}], [{<<"1">>}, {<<"2">>}]},
  376. {ok, 0, [#column{}], []}],
  377. Module:squery(C,
  378. "update test_table1 set value = 'hi2' returning id; "
  379. "update test_table1 set value = 'hi' where false returning id"))
  380. end).
  381. returning_from_delete(Config) ->
  382. Module = ?config(module, Config),
  383. epgsql_ct:with_rollback(Config, fun(C) ->
  384. {ok, 2, _Cols, [{1}, {2}]} = Module:equery(C, "delete from test_table1 returning id"),
  385. ?assertMatch({ok, 0, [#column{}], []},
  386. Module:equery(C, "delete from test_table1 returning id"))
  387. end).
  388. parse(Config) ->
  389. Module = ?config(module, Config),
  390. epgsql_ct:with_connection(Config, fun(C) ->
  391. {ok, S} = Module:parse(C, "select * from test_table1"),
  392. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  393. ok = Module:close(C, S),
  394. ok = Module:sync(C)
  395. end).
  396. parse_column_format(Config) ->
  397. Module = ?config(module, Config),
  398. epgsql_ct:with_connection(Config, fun(C) ->
  399. {ok, S} = Module:parse(C, "select 1::int4, false::bool, 2.0::float4"),
  400. [#column{type = int4},
  401. #column{type = bool},
  402. #column{type = float4}] = S#statement.columns,
  403. ok = Module:bind(C, S, []),
  404. {ok, [{1, false, 2.0}]} = Module:execute(C, S, 0),
  405. ok = Module:close(C, S),
  406. ok = Module:sync(C)
  407. end).
  408. parse_error(Config) ->
  409. Module = ?config(module, Config),
  410. epgsql_ct:with_connection(Config, fun(C) ->
  411. {error, #error{
  412. extra = [{file, _}, {line, _}, {position, <<"8">>}, {routine, _} | _]
  413. }} = Module:parse(C, "select _ from test_table1"),
  414. {ok, S} = Module:parse(C, "select * from test_table1"),
  415. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  416. ok = Module:close(C, S),
  417. ok = Module:sync(C)
  418. end).
  419. parse_and_close(Config) ->
  420. Module = ?config(module, Config),
  421. epgsql_ct:with_connection(Config, fun(C) ->
  422. Parse = fun() -> Module:parse(C, "test", "select * from test_table1", []) end,
  423. {ok, S} = Parse(),
  424. {error, #error{code = <<"42P05">>, codename = duplicate_prepared_statement}} = Parse(),
  425. Module:close(C, S),
  426. {ok, S} = Parse(),
  427. ok = Module:sync(C)
  428. end).
  429. bind(Config) ->
  430. Module = ?config(module, Config),
  431. epgsql_ct:with_connection(Config, fun(C) ->
  432. {ok, S} = Module:parse(C, "select value from test_table1 where id = $1"),
  433. ok = Module:bind(C, S, [1]),
  434. ok = Module:close(C, S),
  435. ok = Module:sync(C)
  436. end).
  437. bind_parameter_format(Config) ->
  438. Module = ?config(module, Config),
  439. epgsql_ct:with_connection(Config, fun(C) ->
  440. {ok, S} = Module:parse(C, "select $1, $2, $3", [int2, text, bool]),
  441. [int2, text, bool] = S#statement.types,
  442. ok = Module:bind(C, S, [1, "hi", true]),
  443. {ok, [{1, <<"hi">>, true}]} = Module:execute(C, S, 0),
  444. ok = Module:close(C, S),
  445. ok = Module:sync(C)
  446. end).
  447. bind_error(Config) ->
  448. Module = ?config(module, Config),
  449. epgsql_ct:with_connection(Config, fun(C) ->
  450. {ok, S} = Module:parse(C, "select $1::char"),
  451. {error, #error{}} = Module:bind(C, S, [0]),
  452. ok = Module:bind(C, S, [$A]),
  453. ok = Module:close(C, S),
  454. ok = Module:sync(C)
  455. end).
  456. bind_and_close(Config) ->
  457. Module = ?config(module, Config),
  458. epgsql_ct:with_connection(Config, fun(C) ->
  459. {ok, S} = Module:parse(C, "select * from test_table1"),
  460. ok = Module:bind(C, S, "one", []),
  461. {error, #error{code = <<"42P03">>, codename = duplicate_cursor}} = Module:bind(C, S, "one", []),
  462. ok = Module:close(C, portal, "one"),
  463. ok = Module:bind(C, S, "one", []),
  464. ok = Module:sync(C)
  465. end).
  466. execute_error(Config) ->
  467. Module = ?config(module, Config),
  468. epgsql_ct:with_connection(Config, fun(C) ->
  469. {ok, S} = Module:parse(C, "insert into test_table1 (id, value) values ($1, $2)"),
  470. ok = Module:bind(C, S, [1, <<"foo">>]),
  471. {error, #error{
  472. code = <<"23505">>, codename = unique_violation,
  473. extra = [
  474. {constraint_name, <<"test_table1_pkey">>},
  475. {detail, _},
  476. {file, _},
  477. {line, _},
  478. {routine, _},
  479. {schema_name, <<"public">>} | _%,
  480. %{table_name, <<"test_table1">>}
  481. ]
  482. }} = Module:execute(C, S, 0),
  483. {error, sync_required} = Module:bind(C, S, [3, <<"quux">>]),
  484. ok = Module:sync(C),
  485. ok = Module:bind(C, S, [3, <<"quux">>]),
  486. {ok, _} = Module:execute(C, S, 0),
  487. {ok, 1} = Module:squery(C, "delete from test_table1 where id = 3")
  488. end).
  489. describe(Config) ->
  490. Module = ?config(module, Config),
  491. epgsql_ct:with_connection(Config, fun(C) ->
  492. {ok, S} = Module:parse(C, "select * from test_table1"),
  493. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  494. {ok, S} = Module:describe(C, S),
  495. ok = Module:close(C, S),
  496. ok = Module:sync(C)
  497. end).
  498. describe_with_param(Config) ->
  499. Module = ?config(module, Config),
  500. epgsql_ct:with_connection(Config, fun(C) ->
  501. {ok, S} = Module:parse(C, "select id from test_table1 where id = $1"),
  502. ?assertEqual([int4], S#statement.types),
  503. ?assertMatch([#column{name = <<"id">>}], S#statement.columns),
  504. {ok, S} = Module:describe(C, S),
  505. ok = Module:close(C, S),
  506. ok = Module:sync(C)
  507. end).
  508. describe_named(Config) ->
  509. Module = ?config(module, Config),
  510. epgsql_ct:with_connection(Config, fun(C) ->
  511. {ok, S} = Module:parse(C, "name", "select * from test_table1", []),
  512. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  513. {ok, S} = Module:describe(C, S),
  514. ok = Module:close(C, S),
  515. ok = Module:sync(C)
  516. end).
  517. describe_error(Config) ->
  518. Module = ?config(module, Config),
  519. epgsql_ct:with_connection(Config, fun(C) ->
  520. {error, #error{}} = Module:describe(C, statement, ""),
  521. {ok, S} = Module:parse(C, "select * from test_table1"),
  522. {ok, S} = Module:describe(C, statement, ""),
  523. ok = Module:sync(C)
  524. end).
  525. portal(Config) ->
  526. Module = ?config(module, Config),
  527. epgsql_ct:with_connection(Config, fun(C) ->
  528. {ok, S} = Module:parse(C, "select value from test_table1"),
  529. ok = Module:bind(C, S, []),
  530. {partial, [{<<"one">>}]} = Module:execute(C, S, 1),
  531. {partial, [{<<"two">>}]} = Module:execute(C, S, 1),
  532. {ok, []} = Module:execute(C, S,1),
  533. ok = Module:close(C, S),
  534. ok = Module:sync(C)
  535. end).
  536. returning(Config) ->
  537. Module = ?config(module, Config),
  538. epgsql_ct:with_rollback(Config, fun(C) ->
  539. {ok, S} = Module:parse(C, "update test_table1 set value = $1 returning id"),
  540. ok = Module:bind(C, S, ["foo"]),
  541. {ok, 2, [{1}, {2}]} = Module:execute(C, S),
  542. ok = Module:sync(C)
  543. end).
  544. multiple_statement(Config) ->
  545. Module = ?config(module, Config),
  546. epgsql_ct:with_connection(Config, fun(C) ->
  547. {ok, S1} = Module:parse(C, "one", "select value from test_table1 where id = 1", []),
  548. ok = Module:bind(C, S1, []),
  549. {partial, [{<<"one">>}]} = Module:execute(C, S1, 1),
  550. {ok, S2} = Module:parse(C, "two", "select value from test_table1 where id = 2", []),
  551. ok = Module:bind(C, S2, []),
  552. {partial, [{<<"two">>}]} = Module:execute(C, S2, 1),
  553. {ok, []} = Module:execute(C, S1, 1),
  554. {ok, []} = Module:execute(C, S2, 1),
  555. ok = Module:close(C, S1),
  556. ok = Module:close(C, S2),
  557. ok = Module:sync(C)
  558. end).
  559. multiple_portal(Config) ->
  560. Module = ?config(module, Config),
  561. epgsql_ct:with_connection(Config, fun(C) ->
  562. {ok, S} = Module:parse(C, "select value from test_table1 where id = $1"),
  563. ok = Module:bind(C, S, "one", [1]),
  564. ok = Module:bind(C, S, "two", [2]),
  565. {ok, [{<<"one">>}]} = Module:execute(C, S, "one", 0),
  566. {ok, [{<<"two">>}]} = Module:execute(C, S, "two", 0),
  567. ok = Module:close(C, S),
  568. ok = Module:sync(C)
  569. end).
  570. execute_function(Config) ->
  571. Module = ?config(module, Config),
  572. epgsql_ct:with_rollback(Config, fun(C) ->
  573. {ok, _Cols1, [{3}]} = Module:equery(C, "select insert_test1(3, 'three')"),
  574. {ok, _Cols2, [{<<>>}]} = Module:equery(C, "select do_nothing()")
  575. end).
  576. parameter_get(Config) ->
  577. Module = ?config(module, Config),
  578. epgsql_ct:with_connection(Config, fun(C) ->
  579. {ok, <<"off">>} = Module:get_parameter(C, "is_superuser")
  580. end).
  581. parameter_set(Config) ->
  582. Module = ?config(module, Config),
  583. epgsql_ct:with_connection(Config, fun(C) ->
  584. {ok, [], []} = Module:squery(C, "set DateStyle = 'ISO, MDY'"),
  585. {ok, <<"ISO, MDY">>} = Module:get_parameter(C, "DateStyle"),
  586. {ok, _Cols, [{<<"2000-01-02">>}]} = Module:squery(C, "select '2000-01-02'::date"),
  587. {ok, [], []} = Module:squery(C, "set DateStyle = 'German'"),
  588. {ok, <<"German, DMY">>} = Module:get_parameter(C, "DateStyle"),
  589. {ok, _Cols, [{<<"02.01.2000">>}]} = Module:squery(C, "select '2000-01-02'::date")
  590. end).
  591. numeric_type(Config) ->
  592. check_type(Config, int2, "1", 1, [0, 256, -32768, +32767]),
  593. check_type(Config, int4, "1", 1, [0, 512, -2147483648, +2147483647]),
  594. check_type(Config, int8, "1", 1, [0, 1024, -9223372036854775808, +9223372036854775807]),
  595. check_type(Config, float4, "1.0", 1.0, [0.0, 1.23456, -1.23456]),
  596. check_type(Config, float4, "'-Infinity'", minus_infinity, [minus_infinity, plus_infinity, nan]),
  597. check_type(Config, float8, "1.0", 1.0, [0.0, 1.23456789012345, -1.23456789012345]),
  598. check_type(Config, float8, "'nan'", nan, [minus_infinity, plus_infinity, nan]).
  599. character_type(Config) ->
  600. Alpha = unicode:characters_to_binary([16#03B1]),
  601. Ka = unicode:characters_to_binary([16#304B]),
  602. One = unicode:characters_to_binary([16#10D360]),
  603. check_type(Config, bpchar, "'A'", $A, [1, $1, 16#7F, Alpha, Ka, One], "c_char"),
  604. check_type(Config, text, "'hi'", <<"hi">>, [<<"">>, <<"hi">>]),
  605. check_type(Config, varchar, "'hi'", <<"hi">>, [<<"">>, <<"hi">>]),
  606. epgsql_ct:with_connection(
  607. Config,
  608. fun(C) ->
  609. Module = ?config(module, Config),
  610. %% IOlists
  611. ?assertMatch({ok, _, [{<<1087/utf8, 1088/utf8, 1080/utf8,
  612. 1074/utf8, 1077/utf8, 1090/utf8>>}]},
  613. Module:equery(C, "SELECT $1::text", [[1087,1088,1080,1074,1077,1090]])),
  614. %% Deprecated casts
  615. ?assertMatch({ok, _, [{<<"my_atom">>}]},
  616. Module:equery(C, "SELECT $1::varchar", [my_atom])),
  617. ?assertMatch({ok, _, [{<<"12345">>}]},
  618. Module:equery(C, "SELECT $1::varchar", [12345])),
  619. FloatBin = erlang:float_to_binary(1.2345),
  620. ?assertMatch({ok, _, [{FloatBin}]},
  621. Module:equery(C, "SELECT $1::varchar", [1.2345])),
  622. %% String bpchar
  623. ?assertMatch({ok, _, [{<<"hello world">>}]},
  624. Module:equery(C, "SELECT $1::bpchar", ["hello world"]))
  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. ?assertMatch(?TIMEOUT_ERROR, Module:squery(C, "SELECT pg_sleep(1)")),
  786. ?assertMatch(?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. ?assertMatch(?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])).