epgsql_SUITE.erl 44 KB

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