epgsql_SUITE.erl 66 KB

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