epgsql_SUITE.erl 46 KB

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