epgsql_SUITE.erl 60 KB

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