epgsql_SUITE.erl 52 KB

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