epgsql_SUITE.erl 65 KB

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