epgsql_SUITE.erl 43 KB

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