epgsql_SUITE.erl 51 KB

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