epgsql_SUITE.erl 59 KB

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