epgsql_SUITE.erl 70 KB

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