epgsql_SUITE.erl 65 KB

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