epgsql_SUITE.erl 70 KB

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