epgsql_SUITE.erl 67 KB

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