epgsql_SUITE.erl 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793
  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. [{ok, _, [{<<"1">>}]}, {ok, _, [{<<"2">>}]}] = Module:squery(C, "select 1; select 2"),
  488. [{ok, _, [{<<"1">>}]}, {error, #error{}}] = Module:squery(C, "select 1; select foo;")
  489. end).
  490. execute_batch(Config) ->
  491. Module = ?config(module, Config),
  492. epgsql_ct:with_connection(Config, fun(C) ->
  493. {ok, S1} = Module:parse(C, "one", "select $1", [int4]),
  494. {ok, S2} = Module:parse(C, "two", "select $1 + $2", [int4, int4]),
  495. [{ok, [{1}]}, {ok, [{3}]}] =
  496. Module:execute_batch(C, [{S1, [1]}, {S2, [1, 2]}])
  497. end).
  498. execute_batch_3_named_stmt(Config) ->
  499. Module = ?config(module, Config),
  500. epgsql_ct:with_connection(Config, fun(C) ->
  501. {ok, Stmt} = Module:parse(C, "my_stmt", "select $1 + $2", [int4, int4]),
  502. ?assertMatch(
  503. {[#column{type = int4, _ = _}], [{ok, [{3}]}, {ok, [{7}]}]},
  504. Module:execute_batch(C, Stmt, [[1, 2], [3, 4]]))
  505. end).
  506. execute_batch_3_unnamed_stmt(Config) ->
  507. Module = ?config(module, Config),
  508. epgsql_ct:with_connection(Config, fun(C) ->
  509. {ok, Stmt} = Module:parse(C, "select $1::integer + $2::integer"),
  510. ?assertMatch(
  511. {[#column{type = int4, _ = _}], [{ok, [{3}]}, {ok, [{7}]}]},
  512. Module:execute_batch(C, Stmt, [[2, 1], [4, 3]]))
  513. end).
  514. execute_batch_3_sql(Config) ->
  515. Module = ?config(module, Config),
  516. epgsql_ct:with_connection(Config, fun(C) ->
  517. ?assertMatch(
  518. {[#column{type = int4, _ = _}], [{ok, [{3}]}, {ok, [{7}]}]},
  519. Module:execute_batch(C, "select $1::integer + $2::integer", [[1, 2], [3, 4]]))
  520. end).
  521. batch_error(Config) ->
  522. Module = ?config(module, Config),
  523. epgsql_ct:with_rollback(Config, fun(C) ->
  524. {ok, S} = Module:parse(C, "insert into test_table1(id, value) values($1, $2)"),
  525. [{ok, 1}, {error, Error}] =
  526. Module:execute_batch(
  527. C,
  528. [{S, [3, "batch_error 3"]},
  529. {S, [2, "batch_error 2"]}, % duplicate key error
  530. {S, [5, "batch_error 5"]}, % won't be executed
  531. {S, [6, "batch_error 6"]} % won't be executed
  532. ]),
  533. ?assertMatch(#error{}, Error)
  534. end).
  535. single_batch(Config) ->
  536. Module = ?config(module, Config),
  537. epgsql_ct:with_connection(Config, fun(C) ->
  538. {ok, S1} = Module:parse(C, "one", "select $1", [int4]),
  539. [{ok, [{1}]}] = Module:execute_batch(C, [{S1, [1]}])
  540. end).
  541. extended_select(Config) ->
  542. Module = ?config(module, Config),
  543. epgsql_ct:with_connection(Config, fun(C) ->
  544. {ok, Cols, Rows} = Module:equery(C, "select * from test_table1", []),
  545. [#column{name = <<"id">>, type = int4, size = 4},
  546. #column{name = <<"value">>, type = text, size = -1}] = Cols,
  547. [{1, <<"one">>}, {2, <<"two">>}] = Rows
  548. end).
  549. extended_sync_ok(Config) ->
  550. Module = ?config(module, Config),
  551. epgsql_ct:with_connection(Config, fun(C) ->
  552. {ok, _Cols, [{<<"one">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [1]),
  553. {ok, _Cols, [{<<"two">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [2])
  554. end).
  555. extended_sync_error(Config) ->
  556. Module = ?config(module, Config),
  557. epgsql_ct:with_connection(Config, fun(C) ->
  558. {error, #error{}} = Module:equery(C, "select _alue from test_table1 where id = $1", [1]),
  559. {ok, _Cols, [{<<"one">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [1])
  560. end).
  561. returning_from_insert(Config) ->
  562. Module = ?config(module, Config),
  563. epgsql_ct:with_rollback(Config, fun(C) ->
  564. {ok, 1, _Cols, [{3}]} = Module:equery(C, "insert into test_table1 (id) values (3) returning id")
  565. end).
  566. returning_from_update(Config) ->
  567. Module = ?config(module, Config),
  568. epgsql_ct:with_rollback(Config, fun(C) ->
  569. {ok, 2, _Cols, [{1}, {2}]} = Module:equery(C, "update test_table1 set value = 'hi' returning id"),
  570. ?assertMatch({ok, 0, [#column{}], []},
  571. Module:equery(C, "update test_table1 set value = 'hi' where false returning id")),
  572. ?assertMatch([{ok, 2, [#column{}], [{<<"1">>}, {<<"2">>}]},
  573. {ok, 0, [#column{}], []}],
  574. Module:squery(C,
  575. "update test_table1 set value = 'hi2' returning id; "
  576. "update test_table1 set value = 'hi' where false returning id"))
  577. end).
  578. returning_from_delete(Config) ->
  579. Module = ?config(module, Config),
  580. epgsql_ct:with_rollback(Config, fun(C) ->
  581. {ok, 2, _Cols, [{1}, {2}]} = Module:equery(C, "delete from test_table1 returning id"),
  582. ?assertMatch({ok, 0, [#column{}], []},
  583. Module:equery(C, "delete from test_table1 returning id"))
  584. end).
  585. parse(Config) ->
  586. Module = ?config(module, Config),
  587. epgsql_ct:with_connection(Config, fun(C) ->
  588. {ok, S} = Module:parse(C, "select * from test_table1"),
  589. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  590. ok = Module:close(C, S),
  591. ok = Module:sync(C)
  592. end).
  593. parse_column_format(Config) ->
  594. Module = ?config(module, Config),
  595. epgsql_ct:with_connection(Config, fun(C) ->
  596. {ok, S} = Module:parse(C, "select 1::int4, false::bool, 2.0::float4"),
  597. [#column{type = int4, table_oid = 0, table_attr_number = 0},
  598. #column{type = bool, table_oid = 0, table_attr_number = 0},
  599. #column{type = float4, table_oid = 0, table_attr_number = 0}] = S#statement.columns,
  600. ok = Module:bind(C, S, []),
  601. {ok, [{1, false, 2.0}]} = Module:execute(C, S, 0),
  602. ok = Module:close(C, S),
  603. ok = Module:sync(C)
  604. end).
  605. parse_error(Config) ->
  606. Module = ?config(module, Config),
  607. epgsql_ct:with_connection(Config, fun(C) ->
  608. {error, #error{
  609. extra = [{file, _}, {line, _}, {position, <<"8">>}, {routine, _} | _]
  610. }} = Module:parse(C, "select _ from test_table1"),
  611. {ok, S} = Module:parse(C, "select * from test_table1"),
  612. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  613. ok = Module:close(C, S),
  614. ok = Module:sync(C)
  615. end).
  616. parse_and_close(Config) ->
  617. Module = ?config(module, Config),
  618. epgsql_ct:with_connection(Config, fun(C) ->
  619. Parse = fun() -> Module:parse(C, "test", "select * from test_table1", []) end,
  620. {ok, S} = Parse(),
  621. {error, #error{code = <<"42P05">>, codename = duplicate_prepared_statement}} = Parse(),
  622. Module:close(C, S),
  623. {ok, S} = Parse(),
  624. ok = Module:sync(C)
  625. end).
  626. bind(Config) ->
  627. Module = ?config(module, Config),
  628. epgsql_ct:with_connection(Config, fun(C) ->
  629. {ok, S} = Module:parse(C, "select value from test_table1 where id = $1"),
  630. ok = Module:bind(C, S, [1]),
  631. ok = Module:close(C, S),
  632. ok = Module:sync(C)
  633. end).
  634. bind_parameter_format(Config) ->
  635. Module = ?config(module, Config),
  636. epgsql_ct:with_connection(Config, fun(C) ->
  637. {ok, S} = Module:parse(C, "select $1, $2, $3", [int2, text, bool]),
  638. [int2, text, bool] = S#statement.types,
  639. ok = Module:bind(C, S, [1, "hi", true]),
  640. {ok, [{1, <<"hi">>, true}]} = Module:execute(C, S, 0),
  641. ok = Module:close(C, S),
  642. ok = Module:sync(C)
  643. end).
  644. bind_error(Config) ->
  645. Module = ?config(module, Config),
  646. epgsql_ct:with_connection(Config, fun(C) ->
  647. {ok, S} = Module:parse(C, "select $1::char"),
  648. {error, #error{}} = Module:bind(C, S, [0]),
  649. ok = Module:bind(C, S, [$A]),
  650. ok = Module:close(C, S),
  651. ok = Module:sync(C)
  652. end).
  653. bind_and_close(Config) ->
  654. Module = ?config(module, Config),
  655. epgsql_ct:with_connection(Config, fun(C) ->
  656. {ok, S} = Module:parse(C, "select * from test_table1"),
  657. ok = Module:bind(C, S, "one", []),
  658. {error, #error{code = <<"42P03">>, codename = duplicate_cursor}} = Module:bind(C, S, "one", []),
  659. ok = Module:close(C, portal, "one"),
  660. ok = Module:bind(C, S, "one", []),
  661. ok = Module:sync(C)
  662. end).
  663. execute_error(Config) ->
  664. Module = ?config(module, Config),
  665. epgsql_ct:with_connection(Config, fun(C) ->
  666. {ok, S} = Module:parse(C, "insert into test_table1 (id, value) values ($1, $2)"),
  667. ok = Module:bind(C, S, [1, <<"foo">>]),
  668. {error, #error{
  669. code = <<"23505">>, codename = unique_violation,
  670. extra = [
  671. {constraint_name, <<"test_table1_pkey">>},
  672. {detail, _},
  673. {file, _},
  674. {line, _},
  675. {routine, _},
  676. {schema_name, <<"public">>} | _%,
  677. %{table_name, <<"test_table1">>}
  678. ]
  679. }} = Module:execute(C, S, 0),
  680. {error, sync_required} = Module:bind(C, S, [3, <<"quux">>]),
  681. ok = Module:sync(C),
  682. ok = Module:bind(C, S, [3, <<"quux">>]),
  683. {ok, _} = Module:execute(C, S, 0),
  684. {ok, 1} = Module:squery(C, "delete from test_table1 where id = 3")
  685. end).
  686. describe(Config) ->
  687. Module = ?config(module, Config),
  688. epgsql_ct:with_connection(Config, fun(C) ->
  689. {ok, S} = Module:parse(C, "select * from test_table1"),
  690. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  691. {ok, S} = Module:describe(C, S),
  692. ok = Module:close(C, S),
  693. ok = Module:sync(C)
  694. end).
  695. describe_with_param(Config) ->
  696. Module = ?config(module, Config),
  697. epgsql_ct:with_connection(Config, fun(C) ->
  698. {ok, S} = Module:parse(C, "select id from test_table1 where id = $1"),
  699. ?assertEqual([int4], S#statement.types),
  700. ?assertMatch([#column{name = <<"id">>}], S#statement.columns),
  701. {ok, S} = Module:describe(C, S),
  702. ok = Module:close(C, S),
  703. ok = Module:sync(C)
  704. end).
  705. describe_named(Config) ->
  706. Module = ?config(module, Config),
  707. epgsql_ct:with_connection(Config, fun(C) ->
  708. {ok, S} = Module:parse(C, "name", "select * from test_table1", []),
  709. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  710. {ok, S} = Module:describe(C, S),
  711. ok = Module:close(C, S),
  712. ok = Module:sync(C)
  713. end).
  714. describe_error(Config) ->
  715. Module = ?config(module, Config),
  716. epgsql_ct:with_connection(Config, fun(C) ->
  717. {error, #error{}} = Module:describe(C, statement, ""),
  718. {ok, S} = Module:parse(C, "select * from test_table1"),
  719. {ok, S} = Module:describe(C, statement, ""),
  720. ok = Module:sync(C)
  721. end).
  722. describe_portal(Config) ->
  723. Module = ?config(module, Config),
  724. epgsql_ct:with_connection(Config, fun(C) ->
  725. {ok, Stmt} = Module:parse(C, "my_stmt", "select * from test_table1 WHERE id = $1", []),
  726. ok = Module:bind(C, Stmt, "my_portal", [1]),
  727. {ok, Columns} = Module:describe(C, portal, "my_portal"),
  728. ?assertMatch(
  729. [#column{name = <<"id">>,
  730. type = int4},
  731. #column{name = <<"value">>,
  732. type = text}],
  733. Columns
  734. ),
  735. ok = Module:close(C, Stmt),
  736. ok = Module:sync(C)
  737. end).
  738. portal(Config) ->
  739. Module = ?config(module, Config),
  740. epgsql_ct:with_connection(Config, fun(C) ->
  741. {ok, S} = Module:parse(C, "select value from test_table1"),
  742. ok = Module:bind(C, S, []),
  743. {partial, [{<<"one">>}]} = Module:execute(C, S, 1),
  744. {partial, [{<<"two">>}]} = Module:execute(C, S, 1),
  745. {ok, []} = Module:execute(C, S,1),
  746. ok = Module:close(C, S),
  747. ok = Module:sync(C)
  748. end).
  749. returning(Config) ->
  750. Module = ?config(module, Config),
  751. epgsql_ct:with_rollback(Config, fun(C) ->
  752. {ok, S} = Module:parse(C, "update test_table1 set value = $1 returning id"),
  753. ok = Module:bind(C, S, ["foo"]),
  754. {ok, 2, [{1}, {2}]} = Module:execute(C, S),
  755. ok = Module:sync(C)
  756. end).
  757. multiple_statement(Config) ->
  758. Module = ?config(module, Config),
  759. epgsql_ct:with_connection(Config, fun(C) ->
  760. {ok, S1} = Module:parse(C, "one", "select value from test_table1 where id = 1", []),
  761. ok = Module:bind(C, S1, []),
  762. {partial, [{<<"one">>}]} = Module:execute(C, S1, 1),
  763. {ok, S2} = Module:parse(C, "two", "select value from test_table1 where id = 2", []),
  764. ok = Module:bind(C, S2, []),
  765. {partial, [{<<"two">>}]} = Module:execute(C, S2, 1),
  766. {ok, []} = Module:execute(C, S1, 1),
  767. {ok, []} = Module:execute(C, S2, 1),
  768. ok = Module:close(C, S1),
  769. ok = Module:close(C, S2),
  770. ok = Module:sync(C)
  771. end).
  772. multiple_portal(Config) ->
  773. Module = ?config(module, Config),
  774. epgsql_ct:with_connection(Config, fun(C) ->
  775. {ok, S} = Module:parse(C, "select value from test_table1 where id = $1"),
  776. ok = Module:bind(C, S, "one", [1]),
  777. ok = Module:bind(C, S, "two", [2]),
  778. {ok, [{<<"one">>}]} = Module:execute(C, S, "one", 0),
  779. {ok, [{<<"two">>}]} = Module:execute(C, S, "two", 0),
  780. ok = Module:close(C, S),
  781. ok = Module:sync(C)
  782. end).
  783. execute_function(Config) ->
  784. Module = ?config(module, Config),
  785. epgsql_ct:with_rollback(Config, fun(C) ->
  786. {ok, _Cols1, [{3}]} = Module:equery(C, "select insert_test1(3, 'three')"),
  787. {ok, _Cols2, [{<<>>}]} = Module:equery(C, "select do_nothing()")
  788. end).
  789. parameter_get(Config) ->
  790. Module = ?config(module, Config),
  791. epgsql_ct:with_connection(Config, fun(C) ->
  792. {ok, <<"off">>} = Module:get_parameter(C, "is_superuser")
  793. end).
  794. parameter_set(Config) ->
  795. Module = ?config(module, Config),
  796. epgsql_ct:with_connection(Config, fun(C) ->
  797. {ok, [], []} = Module:squery(C, "set DateStyle = 'ISO, MDY'"),
  798. {ok, <<"ISO, MDY">>} = Module:get_parameter(C, "DateStyle"),
  799. {ok, _Cols, [{<<"2000-01-02">>}]} = Module:squery(C, "select '2000-01-02'::date"),
  800. {ok, [], []} = Module:squery(C, "set DateStyle = 'German'"),
  801. {ok, <<"German, DMY">>} = Module:get_parameter(C, "DateStyle"),
  802. {ok, _Cols, [{<<"02.01.2000">>}]} = Module:squery(C, "select '2000-01-02'::date")
  803. end).
  804. numeric_type(Config) ->
  805. check_type(Config, int2, "1", 1, [0, 256, -32768, +32767]),
  806. check_type(Config, int4, "1", 1, [0, 512, -2147483648, +2147483647]),
  807. check_type(Config, int8, "1", 1, [0, 1024, -9223372036854775808, +9223372036854775807]),
  808. check_type(Config, float4, "1.0", 1.0, [0.0, 1.23456, -1.23456]),
  809. check_type(Config, float4, "'-Infinity'", minus_infinity, [minus_infinity, plus_infinity, nan]),
  810. check_type(Config, float8, "1.0", 1.0, [0.0, 1.23456789012345, -1.23456789012345]),
  811. check_type(Config, float8, "'nan'", nan, [minus_infinity, plus_infinity, nan]),
  812. %% Check overflow protection. Connection just crashes for now instead of silently
  813. %% truncating the data. Some cleaner behaviour can be introduced later.
  814. epgsql_ct:with_connection(Config, fun(C) ->
  815. Module = ?config(module, Config),
  816. Trap = process_flag(trap_exit, true),
  817. try Module:equery(C, "SELECT $1::int2", [32768]) of
  818. {error, closed} ->
  819. %% epgsqla/epgsqli
  820. ok
  821. catch exit:Reason ->
  822. %% epgsql
  823. ?assertMatch({{{integer_overflow, int2, _}, _}, _}, Reason),
  824. receive {'EXIT', C, _} -> ok
  825. after 1000 -> error(timeout)
  826. end
  827. end,
  828. process_flag(trap_exit, Trap)
  829. end).
  830. character_type(Config) ->
  831. Alpha = unicode:characters_to_binary([16#03B1]),
  832. Ka = unicode:characters_to_binary([16#304B]),
  833. One = unicode:characters_to_binary([16#10D360]),
  834. check_type(Config, bpchar, "'A'", $A, [1, $1, 16#7F, Alpha, Ka, One], "c_char"),
  835. check_type(Config, text, "'hi'", <<"hi">>, [<<"">>, <<"hi">>]),
  836. check_type(Config, varchar, "'hi'", <<"hi">>, [<<"">>, <<"hi">>]),
  837. epgsql_ct:with_connection(
  838. Config,
  839. fun(C) ->
  840. Module = ?config(module, Config),
  841. %% IOlists
  842. ?assertMatch({ok, _, [{<<1087/utf8, 1088/utf8, 1080/utf8,
  843. 1074/utf8, 1077/utf8, 1090/utf8>>}]},
  844. Module:equery(C, "SELECT $1::text", [[1087,1088,1080,1074,1077,1090]])),
  845. %% Deprecated casts
  846. ?assertMatch({ok, _, [{<<"my_atom">>}]},
  847. Module:equery(C, "SELECT $1::varchar", [my_atom])),
  848. ?assertMatch({ok, _, [{<<"12345">>}]},
  849. Module:equery(C, "SELECT $1::varchar", [12345])),
  850. FloatBin = erlang:float_to_binary(1.2345),
  851. ?assertMatch({ok, _, [{FloatBin}]},
  852. Module:equery(C, "SELECT $1::varchar", [1.2345])),
  853. %% String bpchar
  854. ?assertMatch({ok, _, [{<<"hello world">>}]},
  855. Module:equery(C, "SELECT $1::bpchar", ["hello world"]))
  856. end).
  857. uuid_type(Config) ->
  858. check_type(Config, uuid,
  859. io_lib:format("'~s'", [uuid_to_bin_string(?UUID1)]),
  860. uuid_to_bin_string(?UUID1), []).
  861. point_type(Config) ->
  862. check_type(Config, point, "'(23.15, 100)'", {23.15, 100.0}, []).
  863. geometry_type(Config) ->
  864. check_type(Config, geometry, "'COMPOUNDCURVE(CIRCULARSTRING(0 0,1 1,1 0),(1 0,0 1))'",
  865. {compound_curve,'2d', [
  866. {circular_string,'2d', [
  867. {point,'2d',0.0,0.0,undefined,undefined},
  868. {point,'2d',1.0,1.0,undefined,undefined},
  869. {point,'2d',1.0,0.0,undefined,undefined}
  870. ]},
  871. {line_string,'2d', [
  872. {point,'2d',1.0,0.0,undefined,undefined},
  873. {point,'2d',0.0,1.0,undefined,undefined}
  874. ]}
  875. ]}, []).
  876. uuid_select(Config) ->
  877. Module = ?config(module, Config),
  878. epgsql_ct:with_rollback(Config, fun(C) ->
  879. U1 = uuid_to_bin_string(?UUID1),
  880. U2 = uuid_to_bin_string(?UUID2),
  881. U3 = uuid_to_bin_string(?UUID3),
  882. {ok, 1} =
  883. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID1', $1)",
  884. [U1]),
  885. {ok, 1} =
  886. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID2', $1)",
  887. [U2]),
  888. {ok, 1} =
  889. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID3', $1)",
  890. [U3]),
  891. Res = Module:equery(C, "select c_varchar, c_uuid from test_table2 where c_uuid = any($1)",
  892. [[U1, U2]]),
  893. ?assertMatch(
  894. {ok,[#column{name = <<"c_varchar">>, type = varchar},
  895. #column{name = <<"c_uuid">>, type = uuid}],
  896. [{<<"UUID1">>, U1},
  897. {<<"UUID2">>, U2}]}, Res)
  898. end).
  899. date_time_type(Config) ->
  900. Module = ?config(module, Config),
  901. epgsql_ct:with_connection(Config, fun(C) ->
  902. case Module:get_parameter(C, "integer_datetimes") of
  903. {ok, <<"on">>} -> MaxTsDate = 294276;
  904. {ok, <<"off">>} -> MaxTsDate = 5874897
  905. end,
  906. check_type(Config, date, "'2008-01-02'", {2008,1,2}, [{-4712,1,1}, {5874897,1,1}]),
  907. check_type(Config, time, "'00:01:02'", {0,1,2.0}, [{0,0,0.0}, {24,0,0.0}]),
  908. check_type(Config, timetz, "'00:01:02-01'", {{0,1,2.0},1*60*60},
  909. [{{0,0,0.0},0}, {{24,0,0.0},-13*60*60}]),
  910. check_type(Config, timestamp, "'2008-01-02 03:04:05'", {{2008,1,2},{3,4,5.0}},
  911. [{{-4712,1,1},{0,0,0.0}}, {{MaxTsDate,12,31}, {23,59,59.0}}, {1322,334285,440966}]),
  912. check_type(Config, timestamptz, "'2011-01-02 03:04:05+3'", {{2011, 1, 2}, {0, 4, 5.0}}, [{1324,875970,286983}]),
  913. check_type(Config, interval, "'1 hour 2 minutes 3.1 seconds'", {{1,2,3.1},0,0},
  914. [{{0,0,0.0},0,-178000000 * 12}, {{0,0,0.0},0,178000000 * 12}])
  915. end).
  916. json_type(Config) ->
  917. Module = ?config(module, Config),
  918. epgsql_ct:with_connection(Config, fun(C) ->
  919. check_type(Config, json, "'{}'", <<"{}">>,
  920. [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>],
  921. get_type_col(json), C),
  922. check_type(Config, jsonb, "'{}'", <<"{}">>,
  923. [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>],
  924. get_type_col(jsonb), C),
  925. epgsql:update_type_cache(C, [{epgsql_codec_json, epgsql_fake_json_mod}]),
  926. RowId = "json_type_custom_mod_" ++ atom_to_list(Module),
  927. {ok, 1} = Module:equery(C, "insert into test_table2 (c_varchar, c_json, c_jsonb) values ($1, $2, $3)", [RowId, {"{}"}, {"{}"}]),
  928. Res = Module:equery(C, "select c_json, c_jsonb from test_table2 where c_varchar = $1", [RowId]),
  929. ?assertMatch(
  930. {ok, [#column{name = <<"c_json">>, type = json}, #column{name = <<"c_jsonb">>, type = jsonb}],
  931. [{{<<"{}">>}, {<<"{}">>}}]},
  932. Res
  933. )
  934. end).
  935. misc_type(Config) ->
  936. check_type(Config, bool, "true", true, [true, false]),
  937. check_type(Config, bytea, "E'\001\002'", <<1,2>>, [<<>>, <<0,128,255>>]).
  938. hstore_type(Config) ->
  939. Module = ?config(module, Config),
  940. Values = [
  941. {[]},
  942. {[{null, null}]},
  943. {[{null, undefined}]},
  944. {[{1, null}]},
  945. {[{1.0, null}]},
  946. {[{1, undefined}]},
  947. {[{1.0, undefined}]},
  948. {[{<<"a">>, <<"c">>}, {<<"c">>, <<"d">>}]},
  949. {[{<<"a">>, <<"c">>}, {<<"c">>, null}]},
  950. {[{<<"a">>, <<"c">>}, {<<"c">>, undefined}]}
  951. ],
  952. check_type(Config, hstore, "''", {[]}, []),
  953. check_type(Config, hstore,
  954. "'a => 1, b => 2.0, c => null'",
  955. {[{<<"a">>, <<"1">>}, {<<"b">>, <<"2.0">>}, {<<"c">>, null}]}, Values),
  956. epgsql_ct:with_connection(
  957. Config,
  958. fun(C) ->
  959. %% Maps as input
  960. [begin
  961. {ok, _, [{Res}]} = Module:equery(C, "select $1::hstore", [maps:from_list(KV)]),
  962. ?assert(compare(hstore, Res, Jiffy))
  963. end || {KV} = Jiffy <- Values],
  964. %% Maps as output
  965. {ok, [hstore]} = epgsql:update_type_cache(
  966. C, [{epgsql_codec_hstore, #{return => map}}]),
  967. [begin
  968. {ok, _, [{Res}]} = Module:equery(C, "select $1::hstore", [maps:from_list(KV)]),
  969. HstoreMap = maps:from_list([{format_hstore_key(K), format_hstore_value(V)} || {K, V} <- KV]),
  970. ?assertEqual(HstoreMap, Res)
  971. end || {KV} <- Values],
  972. %% Proplist as output
  973. {ok, [hstore]} = epgsql:update_type_cache(
  974. C, [{epgsql_codec_hstore, #{return => proplist}}]),
  975. [begin
  976. {ok, _, [{Res}]} = Module:equery(C, "select $1::hstore", [Jiffy]),
  977. HstoreProplist = [{format_hstore_key(K), format_hstore_value(V)} || {K, V} <- KV],
  978. ?assertEqual(lists:sort(HstoreProplist), lists:sort(Res))
  979. end || {KV} = Jiffy <- Values],
  980. %% Custom nulls
  981. Nulls = [nil, 'NULL', aaaa],
  982. {ok, [hstore]} = epgsql:update_type_cache(
  983. C, [{epgsql_codec_hstore, #{return => map,
  984. nulls => Nulls}}]),
  985. K = <<"k">>,
  986. [begin
  987. {ok, _, [{Res}]} = Module:equery(C, "select $1::hstore", [#{K => V}]),
  988. ?assertEqual(#{K => nil}, Res)
  989. end || V <- Nulls]
  990. end).
  991. net_type(Config) ->
  992. 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}]),
  993. check_type(Config, inet, "'127.0.0.1'", {127,0,0,1}, [{127,0,0,1}, {0,0,0,0,0,0,0,1}]),
  994. %% macaddr8 available only on PG>=10
  995. check_type(Config, macaddr,
  996. "'FF:FF:FF:FF:FF:FF'", {255, 255, 255, 255, 255, 255},
  997. [{255, 255, 255, 255, 255, 255},
  998. {6, 0, 0, 0, 0, 0}]).
  999. array_type(Config) ->
  1000. Module = ?config(module, Config),
  1001. epgsql_ct:with_connection(Config, fun(C) ->
  1002. {ok, _, [{[1, 2]}]} = Module:equery(C, "select ($1::int[])[1:2]", [[1, 2, 3]]),
  1003. {ok, _, [{[{1, <<"one">>}, {2, <<"two">>}]}]} =
  1004. Module:equery(C, "select Array(select (id, value) from test_table1)", []),
  1005. {ok, _, [{ [[1], [null], [3], [null]] }]} =
  1006. Module:equery(C, "select $1::int2[]", [ [[1], [null], [3], [undefined]] ]),
  1007. Select = fun(Type, AIn) ->
  1008. Query = "select $1::" ++ atom_to_list(Type) ++ "[]",
  1009. {ok, _Cols, [{AOut}]} = Module:equery(C, Query, [AIn]),
  1010. case lists:all(fun({VIn, VOut}) ->
  1011. compare(Type, VIn, VOut)
  1012. end, lists:zip(AIn, AOut)) of
  1013. true -> ok;
  1014. false -> ?assertEqual(AIn, AOut)
  1015. end
  1016. end,
  1017. Select(int2, []),
  1018. Select(int2, [1, 2, 3, 4]),
  1019. Select(int2, [[1], [2], [3], [4]]),
  1020. Select(int2, [[[[[[1, 2]]]]]]),
  1021. Select(int2, [1, null, 3, undefined]),
  1022. Select(int2, [[1], [null], [3], [null]]),
  1023. Select(bool, [true]),
  1024. Select(char, [$a, $b, $c]),
  1025. Select(int4, [[1, 2]]),
  1026. Select(int8, [[[[1, 2]], [[3, 4]]]]),
  1027. Select(text, [<<"one">>, <<"two>">>]),
  1028. Select(varchar, [<<"one">>, <<"two>">>]),
  1029. Select(float4, [0.0, 1.0, 0.123]),
  1030. Select(float8, [0.0, 1.0, 0.123]),
  1031. Select(date, [{2008,1,2}, {2008,1,3}]),
  1032. Select(time, [{0,1,2.0}, {0,1,3.0}]),
  1033. Select(timetz, [{{0,1,2.0},1*60*60}, {{0,1,3.0},1*60*60}]),
  1034. Select(timestamp, [{{2008,1,2},{3,4,5.0}}, {{2008,1,2},{3,4,6.0}}]),
  1035. Select(timestamptz, [{{2008,1,2},{3,4,5.0}}, {{2008,1,2},{3,4,6.0}}]),
  1036. Select(interval, [{{1,2,3.1},0,0}, {{1,2,3.2},0,0}]),
  1037. Select(hstore, [{[{null, null}, {a, 1}, {1, 2}, {b, undefined}]}]),
  1038. Select(hstore, [[{[{null, null}, {a, 1}, {1, 2}, {b, undefined}]}, {[]}], [{[{a, 1}]}, {[{null, 2}]}]]),
  1039. Select(cidr, [{{127,0,0,1}, 32}, {{0,0,0,0,0,0,0,1}, 128}]),
  1040. Select(inet, [{127,0,0,1}, {0,0,0,0,0,0,0,1}]),
  1041. Select(json, [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>]),
  1042. Select(jsonb, [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>])
  1043. end).
  1044. record_type(Config) ->
  1045. Module = ?config(module, Config),
  1046. epgsql_ct:with_connection(Config, fun(C) ->
  1047. Select = fun(Sql, Expected) ->
  1048. {ok, _Columns, [Row]} = Module:equery(C, Sql, []),
  1049. ?assertMatch(Expected, Row)
  1050. end,
  1051. %% Simple record
  1052. Select("select (1,2)", {{1, 2}}),
  1053. %% Record inside other record
  1054. Select("select (1, (select (2,3)))", {{1, {2, 3}}}),
  1055. %% Array inside record
  1056. Select("select (1, '{2,3}'::int[])", {{1, [2, 3]}}),
  1057. %% Array of records inside record
  1058. Select("select (0, ARRAY(select (id, value) from test_table1))", {{0,[{1,<<"one">>},{2,<<"two">>}]}}),
  1059. %% Record with NULLs
  1060. Select("select (1, NULL::integer, 2)", {{1, null, 2}})
  1061. end).
  1062. custom_types(Config) ->
  1063. Module = ?config(module, Config),
  1064. epgsql_ct:with_connection(Config, fun(C) ->
  1065. Module:squery(C, "drop table if exists t_foo;"),
  1066. Module:squery(C, "drop type if exists my_type;"),
  1067. {ok, [], []} = Module:squery(C, "create type my_type as enum('foo', 'bar');"),
  1068. {ok, [my_type]} = epgsql:update_type_cache(C, [{epgsql_codec_test_enum, [foo, bar]}]),
  1069. {ok, [], []} = Module:squery(C, "create table t_foo (col my_type);"),
  1070. {ok, S} = Module:parse(C, "insert_foo", "insert into t_foo values ($1)", [my_type]),
  1071. ok = Module:bind(C, S, [bar]),
  1072. {ok, 1} = Module:execute(C, S),
  1073. ?assertMatch({ok, _, [{bar}]}, Module:equery(C, "SELECT col FROM t_foo"))
  1074. end).
  1075. custom_null(Config) ->
  1076. Module = ?config(module, Config),
  1077. epgsql_ct:with_connection(Config, fun(C) ->
  1078. Test3 = fun(Type, In, Out) ->
  1079. Q = ["SELECT $1::", Type],
  1080. {ok, _, [{Res}]} = Module:equery(C, Q, [In]),
  1081. ?assertEqual(Out, Res)
  1082. end,
  1083. Test = fun(Type, In) ->
  1084. Test3(Type, In, In)
  1085. end,
  1086. Test("int2", nil),
  1087. Test3("int2", 'NULL', nil),
  1088. Test("text", nil),
  1089. Test3("text", 'NULL', nil),
  1090. Test3("text", null, <<"null">>),
  1091. Test("int2[]", [nil, 1, nil, 2]),
  1092. Test3("text[]", [null, <<"ok">>], [<<"null">>, <<"ok">>]),
  1093. Test3("int2[]", ['NULL', 1, nil, 2], [nil, 1, nil, 2]),
  1094. Test("int2[]", [[nil], [1], [nil], [2]]),
  1095. Test3("int2[]", [['NULL'], [1], [nil], [2]], [[nil], [1], [nil], [2]]),
  1096. ?assertMatch(
  1097. {ok, _, [{ {1, nil, {2, nil, 3}} }]},
  1098. Module:equery(C, "SELECT (1, NULL, (2, NULL, 3))", []))
  1099. end,
  1100. [{nulls, [nil, 'NULL']}]).
  1101. text_format(Config) ->
  1102. Module = ?config(module, Config),
  1103. epgsql_ct:with_connection(Config, fun(C) ->
  1104. Select = fun(Type, V) ->
  1105. V2 = list_to_binary(V),
  1106. Query = "select $1::" ++ Type,
  1107. ?assertMatch({ok, _Cols, [{V2}]}, Module:equery(C, Query, [V])),
  1108. ?assertMatch({ok, _Cols, [{V2}]}, Module:equery(C, Query, [V2]))
  1109. end,
  1110. Select("numeric", "123456")
  1111. end).
  1112. query_timeout(Config) ->
  1113. Module = ?config(module, Config),
  1114. epgsql_ct:with_connection(Config, fun(C) ->
  1115. {ok, _, _} = Module:squery(C, "SET statement_timeout = 500"),
  1116. ?assertMatch(?TIMEOUT_ERROR, Module:squery(C, "SELECT pg_sleep(1)")),
  1117. ?assertMatch(?TIMEOUT_ERROR, Module:equery(C, "SELECT pg_sleep(2)")),
  1118. {ok, _Cols, [{1}]} = Module:equery(C, "SELECT 1")
  1119. end, []).
  1120. execute_timeout(Config) ->
  1121. Module = ?config(module, Config),
  1122. epgsql_ct:with_connection(Config, fun(C) ->
  1123. {ok, _, _} = Module:squery(C, "SET statement_timeout = 500"),
  1124. {ok, S} = Module:parse(C, "select pg_sleep($1)"),
  1125. ok = Module:bind(C, S, [2]),
  1126. ?assertMatch(?TIMEOUT_ERROR, Module:execute(C, S, 0)),
  1127. ok = Module:sync(C),
  1128. ok = Module:bind(C, S, [0]),
  1129. {ok, [{<<>>}]} = Module:execute(C, S, 0),
  1130. ok = Module:close(C, S),
  1131. ok = Module:sync(C)
  1132. end, []).
  1133. connection_closed(Config) ->
  1134. {Host, Port} = epgsql_ct:connection_data(Config),
  1135. Module = ?config(module, Config),
  1136. P = self(),
  1137. spawn_link(fun() ->
  1138. process_flag(trap_exit, true),
  1139. {ok, C} = Module:connect(Host, "epgsql_test",[
  1140. {port, Port},
  1141. {database, "epgsql_test_db1"}
  1142. ]),
  1143. P ! {connected, C},
  1144. receive
  1145. Any -> P ! Any
  1146. end
  1147. end),
  1148. receive
  1149. {connected, C} ->
  1150. timer:sleep(100),
  1151. Module:close(C),
  1152. {'EXIT', C, _} = receive R -> R end
  1153. end,
  1154. epgsql_ct:flush().
  1155. connection_closed_by_server(Config) ->
  1156. Module = ?config(module, Config),
  1157. epgsql_ct:with_connection(Config, fun(C1) ->
  1158. P = self(),
  1159. spawn_link(fun() ->
  1160. process_flag(trap_exit, true),
  1161. epgsql_ct:with_connection(Config, fun(C2) ->
  1162. {ok, _, [{Pid}]} = Module:equery(C2, "select pg_backend_pid()"),
  1163. % emulate of disconnection
  1164. {ok, _, [{true}]} = Module:equery(C1,
  1165. "select pg_terminate_backend($1)", [Pid]),
  1166. receive
  1167. {'EXIT', C2, {shutdown, #error{code = <<"57P01">>}}} ->
  1168. P ! ok;
  1169. Other ->
  1170. ct:pal("Unexpected msg: ~p~n", [Other]),
  1171. P ! error
  1172. end
  1173. end)
  1174. end),
  1175. receive ok -> ok end
  1176. end).
  1177. active_connection_closed(Config) ->
  1178. {Host, Port} = epgsql_ct:connection_data(Config),
  1179. Module = ?config(module, Config),
  1180. P = self(),
  1181. F = fun() ->
  1182. process_flag(trap_exit, true),
  1183. {ok, C} = Module:connect(Host, [
  1184. {database, "epgsql_test_db1"},
  1185. {port, Port}
  1186. ]),
  1187. P ! {connected, C},
  1188. R = Module:squery(C, "select pg_sleep(10)"),
  1189. P ! R
  1190. end,
  1191. spawn_link(F),
  1192. receive
  1193. {connected, C} ->
  1194. timer:sleep(100),
  1195. Module:close(C),
  1196. {error, closed} = receive R -> R end
  1197. end,
  1198. epgsql_ct:flush().
  1199. warning_notice(Config) ->
  1200. Module = ?config(module, Config),
  1201. epgsql_ct:with_connection(Config, fun(C) ->
  1202. Q = "create function pg_temp.raise() returns void as $$
  1203. begin
  1204. raise warning 'oops';
  1205. end;
  1206. $$ language plpgsql;
  1207. select pg_temp.raise()",
  1208. [{ok, _, _}, _] = Module:squery(C, Q),
  1209. receive
  1210. {epgsql, C, {notice, #error{message = <<"oops">>, extra = Extra}}} ->
  1211. ?assertMatch([{file, _},{line, _},{routine, _} | _], Extra),
  1212. ok
  1213. after
  1214. 100 -> erlang:error(didnt_receive_notice)
  1215. end
  1216. end, [{async, self()}]).
  1217. listen_notify(Config) ->
  1218. Module = ?config(module, Config),
  1219. epgsql_ct:with_connection(Config, fun(C) ->
  1220. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  1221. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  1222. {ok, [], []} = Module:squery(C, "notify epgsql_test"),
  1223. receive
  1224. {epgsql, C, {notification, <<"epgsql_test">>, Pid, <<>>}} -> ok
  1225. after
  1226. 100 -> erlang:error(didnt_receive_notification)
  1227. end
  1228. end, [{async, self()}]).
  1229. listen_notify_payload(Config) ->
  1230. Module = ?config(module, Config),
  1231. epgsql_ct:with_min_version(Config, [9, 0], fun(C) ->
  1232. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  1233. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  1234. {ok, [], []} = Module:squery(C, "notify epgsql_test, 'test!'"),
  1235. receive
  1236. {epgsql, C, {notification, <<"epgsql_test">>, Pid, <<"test!">>}} -> ok
  1237. after
  1238. 100 -> erlang:error(didnt_receive_notification)
  1239. end
  1240. end, [{async, self()}]).
  1241. set_notice_receiver(Config) ->
  1242. Module = ?config(module, Config),
  1243. epgsql_ct:with_min_version(Config, [9, 0], fun(C) ->
  1244. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  1245. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  1246. EnsureNoNotification = fun(Payload) ->
  1247. {ok, [], []} = Module:squery(C, ["notify epgsql_test, '", Payload, "'"]),
  1248. receive
  1249. {epgsql, _, _} -> erlang:error(got_unexpected_notification)
  1250. after
  1251. 10 -> ok
  1252. end
  1253. end,
  1254. EnsureNotification = fun(Payload) ->
  1255. {ok, [], []} = Module:squery(C, ["notify epgsql_test, '", Payload, "'"]),
  1256. receive
  1257. {epgsql, C, {notification, <<"epgsql_test">>, Pid, Payload}} -> ok
  1258. after
  1259. 100 -> erlang:error(didnt_receive_notification)
  1260. end
  1261. end,
  1262. Self = self(),
  1263. EnsureNoNotification(<<"test1">>),
  1264. % Set pid()
  1265. {ok, undefined} = Module:set_notice_receiver(C, Self),
  1266. EnsureNotification(<<"test2">>),
  1267. %% test PL/PgSQL NOTICE
  1268. {ok, [], []} = Module:squery(C, ["DO $$ BEGIN RAISE WARNING 'test notice'; END $$;"]),
  1269. receive
  1270. {epgsql, C, {notice, #error{severity = warning,
  1271. code = <<"01000">>,
  1272. message = <<"test notice">>,
  1273. extra = _}}} -> ok
  1274. after
  1275. 100 -> erlang:error(didnt_receive_notice)
  1276. end,
  1277. % set registered pid
  1278. Receiver = pg_notification_receiver,
  1279. register(Receiver, Self),
  1280. {ok, Self} = Module:set_notice_receiver(C, Receiver),
  1281. EnsureNotification(<<"test3">>),
  1282. % make registered name invalid
  1283. unregister(Receiver),
  1284. EnsureNoNotification(<<"test4">>),
  1285. % disable
  1286. {ok, Receiver} = Module:set_notice_receiver(C, undefined),
  1287. EnsureNoNotification(<<"test5">>)
  1288. end, []).
  1289. get_cmd_status(Config) ->
  1290. Module = ?config(module, Config),
  1291. epgsql_ct:with_connection(Config, fun(C) ->
  1292. {ok, [], []} = Module:squery(C, "BEGIN"),
  1293. ?assertEqual({ok, 'begin'}, Module:get_cmd_status(C)),
  1294. {ok, [], []} = epgsql:equery(C, "CREATE TEMPORARY TABLE cmd_status_t(col INTEGER)"),
  1295. ?assertEqual({ok, 'create'}, Module:get_cmd_status(C)),
  1296. %% Some commands have number of affected rows in status
  1297. {ok, N} = Module:squery(C, "INSERT INTO cmd_status_t (col) VALUES (1), (2)"),
  1298. ?assertEqual({ok, {'insert', N}}, Module:get_cmd_status(C)),
  1299. {ok, 1} = Module:squery(C, "UPDATE cmd_status_t SET col=3 WHERE col=1"),
  1300. ?assertEqual({ok, {'update', 1}}, Module:get_cmd_status(C)),
  1301. %% Failed queries have no status
  1302. {error, _} = Module:squery(C, "DELETE FROM cmd_status_t WHERE not_col=2"),
  1303. ?assertEqual({ok, undefined}, Module:get_cmd_status(C)),
  1304. %% if COMMIT failed, status will be 'rollback'
  1305. {ok, [], []} = Module:squery(C, "COMMIT"),
  1306. ?assertEqual({ok, 'rollback'}, Module:get_cmd_status(C)),
  1307. %% Only last command's status returned
  1308. [_, _, _] = Module:squery(C, "BEGIN; SELECT 1; COMMIT"),
  1309. ?assertEqual({ok, 'commit'}, Module:get_cmd_status(C))
  1310. end).
  1311. get_backend_pid(Config) ->
  1312. Module = ?config(module, Config),
  1313. epgsql_ct:with_connection(Config, fun(C) ->
  1314. {ok, [#column{}], [{PidBin}]} = Module:squery(C, "SELECT pg_backend_pid()"),
  1315. Pid = Module:get_backend_pid(C),
  1316. ?assertEqual(PidBin, integer_to_binary(Pid))
  1317. end).
  1318. range_type(Config) ->
  1319. epgsql_ct:with_min_version(Config, [9, 2], fun(_C) ->
  1320. check_type(Config, int4range, "int4range(10, 20)", {10, 20}, [
  1321. {1, 58}, {-1, 12}, {-985521, 5412687}, {minus_infinity, 0},
  1322. {984655, plus_infinity}, {minus_infinity, plus_infinity}
  1323. ]),
  1324. check_type(Config, int4range, "int4range(10, 10)", empty, [])
  1325. end, []).
  1326. range8_type(Config) ->
  1327. epgsql_ct:with_min_version(Config, [9, 2], fun(_C) ->
  1328. check_type(Config, int8range, "int8range(10, 20)", {10, 20}, [
  1329. {1, 58}, {-1, 12}, {-9223372036854775808, 5412687},
  1330. {minus_infinity, 9223372036854775807},
  1331. {984655, plus_infinity}, {minus_infinity, plus_infinity}
  1332. ]),
  1333. check_type(Config, int8range, "int8range(10, 10)", empty, [])
  1334. end, []).
  1335. date_time_range_type(Config) ->
  1336. epgsql_ct:with_min_version(Config, [9, 2], fun(_C) ->
  1337. 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}}}, []),
  1338. 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}}}, []),
  1339. 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}}}, []),
  1340. 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}}}, []),
  1341. 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}}}, []),
  1342. check_type(Config, tsrange, "tsrange('2008-01-02 03:04:05', '2008-01-02 03:04:05')", empty, []),
  1343. check_type(Config, daterange, "daterange('2008-01-02', '2008-02-02')", {{2008,1,2}, {2008, 2, 2}}, [{{-4712,1,1}, {5874897,1,1}}]),
  1344. 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}}}]),
  1345. check_type(Config, tstzrange, "tstzrange('2008-01-02 03:04:05', null)", {{{2008,1,2},{3,4,5.0}}, plus_infinity}, []),
  1346. check_type(Config, tstzrange, "tstzrange('2008-01-02 03:04:05', null, '[]')", {{{2008,1,2},{3,4,5.0}}, plus_infinity}, []),
  1347. check_type(Config, tstzrange, "tstzrange('2008-01-02 03:04:05', null, '()')", {{{2008,1,2},{3,4,5.0}}, plus_infinity}, []),
  1348. check_type(Config, tstzrange, "tstzrange(null, '2008-01-02 03:04:05')", {minus_infinity, {{2008,1,2},{3,4,5.0}}}, []),
  1349. check_type(Config, tstzrange, "tstzrange(null, '2008-01-02 03:04:05', '[]')", {minus_infinity, {{2008,1,2},{3,4,5.0}}}, []),
  1350. check_type(Config, tstzrange, "tstzrange(null, '2008-01-02 03:04:05', '()')", {minus_infinity, {{2008,1,2},{3,4,5.0}}}, [])
  1351. end, []).
  1352. with_transaction(Config) ->
  1353. Module = ?config(module, Config),
  1354. epgsql_ct:with_connection(
  1355. Config,
  1356. fun(C) ->
  1357. %% Success case
  1358. ?assertEqual(
  1359. success, Module:with_transaction(C, fun(_) -> success end)),
  1360. ?assertEqual(
  1361. success, Module:with_transaction(C, fun(_) -> success end,
  1362. [{ensure_committed, true}])),
  1363. %% begin_opts
  1364. ?assertMatch(
  1365. [{ok, _, [{<<"serializable">>}]},
  1366. {ok, _, [{<<"on">>}]}],
  1367. Module:with_transaction(
  1368. C, fun(C1) ->
  1369. Module:squery(C1, ("SHOW transaction_isolation; "
  1370. "SHOW transaction_read_only"))
  1371. end,
  1372. [{begin_opts, "READ ONLY ISOLATION LEVEL SERIALIZABLE"}])),
  1373. %% ensure_committed failure
  1374. ?assertError(
  1375. {ensure_committed_failed, rollback},
  1376. Module:with_transaction(
  1377. C, fun(C1) ->
  1378. {error, _} = Module:squery(C1, "SELECT col FROM _nowhere_"),
  1379. ok
  1380. end,
  1381. [{ensure_committed, true}])),
  1382. %% reraise
  1383. ?assertEqual(
  1384. {rollback, my_err},
  1385. Module:with_transaction(
  1386. C, fun(_) -> error(my_err) end,
  1387. [{reraise, false}])),
  1388. ?assertError(
  1389. my_err,
  1390. Module:with_transaction(
  1391. C, fun(_) -> error(my_err) end, []))
  1392. end, []).
  1393. %% @doc Mixing all 3 API interfaces with same connection
  1394. mixed_api(Config) ->
  1395. epgsql = ?config(module, Config),
  1396. epgsql_ct:with_connection(
  1397. Config,
  1398. fun(C) ->
  1399. {ok, Stmt} = epgsql:parse(
  1400. C, "SELECT id, $1::text AS val FROM generate_series(1, 5) AS t(id)"),
  1401. ABindRef = epgsqla:bind(C, Stmt, "a_portal", [<<"epgsqla">>]),
  1402. IBindRef = epgsqli:bind(C, Stmt, "i_portal", [<<"epgsqli">>]),
  1403. AExecute1Ref = epgsqla:execute(C, Stmt, "a_portal", 3),
  1404. IExecute1Ref = epgsqli:execute(C, Stmt, "i_portal", 3),
  1405. ?assertEqual({partial, [{4, <<"epgsqla">>}]},
  1406. epgsql:execute(C, Stmt, "a_portal", 1)),
  1407. ?assertEqual({partial, [{4, <<"epgsqli">>}]},
  1408. epgsql:execute(C, Stmt, "i_portal", 1)),
  1409. %% by the time epgsql:execute returns, we should already have all the asynchronous
  1410. %% responses in our message queue (epgsql:execute uses selective receive),
  1411. %% but let's try to run some more finalizers.
  1412. %% Note: we are calling epgsqla on i_portal and epgsqli on a_portal!
  1413. AExecute2Ref = epgsqla:execute(C, Stmt, "i_portal", 0),
  1414. IExecute2Ref = epgsqli:execute(C, Stmt, "a_portal", 0),
  1415. ok = epgsql:close(C, Stmt),
  1416. ?assertEqual(
  1417. [{C, ABindRef, ok},
  1418. {C, IBindRef, ok},
  1419. {C, AExecute1Ref, {partial, [{1, <<"epgsqla">>},
  1420. {2, <<"epgsqla">>},
  1421. {3, <<"epgsqla">>}
  1422. ]}},
  1423. {C, IExecute1Ref, {data, {1, <<"epgsqli">>}}},
  1424. {C, IExecute1Ref, {data, {2, <<"epgsqli">>}}},
  1425. {C, IExecute1Ref, {data, {3, <<"epgsqli">>}}},
  1426. {C, IExecute1Ref, suspended},
  1427. {C, AExecute2Ref, {ok, [{5, <<"epgsqli">>}]}},
  1428. {C, IExecute2Ref, {data, {5, <<"epgsqla">>}}},
  1429. {C, IExecute2Ref, {complete, select}}],
  1430. receive_for_conn(C, 10, 1000))
  1431. end).
  1432. pipelined_prepared_query(Config) ->
  1433. epgsql_cast = ?config(module, Config),
  1434. epgsql_ct:with_connection(
  1435. Config,
  1436. fun(C) ->
  1437. {ok, #statement{types = Types} = Stmt} =
  1438. epgsql_cast:parse(C, "SELECT $1::integer as c1, 'hello' as c2"),
  1439. Refs = [{epgsqla:prepared_query(C, Stmt, lists:zip(Types, [I])), I}
  1440. || I <- lists:seq(1, 10)],
  1441. Timer = erlang:send_after(5000, self(), timeout),
  1442. [receive
  1443. {C, Ref, {ok, Columns, Rows}} ->
  1444. ?assertMatch([#column{name = <<"c1">>, type = int4},
  1445. #column{name = <<"c2">>, type = text}], Columns),
  1446. ?assertEqual([{I, <<"hello">>}], Rows);
  1447. Other ->
  1448. %% We expect responses in the same order as we send requests
  1449. error({unexpected_message, Other})
  1450. end || {Ref, I} <- Refs],
  1451. erlang:cancel_timer(Timer)
  1452. end).
  1453. pipelined_parse_batch_execute(Config) ->
  1454. epgsql_cast = ?config(module, Config),
  1455. epgsql_ct:with_connection(
  1456. Config,
  1457. fun(C) ->
  1458. ParseRefs =
  1459. [begin
  1460. Name = io_lib:format("stmt_~w", [I]),
  1461. {epgsqla:parse(C, Name,
  1462. io_lib:format("SELECT $1 AS in, ~w00 AS out", [I]),
  1463. [int4]),
  1464. I}
  1465. end || I <- lists:seq(1, 5)],
  1466. Timer = erlang:send_after(5000, self(), timeout),
  1467. Batch =
  1468. [receive
  1469. {C, Ref, {ok, #statement{columns = Cols} = Stmt}} ->
  1470. ?assertMatch([#column{name = <<"in">>, type = int4},
  1471. #column{name = <<"out">>}],
  1472. Cols),
  1473. {Stmt, [I]};
  1474. Other ->
  1475. error({unexpected_message, Other})
  1476. end || {Ref, I} <- ParseRefs],
  1477. ?assertMatch([{ok, [{1, 100}]},
  1478. {ok, [{2, 200}]},
  1479. {ok, [{3, 300}]},
  1480. {ok, [{4, 400}]},
  1481. {ok, [{5, 500}]}],
  1482. epgsql:execute_batch(C, Batch)),
  1483. CloseRefs = [epgsqla:close(C, Stmt) || {Stmt, _} <- Batch],
  1484. [receive
  1485. {C, Ref, ok} ->
  1486. ok;
  1487. Other ->
  1488. error({unexpected_message, Other})
  1489. end || Ref <- CloseRefs],
  1490. erlang:cancel_timer(Timer)
  1491. end).
  1492. incremental_sock_active_n(Config) ->
  1493. epgsql_incremental = ?config(module, Config),
  1494. Q = "SELECT *, 'Hello world' FROM generate_series(0, 10240)",
  1495. epgsql_ct:with_connection(Config,
  1496. fun(C) ->
  1497. Ref = epgsqli:squery(C, Q),
  1498. {done, NumPassive, Others, Rows} = recv_incremental_active_n(C, Ref),
  1499. ?assertMatch([{columns, _}, {complete, _}], Others),
  1500. ?assert(NumPassive > 0),
  1501. ?assertMatch([{<<"0">>, <<"Hello world">>},
  1502. {<<"1">>, <<"Hello world">>} | _], Rows),
  1503. ?assertEqual(10241, length(Rows))
  1504. end,
  1505. "epgsql_test",
  1506. [{socket_active, 2}]).
  1507. -ifdef(OTP_RELEASE).
  1508. incremental_sock_active_n_ssl(Config) ->
  1509. epgsql_incremental = ?config(module, Config),
  1510. Q = "SELECT *, 'Hello world' FROM generate_series(0, 10240)",
  1511. epgsql_ct:with_connection(Config,
  1512. fun(C) ->
  1513. Ref = epgsqli:squery(C, Q),
  1514. {done, NumPassive, Others, Rows} = recv_incremental_active_n(C, Ref),
  1515. ?assertMatch([{columns, _}, {complete, _}], Others),
  1516. ?assert(NumPassive > 0),
  1517. ?assertMatch([{<<"0">>, <<"Hello world">>},
  1518. {<<"1">>, <<"Hello world">>} | _], Rows),
  1519. ?assertEqual(10241, length(Rows))
  1520. end,
  1521. "epgsql_test",
  1522. [{ssl, true}, {ssl_opts, [{verify, verify_none}]}, {socket_active, 2}]).
  1523. -else.
  1524. %% {active, N} for SSL is only supported on OTP-21+
  1525. incremental_sock_active_n_ssl(_Config) ->
  1526. noop.
  1527. -endif.
  1528. recv_incremental_active_n(C, Ref) ->
  1529. recv_incremental_active_n(C, Ref, 0, [], []).
  1530. recv_incremental_active_n(C, Ref, NumPassive, Rows, Others) ->
  1531. receive
  1532. {C, Ref, {data, Row}} ->
  1533. recv_incremental_active_n(C, Ref, NumPassive, [Row | Rows], Others);
  1534. {epgsql, C, socket_passive} ->
  1535. ok = epgsql:activate(C),
  1536. recv_incremental_active_n(C, Ref, NumPassive + 1, Rows, Others);
  1537. {C, Ref, {error, _} = E} ->
  1538. E;
  1539. {C, Ref, done} ->
  1540. {done, NumPassive, lists:reverse(Others), lists:reverse(Rows)};
  1541. {C, Ref, Other} ->
  1542. recv_incremental_active_n(C, Ref, NumPassive, Rows, [Other | Others]);
  1543. Other ->
  1544. recv_incremental_active_n(C, Ref, NumPassive, Rows, [Other | Others])
  1545. after 5000 ->
  1546. error({timeout, NumPassive, Others, Rows})
  1547. end.
  1548. redacted_state(Config) ->
  1549. case erlang:system_info(otp_release) of
  1550. V = [_, _] when V > "20" ->
  1551. redacted_state_(Config);
  1552. V ->
  1553. {skip, {"Logger facility is available starting OTP 21, running on OTP " ++ V}}
  1554. end.
  1555. redacted_state_(Config) ->
  1556. _Handle = ct:timetrap({seconds, 3}),
  1557. try
  1558. logger:add_handler(?MODULE, ?MODULE, #{relay_to => self()}),
  1559. C = epgsql_ct:connect(Config),
  1560. true = unlink(C),
  1561. Reason = {please, ?MODULE, ?FUNCTION_NAME},
  1562. ok = proc_lib:stop(C, Reason, 1000),
  1563. receive
  1564. {log, Message} ->
  1565. ?assertMatch({report, #{label := {gen_server, terminate},
  1566. reason := Reason,
  1567. state := _}},
  1568. Message),
  1569. {report, #{state := State}} = Message,
  1570. ?assertMatch(#{rows := information_redacted},
  1571. epgsql_sock:state_to_map(State))
  1572. end
  1573. after
  1574. logger:remove_handler(?MODULE)
  1575. end.
  1576. %% =============================================================================
  1577. %% Logger handler
  1578. %% ============================================================================
  1579. log(#{msg := Msg}, #{relay_to := Pid}) ->
  1580. Pid ! {log, Msg};
  1581. log(_, _) ->
  1582. ok.
  1583. %% =============================================================================
  1584. %% Internal functions
  1585. %% ============================================================================
  1586. receive_for_conn(_, 0, _) -> [];
  1587. receive_for_conn(C, N, Timeout) ->
  1588. receive
  1589. {C, _, _} = Msg ->
  1590. [Msg | receive_for_conn(C, N - 1, Timeout)];
  1591. Other ->
  1592. error({unexpected_msg, Other})
  1593. after Timeout ->
  1594. error({timeout, {remaining_msgs, N}})
  1595. end.
  1596. get_type_col(Type) ->
  1597. "c_" ++ atom_to_list(Type).
  1598. check_type(Config, Type, In, Out, Values) ->
  1599. Column = get_type_col(Type),
  1600. check_type(Config, Type, In, Out, Values, Column).
  1601. check_type(Config, Type, In, Out, Values, Column) ->
  1602. epgsql_ct:with_connection(Config, fun(C) ->
  1603. check_type(Config, Type, In, Out, Values, Column, C)
  1604. end).
  1605. check_type(Config, Type, In, Out, Values, Column, C) ->
  1606. Module = ?config(module, Config),
  1607. Select = io_lib:format("select ~s::~w", [In, Type]),
  1608. Res = Module:equery(C, Select),
  1609. ?assertMatch({ok, [#column{type = Type}], [{Out}]}, Res),
  1610. Sql = io_lib:format("insert into test_table2 (~s) values ($1) returning ~s", [Column, Column]),
  1611. {ok, #statement{columns = [#column{type = Type}]} = S} = Module:parse(C, Sql),
  1612. Insert = fun(V) ->
  1613. ok = Module:bind(C, S, [V]),
  1614. {ok, 1, [{V2}]} = Module:execute(C, S),
  1615. case compare(Type, V, V2) of
  1616. true -> ok;
  1617. false -> error({write_read_compare_failed, io_lib:format("~p =/= ~p", [V, V2])})
  1618. end,
  1619. ok = Module:sync(C)
  1620. end,
  1621. lists:foreach(Insert, [null, undefined | Values]).
  1622. compare(_Type, null, null) -> true;
  1623. compare(_Type, undefined, null) -> true;
  1624. compare(float4, V1, V2) when is_float(V1) -> abs(V2 - V1) < 0.000001;
  1625. compare(float8, V1, V2) when is_float(V1) -> abs(V2 - V1) < 0.000000000000001;
  1626. compare(hstore, {V1}, V2) -> compare(hstore, V1, V2);
  1627. compare(hstore, V1, {V2}) -> compare(hstore, V1, V2);
  1628. compare(hstore, V1, V2) ->
  1629. orddict:from_list(format_hstore(V1)) =:= orddict:from_list(format_hstore(V2));
  1630. compare(Type, V1 = {_, _, MS}, {D2, {H2, M2, S2}}) when Type == timestamp;
  1631. Type == timestamptz ->
  1632. {D1, {H1, M1, S1}} = calendar:now_to_universal_time(V1),
  1633. ({D1, H1, M1} =:= {D2, H2, M2}) and (abs(S1 + MS/1000000 - S2) < 0.000000000000001);
  1634. compare(_Type, V1, V2) -> V1 =:= V2.
  1635. format_hstore({Hstore}) -> Hstore;
  1636. format_hstore(Hstore) ->
  1637. [{format_hstore_key(Key), format_hstore_value(Value)} || {Key, Value} <- Hstore].
  1638. format_hstore_key(Key) -> format_hstore_string(Key).
  1639. format_hstore_value(null) -> null;
  1640. format_hstore_value(undefined) -> null;
  1641. format_hstore_value(Value) -> format_hstore_string(Value).
  1642. format_hstore_string(Num) when is_number(Num) -> iolist_to_binary(io_lib:format("~w", [Num]));
  1643. format_hstore_string(Str) -> iolist_to_binary(io_lib:format("~s", [Str])).