epgsql_SUITE.erl 60 KB

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