epgsql_SUITE.erl 59 KB

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