epgsql_SUITE.erl 47 KB

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