epgsql_SUITE.erl 66 KB

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