epgsql_SUITE.erl 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  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. epgsql_ct:with_connection(
  603. Config,
  604. fun(C) ->
  605. Module = ?config(module, Config),
  606. %% IOlists
  607. ?assertMatch({ok, _, [{<<1087/utf8, 1088/utf8, 1080/utf8,
  608. 1074/utf8, 1077/utf8, 1090/utf8>>}]},
  609. Module:equery(C, "SELECT $1::text", [[1087,1088,1080,1074,1077,1090]])),
  610. %% Deprecated casts
  611. ?assertMatch({ok, _, [{<<"my_atom">>}]},
  612. Module:equery(C, "SELECT $1::varchar", [my_atom])),
  613. ?assertMatch({ok, _, [{<<"12345">>}]},
  614. Module:equery(C, "SELECT $1::varchar", [12345])),
  615. FloatBin = erlang:float_to_binary(1.2345),
  616. ?assertMatch({ok, _, [{FloatBin}]},
  617. Module:equery(C, "SELECT $1::varchar", [1.2345]))
  618. end).
  619. uuid_type(Config) ->
  620. check_type(Config, uuid,
  621. io_lib:format("'~s'", [uuid_to_bin_string(?UUID1)]),
  622. uuid_to_bin_string(?UUID1), []).
  623. point_type(Config) ->
  624. check_type(Config, point, "'(23.15, 100)'", {23.15, 100.0}, []).
  625. geometry_type(Config) ->
  626. check_type(Config, geometry, "'COMPOUNDCURVE(CIRCULARSTRING(0 0,1 1,1 0),(1 0,0 1))'",
  627. {compound_curve,'2d', [
  628. {circular_string,'2d', [
  629. {point,'2d',0.0,0.0,undefined,undefined},
  630. {point,'2d',1.0,1.0,undefined,undefined},
  631. {point,'2d',1.0,0.0,undefined,undefined}
  632. ]},
  633. {line_string,'2d', [
  634. {point,'2d',1.0,0.0,undefined,undefined},
  635. {point,'2d',0.0,1.0,undefined,undefined}
  636. ]}
  637. ]}, []).
  638. uuid_select(Config) ->
  639. Module = ?config(module, Config),
  640. epgsql_ct:with_rollback(Config, fun(C) ->
  641. U1 = uuid_to_bin_string(?UUID1),
  642. U2 = uuid_to_bin_string(?UUID2),
  643. U3 = uuid_to_bin_string(?UUID3),
  644. {ok, 1} =
  645. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID1', $1)",
  646. [U1]),
  647. {ok, 1} =
  648. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID2', $1)",
  649. [U2]),
  650. {ok, 1} =
  651. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID3', $1)",
  652. [U3]),
  653. Res = Module:equery(C, "select c_varchar, c_uuid from test_table2 where c_uuid = any($1)",
  654. [[U1, U2]]),
  655. ?assertMatch(
  656. {ok,[#column{name = <<"c_varchar">>, type = varchar},
  657. #column{name = <<"c_uuid">>, type = uuid}],
  658. [{<<"UUID1">>, U1},
  659. {<<"UUID2">>, U2}]}, Res)
  660. end).
  661. date_time_type(Config) ->
  662. Module = ?config(module, Config),
  663. epgsql_ct:with_connection(Config, fun(C) ->
  664. case Module:get_parameter(C, "integer_datetimes") of
  665. {ok, <<"on">>} -> MaxTsDate = 294276;
  666. {ok, <<"off">>} -> MaxTsDate = 5874897
  667. end,
  668. check_type(Config, date, "'2008-01-02'", {2008,1,2}, [{-4712,1,1}, {5874897,1,1}]),
  669. check_type(Config, time, "'00:01:02'", {0,1,2.0}, [{0,0,0.0}, {24,0,0.0}]),
  670. check_type(Config, timetz, "'00:01:02-01'", {{0,1,2.0},1*60*60},
  671. [{{0,0,0.0},0}, {{24,0,0.0},-13*60*60}]),
  672. check_type(Config, timestamp, "'2008-01-02 03:04:05'", {{2008,1,2},{3,4,5.0}},
  673. [{{-4712,1,1},{0,0,0.0}}, {{MaxTsDate,12,31}, {23,59,59.0}}, {1322,334285,440966}]),
  674. check_type(Config, timestamptz, "'2011-01-02 03:04:05+3'", {{2011, 1, 2}, {0, 4, 5.0}}, [{1324,875970,286983}]),
  675. check_type(Config, interval, "'1 hour 2 minutes 3.1 seconds'", {{1,2,3.1},0,0},
  676. [{{0,0,0.0},0,-178000000 * 12}, {{0,0,0.0},0,178000000 * 12}])
  677. end).
  678. json_type(Config) ->
  679. check_type(Config, json, "'{}'", <<"{}">>,
  680. [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>]),
  681. check_type(Config, jsonb, "'{}'", <<"{}">>,
  682. [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>]).
  683. misc_type(Config) ->
  684. check_type(Config, bool, "true", true, [true, false]),
  685. check_type(Config, bytea, "E'\001\002'", <<1,2>>, [<<>>, <<0,128,255>>]).
  686. hstore_type(Config) ->
  687. Values = [
  688. {[]},
  689. {[{null, null}]},
  690. {[{null, undefined}]},
  691. {[{1, null}]},
  692. {[{1.0, null}]},
  693. {[{1, undefined}]},
  694. {[{1.0, undefined}]},
  695. {[{<<"a">>, <<"c">>}, {<<"c">>, <<"d">>}]},
  696. {[{<<"a">>, <<"c">>}, {<<"c">>, null}]},
  697. {[{<<"a">>, <<"c">>}, {<<"c">>, undefined}]}
  698. ],
  699. check_type(Config, hstore, "''", {[]}, []),
  700. check_type(Config, hstore,
  701. "'a => 1, b => 2.0, c => null'",
  702. {[{<<"a">>, <<"1">>}, {<<"b">>, <<"2.0">>}, {<<"c">>, null}]}, Values).
  703. net_type(Config) ->
  704. 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}]),
  705. check_type(Config, inet, "'127.0.0.1'", {127,0,0,1}, [{127,0,0,1}, {0,0,0,0,0,0,0,1}]),
  706. %% macaddr8 available only on PG>=10
  707. check_type(Config, macaddr,
  708. "'FF:FF:FF:FF:FF:FF'", {255, 255, 255, 255, 255, 255},
  709. [{255, 255, 255, 255, 255, 255},
  710. {6, 0, 0, 0, 0, 0}]).
  711. array_type(Config) ->
  712. Module = ?config(module, Config),
  713. epgsql_ct:with_connection(Config, fun(C) ->
  714. {ok, _, [{[1, 2]}]} = Module:equery(C, "select ($1::int[])[1:2]", [[1, 2, 3]]),
  715. {ok, _, [{[{1, <<"one">>}, {2, <<"two">>}]}]} =
  716. Module:equery(C, "select Array(select (id, value) from test_table1)", []),
  717. Select = fun(Type, A) ->
  718. Query = "select $1::" ++ atom_to_list(Type) ++ "[]",
  719. {ok, _Cols, [{A2}]} = Module:equery(C, Query, [A]),
  720. case lists:all(fun({V, V2}) -> compare(Type, V, V2) end, lists:zip(A, A2)) of
  721. true -> ok;
  722. false -> ?assertMatch(A, A2)
  723. end
  724. end,
  725. Select(int2, []),
  726. Select(int2, [1, 2, 3, 4]),
  727. Select(int2, [[1], [2], [3], [4]]),
  728. Select(int2, [[[[[[1, 2]]]]]]),
  729. Select(bool, [true]),
  730. Select(char, [$a, $b, $c]),
  731. Select(int4, [[1, 2]]),
  732. Select(int8, [[[[1, 2]], [[3, 4]]]]),
  733. Select(text, [<<"one">>, <<"two>">>]),
  734. Select(varchar, [<<"one">>, <<"two>">>]),
  735. Select(float4, [0.0, 1.0, 0.123]),
  736. Select(float8, [0.0, 1.0, 0.123]),
  737. Select(date, [{2008,1,2}, {2008,1,3}]),
  738. Select(time, [{0,1,2.0}, {0,1,3.0}]),
  739. Select(timetz, [{{0,1,2.0},1*60*60}, {{0,1,3.0},1*60*60}]),
  740. Select(timestamp, [{{2008,1,2},{3,4,5.0}}, {{2008,1,2},{3,4,6.0}}]),
  741. Select(timestamptz, [{{2008,1,2},{3,4,5.0}}, {{2008,1,2},{3,4,6.0}}]),
  742. Select(interval, [{{1,2,3.1},0,0}, {{1,2,3.2},0,0}]),
  743. Select(hstore, [{[{null, null}, {a, 1}, {1, 2}, {b, undefined}]}]),
  744. Select(hstore, [[{[{null, null}, {a, 1}, {1, 2}, {b, undefined}]}, {[]}], [{[{a, 1}]}, {[{null, 2}]}]]),
  745. Select(cidr, [{{127,0,0,1}, 32}, {{0,0,0,0,0,0,0,1}, 128}]),
  746. Select(inet, [{127,0,0,1}, {0,0,0,0,0,0,0,1}]),
  747. Select(json, [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>]),
  748. Select(jsonb, [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>])
  749. end).
  750. custom_types(Config) ->
  751. Module = ?config(module, Config),
  752. epgsql_ct:with_connection(Config, fun(C) ->
  753. Module:squery(C, "drop table if exists t_foo;"),
  754. Module:squery(C, "drop type if exists my_type;"),
  755. {ok, [], []} = Module:squery(C, "create type my_type as enum('foo', 'bar');"),
  756. {ok, [my_type]} = epgsql:update_type_cache(C, [{epgsql_codec_test_enum, [foo, bar]}]),
  757. {ok, [], []} = Module:squery(C, "create table t_foo (col my_type);"),
  758. {ok, S} = Module:parse(C, "insert_foo", "insert into t_foo values ($1)", [my_type]),
  759. ok = Module:bind(C, S, [bar]),
  760. {ok, 1} = Module:execute(C, S),
  761. ?assertMatch({ok, _, [{bar}]}, Module:equery(C, "SELECT col FROM t_foo"))
  762. end).
  763. text_format(Config) ->
  764. Module = ?config(module, Config),
  765. epgsql_ct:with_connection(Config, fun(C) ->
  766. Select = fun(Type, V) ->
  767. V2 = list_to_binary(V),
  768. Query = "select $1::" ++ Type,
  769. ?assertMatch({ok, _Cols, [{V2}]}, Module:equery(C, Query, [V])),
  770. ?assertMatch({ok, _Cols, [{V2}]}, Module:equery(C, Query, [V2]))
  771. end,
  772. Select("numeric", "123456")
  773. end).
  774. query_timeout(Config) ->
  775. Module = ?config(module, Config),
  776. epgsql_ct:with_connection(Config, fun(C) ->
  777. {ok, _, _} = Module:squery(C, "SET statement_timeout = 500"),
  778. ?TIMEOUT_ERROR = Module:squery(C, "SELECT pg_sleep(1)"),
  779. ?TIMEOUT_ERROR = Module:equery(C, "SELECT pg_sleep(2)"),
  780. {ok, _Cols, [{1}]} = Module:equery(C, "SELECT 1")
  781. end, []).
  782. execute_timeout(Config) ->
  783. Module = ?config(module, Config),
  784. epgsql_ct:with_connection(Config, fun(C) ->
  785. {ok, _, _} = Module:squery(C, "SET statement_timeout = 500"),
  786. {ok, S} = Module:parse(C, "select pg_sleep($1)"),
  787. ok = Module:bind(C, S, [2]),
  788. ?TIMEOUT_ERROR = Module:execute(C, S, 0),
  789. ok = Module:sync(C),
  790. ok = Module:bind(C, S, [0]),
  791. {ok, [{<<>>}]} = Module:execute(C, S, 0),
  792. ok = Module:close(C, S),
  793. ok = Module:sync(C)
  794. end, []).
  795. connection_closed(Config) ->
  796. {Host, Port} = epgsql_ct:connection_data(Config),
  797. Module = ?config(module, Config),
  798. P = self(),
  799. spawn_link(fun() ->
  800. process_flag(trap_exit, true),
  801. {ok, C} = Module:connect(Host, "epgsql_test",[
  802. {port, Port},
  803. {database, "epgsql_test_db1"}
  804. ]),
  805. P ! {connected, C},
  806. receive
  807. Any -> P ! Any
  808. end
  809. end),
  810. receive
  811. {connected, C} ->
  812. timer:sleep(100),
  813. Module:close(C),
  814. {'EXIT', C, _} = receive R -> R end
  815. end,
  816. epgsql_ct:flush().
  817. connection_closed_by_server(Config) ->
  818. Module = ?config(module, Config),
  819. epgsql_ct:with_connection(Config, fun(C1) ->
  820. P = self(),
  821. spawn_link(fun() ->
  822. process_flag(trap_exit, true),
  823. epgsql_ct:with_connection(Config, fun(C2) ->
  824. {ok, _, [{Pid}]} = Module:equery(C2, "select pg_backend_pid()"),
  825. % emulate of disconnection
  826. {ok, _, [{true}]} = Module:equery(C1,
  827. "select pg_terminate_backend($1)", [Pid]),
  828. receive
  829. {'EXIT', C2, {shutdown, #error{code = <<"57P01">>}}} ->
  830. P ! ok;
  831. Other ->
  832. ?debugFmt("Unexpected msg: ~p~n", [Other]),
  833. P ! error
  834. end
  835. end)
  836. end),
  837. receive ok -> ok end
  838. end).
  839. active_connection_closed(Config) ->
  840. {Host, Port} = epgsql_ct:connection_data(Config),
  841. Module = ?config(module, Config),
  842. P = self(),
  843. F = fun() ->
  844. process_flag(trap_exit, true),
  845. {ok, C} = Module:connect(Host, [
  846. {database, "epgsql_test_db1"},
  847. {port, Port}
  848. ]),
  849. P ! {connected, C},
  850. R = Module:squery(C, "select pg_sleep(10)"),
  851. P ! R
  852. end,
  853. spawn_link(F),
  854. receive
  855. {connected, C} ->
  856. timer:sleep(100),
  857. Module:close(C),
  858. {error, closed} = receive R -> R end
  859. end,
  860. epgsql_ct:flush().
  861. warning_notice(Config) ->
  862. Module = ?config(module, Config),
  863. epgsql_ct:with_connection(Config, fun(C) ->
  864. Q = "create function pg_temp.raise() returns void as $$
  865. begin
  866. raise warning 'oops';
  867. end;
  868. $$ language plpgsql;
  869. select pg_temp.raise()",
  870. [{ok, _, _}, _] = Module:squery(C, Q),
  871. receive
  872. {epgsql, C, {notice, #error{message = <<"oops">>, extra = Extra}}} ->
  873. ?assertMatch([{file, _},{line, _},{routine, _} | _], Extra),
  874. ok
  875. after
  876. 100 -> erlang:error(didnt_receive_notice)
  877. end
  878. end, [{async, self()}]).
  879. listen_notify(Config) ->
  880. Module = ?config(module, Config),
  881. epgsql_ct:with_connection(Config, fun(C) ->
  882. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  883. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  884. {ok, [], []} = Module:squery(C, "notify epgsql_test"),
  885. receive
  886. {epgsql, C, {notification, <<"epgsql_test">>, Pid, <<>>}} -> ok
  887. after
  888. 100 -> erlang:error(didnt_receive_notification)
  889. end
  890. end, [{async, self()}]).
  891. listen_notify_payload(Config) ->
  892. Module = ?config(module, Config),
  893. epgsql_ct:with_min_version(Config, 9.0, fun(C) ->
  894. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  895. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  896. {ok, [], []} = Module:squery(C, "notify epgsql_test, 'test!'"),
  897. receive
  898. {epgsql, C, {notification, <<"epgsql_test">>, Pid, <<"test!">>}} -> ok
  899. after
  900. 100 -> erlang:error(didnt_receive_notification)
  901. end
  902. end, [{async, self()}]).
  903. set_notice_receiver(Config) ->
  904. Module = ?config(module, Config),
  905. epgsql_ct:with_min_version(Config, 9.0, fun(C) ->
  906. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  907. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  908. EnsureNoNotification = fun(Payload) ->
  909. {ok, [], []} = Module:squery(C, ["notify epgsql_test, '", Payload, "'"]),
  910. receive
  911. {epgsql, _, _} -> erlang:error(got_unexpected_notification)
  912. after
  913. 10 -> ok
  914. end
  915. end,
  916. EnsureNotification = fun(Payload) ->
  917. {ok, [], []} = Module:squery(C, ["notify epgsql_test, '", Payload, "'"]),
  918. receive
  919. {epgsql, C, {notification, <<"epgsql_test">>, Pid, Payload}} -> ok
  920. after
  921. 100 -> erlang:error(didnt_receive_notification)
  922. end
  923. end,
  924. Self = self(),
  925. EnsureNoNotification(<<"test1">>),
  926. % Set pid()
  927. {ok, undefined} = Module:set_notice_receiver(C, Self),
  928. EnsureNotification(<<"test2">>),
  929. %% test PL/PgSQL NOTICE
  930. {ok, [], []} = Module:squery(C, ["DO $$ BEGIN RAISE WARNING 'test notice'; END $$;"]),
  931. receive
  932. {epgsql, C, {notice, #error{severity = warning,
  933. code = <<"01000">>,
  934. message = <<"test notice">>,
  935. extra = _}}} -> ok
  936. after
  937. 100 -> erlang:error(didnt_receive_notice)
  938. end,
  939. % set registered pid
  940. Receiver = pg_notification_receiver,
  941. register(Receiver, Self),
  942. {ok, Self} = Module:set_notice_receiver(C, Receiver),
  943. EnsureNotification(<<"test3">>),
  944. % make registered name invalid
  945. unregister(Receiver),
  946. EnsureNoNotification(<<"test4">>),
  947. % disable
  948. {ok, Receiver} = Module:set_notice_receiver(C, undefined),
  949. EnsureNoNotification(<<"test5">>)
  950. end, []).
  951. get_cmd_status(Config) ->
  952. Module = ?config(module, Config),
  953. epgsql_ct:with_connection(Config, fun(C) ->
  954. {ok, [], []} = Module:squery(C, "BEGIN"),
  955. ?assertEqual({ok, 'begin'}, Module:get_cmd_status(C)),
  956. {ok, [], []} = epgsql:equery(C, "CREATE TEMPORARY TABLE cmd_status_t(col INTEGER)"),
  957. ?assertEqual({ok, 'create'}, Module:get_cmd_status(C)),
  958. %% Some commands have number of affected rows in status
  959. {ok, N} = Module:squery(C, "INSERT INTO cmd_status_t (col) VALUES (1), (2)"),
  960. ?assertEqual({ok, {'insert', N}}, Module:get_cmd_status(C)),
  961. {ok, 1} = Module:squery(C, "UPDATE cmd_status_t SET col=3 WHERE col=1"),
  962. ?assertEqual({ok, {'update', 1}}, Module:get_cmd_status(C)),
  963. %% Failed queries have no status
  964. {error, _} = Module:squery(C, "DELETE FROM cmd_status_t WHERE not_col=2"),
  965. ?assertEqual({ok, undefined}, Module:get_cmd_status(C)),
  966. %% if COMMIT failed, status will be 'rollback'
  967. {ok, [], []} = Module:squery(C, "COMMIT"),
  968. ?assertEqual({ok, 'rollback'}, Module:get_cmd_status(C)),
  969. %% Only last command's status returned
  970. [_, _, _] = Module:squery(C, "BEGIN; SELECT 1; COMMIT"),
  971. ?assertEqual({ok, 'commit'}, Module:get_cmd_status(C))
  972. end).
  973. range_type(Config) ->
  974. epgsql_ct:with_min_version(Config, 9.2, fun(_C) ->
  975. check_type(Config, int4range, "int4range(10, 20)", {10, 20}, [
  976. {1, 58}, {-1, 12}, {-985521, 5412687}, {minus_infinity, 0},
  977. {984655, plus_infinity}, {minus_infinity, plus_infinity}
  978. ])
  979. end, []).
  980. range8_type(Config) ->
  981. epgsql_ct:with_min_version(Config, 9.2, fun(_C) ->
  982. check_type(Config, int8range, "int8range(10, 20)", {10, 20}, [
  983. {1, 58}, {-1, 12}, {-9223372036854775808, 5412687},
  984. {minus_infinity, 9223372036854775807},
  985. {984655, plus_infinity}, {minus_infinity, plus_infinity}
  986. ])
  987. end, []).
  988. with_transaction(Config) ->
  989. Module = ?config(module, Config),
  990. epgsql_ct:with_connection(
  991. Config,
  992. fun(C) ->
  993. %% Success case
  994. ?assertEqual(
  995. success, Module:with_transaction(C, fun(_) -> success end)),
  996. ?assertEqual(
  997. success, Module:with_transaction(C, fun(_) -> success end,
  998. [{ensure_committed, true}])),
  999. %% begin_opts
  1000. ?assertMatch(
  1001. [{ok, _, [{<<"serializable">>}]},
  1002. {ok, _, [{<<"on">>}]}],
  1003. Module:with_transaction(
  1004. C, fun(C1) ->
  1005. Module:squery(C1, ("SHOW transaction_isolation; "
  1006. "SHOW transaction_read_only"))
  1007. end,
  1008. [{begin_opts, "READ ONLY ISOLATION LEVEL SERIALIZABLE"}])),
  1009. %% ensure_committed failure
  1010. ?assertError(
  1011. {ensure_committed_failed, rollback},
  1012. Module:with_transaction(
  1013. C, fun(C1) ->
  1014. {error, _} = Module:squery(C1, "SELECT col FROM _nowhere_"),
  1015. ok
  1016. end,
  1017. [{ensure_committed, true}])),
  1018. %% reraise
  1019. ?assertEqual(
  1020. {rollback, my_err},
  1021. Module:with_transaction(
  1022. C, fun(_) -> error(my_err) end,
  1023. [{reraise, false}])),
  1024. ?assertError(
  1025. my_err,
  1026. Module:with_transaction(
  1027. C, fun(_) -> error(my_err) end, []))
  1028. end, []).
  1029. %% =============================================================================
  1030. %% Internal functions
  1031. %% ============================================================================
  1032. check_type(Config, Type, In, Out, Values) ->
  1033. Column = "c_" ++ atom_to_list(Type),
  1034. check_type(Config, Type, In, Out, Values, Column).
  1035. check_type(Config, Type, In, Out, Values, Column) ->
  1036. Module = ?config(module, Config),
  1037. epgsql_ct:with_connection(Config, fun(C) ->
  1038. Select = io_lib:format("select ~s::~w", [In, Type]),
  1039. Res = Module:equery(C, Select),
  1040. ?assertMatch({ok, [#column{type = Type}], [{Out}]}, Res),
  1041. Sql = io_lib:format("insert into test_table2 (~s) values ($1) returning ~s", [Column, Column]),
  1042. {ok, #statement{columns = [#column{type = Type}]} = S} = Module:parse(C, Sql),
  1043. Insert = fun(V) ->
  1044. ok = Module:bind(C, S, [V]),
  1045. {ok, 1, [{V2}]} = Module:execute(C, S),
  1046. case compare(Type, V, V2) of
  1047. true -> ok;
  1048. false ->
  1049. error({write_read_compare_failed,
  1050. iolist_to_binary(
  1051. io_lib:format("~p =/= ~p~n", [V, V2]))})
  1052. end,
  1053. ok = Module:sync(C)
  1054. end,
  1055. lists:foreach(Insert, [null, undefined | Values])
  1056. end).
  1057. compare(_Type, null, null) -> true;
  1058. compare(_Type, undefined, null) -> true;
  1059. compare(float4, V1, V2) when is_float(V1) -> abs(V2 - V1) < 0.000001;
  1060. compare(float8, V1, V2) when is_float(V1) -> abs(V2 - V1) < 0.000000000000001;
  1061. compare(hstore, {V1}, V2) -> compare(hstore, V1, V2);
  1062. compare(hstore, V1, {V2}) -> compare(hstore, V1, V2);
  1063. compare(hstore, V1, V2) ->
  1064. orddict:from_list(format_hstore(V1)) =:= orddict:from_list(format_hstore(V2));
  1065. compare(Type, V1 = {_, _, MS}, {D2, {H2, M2, S2}}) when Type == timestamp;
  1066. Type == timestamptz ->
  1067. {D1, {H1, M1, S1}} = calendar:now_to_universal_time(V1),
  1068. ({D1, H1, M1} =:= {D2, H2, M2}) and (abs(S1 + MS/1000000 - S2) < 0.000000000000001);
  1069. compare(_Type, V1, V2) -> V1 =:= V2.
  1070. format_hstore({Hstore}) -> Hstore;
  1071. format_hstore(Hstore) ->
  1072. [{format_hstore_key(Key), format_hstore_value(Value)} || {Key, Value} <- Hstore].
  1073. format_hstore_key(Key) -> format_hstore_string(Key).
  1074. format_hstore_value(null) -> null;
  1075. format_hstore_value(undefined) -> null;
  1076. format_hstore_value(Value) -> format_hstore_string(Value).
  1077. format_hstore_string(Num) when is_number(Num) -> iolist_to_binary(io_lib:format("~w", [Num]));
  1078. format_hstore_string(Str) -> iolist_to_binary(io_lib:format("~s", [Str])).