epgsql_SUITE.erl 65 KB

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