epgsql_SUITE.erl 47 KB

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